summaryrefslogtreecommitdiff
path: root/src/vte.c
blob: 45ec240348414836e4f42bb472097fb483a3eedb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
/*
 * Copyright (C) 2001,2002 Red Hat, Inc.
 *
 * This is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Library 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 Library General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#ident "$Id$"
#include "../config.h"
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <errno.h>
#include <fcntl.h>
#include <langinfo.h>
#include <math.h>
#include <pwd.h>
#include <regex.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <wchar.h>
#include <glib.h>
#include <glib-object.h>
#include <gdk/gdk.h>
#include <gdk/gdkkeysyms.h>
#include <gdk/gdkx.h>
#include <gtk/gtk.h>
#include <pango/pango.h>
#include <pango/pangox.h>
#include "caps.h"
#include "debug.h"
#include "iso2022.h"
#include "marshal.h"
#include "pty.h"
#include "reaper.h"
#include "ring.h"
#include "termcap.h"
#include "table.h"
#include "vte.h"
#include "vteaccess.h"
#include <X11/Xlib.h>
#ifdef HAVE_XFT
#include <X11/Xft/Xft.h>
#endif

#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif

#ifndef HAVE_WINT_T
typedef long wint_t;
#endif

#ifdef ENABLE_NLS
#include <libintl.h>
#define _(String) dgettext(PACKAGE, String)
#else
#define _(String) String
#define bindtextdomain(package,dir)
#endif

#define VTE_PAD_WIDTH			2
#define VTE_TAB_WIDTH			8
#define VTE_LINE_WIDTH			1
#define VTE_COLOR_SET_SIZE		8
#define VTE_COLOR_PLAIN_OFFSET		0
#define VTE_COLOR_BRIGHT_OFFSET		8
#define VTE_DEF_FG			16
#define VTE_DEF_BG			(VTE_DEF_FG + 1)
#define VTE_BOLD_FG			(VTE_DEF_BG + 1)
#define VTE_SATURATION_MAX		10000
#define VTE_SCROLLBACK_MIN		100
#define VTE_DEFAULT_EMULATION		"xterm"
#define VTE_DEFAULT_CURSOR		GDK_XTERM
#define VTE_MOUSING_CURSOR		GDK_LEFT_PTR
#define VTE_XFT_HARD_LIMIT		88
#define VTE_TAB_MAX			999
#define VTE_X_FIXED			"-*-fixed-medium-r-normal-*-20-*"
#define VTE_REPRESENTATIVE_CHARACTERS	"ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
					"abcdefgjijklmnopqrstuvwxyz" \
					"0123456789./+@"
#define VTE_REPRESENTATIVE_WIDER_CHARACTER	'M'
#define VTE_REPRESENTATIVE_NARROWER_CHARACTER	'l'
#define VTE_INPUT_RETRY_PRIORITY	G_PRIORITY_HIGH
#define VTE_INPUT_PRIORITY		G_PRIORITY_DEFAULT_IDLE
#define VTE_CHILD_INPUT_PRIORITY	G_PRIORITY_DEFAULT_IDLE
#define VTE_CHILD_OUTPUT_PRIORITY	G_PRIORITY_HIGH
#define VTE_FX_PRIORITY			G_PRIORITY_DEFAULT_IDLE
#define VTE_PREFER_PANGOX

/* The structure we use to hold characters we're supposed to display -- this
 * includes any supported visible attributes. */
struct vte_charcell {
	gunichar c;		/* The Unicode character. */
	guint16 columns: 2;	/* Number of visible columns (as determined
				   by g_unicode_iswide(c)). */
	guint16 fore: 5;	/* Indices in the color palette for the */
	guint16 back: 5;	/* foreground and background of the cell. */
	guint16 standout: 1;	/* Single-bit attributes. */
	guint16 underline: 1;
	guint16 reverse: 1;
	guint16 blink: 1;
	guint16 half: 1;
	guint16 bold: 1;
	guint16 invisible: 1;
	guint16 protect: 1;
	guint16 alternate: 1;
};

/* A match regex, with a tag. */
struct vte_match_regex {
	regex_t reg;
	gint tag;
};

/* A drawing request record, for simplicity. */
struct vte_draw_item {
	gunichar c;
	guint16 xpad;
};

/* The terminal's keypad state.  A terminal can either be using the normal
 * keypad, or the "application" keypad.  Arrow key sequences, for example,
 * are really only defined for "application" mode. */
typedef enum _VteKeypad {
	VTE_KEYPAD_NORMAL,
	VTE_KEYPAD_APPLICATION,
} VteKeypad;

/* The terminal's function key setting. */
typedef enum _VteFKey {
	VTE_FKEY_VT220,
	VTE_FKEY_SUNPC,
} VteFKey;

typedef struct _VteScreen VteScreen;

typedef struct _VteWordCharRange {
	gunichar start, end;
} VteWordCharRange;

/* Terminal private data. */
struct _VteTerminalPrivate {
	/* Emulation setup data. */
	struct vte_termcap *termcap;	/* termcap storage */
	struct vte_table *table;		/* control sequence table */
	const char *termcap_path;	/* path to termcap file */
	const char *emulation;		/* terminal type to emulate */
	GTree *sequences;		/* sequence handlers, keyed by GQuark
					   based on the sequence name */
	struct vte_terminal_flags {	/* boolean termcap flags */
		gboolean am;
		gboolean bw;
		gboolean ul;
	} flags;
	int keypad;			/* this would be a VteKeypad, but we
					   need to guarantee its type */
	int fkey;			/* this would be a VteFKey, but we
					   need to guarantee its type */
	GHashTable *dec_saved;
	int default_column_count, default_row_count;	/* default sizes */
	GTree *unichar_wc_map;		/* mapping between gunichars and wide
					   characters */

	/* PTY handling data. */
	const char *shell;		/* shell we started */
	int pty_master;			/* pty master descriptor */
	GIOChannel *pty_input;		/* master input watch */
	guint pty_input_source;
	GIOChannel *pty_output;		/* master output watch */
	guint pty_output_source;
	pid_t pty_pid;			/* pid of child using pty slave */

	/* Input data queues. */
	const char *encoding;		/* the pty's encoding */
	struct vte_iso2022 *substitutions;
	GIConv incoming_conv;		/* narrow/unichar conversion state */
	unsigned char *incoming;	/* pending output characters */
	gssize n_incoming;
	gboolean processing;
	gint processing_tag;

	/* Output data queue. */
	unsigned char *outgoing;	/* pending input characters */
	gssize n_outgoing;
	GIConv outgoing_conv_wide;
	GIConv outgoing_conv_utf8;

	/* Screen data.  We support the normal screen, and an alternate
	 * screen, which seems to be a DEC-specific feature. */
	struct _VteScreen {
		VteRing *row_data;	/* row data, arranged as a GArray of
					   vte_charcell structures */
		struct vte_cursor_position {
			long row, col;
		} cursor_current, cursor_saved;
					/* the current and saved positions of
					   the [insertion] cursor -- current is
					   absolute, saved is relative to the
					   insertion delta */
		gboolean reverse_mode;	/* reverse mode */
		gboolean insert_mode;	/* insert mode */
		struct vte_scrolling_region {
			int start, end;
		} scrolling_region;	/* the region we scroll in */
		gboolean scrolling_restricted;
		long scroll_delta;	/* scroll offset */
		long insert_delta;	/* insertion offset */
		struct vte_charcell defaults;	/* default characteristics
						   for insertion of any new
						   characters */
		gboolean status_line;
		GString *status_line_contents;
	} normal_screen, alternate_screen, *screen;

	/* Selection information. */
	GArray *word_chars;
	gboolean has_selection;
	gboolean start_selection;
	char *selection;
	enum {
		selection_type_char,
		selection_type_word,
		selection_type_line,
	} selection_type;
	struct selection_event_coords {
		double x, y;
	} selection_origin, selection_last, selection_delayed;
	struct {
		long x, y;
	} selection_start, selection_end;

	/* Miscellaneous options. */
	VteTerminalEraseBinding backspace_binding, delete_binding;
	gboolean alt_sends_escape;
	gboolean audible_bell;
	gboolean visible_bell;
	gboolean xterm_font_tweak;
	GHashTable *tabstops;

	/* Scrolling options. */
	gboolean scroll_on_output;
	gboolean scroll_on_keystroke;
	long scrollback_lines;

	/* Cursor blinking. */
	gboolean cursor_blinks;
	gint cursor_blink_tag;
	gboolean cursor_visible;

	/* Input device options. */
	guint last_keypress_time;
	gboolean mouse_send_xy_on_click;
	gboolean mouse_send_xy_on_button;
	gboolean mouse_hilite_tracking;
	gboolean mouse_cell_motion_tracking;
	gboolean mouse_all_motion_tracking;
	guint mouse_last_button;
	gdouble mouse_last_x, mouse_last_y;
	gboolean mouse_autohide;

	/* State variables for handling match checks. */
	char *match_contents;
	GArray *match_attributes;
	GArray *match_regexes;
	struct {
		long row, column;
	} match_start, match_end;

	/* Data used when rendering the text which does not require server
	 * resources and which can be kept after unrealizing. */
	PangoFontDescription *fontdesc;

	/* GtkSettings that we are monitoring. */
	GtkSettings *connected_settings;

	/* Data used when rendering the text which reflects server resources
	 * and data, which should be dropped when unrealizing and (re)created
	 * when realizing. */
	PangoContext *pcontext;
	XFontSet fontset;
	GTree *fontpaddingl, *fontpaddingr;
	enum VteRenderMethod {
		VteRenderXlib = 0,
		VteRenderPango = 1,
		VteRenderXft1 = 2,
		VteRenderXft2 = 3
	} render_method;
#ifdef HAVE_XFT
	XftFont *ftfont;
#endif
	gboolean palette_initialized;
	struct vte_palette_entry {
		guint16 red, green, blue;
		unsigned long pixel;
#ifdef HAVE_XFT
		XRenderColor rcolor;
		XftColor ftcolor;
#endif
	} palette[VTE_BOLD_FG + 1];

	/* Mouse cursors. */
	GdkCursor *mouse_default_cursor,
		  *mouse_mousing_cursor,
		  *mouse_inviso_cursor;

	/* Input method support. */
	GtkIMContext *im_context;
	char *im_preedit;
	int im_preedit_cursor;

	/* Our accessible peer. */
	AtkObject *accessible;

	/* Background images/"transparency". */
	gboolean bg_transparent;
	gboolean bg_transparent_update_pending;
	guint bg_transparent_update_tag;
	GdkAtom bg_transparent_atom;
	GdkWindow *bg_transparent_window;
	GdkPixbuf *bg_transparent_image;
	GdkPixbuf *bg_image;
	long bg_saturation;	/* out of VTE_SATURATION_MAX */
};

/* A function which can handle a terminal control sequence. */
typedef void (*VteTerminalSequenceHandler)(VteTerminal *terminal,
					   const char *match,
					   GQuark match_quark,
					   GValueArray *params);
static void vte_terminal_set_termcap(VteTerminal *terminal, const char *path,
				     gboolean reset);
static void vte_terminal_setup_background(VteTerminal *terminal,
					  gboolean refresh_transparent);
static void vte_terminal_ensure_cursor(VteTerminal *terminal, gboolean current);
static void vte_terminal_paste(VteTerminal *terminal, GdkAtom board);
static void vte_terminal_insert_char(GtkWidget *widget, gunichar c,
				     gboolean force_insert_mode);
static void vte_sequence_handler_clear_screen(VteTerminal *terminal,
					      const char *match,
					      GQuark match_quark,
					      GValueArray *params);
static void vte_sequence_handler_do(VteTerminal *terminal,
				    const char *match,
				    GQuark match_quark,
				    GValueArray *params);
static void vte_sequence_handler_DO(VteTerminal *terminal,
				    const char *match,
				    GQuark match_quark,
				    GValueArray *params);
static void vte_sequence_handler_ho(VteTerminal *terminal,
				    const char *match,
				    GQuark match_quark,
				    GValueArray *params);
static void vte_sequence_handler_le(VteTerminal *terminal,
				    const char *match,
				    GQuark match_quark,
				    GValueArray *params);
static void vte_sequence_handler_LE(VteTerminal *terminal,
				    const char *match,
				    GQuark match_quark,
				    GValueArray *params);
static void vte_sequence_handler_nd(VteTerminal *terminal,
				    const char *match,
				    GQuark match_quark,
				    GValueArray *params);
static void vte_sequence_handler_sf(VteTerminal *terminal,
				    const char *match,
				    GQuark match_quark,
				    GValueArray *params);
static void vte_sequence_handler_sr(VteTerminal *terminal,
				    const char *match,
				    GQuark match_quark,
				    GValueArray *params);
static void vte_sequence_handler_ue(VteTerminal *terminal,
				    const char *match,
				    GQuark match_quark,
				    GValueArray *params);
static void vte_sequence_handler_up(VteTerminal *terminal,
				    const char *match,
				    GQuark match_quark,
				    GValueArray *params);
static void vte_sequence_handler_UP(VteTerminal *terminal,
				    const char *match,
				    GQuark match_quark,
				    GValueArray *params);
static void vte_sequence_handler_us(VteTerminal *terminal,
				    const char *match,
				    GQuark match_quark,
				    GValueArray *params);
static void vte_sequence_handler_vb(VteTerminal *terminal,
				    const char *match,
				    GQuark match_quark,
				    GValueArray *params);
static gboolean vte_terminal_io_read(GIOChannel *channel,
				     GdkInputCondition condition,
				     gpointer data);
static gboolean vte_terminal_io_write(GIOChannel *channel,
				      GdkInputCondition condition,
				      gpointer data);
static GdkFilterReturn vte_terminal_filter_property_changes(GdkXEvent *xevent,
							    GdkEvent *event,
							    gpointer data);
static void vte_terminal_match_hilite_clear(VteTerminal *terminal);
static void vte_terminal_queue_background_update(VteTerminal *terminal);

/* Free a no-longer-used row data array. */
static void
vte_free_row_data(gpointer freeing, gpointer data)
{
	if (freeing) {
		g_array_free((GArray*)freeing, TRUE);
	}
}

/* Allocate a new line. */
static GArray *
vte_new_row_data(void)
{
	return g_array_new(FALSE, FALSE, sizeof(struct vte_charcell));
}

/* Guess at how many columns a character takes up. */
static gssize
vte_unichar_width(gunichar c)
{
	return g_unichar_isdefined(c) ? (g_unichar_iswide(c) ? 2 : 1) : -1;
}

/* Check how long a string of unichars is.  Slow version. */
static gssize
vte_unicode_strlen(gunichar *c)
{
	int i;
	for (i = 0; c[i] != 0; i++) ;
	return i;
}

/* Convert a gunichar to a wchar_t for use with X. */
static wchar_t
vte_wc_from_unichar(VteTerminal *terminal, gunichar c)
{
#ifdef __STDC_ISO_10646__
	return (wchar_t) c;
#else
	gpointer original, result;
	char *local, utf8_buf[VTE_UTF8_BPC];
	const char *localr;
	wchar_t wc_buf[VTE_UTF8_BPC];
	int ret;
	gsize length, bytes_read, bytes_written;
	mbstate_t state;
	GError *error;
	/* Check the cache. */
	if (g_tree_lookup_extended(terminal->pvt->unichar_wc_map,
				   GINT_TO_POINTER(c),
				   &original,
				   &result)) {
		return GPOINTER_TO_INT(c);
	}
	/* Convert the character to a locally-encoded mbs. */
	length = g_unichar_to_utf8(c, utf8_buf);
	local = g_locale_from_utf8(utf8_buf, length,
				   &bytes_read, &bytes_written, &error);
	if (error == NULL) {
		/* Convert from an mbs to a (single-character) wcs. */
		memset(&state, 0, sizeof(state));
		localr = local;
		ret = mbsrtowcs(wc_buf, &localr, bytes_written, &state);
		if (ret == 1) {
			g_tree_insert(terminal->pvt->unichar_wc_map,
				      GINT_TO_POINTER(c),
				      GINT_TO_POINTER(wc_buf[0]));
			return wc_buf[0];
		}
	}
	/* Punt. */
	if (error != NULL) {
		g_printerr("g_locale_from_utf8(%d): %s", error->code,
			   error->message);
		g_error_free(error);
	}
	return (wchar_t) c;
#endif
}

#ifdef VTE_PREFER_PANGOX
static PangoContext *
vte_terminal_get_pango_context(VteTerminal *terminal)
{
	return pango_x_get_context(GDK_DISPLAY());
}
static void
vte_terminal_maybe_unref_pango_context(VteTerminal *terminal, PangoContext *ctx)
{
	g_object_unref(G_OBJECT(ctx));
}
#else
static PangoContext *
vte_terminal_get_pango_context(VteTerminal *terminal)
{
	return gtk_widget_get_pango_context(terminal);
}
static void
vte_terminal_maybe_unref_pango_context(VteTerminal *terminal, PangoContext *ctx)
{
	/* no-op */
}
#endif

/* Reset defaults for character insertion. */
static void
vte_terminal_set_default_attributes(VteTerminal *terminal)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	terminal->pvt->screen->defaults.c = 0;
	terminal->pvt->screen->defaults.columns = 1;
	terminal->pvt->screen->defaults.fore = VTE_DEF_FG;
	terminal->pvt->screen->defaults.back = VTE_DEF_BG;
	terminal->pvt->screen->defaults.reverse = 0;
	terminal->pvt->screen->defaults.bold = 0;
	terminal->pvt->screen->defaults.invisible = 0;
	terminal->pvt->screen->defaults.protect = 0;
	terminal->pvt->screen->defaults.standout = 0;
	terminal->pvt->screen->defaults.underline = 0;
	terminal->pvt->screen->defaults.half = 0;
	terminal->pvt->screen->defaults.blink = 0;
	/* Alternate charset isn't an attribute, though we treat it as one.
	 * terminal->pvt->screen->defaults.alternate = 0; */
}

/* Cause certain cells to be updated. */
static void
vte_invalidate_cells(VteTerminal *terminal,
		     glong column_start, gint column_count,
		     glong row_start, gint row_count)
{
	GdkRectangle rect;
	GtkWidget *widget;

	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	widget = GTK_WIDGET(terminal);
	if (!GTK_WIDGET_REALIZED(widget)) {
		return;
	}

	/* Subtract the scrolling offset from the row start so that the
	 * resulting rectangle is relative to the visible portion of the
	 * buffer. */
	row_start -= terminal->pvt->screen->scroll_delta;

	/* Clamp the start values to reasonable numbers. */
	column_start = (column_start > 0) ? column_start : 0;
	row_start = (row_start > 0) ? row_start : 0;

	/* Convert the column and row start and end to pixel values
	 * by multiplying by the size of a character cell. */
	rect.x = column_start * terminal->char_width + VTE_PAD_WIDTH;
	rect.width = column_count * terminal->char_width;
	rect.y = row_start * terminal->char_height + VTE_PAD_WIDTH;
	rect.height = row_count * terminal->char_height;

	/* Invalidate the rectangle. */
	gdk_window_invalidate_rect(widget->window, &rect, TRUE);
}

/* Redraw the entire visible portion of the window. */
static void
vte_invalidate_all(VteTerminal *terminal)
{
	GdkRectangle rect;
	GtkWidget *widget;
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	if (!GTK_IS_WIDGET(terminal)) {
	       return;
	}
	widget = GTK_WIDGET(terminal);
	if (!GTK_WIDGET_REALIZED(widget)) {
		return;
	}

	/* Expose the entire widget area. */
	rect.x = 0;
	rect.y = 0;
	rect.width = terminal->column_count * terminal->char_width +
		     2 * VTE_PAD_WIDTH;
	rect.height = terminal->row_count * terminal->char_height +
		      2 * VTE_PAD_WIDTH;
	gdk_window_invalidate_rect((GTK_WIDGET(terminal))->window, &rect, TRUE);
}

/* Scroll a rectangular region up or down by a fixed number of lines. */
static void
vte_terminal_scroll_region(VteTerminal *terminal,
			   long row, long count, long delta)
{
	GtkWidget *widget;
	gboolean repaint = TRUE;

	if ((delta == 0) || (count == 0)) {
		/* Shenanigans! */
		return;
	}

	/* We only do this if we're scrolling the entire window. */
	if (!terminal->pvt->bg_transparent &&
	    (terminal->pvt->bg_image == NULL) &&
	    (row == 0) &&
	    (count == terminal->row_count)) {
		widget = GTK_WIDGET(terminal);
		gdk_window_scroll(widget->window,
				  0, delta * terminal->char_height);
		repaint = FALSE;
	}

	if (repaint) {
		/* We have to repaint the entire area. */
		vte_invalidate_cells(terminal,
				     0, terminal->column_count,
				     row, count);
	}
}

/* Find the character in the given "virtual" position. */
static struct vte_charcell *
vte_terminal_find_charcell(VteTerminal *terminal, long col, long row)
{
	GArray *rowdata;
	struct vte_charcell *ret = NULL;
	VteScreen *screen;
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), NULL);
	screen = terminal->pvt->screen;
	if (vte_ring_contains(screen->row_data, row)) {
		rowdata = vte_ring_index(screen->row_data, GArray*, row);
		if (rowdata->len > col) {
			ret = &g_array_index(rowdata, struct vte_charcell, col);
		}
	}
	return ret;
}

/* Cause the cursor to be redrawn. */
static void
vte_invalidate_cursor_once(gpointer data)
{
	VteTerminal *terminal;
	VteScreen *screen;
	struct vte_charcell *cell;
	gssize preedit_length;
	int columns;

	if (!VTE_IS_TERMINAL(data)) {
		return;
	}
	terminal = VTE_TERMINAL(data);

	if (terminal->pvt->cursor_visible &&
	    GTK_WIDGET_REALIZED(GTK_WIDGET(terminal))) {
		if (terminal->pvt->im_preedit != NULL) {
			preedit_length = strlen(terminal->pvt->im_preedit);
		} else {
			preedit_length = 0;
		}

		screen = terminal->pvt->screen;
		columns = 1;
		cell = vte_terminal_find_charcell(terminal,
						  screen->cursor_current.col,
						  screen->cursor_current.row);
		if (cell != NULL) {
			columns = cell->columns;
		}
		vte_invalidate_cells(terminal,
				     screen->cursor_current.col,
				     columns + preedit_length,
				     screen->cursor_current.row,
				     1);
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_UPDATES)) {
			fprintf(stderr, "Invalidating cursor at (%ld,%ld-%ld)."
				"\n", screen->cursor_current.row,
				screen->cursor_current.col,
				screen->cursor_current.col +
				columns + preedit_length - 1);
		}
#endif
	}
}

/* Invalidate the cursor repeatedly. */
static gboolean
vte_invalidate_cursor_periodic(gpointer data)
{
	VteTerminal *terminal;
	GtkSettings *settings;
	gint blink_cycle = 1000;

	g_return_val_if_fail(VTE_IS_TERMINAL(data), FALSE);
	if (!GTK_WIDGET_REALIZED(GTK_WIDGET(data))) {
		return TRUE;
	}

	terminal = VTE_TERMINAL(data);
	vte_invalidate_cursor_once(data);

	settings = gtk_widget_get_settings(GTK_WIDGET(data));
	if (G_IS_OBJECT(settings)) {
		g_object_get(G_OBJECT(settings), "gtk-cursor-blink-time",
			     &blink_cycle, NULL);
	}
	terminal->pvt->cursor_blink_tag = g_timeout_add_full(G_PRIORITY_LOW,
							     blink_cycle / 2,
							     vte_invalidate_cursor_periodic,
							     terminal,
							     NULL);
	return FALSE;
}

/* Emit a "selection_changed" signal. */
static void
vte_terminal_emit_selection_changed(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `selection-changed'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "selection-changed");
}

/* Emit an "emulation-changed" signal. */
static void
vte_terminal_emit_emulation_changed(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `emulation-changed'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "emulation-changed");
}

/* Emit an "encoding-changed" signal. */
static void
vte_terminal_emit_encoding_changed(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `encoding-changed'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "encoding-changed");
}

/* Emit a "child-exited" signal. */
static void
vte_terminal_emit_child_exited(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `child-exited'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "child-exited");
}

/* Emit a "contents_changed" signal. */
static void
vte_terminal_emit_contents_changed(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `contents-changed'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "contents-changed");
}

/* Emit a "cursor_moved" signal. */
static void
vte_terminal_emit_cursor_moved(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `cursor-moved'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "cursor-moved");
}

/* Emit an "icon-title-changed" signal. */
static void
vte_terminal_emit_icon_title_changed(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `icon-title-changed'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "icon-title-changed");
}

/* Emit a "window-title-changed" signal. */
static void
vte_terminal_emit_window_title_changed(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `window-title-changed'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "window-title-changed");
}

/* Emit a "deiconify-window" signal. */
static void
vte_terminal_emit_deiconify_window(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `deiconify-window'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "deiconify-window");
}

/* Emit a "iconify-window" signal. */
static void
vte_terminal_emit_iconify_window(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `iconify-window'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "iconify-window");
}

/* Emit a "raise-window" signal. */
static void
vte_terminal_emit_raise_window(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `raise-window'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "raise-window");
}

/* Emit a "lower-window" signal. */
static void
vte_terminal_emit_lower_window(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `lower-window'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "lower-window");
}

/* Emit a "maximize-window" signal. */
static void
vte_terminal_emit_maximize_window(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `maximize-window'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "maximize-window");
}

/* Emit a "refresh-window" signal. */
static void
vte_terminal_emit_refresh_window(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `refresh-window'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "refresh-window");
}

/* Emit a "restore-window" signal. */
static void
vte_terminal_emit_restore_window(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `restore-window'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "restore-window");
}

/* Emit a "eof" signal. */
static void
vte_terminal_emit_eof(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `eof'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "eof");
}

/* Emit a "char-size-changed" signal. */
static void
vte_terminal_emit_char_size_changed(VteTerminal *terminal,
				    guint width, guint height)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `char-size-changed'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "char-size-changed",
			      width, height);
}

/* Emit a "resize-window" signal.  (Pixels.) */
static void
vte_terminal_emit_resize_window(VteTerminal *terminal,
				guint width, guint height)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `resize-window'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "resize-window", width, height);
}

/* Emit a "move-window" signal.  (Pixels.) */
static void
vte_terminal_emit_move_window(VteTerminal *terminal, guint x, guint y)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `move-window'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "move-window", x, y);
}

/* Emit a "status-line-changed" signal. */
static void
vte_terminal_emit_status_line_changed(VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_SIGNALS)) {
		fprintf(stderr, "Emitting `status-line-changed'.\n");
	}
#endif
	g_signal_emit_by_name(terminal, "status-line-changed");
}

/* Deselect anything which is selected and refresh the screen if needed. */
static void
vte_terminal_deselect_all(VteTerminal *terminal)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	if (terminal->pvt->has_selection) {
		terminal->pvt->has_selection = FALSE;
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_SELECTION)) {
			fprintf(stderr, "Deselecting all text.\n");
		}
#endif
		vte_terminal_emit_selection_changed (terminal);
		vte_invalidate_all(terminal);
	}
	terminal->pvt->start_selection = FALSE;
}

/* Reset the set of tab stops to the default. */
static void
vte_terminal_set_tabstop(VteTerminal *terminal, int column)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	if (terminal->pvt->tabstops != NULL) {
		/* Just set a non-NULL pointer for this column number. */
		g_hash_table_insert(terminal->pvt->tabstops,
				    GINT_TO_POINTER(2 * column + 1),
				    terminal);
	}
}

/* Remove a tabstop. */
static void
vte_terminal_clear_tabstop(VteTerminal *terminal, int column)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	if (terminal->pvt->tabstops != NULL) {
		/* Remove a tab stop from the hash table. */
		g_hash_table_remove(terminal->pvt->tabstops,
				    GINT_TO_POINTER(2 * column + 1));
	}
}

/* Check if we have a tabstop at a given position. */
static gboolean
vte_terminal_get_tabstop(VteTerminal *terminal, int column)
{
	gpointer hash;
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), FALSE);
	if (terminal->pvt->tabstops != NULL) {
		hash = g_hash_table_lookup(terminal->pvt->tabstops,
					   GINT_TO_POINTER(2 * column + 1));
		return (hash != NULL);
	} else {
		return FALSE;
	}
}

/* Reset the set of tab stops to the default. */
static void
vte_terminal_set_default_tabstops(VteTerminal *terminal)
{
	int i, width;
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	if (terminal->pvt->tabstops != NULL) {
		g_hash_table_destroy(terminal->pvt->tabstops);
	}
	terminal->pvt->tabstops = g_hash_table_new(g_direct_hash,
						   g_direct_equal);
	width = vte_termcap_find_numeric(terminal->pvt->termcap,
					 terminal->pvt->emulation,
					 "it");
	if (width == 0) {
		width = VTE_TAB_WIDTH;
	}
	for (i = 0; i <= VTE_TAB_MAX; i += width) {
		vte_terminal_set_tabstop(terminal, i);
	}
}

/* Clear the cache of the screen contents we keep. */
static void
vte_terminal_match_contents_clear(VteTerminal *terminal)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	if (terminal->pvt->match_contents != NULL) {
		g_free(terminal->pvt->match_contents);
		terminal->pvt->match_contents = NULL;;
	}
	while (terminal->pvt->match_attributes != NULL) {
		g_array_free(terminal->pvt->match_attributes, TRUE);
		terminal->pvt->match_attributes = NULL;
	}
	vte_terminal_match_hilite_clear(terminal);
}

/* Refresh the cache of the screen contents we keep. */
static gboolean
always_selected(VteTerminal *terminal, long row, long column)
{
	return TRUE;
}
static void
vte_terminal_match_contents_refresh(VteTerminal *terminal)
{
	GArray *array;
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	vte_terminal_match_contents_clear(terminal);
	array = g_array_new(FALSE, TRUE, sizeof(struct vte_char_attributes));
	terminal->pvt->match_contents = vte_terminal_get_text(terminal,
							      always_selected,
							      array);
	terminal->pvt->match_attributes = array;
}

/* Display string matching:  clear all matching expressions. */
void
vte_terminal_match_clear_all(VteTerminal *terminal)
{
	struct vte_match_regex *regex;
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	while (terminal->pvt->match_regexes->len > 0) {
		regex = &g_array_index(terminal->pvt->match_regexes,
				       struct vte_match_regex,
				       terminal->pvt->match_regexes->len - 1);
		regfree(&regex->reg);
		memset(&regex->reg, 0, sizeof(regex->reg));
		regex->tag = 0;
		g_array_remove_index(terminal->pvt->match_regexes,
				     terminal->pvt->match_regexes->len - 1);
	}
	vte_terminal_match_hilite_clear(terminal);
}

/* Add a matching expression, returning the tag the widget assigns to that
 * expression. */
int
vte_terminal_match_add(VteTerminal *terminal, const char *match)
{
	struct vte_match_regex regex;
	int ret;
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), -1);
	memset(&regex, 0, sizeof(regex));
	ret = regcomp(&regex.reg, match, REG_EXTENDED);
	if (ret != 0) {
		g_warning(_("Error compiling regular expression \"%s\"."),
			  match);
		return -1;
	}
	regex.tag = terminal->pvt->match_regexes->len;
	g_array_append_val(terminal->pvt->match_regexes, regex);
	return regex.tag;
}

/* Check if a given cell on the screen contains part of a matched string.  If
 * it does, return the string, and store the match tag in the optional tag
 * argument. */
static char *
vte_terminal_match_check_internal(VteTerminal *terminal, long column,
				  long row, int *tag, int *start, int *end)
{
	int i, j, ret, offset;
	struct vte_match_regex *regex = NULL;
	struct vte_char_attributes *attr = NULL;
	gssize coffset;
	regmatch_t matches[256];
	if (tag != NULL) {
		*tag = -1;
	}
	if (start != NULL) {
		*start = 0;
	}
	if (end != NULL) {
		*end = 0;
	}
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), NULL);
	if (terminal->pvt->match_contents == NULL) {
		vte_terminal_match_contents_refresh(terminal);
	}
	/* Map the pointer position to a portion of the string. */
	for (offset = terminal->pvt->match_attributes->len - 1;
	     offset >= 0;
	     offset--) {
		attr = &g_array_index(terminal->pvt->match_attributes,
				      struct vte_char_attributes,
				      offset);
		if (attr != NULL) {
			if ((row == attr->row) && (column == attr->column)) {
				break;
			}
		}
	}
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_EVENTS)) {
		if (offset < 0) {
			fprintf(stderr, "Cursor is not on a character.\n");
		} else {
			fprintf(stderr, "Cursor is on character %d.\n", offset);
		}
	}
#endif
	/* If the pointer isn't on a matchable character, bug out. */
	if (offset < 0) {
		return NULL;
	}
	/* If the pointer is on a newline, bug out. */
	if (g_ascii_isspace(terminal->pvt->match_contents[offset])) {
		return NULL;
	}

	/* Now iterate over each regex we need to match against. */
	for (i = 0; i < terminal->pvt->match_regexes->len; i++) {
		regex = &g_array_index(terminal->pvt->match_regexes,
				       struct vte_match_regex,
				       i);
		if (regex != NULL) {
			/* We'll only match the first item in the buffer which
			 * matches, so we'll have to skip each match until we
			 * stop getting matches. */
			coffset = 0;
			ret = regexec(&regex->reg,
				      terminal->pvt->match_contents + coffset,
				      G_N_ELEMENTS(matches),
				      matches,
				      0);
			while (ret == 0) {
				for (j = 0;
				     j < G_N_ELEMENTS(matches) &&
				     (matches[j].rm_so != -1);
				     j++) {
					/* The offsets should be "sane". */
					g_assert(matches[j].rm_so + coffset < terminal->pvt->match_attributes->len);
					g_assert(matches[j].rm_eo + coffset <= terminal->pvt->match_attributes->len);
#ifdef VTE_DEBUG
					if (vte_debug_on(VTE_DEBUG_MISC)) {
						char *match;
						struct vte_char_attributes *sattr, *eattr;
						match = g_strndup(terminal->pvt->match_contents + matches[j].rm_so + coffset,
								  matches[j].rm_eo - matches[j].rm_so);
						sattr = &g_array_index(terminal->pvt->match_attributes,
								       struct vte_char_attributes,
								       matches[j].rm_so + coffset);
						eattr = &g_array_index(terminal->pvt->match_attributes,
								       struct vte_char_attributes,
								       matches[j].rm_eo + coffset - 1);
						fprintf(stderr, "Match %d `%s' from %d(%ld,%ld) to %d(%ld,%ld) (%d).\n",
							j, match,
							matches[j].rm_so + coffset,
							sattr->column,
							sattr->row,
							matches[j].rm_eo + coffset - 1,
							eattr->column,
							eattr->row,
							offset);
						g_free(match);

					}
#endif
					/* If the pointer is in this substring,
					 * then we're done. */
					if ((offset >= matches[j].rm_so + coffset) &&
					    (offset < matches[j].rm_eo + coffset)) {
						if (tag != NULL) {
							*tag = regex->tag;
						}
						if (start != NULL) {
							*start = matches[j].rm_so + coffset;
						}
						if (end != NULL) {
							*end = matches[j].rm_eo + coffset - 1;
						}
						return g_strndup(terminal->pvt->match_contents + matches[j].rm_so + coffset,
								 matches[j].rm_eo - matches[j].rm_so);
					}
				}
				/* Skip past the beginning of this match to
				 * look for more. */
				coffset += (matches[0].rm_so + 1);
				ret = regexec(&regex->reg,
					      terminal->pvt->match_contents + coffset,
					      G_N_ELEMENTS(matches),
					      matches,
					      0);
			}
		}
	}
	return NULL;
}

char *
vte_terminal_match_check(VteTerminal *terminal, long column, long row, int *tag)
{
	return vte_terminal_match_check_internal(terminal, column, row, tag,
						 NULL, NULL);
}

/* Update the adjustment field of the widget.  This function should be called
 * whenever we add rows to the history or switch screens. */
static void
vte_terminal_adjust_adjustments(VteTerminal *terminal)
{
	gboolean changed;
	long delta, next;
	long page_size;
	long rows;

	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	g_return_if_fail(terminal->pvt->screen != NULL);
	g_return_if_fail(terminal->pvt->screen->row_data != NULL);

	/* Adjust the vertical, uh, adjustment. */
	changed = FALSE;

	/* The lower value should be the first row in the buffer. */
	delta = vte_ring_delta(terminal->pvt->screen->row_data);
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_IO)) {
		fprintf(stderr, "Changing adjustment values "
			"(delta = %ld, scroll = %ld).\n",
			delta, terminal->pvt->screen->scroll_delta);
	}
#endif
	if (terminal->adjustment->lower != delta) {
		terminal->adjustment->lower = delta;
		changed = TRUE;
	}

	/* The upper value is the number of rows which might be visible.  (Add
	 * one to the cursor offset because it's zero-based.) */
	next = vte_ring_delta(terminal->pvt->screen->row_data) +
	       vte_ring_length(terminal->pvt->screen->row_data);
	rows = MAX(next, terminal->pvt->screen->cursor_current.row + 1);
	if (terminal->adjustment->upper != rows) {
		terminal->adjustment->upper = rows;
		changed = TRUE;
	}

	/* The step increment should always be one. */
	if (terminal->adjustment->step_increment != 1) {
		terminal->adjustment->step_increment = 1;
		changed = TRUE;
	}

	/* Set the number of rows the user sees to the number of rows the
	 * user sees. */
	page_size = terminal->row_count;
	if (terminal->adjustment->page_size != page_size) {
		terminal->adjustment->page_size = page_size;
		changed = TRUE;
	}

	/* Clicking in the empty area should scroll one screen, so set the
	 * page size to the number of visible rows. */
	if (terminal->adjustment->page_increment != page_size) {
		terminal->adjustment->page_increment = page_size;
		changed = TRUE;
	}

	/* Set the scrollbar adjustment to where the screen wants it to be. */
	if (floor(gtk_adjustment_get_value(terminal->adjustment)) !=
	    terminal->pvt->screen->scroll_delta) {
		gtk_adjustment_set_value(terminal->adjustment,
					 terminal->pvt->screen->scroll_delta);
		changed = TRUE;
	}

	/* If anything changed, signal that there was a change. */
	if (changed == TRUE) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_IO)) {
			fprintf(stderr, "Changed adjustment values "
				"(delta = %ld, scroll = %ld).\n",
				delta, terminal->pvt->screen->scroll_delta);
		}
#endif
		vte_terminal_match_contents_clear(terminal);
		vte_terminal_emit_contents_changed(terminal);
		gtk_adjustment_changed(terminal->adjustment);
	}
}

/* Scroll up or down in the current screen. */
static void
vte_terminal_scroll_pages(VteTerminal *terminal, gint pages)
{
	glong destination;
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_IO)) {
		fprintf(stderr, "Scrolling %d pages.\n", pages);
	}
#endif
	/* Calculate the ideal position where we want to be before clamping. */
	destination = floor(gtk_adjustment_get_value(terminal->adjustment));
	destination += (pages * terminal->row_count);
	/* Can't scroll past data we have. */
	destination = CLAMP(destination,
			    terminal->adjustment->lower,
			    terminal->adjustment->upper - terminal->row_count);
	/* Tell the scrollbar to adjust itself. */
	gtk_adjustment_set_value(terminal->adjustment, destination);
	gtk_adjustment_changed(terminal->adjustment);
}

/* Scroll so that the scroll delta is the insertion delta. */
static void
vte_terminal_scroll_to_bottom(VteTerminal *terminal)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	if (floor(gtk_adjustment_get_value(terminal->adjustment)) !=
	    terminal->pvt->screen->insert_delta) {
		gtk_adjustment_set_value(terminal->adjustment,
					 terminal->pvt->screen->insert_delta);
		gtk_adjustment_changed(terminal->adjustment);
	}
}

/* Call another function, offsetting any long arguments by the given
 * increment value. */
static void
vte_sequence_handler_offset(VteTerminal *terminal,
			    const char *match,
			    GQuark match_quark,
			    GValueArray *params,
			    int increment,
			    VteTerminalSequenceHandler handler)
{
	int i;
	long val;
	GValue *value;
	/* Decrement the parameters and let the _cs handler deal with it. */
	for (i = 0; (params != NULL) && (i < params->n_values); i++) {
		value = g_value_array_get_nth(params, i);
		if (G_VALUE_HOLDS_LONG(value)) {
			val = g_value_get_long(value);
			val += increment;
			g_value_set_long(value, val);
		}
	}
	handler(terminal, match, match_quark, params);
}

/* Call another function a given number of times, or once. */
static void
vte_sequence_handler_multiple(VteTerminal *terminal,
			      const char *match,
			      GQuark match_quark,
			      GValueArray *params,
			      VteTerminalSequenceHandler handler)
{
	long val = 1;
	int i;
	GValue *value;
	if ((params != NULL) && (params->n_values > 0)) {
		value = g_value_array_get_nth(params, 0);
		if (G_VALUE_HOLDS_LONG(value)) {
			val = g_value_get_long(value);
			val = MAX(val, 1);	/* FIXME: vttest. */
		}
	}
	for (i = 0; i < val; i++) {
		handler(terminal, match, match_quark, NULL);
	}
}

/* Insert a blank line at an arbitrary position. */
static void
vte_insert_line_internal(VteTerminal *terminal, long position)
{
	GArray *array;
	/* Pad out the line data to the insertion point. */
	while (vte_ring_next(terminal->pvt->screen->row_data) < position) {
		array = vte_new_row_data();
		vte_ring_append(terminal->pvt->screen->row_data, array);
	}
	/* If we haven't inserted a line yet, insert a new one. */
	array = vte_new_row_data();
	if (vte_ring_next(terminal->pvt->screen->row_data) >= position) {
		vte_ring_insert(terminal->pvt->screen->row_data, position, array);
	} else {
		vte_ring_append(terminal->pvt->screen->row_data, array);
	}
}

/* Remove a line at an arbitrary position. */
static void
vte_remove_line_internal(VteTerminal *terminal, long position)
{
	if (vte_ring_next(terminal->pvt->screen->row_data) > position) {
		vte_ring_remove(terminal->pvt->screen->row_data,
				position, TRUE);
	}
}

/* Change the encoding used for the terminal to the given codeset, or the
 * locale default if NULL is passed in. */
void
vte_terminal_set_encoding(VteTerminal *terminal, const char *codeset)
{
	const char *old_codeset;
	GQuark encoding_quark;
	GIConv conv, new_iconv, new_oconvw, new_oconvu;
	char *ibuf, *obuf, *obufptr;
	gssize icount, ocount;

	old_codeset = terminal->pvt->encoding;
	if (codeset == NULL) {
		g_get_charset(&codeset);
	}

	/* Open new conversions. */
	new_iconv = g_iconv_open(vte_table_wide_encoding(), codeset);
	if (new_iconv == ((GIConv) -1)) {
		g_warning(_("Unable to convert characters from %s to %s."),
			  codeset, vte_table_wide_encoding());
		if (terminal->pvt->encoding != NULL) {
			/* Keep the current encoding. */
			return;
		}
	}
	new_oconvw = g_iconv_open(codeset, vte_table_wide_encoding());
	if (new_oconvw == ((GIConv) -1)) {
		g_warning(_("Unable to convert characters from %s to %s."),
			  vte_table_wide_encoding(), codeset);
		if (new_iconv != ((GIConv) -1)) {
			g_iconv_close(new_iconv);
		}
		if (terminal->pvt->encoding != NULL) {
			/* Keep the current encoding. */
			return;
		}
	}
	new_oconvu = g_iconv_open(codeset, "UTF-8");
	if (new_oconvu == ((GIConv) -1)) {
		g_warning(_("Unable to convert characters from %s to %s."),
			  "UTF-8", codeset);
		if (new_iconv != ((GIConv) -1)) {
			g_iconv_close(new_iconv);
		}
		if (new_oconvw != ((GIConv) -1)) {
			g_iconv_close(new_oconvw);
		}
		if (terminal->pvt->encoding != NULL) {
			/* Keep the current encoding. */
			return;
		}
	}

	if (new_oconvu == ((GIConv) -1)) {
		codeset = vte_table_narrow_encoding();
		new_iconv = g_iconv_open(vte_table_wide_encoding(), codeset);
		if (new_iconv == ((GIConv) -1)) {
			g_error(_("Unable to convert characters from %s to %s."),
				codeset, vte_table_wide_encoding());
		}
		new_oconvw = g_iconv_open(codeset, vte_table_wide_encoding());
		if (new_oconvw == ((GIConv) -1)) {
			g_error(_("Unable to convert characters from %s to %s."),
				vte_table_wide_encoding(), codeset);
		}
		new_oconvu = g_iconv_open(codeset, "UTF-8");
		if (new_oconvu == ((GIConv) -1)) {
			g_error(_("Unable to convert characters from %s to %s."),
				"UTF-8", codeset);
		}
	}

	/* Set up the conversion for incoming-to-gunichar. */
	if (terminal->pvt->incoming_conv != ((GIConv) -1)) {
		g_iconv_close(terminal->pvt->incoming_conv);
	}
	terminal->pvt->incoming_conv = new_iconv;

	/* Set up the conversions for gunichar/utf-8 to outgoing. */
	if (terminal->pvt->outgoing_conv_wide != ((GIConv) -1)) {
		g_iconv_close(terminal->pvt->outgoing_conv_wide);
	}
	terminal->pvt->outgoing_conv_wide = new_oconvw;

	if (terminal->pvt->outgoing_conv_utf8 != ((GIConv) -1)) {
		g_iconv_close(terminal->pvt->outgoing_conv_utf8);
	}
	terminal->pvt->outgoing_conv_utf8 = new_oconvu;

	/* Set the terminal's encoding to the new value. */
	encoding_quark = g_quark_from_string(codeset);
	terminal->pvt->encoding = g_quark_to_string(encoding_quark);

	/* Convert any buffered output bytes. */
	if ((terminal->pvt->n_outgoing > 0) && (old_codeset != NULL)) {
		icount = terminal->pvt->n_outgoing;
		ibuf = terminal->pvt->outgoing;
		ocount = icount * VTE_UTF8_BPC + 1;
		obuf = obufptr = g_malloc(ocount);
		conv = g_iconv_open(codeset, old_codeset);
		if (conv != ((GIConv) -1)) {
			if (g_iconv(conv, &ibuf, &icount, &obuf, &ocount) == -1) {
				/* Darn, it failed.  Leave it alone. */
				g_free(obufptr);
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_IO)) {
					fprintf(stderr, "Error converting %ld "
						"pending output bytes (%s) "
						"skipping.\n",
						(long) terminal->pvt->n_outgoing,
						strerror(errno));
				}
#endif
			} else {
				g_free(terminal->pvt->outgoing);
				terminal->pvt->outgoing = obufptr;
				terminal->pvt->n_outgoing = obuf - obufptr;
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_IO)) {
					fprintf(stderr, "Converted %ld pending "
						"output bytes.\n",
						(long) terminal->pvt->n_outgoing);
				}
#endif
			}
			g_iconv_close(conv);
		}
	}

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_IO)) {
		fprintf(stderr, "Set terminal encoding to `%s'.\n",
			terminal->pvt->encoding);
	}
#endif
	vte_terminal_emit_encoding_changed(terminal);
}
const char *
vte_terminal_get_encoding(VteTerminal *terminal)
{
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), NULL);
	return terminal->pvt->encoding;
}

/* End alternate character set. */
static void
vte_sequence_handler_ae(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->defaults.alternate = 0;
}

/* Add a line at the current cursor position. */
static void
vte_sequence_handler_al(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	VteScreen *screen;
	GArray *rowdata;
	long start, end, param, i;
	GValue *value;

	/* Find out which part of the screen we're messing with. */
	screen = terminal->pvt->screen;
	start = screen->cursor_current.row;
	if (screen->scrolling_restricted) {
		end = screen->insert_delta + screen->scrolling_region.end;
	} else {
		end = screen->insert_delta + terminal->row_count - 1;
	}

	/* Extract any parameters. */
	param = 1;
	if ((params != NULL) && (params->n_values > 0)) {
		value = g_value_array_get_nth(params, 0);
		param = g_value_get_long(value);
	}

	/* Insert the right number of lines. */
	for (i = 0; i < param; i++) {
		/* Clear a line off the end of the region and add one to the
		 * top of the region. */
		vte_remove_line_internal(terminal, end);
		vte_insert_line_internal(terminal, start);
		/* Get the data for the new row. */
		rowdata = vte_ring_index(screen->row_data, GArray*, start);
		/* Add enough cells to it so that it has the default colors. */
		while (rowdata->len < terminal->column_count) {
			g_array_append_val(rowdata, screen->defaults);
		}
	}

	/* Update the display. */
	vte_terminal_scroll_region(terminal, start, end - start + 1, param);
}

/* Add N lines at the current cursor position. */
static void
vte_sequence_handler_AL(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	vte_sequence_handler_al(terminal, match, match_quark, params);
}

/* Start using alternate character set. */
static void
vte_sequence_handler_as(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->defaults.alternate = 1;
}

/* Beep. */
static void
vte_sequence_handler_bl(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	if (terminal->pvt->audible_bell) {
		/* Feep. */
		gdk_beep();
	}
	if (terminal->pvt->visible_bell) {
		/* Visual bell. */
		vte_sequence_handler_vb(terminal, match, match_quark, params);
	}
}

/* Backtab. */
static void
vte_sequence_handler_bt(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	long newcol;

	/* Calculate which column is the previous tab stop. */
	newcol = terminal->pvt->screen->cursor_current.col;

	if (terminal->pvt->tabstops != NULL) {
		/* Find the next tabstop. */
		for (newcol += (terminal->column_count - 1);
		     newcol >= 0;
		     newcol--) {
			if (vte_terminal_get_tabstop(terminal,
						     newcol % terminal->column_count)) {
				break;
			}
		}
	}

	/* If we have no tab stops, stop right here. */
	if (newcol <= 0) {
		return;
	}

	/* Warp the cursor. */
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_PARSE)) {
		fprintf(stderr, "Moving cursor to column %ld.\n", (long)newcol);
	}
#endif
	terminal->pvt->screen->cursor_current.col = newcol;
}

/* Clear from the cursor position to the beginning of the line. */
static void
vte_sequence_handler_cb(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	GArray *rowdata;
	long i;
	VteScreen *screen;
	struct vte_charcell *pcell;
	screen = terminal->pvt->screen;

	/* Get the data for the row which the cursor points to. */
	vte_terminal_ensure_cursor(terminal, FALSE);
	rowdata = vte_ring_index(screen->row_data,
				 GArray*,
				 screen->cursor_current.row);
	/* Clear the data up to the current column with the default
	 * attributes.  If there is no such character cell, we need
	 * to add one. */
	for (i = 0; i < screen->cursor_current.col; i++) {
		if (i < rowdata->len) {
			/* Muck with the cell in this location. */
			pcell = &g_array_index(rowdata,
					       struct vte_charcell,
					       i);
			if (pcell != NULL) {
				*pcell = screen->defaults;
			}
		} else {
			/* Add new cells until we have one here. */
			g_array_append_val(rowdata, screen->defaults);
		}
	}
	/* Repaint this row. */
	vte_invalidate_cells(terminal,
			     0, terminal->column_count,
			     screen->cursor_current.row, 1);
}

/* Clear below the current line. */
static void
vte_sequence_handler_cd(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	GArray *rowdata;
	long i;
	VteScreen *screen;

	screen = terminal->pvt->screen;
	/* If the cursor is actually on the screen, clear data in the row
	 * the cursor is in and all rows below the cursor. */
	for (i = screen->cursor_current.row;
	     i < vte_ring_next(screen->row_data);
	     i++) {
		/* Get the data for the row we're removing. */
		rowdata = vte_ring_index(screen->row_data, GArray*, i);
		/* Remove it. */
		while ((rowdata != NULL) && (rowdata->len > 0)) {
			g_array_remove_index(rowdata, rowdata->len - 1);
		}
		/* Repaint this row. */
		vte_invalidate_cells(terminal,
				     0, terminal->column_count,
				     i, 1);
	}
}

/* Clear from the cursor position to the end of the line. */
static void
vte_sequence_handler_ce(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	GArray *rowdata;
	VteScreen *screen;

	screen = terminal->pvt->screen;
	/* Get the data for the row which the cursor points to. */
	vte_terminal_ensure_cursor(terminal, FALSE);
	rowdata = vte_ring_index(screen->row_data, GArray*,
				 screen->cursor_current.row);
	/* Remove the data at the end of the array until the current column
	 * is the end of the array. */
	while (rowdata->len > screen->cursor_current.col) {
		g_array_remove_index(rowdata, rowdata->len - 1);
	}
	/* Add enough cells to the end of the line to fill out the row. */
	while (rowdata->len < terminal->column_count) {
		g_array_append_val(rowdata, screen->defaults);
	}
	/* Repaint this row. */
	vte_invalidate_cells(terminal,
			     0, terminal->column_count,
			     screen->cursor_current.row, 1);
}

/* Move the cursor to the given column (horizontal position). */
static void
vte_sequence_handler_ch(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	VteScreen *screen;
	GValue *value;
	long val;

	screen = terminal->pvt->screen;
	/* We only care if there's a parameter in there. */
	if ((params != NULL) && (params->n_values > 0)) {
		value = g_value_array_get_nth(params, 0);
		if (G_VALUE_HOLDS_LONG(value)) {
			val = CLAMP(g_value_get_long(value),
				    0,
				    terminal->column_count - 1);
			/* Move the cursor. */
			screen->cursor_current.col = val;
		}
	}
}

/* Clear the screen and home the cursor. */
static void
vte_sequence_handler_cl(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	vte_sequence_handler_clear_screen(terminal, NULL, 0, NULL);
	vte_sequence_handler_ho(terminal, NULL, 0, NULL);
}

/* Move the cursor to the given position. */
static void
vte_sequence_handler_cm(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	GValue *row, *col;
	long rowval, colval;
	VteScreen *screen;

	screen = terminal->pvt->screen;
	/* We need at least two parameters. */
	if ((params != NULL) && (params->n_values >= 2)) {
		/* The first is the row, the second is the column. */
		row = g_value_array_get_nth(params, 0);
		col = g_value_array_get_nth(params, 1);
		if (G_VALUE_HOLDS_LONG(row) &&
		    G_VALUE_HOLDS_LONG(col)) {
			rowval = g_value_get_long(row);
			colval = g_value_get_long(col);
			rowval = CLAMP(rowval, 0, terminal->row_count - 1);
			colval = CLAMP(colval, 0, terminal->column_count - 1);
			screen->cursor_current.row = rowval +
						     screen->insert_delta;
			screen->cursor_current.col = colval;
		}
	}
}

/* Clear from the current line. */
static void
vte_sequence_handler_clear_current_line(VteTerminal *terminal,
					const char *match,
					GQuark match_quark,
					GValueArray *params)
{
	GArray *rowdata;
	VteScreen *screen;

	screen = terminal->pvt->screen;
	/* If the cursor is actually on the screen, clear data in the row
	 * which corresponds to the cursor. */
	if (vte_ring_next(screen->row_data) > screen->cursor_current.row) {
		/* Get the data for the row which the cursor points to. */
		rowdata = vte_ring_index(screen->row_data, GArray*,
					 screen->cursor_current.row);
		/* Remove it. */
		while (rowdata->len > 0) {
			g_array_remove_index(rowdata, rowdata->len - 1);
		}
		/* Add enough cells to the end of the line to fill out the
		 * row. */
		while (rowdata->len < terminal->column_count) {
			g_array_append_val(rowdata, screen->defaults);
		}
		/* Repaint this row. */
		vte_invalidate_cells(terminal,
				     0, terminal->column_count,
				     screen->cursor_current.row, 1);
	}
}

/* Carriage return. */
static void
vte_sequence_handler_cr(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->cursor_current.col = 0;
}

/* Restrict scrolling and updates to a subset of the visible lines. */
static void
vte_sequence_handler_cs(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	long start, end, rows;
	GValue *value;

	/* We require two parameters. */
	if ((params == NULL) || (params->n_values < 2)) {
		terminal->pvt->screen->scrolling_restricted = FALSE;
		return;
	}
	/* Extract the two values. */
	value = g_value_array_get_nth(params, 0);
	start = g_value_get_long(value);
	value = g_value_array_get_nth(params, 1);
	end = g_value_get_long(value);
	/* Set the right values. */
	terminal->pvt->screen->scrolling_region.start = start;
	terminal->pvt->screen->scrolling_region.end = end;
	terminal->pvt->screen->scrolling_restricted = TRUE;
	/* Special case -- run wild, run free. */
	rows = terminal->row_count;
	if ((terminal->pvt->screen->scrolling_region.start == 0) &&
	    (terminal->pvt->screen->scrolling_region.end == rows - 1)) {
		terminal->pvt->screen->scrolling_restricted = FALSE;
	}
}

/* Restrict scrolling and updates to a subset of the visible lines, because
 * GNU Emacs is special. */
static void
vte_sequence_handler_cS(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	long start, end, rows;
	GValue *value;

	/* We require four parameters. */
	if ((params == NULL) || (params->n_values < 2)) {
		terminal->pvt->screen->scrolling_restricted = FALSE;
		return;
	}
	/* Extract the two parameters we care about, encoded as the number
	 * of lines above and below the scrolling region, respectively. */
	value = g_value_array_get_nth(params, 1);
	start = g_value_get_long(value);
	value = g_value_array_get_nth(params, 2);
	end = (terminal->row_count - 1) - g_value_get_long(value);
	/* Set the right values. */
	terminal->pvt->screen->scrolling_region.start = start;
	terminal->pvt->screen->scrolling_region.end = end;
	terminal->pvt->screen->scrolling_restricted = TRUE;
	/* Special case -- run wild, run free. */
	rows = terminal->row_count;
	if ((terminal->pvt->screen->scrolling_region.start == 0) &&
	    (terminal->pvt->screen->scrolling_region.end == rows - 1)) {
		terminal->pvt->screen->scrolling_restricted = FALSE;
	}
}

/* Clear all tab stops. */
static void
vte_sequence_handler_ct(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	if (terminal->pvt->tabstops != NULL) {
		g_hash_table_destroy(terminal->pvt->tabstops);
		terminal->pvt->tabstops = NULL;
	}
}

/* Move the cursor to the lower left-hand corner. */
static void
vte_sequence_handler_cursor_lower_left(VteTerminal *terminal,
				       const char *match,
				       GQuark match_quark,
				       GValueArray *params)
{
	VteScreen *screen;
	screen = terminal->pvt->screen;
	screen->cursor_current.row = screen->insert_delta +
				     terminal->row_count - 1;
	screen->cursor_current.col = 0;
	vte_terminal_ensure_cursor(terminal, TRUE);
}

/* Move the cursor to the beginning of the next line, scrolling if necessary. */
static void
vte_sequence_handler_cursor_next_line(VteTerminal *terminal,
				      const char *match,
				      GQuark match_quark,
				      GValueArray *params)
{
	terminal->pvt->screen->cursor_current.col = 0;
	vte_sequence_handler_DO(terminal, match, match_quark, params);
}

/* Move the cursor to the beginning of the next line, scrolling if necessary. */
static void
vte_sequence_handler_cursor_preceding_line(VteTerminal *terminal,
					   const char *match,
					   GQuark match_quark,
					   GValueArray *params)
{
	terminal->pvt->screen->cursor_current.col = 0;
	vte_sequence_handler_UP(terminal, match, match_quark, params);
}

/* Move the cursor to the given row (vertical position). */
static void
vte_sequence_handler_cv(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	VteScreen *screen;
	GValue *value;
	long val;
	screen = terminal->pvt->screen;
	/* We only care if there's a parameter in there. */
	if ((params != NULL) && (params->n_values > 0)) {
		value = g_value_array_get_nth(params, 0);
		if (G_VALUE_HOLDS_LONG(value)) {
			/* Move the cursor. */
			val = CLAMP(g_value_get_long(value),
				    0,
				    terminal->row_count - 1);
			screen->cursor_current.row = val + screen->insert_delta;
		}
	}
}

/* Delete a character at the current cursor position. */
static void
vte_sequence_handler_dc(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	VteScreen *screen;
	GArray *rowdata;
	long col;

	screen = terminal->pvt->screen;

	if (vte_ring_next(screen->row_data) > screen->cursor_current.row) {
		/* Get the data for the row which the cursor points to. */
		rowdata = vte_ring_index(screen->row_data,
					 GArray*,
					 screen->cursor_current.row);
		col = screen->cursor_current.col;
		/* Remove the column. */
		if (col < rowdata->len) {
			g_array_remove_index(rowdata, col);
		}
		/* Add new cells until we have enough to fill the row. */
		while (rowdata->len < terminal->column_count) {
			g_array_append_val(rowdata, screen->defaults);
		}
		/* Repaint this row. */
		vte_invalidate_cells(terminal,
				     0, terminal->column_count,
				     screen->cursor_current.row, 1);
	}
}

/* Delete N characters at the current cursor position. */
static void
vte_sequence_handler_DC(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	vte_sequence_handler_multiple(terminal, match, match_quark, params,
				      vte_sequence_handler_dc);
}

/* Delete a line at the current cursor position. */
static void
vte_sequence_handler_dl(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	VteScreen *screen;
	long start, end, param, i;
	GValue *value;

	/* Find out which part of the screen we're messing with. */
	screen = terminal->pvt->screen;
	start = screen->cursor_current.row;
	if (screen->scrolling_restricted) {
		end = screen->insert_delta + screen->scrolling_region.end;
	} else {
		end = screen->insert_delta + terminal->row_count - 1;
	}

	/* Extract any parameters. */
	param = 1;
	if ((params != NULL) && (params->n_values > 0)) {
		value = g_value_array_get_nth(params, 0);
		param = g_value_get_long(value);
	}

	/* Delete the right number of lines. */
	for (i = 0; i < param; i++) {
		/* Clear a line off the end of the region and add one to the
		 * top of the region. */
		vte_remove_line_internal(terminal, start);
		vte_insert_line_internal(terminal, end);
	}

	/* Update the display. */
	vte_terminal_scroll_region(terminal, start, end - start + 1, -param);
}

/* Delete N lines at the current cursor position. */
static void
vte_sequence_handler_DL(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	vte_sequence_handler_dl(terminal, match, match_quark, params);
}

/* Make sure we have enough rows and columns to hold data at the current
 * cursor position. */
static void
vte_terminal_ensure_cursor(VteTerminal *terminal, gboolean current)
{
	GArray *array;
	VteScreen *screen;
	struct vte_charcell cell, *cells;
	long add, i;

	screen = terminal->pvt->screen;

	/* Figure out how many rows we need to add. */
	while (screen->cursor_current.row >= vte_ring_next(screen->row_data)) {
		/* Create a new row. */
		array = vte_new_row_data();
		vte_ring_append(screen->row_data, array);
	}

	/* Find the row the cursor is in. */
	array = vte_ring_index(screen->row_data,
			       GArray*,
			       screen->cursor_current.row);
	if ((array->len <= screen->cursor_current.col) &&
	    (array->len < terminal->column_count)) {
		/* Set up defaults we'll use when adding new cells. */
		cell = screen->defaults;
		cell.c = ' ';
		cell.columns = 1;
		if (!current) {
			cell.fore = VTE_DEF_FG;
			cell.back = VTE_DEF_BG;
		}
		/* Add enough cells at the end to make sure we have
		 * enough for all visible columns. */
		add = screen->cursor_current.col - array->len;
		if (add > 0) {
			cells = g_malloc(sizeof(cell) * add);
			cells[0] = cell;
			for (i = 1; i < add; i = i * 2) {
				memcpy(&cells[i], 
				       &cells[0],
				       sizeof(cell) * MIN(add - i, i));
			}
#ifdef VTE_DEBUG
			for (i = 0; i < add; i++) {
				g_assert(memcmp(&cells[i], &cell, sizeof(cell)) == 0);
			}
#endif
			array = g_array_append_vals(array, cells, add);
			g_free(cells);
		}
	}
}

static void
vte_terminal_scroll_insertion(VteTerminal *terminal)
{
	long rows, delta;
	VteScreen *screen;

	screen = terminal->pvt->screen;

	/* Make sure that the bottom row is visible, and that it's in
	 * the buffer (even if it's empty).  This usually causes the
	 * top row to become a history-only row. */
	rows = MAX(vte_ring_next(screen->row_data),
		   screen->cursor_current.row + 1);
	delta = MAX(0, rows - terminal->row_count);

	/* Adjust the insert delta and scroll if needed. */
	if (delta != screen->insert_delta) {
		vte_terminal_ensure_cursor(terminal, FALSE);
		screen->insert_delta = delta;
		/* Update scroll bar adjustments. */
		vte_terminal_adjust_adjustments(terminal);
	}
}

/* Cursor down, no scrolling. */
static void
vte_sequence_handler_do(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	GtkWidget *widget;
	long start, end;
	VteScreen *screen;

	widget = GTK_WIDGET(terminal);
	screen = terminal->pvt->screen;

	if (screen->scrolling_restricted) {
		start = screen->insert_delta + screen->scrolling_region.start;
		end = screen->insert_delta + screen->scrolling_region.end;
	} else {
		start = screen->insert_delta;
		end = start + terminal->row_count - 1;
	}

	/* Move the cursor down. */
	screen->cursor_current.row = MIN(screen->cursor_current.row + 1, end);
}

/* Cursor down, no scrolling. */
static void
vte_sequence_handler_DO(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	vte_sequence_handler_multiple(terminal, match, match_quark, params,
				      vte_sequence_handler_do);
}

/* Start using alternate character set. */
static void
vte_sequence_handler_eA(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	vte_sequence_handler_ae(terminal, match, match_quark, params);
}

/* Erase characters starting at the cursor position (overwriting N with
 * spaces, but not moving the cursor). */
static void
vte_sequence_handler_ec(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	VteScreen *screen;
	GArray *rowdata;
	GValue *value;
	struct vte_charcell *cell;
	long col, i, count;

	screen = terminal->pvt->screen;

	/* If we got a parameter, use it. */
	count = 1;
	if ((params != NULL) && (params->n_values > 0)) {
		value = g_value_array_get_nth(params, 0);
		if (G_VALUE_HOLDS_LONG(value)) {
			count = g_value_get_long(value);
		}
	}

	/* Clear out the given number of characters. */
	if (vte_ring_next(screen->row_data) > screen->cursor_current.row) {
		/* Get the data for the row which the cursor points to. */
		rowdata = vte_ring_index(screen->row_data,
					 GArray*,
					 screen->cursor_current.row);
		/* Write over the characters.  (If there aren't enough, we'll
		 * need to create them.) */
		for (i = 0; i < count; i++) {
			col = screen->cursor_current.col + i;
			if (col >= 0) {
				if (col < rowdata->len) {
					/* Replace this cell with the current
					 * defaults. */
					cell = &g_array_index(rowdata,
							      struct vte_charcell,
							      col);
					*cell = screen->defaults;
				} else {
					/* Add a new cell. */
					g_array_append_val(rowdata,
							   screen->defaults);
				}
			}
		}
		/* Repaint this row. */
		vte_invalidate_cells(terminal,
				     0, terminal->column_count,
				     screen->cursor_current.row, 1);
	}
}

/* End insert mode. */
static void
vte_sequence_handler_ei(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->insert_mode = FALSE;
}

/* Move from status line. */
static void
vte_sequence_handler_fs(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->status_line = FALSE;
}

/* Move the cursor to the home position. */
static void
vte_sequence_handler_ho(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	VteScreen *screen;
	screen = terminal->pvt->screen;
	screen->cursor_current.row = screen->insert_delta;
	screen->cursor_current.col = 0;
}

/* Move the cursor to a specified position. */
static void
vte_sequence_handler_horizontal_and_vertical_position(VteTerminal *terminal,
						      const char *match,
						      GQuark match_quark,
						      GValueArray *params)
{
	vte_sequence_handler_offset(terminal, match, match_quark, params,
				    -1, vte_sequence_handler_cm);
}

/* Insert a character. */
static void
vte_sequence_handler_ic(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	struct vte_cursor_position save;
	VteScreen *screen;

	screen = terminal->pvt->screen;

	save = screen->cursor_current;

	vte_terminal_insert_char(GTK_WIDGET(terminal), ' ', TRUE);

	screen->cursor_current = save;
}

/* Insert N characters. */
static void
vte_sequence_handler_IC(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	vte_sequence_handler_multiple(terminal, match, match_quark, params,
				      vte_sequence_handler_ic);
}

/* Begin insert mode. */
static void
vte_sequence_handler_im(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->insert_mode = TRUE;
}

/* Cursor down, with scrolling. */
static void
vte_sequence_handler_index(VteTerminal *terminal,
			   const char *match,
			   GQuark match_quark,
			   GValueArray *params)
{
	vte_sequence_handler_sf(terminal, match, match_quark, params);
}

/* Send me a backspace key sym, will you?  Guess that the application meant
 * to send the cursor back one position. */
static void
vte_sequence_handler_kb(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	/* Move the cursor left. */
	vte_sequence_handler_le(terminal, match, match_quark, params);
}

/* Keypad mode end. */
static void
vte_sequence_handler_ke(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->keypad = VTE_KEYPAD_NORMAL;
}

/* Keypad mode start. */
static void
vte_sequence_handler_ks(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->keypad = VTE_KEYPAD_APPLICATION;
}

/* Cursor left. */
static void
vte_sequence_handler_le(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	VteScreen *screen;

	screen = terminal->pvt->screen;
	if (screen->cursor_current.col > 0) {
		/* There's room to move left, so do so. */
		screen->cursor_current.col--;
	} else {
		if (terminal->pvt->flags.bw) {
			/* Wrap to the previous line. */
			screen->cursor_current.col = terminal->column_count - 1;
			screen->cursor_current.row = MAX(screen->cursor_current.row - 1,
							 screen->insert_delta);
		} else {
			/* Stick to the first column. */
			screen->cursor_current.col = 0;
		}
	}
}

/* Move the cursor left N columns. */
static void
vte_sequence_handler_LE(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	vte_sequence_handler_multiple(terminal, match, match_quark, params,
				      vte_sequence_handler_le);
}

/* Move the cursor to the lower left corner of the display. */
static void
vte_sequence_handler_ll(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	VteScreen *screen;
	screen = terminal->pvt->screen;
	screen->cursor_current.row = screen->insert_delta +
				     terminal->row_count - 1;
	screen->cursor_current.col = 0;
}

/* Blink on. */
static void
vte_sequence_handler_mb(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->defaults.blink = 1;
}

/* Bold on. */
static void
vte_sequence_handler_md(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->defaults.bold = 1;
}

/* End modes. */
static void
vte_sequence_handler_me(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	vte_terminal_set_default_attributes(terminal);
}

/* Half-bright on. */
static void
vte_sequence_handler_mh(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->defaults.half = 1;
}

/* Invisible on. */
static void
vte_sequence_handler_mk(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->defaults.invisible = 1;
}

/* Protect on. */
static void
vte_sequence_handler_mp(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->defaults.protect = 1;
}

/* Reverse on. */
static void
vte_sequence_handler_mr(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->defaults.reverse = 1;
}

/* Cursor right. */
static void
vte_sequence_handler_nd(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	VteScreen *screen;
	screen = terminal->pvt->screen;
	if ((screen->cursor_current.col + 1) < terminal->column_count) {
		/* There's room to move right. */
		screen->cursor_current.col++;
	}
}

/* Move the cursor to the beginning of the next line, scrolling if necessary. */
static void
vte_sequence_handler_next_line(VteTerminal *terminal,
			       const char *match,
			       GQuark match_quark,
			       GValueArray *params)
{
	terminal->pvt->screen->cursor_current.col = 0;
	vte_sequence_handler_DO(terminal, match, match_quark, params);
}

/* No-op. */
static void
vte_sequence_handler_noop(VteTerminal *terminal,
			  const char *match,
			  GQuark match_quark,
			  GValueArray *params)
{
}

/* Carriage return command(?). */
static void
vte_sequence_handler_nw(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	vte_sequence_handler_cr(terminal, match, match_quark, params);
}

/* Restore cursor (position). */
static void
vte_sequence_handler_rc(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	VteScreen *screen;
	screen = terminal->pvt->screen;
	screen->cursor_current.col = screen->cursor_saved.col;
	screen->cursor_current.row = CLAMP(screen->cursor_saved.row +
					   screen->insert_delta,
					   screen->insert_delta,
					   screen->insert_delta +
					   terminal->row_count - 1);
}

/* Cursor down, with scrolling. */
static void
vte_sequence_handler_reverse_index(VteTerminal *terminal,
				   const char *match,
				   GQuark match_quark,
				   GValueArray *params)
{
	vte_sequence_handler_sr(terminal, match, match_quark, params);
}

/* Cursor right N characters. */
static void
vte_sequence_handler_RI(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	vte_sequence_handler_multiple(terminal, match, match_quark, params,
				      vte_sequence_handler_nd);
}

/* Save cursor (position). */
static void
vte_sequence_handler_sc(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	VteScreen *screen;
	screen = terminal->pvt->screen;
	screen->cursor_saved.col = screen->cursor_current.col;
	screen->cursor_saved.row = CLAMP(screen->cursor_current.row -
					 screen->insert_delta,
					 0, terminal->row_count - 1);
}

/* Standout end. */
static void
vte_sequence_handler_se(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	char *bold, *underline, *standout, *reverse, *half, *blink;

	/* Standout may be mapped to another attribute, so attempt to do
	 * the Right Thing here. */

	standout = vte_termcap_find_string(terminal->pvt->termcap,
				           terminal->pvt->emulation,
				           "so");
	g_assert(standout != NULL);
	blink = vte_termcap_find_string(terminal->pvt->termcap,
				        terminal->pvt->emulation,
				        "mb");
	bold = vte_termcap_find_string(terminal->pvt->termcap,
				       terminal->pvt->emulation,
				       "md");
	half = vte_termcap_find_string(terminal->pvt->termcap,
				       terminal->pvt->emulation,
				       "mh");
	reverse = vte_termcap_find_string(terminal->pvt->termcap,
				          terminal->pvt->emulation,
				          "mr");
	underline = vte_termcap_find_string(terminal->pvt->termcap,
				            terminal->pvt->emulation,
				            "us");

	/* If the standout sequence is the same as another sequence, do what
	 * we'd do for that other sequence instead. */
	if (blink && (g_ascii_strcasecmp(standout, blink) == 0)) {
		vte_sequence_handler_me(terminal, match, match_quark, params);
	} else
	if (bold && (g_ascii_strcasecmp(standout, bold) == 0)) {
		vte_sequence_handler_me(terminal, match, match_quark, params);
	} else
	if (half && (g_ascii_strcasecmp(standout, half) == 0)) {
		vte_sequence_handler_me(terminal, match, match_quark, params);
	} else
	if (reverse && (g_ascii_strcasecmp(standout, reverse) == 0)) {
		vte_sequence_handler_me(terminal, match, match_quark, params);
	} else
	if (underline && (g_ascii_strcasecmp(standout, underline) == 0)) {
		vte_sequence_handler_ue(terminal, match, match_quark, params);
	} else {
		/* Otherwise just set standout mode. */
		terminal->pvt->screen->defaults.standout = 0;
	}

	if (blink) {
		g_free(blink);
	}
	if (bold) {
		g_free(bold);
	}
	if (half) {
		g_free(half);
	}
	if (reverse) {
		g_free(reverse);
	}
	if (underline) {
		g_free(underline);
	}
	g_free(standout);
}

/* Cursor down, with scrolling. */
static void
vte_sequence_handler_sf(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	GtkWidget *widget;
	long start, end;
	VteScreen *screen;

	widget = GTK_WIDGET(terminal);
	screen = terminal->pvt->screen;

	if (screen->scrolling_restricted) {
		start = screen->insert_delta + screen->scrolling_region.start;
		end = screen->insert_delta + screen->scrolling_region.end;
	} else {
		start = screen->insert_delta;
		end = start + terminal->row_count - 1;
	}

	if (screen->cursor_current.row == end) {
		if (screen->scrolling_restricted) {
			/* If we're at the bottom of the scrolling region, add a
			 * line at the top to scroll the bottom off. */
			vte_remove_line_internal(terminal, start);
			vte_insert_line_internal(terminal, end);
			/* Update the display. */
			vte_terminal_scroll_region(terminal, start,
						   end - start + 1, -1);
		} else {
			/* Scroll up with history. */
			screen->cursor_current.row++;
			vte_terminal_scroll_insertion(terminal);
		}
	} else {
		/* Otherwise, just move the cursor down. */
		screen->cursor_current.row++;
	}
}

/* Cursor down, with scrolling. */
static void
vte_sequence_handler_SF(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	vte_sequence_handler_multiple(terminal, match, match_quark, params,
				      vte_sequence_handler_sf);
}

/* Standout start. */
static void
vte_sequence_handler_so(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	char *bold, *underline, *standout, *reverse, *half, *blink;

	/* Standout may be mapped to another attribute, so attempt to do
	 * the Right Thing here. */

	standout = vte_termcap_find_string(terminal->pvt->termcap,
				           terminal->pvt->emulation,
				           "so");
	g_assert(standout != NULL);
	blink = vte_termcap_find_string(terminal->pvt->termcap,
				        terminal->pvt->emulation,
				        "mb");
	bold = vte_termcap_find_string(terminal->pvt->termcap,
				       terminal->pvt->emulation,
				       "md");
	half = vte_termcap_find_string(terminal->pvt->termcap,
				       terminal->pvt->emulation,
				       "mh");
	reverse = vte_termcap_find_string(terminal->pvt->termcap,
				          terminal->pvt->emulation,
				          "mr");
	underline = vte_termcap_find_string(terminal->pvt->termcap,
				            terminal->pvt->emulation,
				            "us");

	/* If the standout sequence is the same as another sequence, do what
	 * we'd do for that other sequence instead. */
	if (blink && (g_ascii_strcasecmp(standout, blink) == 0)) {
		vte_sequence_handler_mb(terminal, match, match_quark, params);
	} else
	if (bold && (g_ascii_strcasecmp(standout, bold) == 0)) {
		vte_sequence_handler_md(terminal, match, match_quark, params);
	} else
	if (half && (g_ascii_strcasecmp(standout, half) == 0)) {
		vte_sequence_handler_mh(terminal, match, match_quark, params);
	} else
	if (reverse && (g_ascii_strcasecmp(standout, reverse) == 0)) {
		vte_sequence_handler_mr(terminal, match, match_quark, params);
	} else
	if (underline && (g_ascii_strcasecmp(standout, underline) == 0)) {
		vte_sequence_handler_us(terminal, match, match_quark, params);
	} else {
		/* Otherwise just set standout mode. */
		terminal->pvt->screen->defaults.standout = 1;
	}

	if (blink) {
		g_free(blink);
	}
	if (bold) {
		g_free(bold);
	}
	if (half) {
		g_free(half);
	}
	if (reverse) {
		g_free(reverse);
	}
	if (underline) {
		g_free(underline);
	}
	g_free(standout);
}

/* Cursor up, scrolling if need be. */
static void
vte_sequence_handler_sr(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	GtkWidget *widget;
	long start, end;
	VteScreen *screen;

	widget = GTK_WIDGET(terminal);
	screen = terminal->pvt->screen;

	if (screen->scrolling_restricted) {
		start = screen->scrolling_region.start + screen->insert_delta;
		end = screen->scrolling_region.end + screen->insert_delta;
	} else {
		start = terminal->pvt->screen->insert_delta;
		end = start + terminal->row_count - 1;
	}

	if (screen->cursor_current.row == start) {
		/* If we're at the top of the scrolling region, add a
		 * line at the top to scroll the bottom off. */
		vte_remove_line_internal(terminal, end);
		vte_insert_line_internal(terminal, start);
		/* Update the display. */
		vte_terminal_scroll_region(terminal, start, end - start + 1, 1);
	} else {
		/* Otherwise, just move the cursor up. */
		screen->cursor_current.row--;
	}
}

/* Cursor up, with scrolling. */
static void
vte_sequence_handler_SR(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	vte_sequence_handler_multiple(terminal, match, match_quark, params,
				      vte_sequence_handler_sr);
}

/* Set tab stop in the current column. */
static void
vte_sequence_handler_st(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	if (terminal->pvt->tabstops == NULL) {
		terminal->pvt->tabstops = g_hash_table_new(g_direct_hash,
							   g_direct_equal);
	}
	vte_terminal_set_tabstop(terminal,
				 terminal->pvt->screen->cursor_current.col);
}

/* Tab. */
static void
vte_sequence_handler_ta(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	long newcol;

	/* Calculate which column is the next tab stop. */
	newcol = terminal->pvt->screen->cursor_current.col;

	if (terminal->pvt->tabstops != NULL) {
		/* Find the next tabstop. */
		for (newcol++; newcol < VTE_TAB_MAX; newcol++) {
			if (vte_terminal_get_tabstop(terminal, newcol)) {
				break;
			}
		}
	}

	/* If we have no tab stops, stop at the right-most column. */
	if (newcol >= VTE_TAB_MAX) {
		newcol = terminal->column_count - 1;
	}

	/* Wrap to the next line if need be. */
	if (newcol >= terminal->column_count) {
		if (terminal->pvt->flags.am) {
			/* Move to the next line. */
			terminal->pvt->screen->cursor_current.col = 0;
			vte_sequence_handler_do(terminal, match,
						match_quark, params);
		} else {
			/* Stay in the rightmost column. */
			newcol = terminal->column_count - 1;
		}
	} else {
		terminal->pvt->screen->cursor_current.col = newcol;
	}
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_PARSE)) {
		fprintf(stderr, "Moving cursor to column %ld.\n", (long)newcol);
	}
#endif
}

/* Clear tabs selectively. */
static void
vte_sequence_handler_tab_clear(VteTerminal *terminal,
			       const char *match,
			       GQuark match_quark,
			       GValueArray *params)
{
	GValue *value;
	long param = 0;

	if ((params != NULL) && (params->n_values > 0)) {
		value = g_value_array_get_nth(params, 0);
		if (G_VALUE_HOLDS_LONG(value)) {
			param = g_value_get_long(value);
		}
	}
	if (param == 0) {
		vte_terminal_clear_tabstop(terminal,
					   terminal->pvt->screen->cursor_current.col);
	} else
	if (param == 3) {
		if (terminal->pvt->tabstops != NULL) {
			g_hash_table_destroy(terminal->pvt->tabstops);
			terminal->pvt->tabstops = NULL;
		}
	}
}

/* Move to status line. */
static void
vte_sequence_handler_ts(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->status_line = TRUE;
	g_string_truncate(terminal->pvt->screen->status_line_contents, 0);
	vte_terminal_emit_status_line_changed(terminal);
}

/* Underline this character and move right. */
static void
vte_sequence_handler_uc(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	struct vte_charcell *cell;
	VteScreen *screen;

	screen = terminal->pvt->screen;
	cell = vte_terminal_find_charcell(terminal,
					  screen->cursor_current.col,
					  screen->cursor_current.row);
	if (cell != NULL) {
		/* Set this character to be underlined. */
		cell->underline = 1;
		/* Cause the character to be repainted. */
		vte_invalidate_cells(terminal,
				     screen->cursor_current.col, 1,
				     screen->cursor_current.row, 1);
		/* Move the cursor right. */
		vte_sequence_handler_nd(terminal, match, match_quark, params);
	}
}

/* Underline end. */
static void
vte_sequence_handler_ue(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->defaults.underline = 0;
}

/* Cursor up, no scrolling. */
static void
vte_sequence_handler_up(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	VteScreen *screen;
	long start, end;

	screen = terminal->pvt->screen;

	if (screen->scrolling_restricted) {
		start = screen->insert_delta + screen->scrolling_region.start;
		end = screen->insert_delta + screen->scrolling_region.end;
	} else {
		start = screen->insert_delta;
		end = start + terminal->row_count - 1;
	}

	screen->cursor_current.row = MAX(screen->cursor_current.row - 1, start);
}

/* Cursor up N lines, no scrolling. */
static void
vte_sequence_handler_UP(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	vte_sequence_handler_multiple(terminal, match, match_quark, params,
				      vte_sequence_handler_up);
}

/* Underline start. */
static void
vte_sequence_handler_us(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->screen->defaults.underline = 1;
}

/* Visible bell. */
static void
vte_sequence_handler_vb(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	Display *display;
	GdkDrawable *gdrawable;
	Drawable drawable;
	GC gc;
	gint x_offs, y_offs;

	if (GTK_WIDGET_REALIZED(GTK_WIDGET(terminal))) {
		/* Fill the screen with the default foreground color, and then
		 * repaint everything, to provide visual bell. */
		gdk_window_get_internal_paint_info(GTK_WIDGET(terminal)->window,
						   &gdrawable,
						   &x_offs,
						   &y_offs);
		display = gdk_x11_drawable_get_xdisplay(gdrawable);
		drawable = gdk_x11_drawable_get_xid(gdrawable);
		gc = XCreateGC(display, drawable, 0, NULL);

		XSetForeground(display, gc,
			       terminal->pvt->palette[VTE_BOLD_FG].pixel);
		XFillRectangle(display, drawable, gc,
			       x_offs, y_offs,
			       terminal->column_count * terminal->char_width,
			       terminal->row_count * terminal->char_height);
		gdk_window_process_all_updates();

		vte_invalidate_all(terminal);
		gdk_window_process_all_updates();
	}
}

/* Cursor visible. */
static void
vte_sequence_handler_ve(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->cursor_visible = TRUE;
}

/* Cursor invisible. */
static void
vte_sequence_handler_vi(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->cursor_visible = FALSE;
}

/* Cursor standout. */
static void
vte_sequence_handler_vs(VteTerminal *terminal,
			const char *match,
			GQuark match_quark,
			GValueArray *params)
{
	terminal->pvt->cursor_visible = TRUE; /* FIXME: should be *more*
						 visible. */
}

/* Handle ANSI color setting and related stuffs (SGR). */
static void
vte_sequence_handler_character_attributes(VteTerminal *terminal,
					  const char *match,
					  GQuark match_quark,
					  GValueArray *params)
{
	unsigned int i;
	GValue *value;
	long param;
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	/* The default parameter is zero. */
	param = 0;
	/* Step through each numeric parameter. */
	for (i = 0; (params != NULL) && (i < params->n_values); i++) {
		/* If this parameter isn't a number, skip it. */
		value = g_value_array_get_nth(params, i);
		if (!G_VALUE_HOLDS_LONG(value)) {
			continue;
		}
		param = g_value_get_long(value);
		switch (param) {
			case 0:
				vte_terminal_set_default_attributes(terminal);
				break;
			case 1:
				terminal->pvt->screen->defaults.bold = 1;
				break;
			case 4:
				terminal->pvt->screen->defaults.underline = 1;
				break;
			case 5:
				terminal->pvt->screen->defaults.blink = 1;
				break;
			case 7:
				terminal->pvt->screen->defaults.reverse = 1;
				break;
			case 8:
				terminal->pvt->screen->defaults.invisible = 1;
				break;
			case 21: /* one of these is the linux console */
			case 22: /* one of these is ecma, i forget which */
				terminal->pvt->screen->defaults.bold = 0;
				break;
			case 24:
				terminal->pvt->screen->defaults.underline = 0;
				break;
			case 25:
				terminal->pvt->screen->defaults.blink = 0;
				break;
			case 27:
				terminal->pvt->screen->defaults.reverse = 0;
				break;
			case 28:
				terminal->pvt->screen->defaults.invisible = 0;
				break;
			case 30:
			case 31:
			case 32:
			case 33:
			case 34:
			case 35:
			case 36:
			case 37:
				terminal->pvt->screen->defaults.fore = param - 30;
				break;
			case 38:
				/* default foreground, underscore */
				terminal->pvt->screen->defaults.fore = VTE_DEF_FG;
				terminal->pvt->screen->defaults.underline = 1;
				break;
			case 39:
				/* default foreground, no underscore */
				terminal->pvt->screen->defaults.fore = VTE_DEF_FG;
				terminal->pvt->screen->defaults.underline = 0;
				break;
			case 40:
			case 41:
			case 42:
			case 43:
			case 44:
			case 45:
			case 46:
			case 47:
				terminal->pvt->screen->defaults.back = param - 40;
				break;
			case 49:
				/* default background */
				terminal->pvt->screen->defaults.back = VTE_DEF_BG;
				break;
			case 90:
			case 91:
			case 92:
			case 93:
			case 94:
			case 95:
			case 96:
			case 97:
				terminal->pvt->screen->defaults.fore = param - 90;
				break;
			case 100:
			case 101:
			case 102:
			case 103:
			case 104:
			case 105:
			case 106:
			case 107:
				terminal->pvt->screen->defaults.back = param - 100;
				break;
		}
	}
	/* If we had no parameters, default to the defaults. */
	if (i == 0) {
		vte_terminal_set_default_attributes(terminal);
	}
}

/* Clear above the current line. */
static void
vte_sequence_handler_clear_above_current(VteTerminal *terminal,
					 const char *match,
					 GQuark match_quark,
					 GValueArray *params)
{
	GArray *rowdata;
	long i;
	VteScreen *screen;
	screen = terminal->pvt->screen;
	/* If the cursor is actually on the screen, clear data in the row
	 * which corresponds to the cursor. */
	for (i = screen->insert_delta; i < screen->cursor_current.row; i++) {
		if (vte_ring_next(screen->row_data) > i) {
			/* Get the data for the row we're erasing. */
			rowdata = vte_ring_index(screen->row_data, GArray*, i);
			/* Remove it. */
			while (rowdata->len > 0) {
				g_array_remove_index(rowdata, rowdata->len - 1);
			}
			/* Add new cells until we fill the row. */
			while (rowdata->len < terminal->column_count) {
				g_array_append_val(rowdata, screen->defaults);
			}
			/* Repaint the row. */
			vte_invalidate_cells(terminal,
					     0, terminal->column_count,
					     i, 1);
		}
	}
}

/* Clear the entire screen. */
static void
vte_sequence_handler_clear_screen(VteTerminal *terminal,
				  const char *match,
				  GQuark match_quark,
				  GValueArray *params)
{
	GArray *rowdata;
	long i;
	VteScreen *screen;
	screen = terminal->pvt->screen;
	/* Clear the data in all of the visible rows to the defaults. */
	for (i = screen->insert_delta;
	     i < screen->insert_delta + terminal->row_count;
	     i++) {
		if (vte_ring_contains(screen->row_data, i)) {
			/* Get the data for the row we're removing. */
			rowdata = vte_ring_index(screen->row_data, GArray*, i);
		} else {
			/* Add a new row */
			rowdata = vte_new_row_data();
			vte_ring_append(terminal->pvt->screen->row_data,
					rowdata);
		}
		/* Remove the row's contents. */
		while (rowdata->len > 0) {
			g_array_remove_index(rowdata, rowdata->len - 1);
		}
		/* Add new cells until we have enough to fill the row. */
		while (rowdata->len < terminal->column_count) {
			g_array_append_val(rowdata, screen->defaults);
		}
	}
	/* Redraw everything. */
	vte_invalidate_all(terminal);
}

/* Move the cursor to the given column, 1-based. */
static void
vte_sequence_handler_cursor_character_absolute(VteTerminal *terminal,
					       const char *match,
					       GQuark match_quark,
					       GValueArray *params)
{
	vte_sequence_handler_offset(terminal, match, match_quark, params,
				    -1, vte_sequence_handler_ch);
}

/* Move the cursor to the given position, 1-based. */
static void
vte_sequence_handler_cursor_position(VteTerminal *terminal,
				     const char *match,
				     GQuark match_quark,
				     GValueArray *params)
{
	vte_sequence_handler_offset(terminal, match, match_quark, params,
				    -1, vte_sequence_handler_cm);
}

/* Request terminal attributes. */
static void
vte_sequence_handler_request_terminal_parameters(VteTerminal *terminal,
						 const char *match,
						 GQuark match_quark,
						 GValueArray *params)
{
	vte_terminal_feed_child(terminal, "[?x", -1);
}

/* Request terminal attributes. */
static void
vte_sequence_handler_return_terminal_status(VteTerminal *terminal,
					    const char *match,
					    GQuark match_quark,
					    GValueArray *params)
{
	vte_terminal_feed_child(terminal, "xterm", -1);
}

/* Send primary device attributes. */
static void
vte_sequence_handler_send_primary_device_attributes(VteTerminal *terminal,
						    const char *match,
						    GQuark match_quark,
						    GValueArray *params)
{
	/* Claim to be a VT220 with only national character set support. */
	vte_terminal_feed_child(terminal, "[?60;9c", -1);
}

/* Send secondary device attributes. */
static void
vte_sequence_handler_send_secondary_device_attributes(VteTerminal *terminal,
						      const char *match,
						      GQuark match_quark,
						      GValueArray *params)
{
	char **version, *ret;
	long ver = 0, i;
	/* Claim to be a VT220, more or less.  The '>' in the response appears
	 * to be undocumented. */
	version = g_strsplit(VERSION, ".", 0);
	if (version != NULL) {
		for (i = 0; version[i] != NULL; i++) {
			ver = ver * 100;
			ver += atol(version[i]);
		}
		g_strfreev(version);
	}
	ret = g_strdup_printf("[>1;%ld;0c", ver);
	vte_terminal_feed_child(terminal, ret, -1);
	g_free(ret);
}

/* Set icon/window titles. */
static void
vte_sequence_handler_set_title_internal(VteTerminal *terminal,
					const char *match,
					GQuark match_quark,
					GValueArray *params,
					const char *signal)
{
	GValue *value;
	GIConv conv;
	char *inbuf = NULL, *outbuf = NULL, *outbufptr = NULL;
	gssize inbuf_len, outbuf_len;
	/* Get the string parameter's value. */
	value = g_value_array_get_nth(params, 0);
	if (value) {
		if (G_VALUE_HOLDS_LONG(value)) {
			/* Convert the long to a string. */
			outbufptr = g_strdup_printf("%ld",
						    g_value_get_long(value));
		} else
		if (G_VALUE_HOLDS_STRING(value)) {
			/* Copy the string into the buffer. */
			outbufptr = g_value_dup_string(value);
		} else
		if (G_VALUE_HOLDS_POINTER(value)) {
			/* Convert the unicode-character string into a
			 * multibyte string. */
			conv = g_iconv_open("UTF-8", vte_table_wide_encoding());
			inbuf = g_value_get_pointer(value);
			inbuf_len = vte_unicode_strlen((gunichar*)inbuf) *
				    sizeof(gunichar);
			outbuf_len = (inbuf_len * VTE_UTF8_BPC) + 1;
			outbuf = outbufptr = g_malloc0(outbuf_len);
			if (conv != ((GIConv) -1)) {
				if (g_iconv(conv, &inbuf, &inbuf_len,
					    &outbuf, &outbuf_len) == -1) {
#ifdef VTE_DEBUG
					if (vte_debug_on(VTE_DEBUG_IO)) {
						fprintf(stderr, "Error "
							"converting %ld title "
							"bytes (%s), "
							"skipping.\n",
							(long) terminal->pvt->n_outgoing,
							strerror(errno));
					}
#endif
					g_free(outbufptr);
					outbufptr = NULL;
				}
			}
			g_iconv_close(conv);
		}
		if (outbufptr != NULL) {
			/* Emit the signal */
			if (strcmp(signal, "window_title_changed") == 0) {
				g_free(terminal->window_title);
				terminal->window_title = outbufptr;
				vte_terminal_emit_window_title_changed(terminal);
			}
			else if (strcmp (signal, "icon_title_changed") == 0) {
				g_free (terminal->icon_title);
				terminal->icon_title = outbufptr;
				vte_terminal_emit_icon_title_changed(terminal);
			}
		}
	}
}

/* Set one or the other. */
static void
vte_sequence_handler_set_icon_title(VteTerminal *terminal,
				    const char *match,
				    GQuark match_quark,
				    GValueArray *params)
{
	vte_sequence_handler_set_title_internal(terminal, match, match_quark,
						params, "icon_title_changed");
}
static void
vte_sequence_handler_set_window_title(VteTerminal *terminal,
				      const char *match,
				      GQuark match_quark,
				      GValueArray *params)
{
	vte_sequence_handler_set_title_internal(terminal, match, match_quark,
						params, "window_title_changed");
}

/* Set both the window and icon titles to the same string. */
static void
vte_sequence_handler_set_icon_and_window_title(VteTerminal *terminal,
						  const char *match,
						  GQuark match_quark,
						  GValueArray *params)
{
	vte_sequence_handler_set_title_internal(terminal, match, match_quark,
						params, "icon_title_changed");
	vte_sequence_handler_set_title_internal(terminal, match, match_quark,
						params, "window_title_changed");
}

/* Restrict the scrolling region. */
static void
vte_sequence_handler_set_scrolling_region(VteTerminal *terminal,
					  const char *match,
					  GQuark match_quark,
					  GValueArray *params)
{
	vte_sequence_handler_offset(terminal, match, match_quark, params,
				    -1, vte_sequence_handler_cs);
}

/* Show or hide the pointer. */
static void
vte_terminal_set_pointer_visible(VteTerminal *terminal, gboolean visible)
{
	GdkCursor *cursor = NULL;
	if (visible || !terminal->pvt->mouse_autohide) {
		if (terminal->pvt->mouse_send_xy_on_click ||
		    terminal->pvt->mouse_send_xy_on_button ||
		    terminal->pvt->mouse_hilite_tracking ||
		    terminal->pvt->mouse_cell_motion_tracking ||
		    terminal->pvt->mouse_all_motion_tracking) {
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_IO)) {
				fprintf(stderr, "Setting mousing cursor.\n");
			}
#endif
			cursor = terminal->pvt->mouse_mousing_cursor;
		} else {
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_IO)) {
				fprintf(stderr, "Setting default mouse "
					"cursor.\n");
			}
#endif
			cursor = terminal->pvt->mouse_default_cursor;
		}
	} else {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_IO)) {
			fprintf(stderr, "Setting to invisible cursor.\n");
		}
#endif
		cursor = terminal->pvt->mouse_inviso_cursor;
	}
	if (cursor) {
		if (GTK_WIDGET_REALIZED(GTK_WIDGET(terminal))) {
			gdk_window_set_cursor((GTK_WIDGET(terminal))->window,
					      cursor);
		}
	}
}

/* Manipulate certain terminal attributes. */
static void
vte_sequence_handler_decset_internal(VteTerminal *terminal,
				     int setting,
				     gboolean restore,
				     gboolean save,
				     gboolean set)
{
	gboolean recognized = FALSE;
	gpointer p;
	int i;
	struct {
		int setting;
		gboolean *bvalue;
		gint *ivalue;
		gpointer *pvalue;
		gpointer fvalue;
		gpointer tvalue;
		VteTerminalSequenceHandler reset, set;
	} settings[] = {
		/* Application/normal keypad. */
		{1, NULL, &terminal->pvt->keypad, NULL,
		 GINT_TO_POINTER(VTE_KEYPAD_NORMAL),
		 GINT_TO_POINTER(VTE_KEYPAD_APPLICATION),
		 NULL, NULL,},
		/* Reverse video. */
		{5, &terminal->pvt->screen->reverse_mode, NULL, NULL,
		 GINT_TO_POINTER(FALSE),
		 GINT_TO_POINTER(TRUE),
		 NULL, NULL,},
		/* Wraparound mode. */
		{7, &terminal->pvt->flags.am, NULL, NULL,
		 GINT_TO_POINTER(FALSE),
		 GINT_TO_POINTER(TRUE),
		 NULL, NULL,},
		/* Send-coords-on-click. */
		{9, &terminal->pvt->mouse_send_xy_on_click, NULL, NULL,
		 GINT_TO_POINTER(FALSE),
		 GINT_TO_POINTER(TRUE),
		 NULL, NULL,},
		/* Cursor visible. */
		{25, &terminal->pvt->cursor_visible, NULL, NULL,
		 GINT_TO_POINTER(FALSE),
		 GINT_TO_POINTER(TRUE),
		 NULL, NULL,},
		/* Alternate screen. */
		{47, NULL, NULL, (gpointer*) &terminal->pvt->screen,
		 &terminal->pvt->normal_screen,
		 &terminal->pvt->alternate_screen,
		 NULL, NULL,},
		/* Send-coords-on-button. */
		{1000, &terminal->pvt->mouse_send_xy_on_button, NULL, NULL,
		 GINT_TO_POINTER(FALSE),
		 GINT_TO_POINTER(TRUE),
		 NULL, NULL,},
		/* Hilite tracking*/
		{1001, &terminal->pvt->mouse_hilite_tracking, NULL, NULL,
		 GINT_TO_POINTER(FALSE),
		 GINT_TO_POINTER(TRUE),
		 NULL, NULL,},
		/* Cell motion tracking*/
		{1002, &terminal->pvt->mouse_cell_motion_tracking, NULL, NULL,
		 GINT_TO_POINTER(FALSE),
		 GINT_TO_POINTER(TRUE),
		 NULL, NULL,},
		/* All motion tracking*/
		{1003, &terminal->pvt->mouse_all_motion_tracking, NULL, NULL,
		 GINT_TO_POINTER(FALSE),
		 GINT_TO_POINTER(TRUE),
		 NULL, NULL,},
		/* Use alternate screen buffer. */
		{1047, NULL, NULL, (gpointer*) &terminal->pvt->screen,
		 &terminal->pvt->normal_screen,
		 &terminal->pvt->alternate_screen,
		 NULL, NULL,},
		/* Save/restore cursor position. */
		{1048, NULL, NULL, NULL,
		 NULL,
		 NULL,
		 vte_sequence_handler_rc,
		 vte_sequence_handler_sc,},
		/* Use alternate screen buffer, saving the cursor position. */
		{1049, NULL, NULL, (gpointer*) &terminal->pvt->screen,
		 &terminal->pvt->normal_screen,
		 &terminal->pvt->alternate_screen,
		 vte_sequence_handler_rc,
		 vte_sequence_handler_sc,},
		/* Sun/VT220 keyboard mode. */
		{1051, NULL, NULL, (gpointer*) &terminal->pvt->fkey,
		 GINT_TO_POINTER(VTE_FKEY_VT220),
		 GINT_TO_POINTER(VTE_FKEY_SUNPC),
		 NULL, NULL},
	};

	g_return_if_fail(VTE_IS_TERMINAL(terminal));

	/* Handle the setting. */
	for (i = 0; i < G_N_ELEMENTS(settings); i++)
	if (settings[i].setting == setting) {
		recognized = TRUE;
		/* Read the old setting. */
		if (restore) {
			p = g_hash_table_lookup(terminal->pvt->dec_saved,
						GINT_TO_POINTER(setting));
			set = (p != NULL);
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_PARSE)) {
				fprintf(stderr, "Setting %d was %s.\n",
					setting, set ? "set" : "unset");
			}
#endif
		}
		/* Save the current setting. */
		if (save) {
			if (settings[i].bvalue) {
				set = *(settings[i].bvalue) != FALSE;
			} else
			if (settings[i].ivalue) {
				set = *(settings[i].ivalue) ==
				      GPOINTER_TO_INT(settings[i].tvalue);
			} else
			if (settings[i].pvalue) {
				set = *(settings[i].pvalue) ==
				      settings[i].tvalue;
			}
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_PARSE)) {
				fprintf(stderr, "Setting %d is %s, saving.\n",
					setting, set ? "set" : "unset");
			}
#endif
			g_hash_table_insert(terminal->pvt->dec_saved,
					    GINT_TO_POINTER(setting),
					    GINT_TO_POINTER(set));
		}
		/* Change the current setting to match the new/saved value. */
		if (!save) {
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_PARSE)) {
				fprintf(stderr, "Setting %d to %s.\n",
					setting, set ? "set" : "unset");
			}
#endif
			if (settings[i].set && set) {
				settings[i].set(terminal, NULL, 0, NULL);
			}
			if (settings[i].bvalue) {
				*(settings[i].bvalue) = set;
			} else
			if (settings[i].ivalue) {
				*(settings[i].ivalue) = set ?
					GPOINTER_TO_INT(settings[i].tvalue) :
					GPOINTER_TO_INT(settings[i].fvalue);
			} else
			if (settings[i].pvalue) {
				*(settings[i].pvalue) = set ?
					settings[i].tvalue :
					settings[i].fvalue;
			}
			if (settings[i].reset && !set) {
				settings[i].reset(terminal, NULL, 0, NULL);
			}
		}
	}

	/* Do whatever's necessary when the setting changes. */
	switch (setting) {
		case 5:
			/* Repaint everything in reverse mode. */
			vte_invalidate_all(terminal);
			break;
		case 25:
		case 1048:
			/* Repaint the cell the cursor is in. */
			vte_invalidate_cursor_once(terminal);
			break;
		case 47:
		case 1047:
		case 1049:
			/* Clear the alternate screen if we're switching
			 * to it. */
			if (set) {
				vte_sequence_handler_clear_screen(terminal,
								  NULL,
								  0,
								  NULL);
			}
			/* Reset scrollbars and repaint everything. */
			vte_terminal_adjust_adjustments(terminal);
			vte_invalidate_all(terminal);
			break;
		case 9:
		case 1000:
		case 1001:
		case 1002:
		case 1003:
			/* Make the pointer visible. */
			vte_terminal_set_pointer_visible(terminal, TRUE);
			break;
		default:
			break;
	}
#ifdef VTE_DEBUG
	if (!recognized) {
		g_warning("DECSET/DECRESET mode %d not recognized, ignoring.\n",
			  setting);
	}
#endif
}

/* Set the application or normal keypad. */
static void
vte_sequence_handler_application_keypad(VteTerminal *terminal,
					const char *match,
					GQuark match_quark,
					GValueArray *params)
{
	terminal->pvt->keypad = VTE_KEYPAD_APPLICATION;
}

static void
vte_sequence_handler_normal_keypad(VteTerminal *terminal,
				   const char *match,
				   GQuark match_quark,
				   GValueArray *params)
{
	terminal->pvt->keypad = VTE_KEYPAD_NORMAL;
}

/* Move the cursor. */
static void
vte_sequence_handler_character_position_absolute(VteTerminal *terminal,
						 const char *match,
						 GQuark match_quark,
						 GValueArray *params)
{
	vte_sequence_handler_offset(terminal, match, match_quark, params,
				    -1, vte_sequence_handler_ch);
}
static void
vte_sequence_handler_line_position_absolute(VteTerminal *terminal,
					    const char *match,
					    GQuark match_quark,
					    GValueArray *params)
{
	vte_sequence_handler_offset(terminal, match, match_quark, params,
				    -1, vte_sequence_handler_cv);
}

/* Toggle a terminal mode. */
static void
vte_sequence_handler_set_mode_internal(VteTerminal *terminal,
				       long setting, gboolean value)
{
	switch (setting) {
		case 2:		/* keyboard action mode (?) */
			break;
		case 4:		/* insert/overtype mode */
			terminal->pvt->screen->insert_mode = value;
			break;
		case 12:	/* send/receive mode (local echo?) */
			break;
		case 20:	/* automatic newline / normal linefeed mode */
			break;
		default:
			break;
	}
}

/* Set certain terminal attributes. */
static void
vte_sequence_handler_set_mode(VteTerminal *terminal,
			      const char *match,
			      GQuark match_quark,
			      GValueArray *params)
{
	int i;
	long setting;
	GValue *value;
	if ((params == NULL) || (params->n_values == 0)) {
		return;
	}
	for (i = 0; i < params->n_values; i++) {
		value = g_value_array_get_nth(params, i);
		if (!G_VALUE_HOLDS_LONG(value)) {
			continue;
		}
		setting = g_value_get_long(value);
		vte_sequence_handler_set_mode_internal(terminal, setting,
						       TRUE);
	}
}

/* Unset certain terminal attributes. */
static void
vte_sequence_handler_reset_mode(VteTerminal *terminal,
			        const char *match,
			        GQuark match_quark,
			        GValueArray *params)
{
	int i;
	long setting;
	GValue *value;
	if ((params == NULL) || (params->n_values == 0)) {
		return;
	}
	for (i = 0; i < params->n_values; i++) {
		value = g_value_array_get_nth(params, i);
		if (!G_VALUE_HOLDS_LONG(value)) {
			continue;
		}
		setting = g_value_get_long(value);
		vte_sequence_handler_set_mode_internal(terminal, setting,
						       FALSE);
	}
}

/* Set certain terminal attributes. */
static void
vte_sequence_handler_decset(VteTerminal *terminal,
			    const char *match,
			    GQuark match_quark,
			    GValueArray *params)
{
	GValue *value;
	long setting;
	int i;
	if ((params == NULL) || (params->n_values == 0)) {
		return;
	}
	for (i = 0; i < params->n_values; i++) {
		value = g_value_array_get_nth(params, i);
		if (!G_VALUE_HOLDS_LONG(value)) {
			continue;
		}
		setting = g_value_get_long(value);
		vte_sequence_handler_decset_internal(terminal, setting,
						     FALSE, FALSE, TRUE);
	}
}

/* Unset certain terminal attributes. */
static void
vte_sequence_handler_decreset(VteTerminal *terminal,
			      const char *match,
			      GQuark match_quark,
			      GValueArray *params)
{
	GValue *value;
	long setting;
	int i;
	if ((params == NULL) || (params->n_values == 0)) {
		return;
	}
	for (i = 0; i < params->n_values; i++) {
		value = g_value_array_get_nth(params, i);
		if (!G_VALUE_HOLDS_LONG(value)) {
			continue;
		}
		setting = g_value_get_long(value);
		vte_sequence_handler_decset_internal(terminal, setting,
						     FALSE, FALSE, FALSE);
	}
}

/* Erase a specified number of characters. */
static void
vte_sequence_handler_erase_characters(VteTerminal *terminal,
				      const char *match,
				      GQuark match_quark,
				      GValueArray *params)
{
	vte_sequence_handler_ec(terminal, match, match_quark, params);
}

/* Erase certain lines in the display. */
static void
vte_sequence_handler_erase_in_display(VteTerminal *terminal,
				      const char *match,
				      GQuark match_quark,
				      GValueArray *params)
{
	GValue *value;
	long param;
	int i;
	/* The default parameter is 0. */
	param = 0;
	/* Pull out a parameter. */
	for (i = 0; (params != NULL) && (i < params->n_values); i++) {
		value = g_value_array_get_nth(params, i);
		if (!G_VALUE_HOLDS_LONG(value)) {
			continue;
		}
		param = g_value_get_long(value);
	}
	/* Clear the right area. */
	switch (param) {
		case 0:
			/* Clear below the current line. */
			vte_sequence_handler_cd(terminal, NULL, 0, NULL);
			break;
		case 1:
			/* Clear above the current line. */
			vte_sequence_handler_clear_above_current(terminal,
								 NULL,
								 0,
								 NULL);
			/* Clear everything to the left of the cursor, too. */
			/* FIXME: vttest. */
			vte_sequence_handler_cb(terminal, NULL, 0, NULL);
			break;
		case 2:
			/* Clear the entire screen. */
			vte_sequence_handler_clear_screen(terminal,
							  NULL,
							  0,
							  NULL);
			break;
		default:
			break;
	}
}

/* Erase certain parts of the current line in the display. */
static void
vte_sequence_handler_erase_in_line(VteTerminal *terminal,
				   const char *match,
				   GQuark match_quark,
				   GValueArray *params)
{
	GValue *value;
	long param;
	int i;
	/* The default parameter is 0. */
	param = 0;
	/* Pull out a parameter. */
	for (i = 0; (params != NULL) && (i < params->n_values); i++) {
		value = g_value_array_get_nth(params, i);
		if (!G_VALUE_HOLDS_LONG(value)) {
			continue;
		}
		param = g_value_get_long(value);
	}
	/* Clear the right area. */
	switch (param) {
		case 0:
			/* Clear to end of the line. */
			vte_sequence_handler_ce(terminal, NULL, 0, NULL);
			break;
		case 1:
			/* Clear to start of the line. */
			vte_sequence_handler_cb(terminal, NULL, 0, NULL);
			break;
		case 2:
			/* Clear the entire line. */
			vte_sequence_handler_clear_current_line(terminal,
								NULL, 0, NULL);
			break;
		default:
			break;
	}
}

/* Perform a full-bore reset. */
static void
vte_sequence_handler_full_reset(VteTerminal *terminal,
				const char *match,
				GQuark match_quark,
				GValueArray *params)
{
	vte_terminal_reset(terminal, TRUE, TRUE);
}

/* Insert a specified number of blank characters. */
static void
vte_sequence_handler_insert_blank_characters(VteTerminal *terminal,
					     const char *match,
					     GQuark match_quark,
					     GValueArray *params)
{
	vte_sequence_handler_IC(terminal, match, match_quark, params);
}

/* Insert a certain number of lines below the current cursor. */
static void
vte_sequence_handler_insert_lines(VteTerminal *terminal,
				  const char *match,
				  GQuark match_quark,
				  GValueArray *params)
{
	GArray *rowdata;
	GValue *value;
	VteScreen *screen;
	long param, end, row;
	int i;
	screen = terminal->pvt->screen;
	/* The default is one. */
	param = 1;
	/* Extract any parameters. */
	if ((params != NULL) && (params->n_values > 0)) {
		value = g_value_array_get_nth(params, 0);
		param = g_value_get_long(value);
	}
	/* Find the region we're messing with. */
	row = screen->cursor_current.row;
	if (screen->scrolling_restricted) {
		end = screen->insert_delta + screen->scrolling_region.end;
	} else {
		end = screen->insert_delta + terminal->row_count - 1;
	}
	/* Insert the new lines at the cursor. */
	for (i = 0; i < param; i++) {
		/* Clear a line off the end of the region and add one to the
		 * top of the region. */
		vte_remove_line_internal(terminal, end);
		vte_insert_line_internal(terminal, row);
		/* Get the data for the new row. */
		rowdata = vte_ring_index(screen->row_data, GArray*, row);
		/* Add enough cells to it so that it has the default colors. */
		while (rowdata->len < terminal->column_count) {
			g_array_append_val(rowdata, screen->defaults);
		}
	}
	/* Update the display. */
	vte_terminal_scroll_region(terminal, row, end - row + 1, param);
}

/* Delete certain lines from the scrolling region. */
static void
vte_sequence_handler_delete_lines(VteTerminal *terminal,
				  const char *match,
				  GQuark match_quark,
				  GValueArray *params)
{
	GValue *value;
	GArray *rowdata;
	VteScreen *screen;
	long param, end, row;
	int i;

	screen = terminal->pvt->screen;
	/* The default is one. */
	param = 1;
	/* Extract any parameters. */
	if ((params != NULL) && (params->n_values > 0)) {
		value = g_value_array_get_nth(params, 0);
		param = g_value_get_long(value);
	}
	/* Find the region we're messing with. */
	row = screen->cursor_current.row;
	if (screen->scrolling_restricted) {
		end = screen->insert_delta + screen->scrolling_region.end;
	} else {
		end = screen->insert_delta + terminal->row_count - 1;
	}
	/* Clear them from below the current cursor. */
	for (i = 0; i < param; i++) {
		/* Insert a line at the end of the region and remove one from
		 * the top of the region. */
		vte_remove_line_internal(terminal, row);
		vte_insert_line_internal(terminal, end);
		/* Get the data for the new row. */
		rowdata = vte_ring_index(screen->row_data, GArray*, end);
		/* Add enough cells to it so that it has the default colors. */
		while (rowdata->len < terminal->column_count) {
			g_array_append_val(rowdata, screen->defaults);
		}
	}
	/* Update the display. */
	vte_terminal_scroll_region(terminal, row, end - row + 1, -param);
}

/* Set the terminal encoding. */
static void
vte_sequence_handler_local_charset(VteTerminal *terminal,
				   const char *match,
				   GQuark match_quark,
				   GValueArray *params)
{
	G_CONST_RETURN char *locale_encoding;
#ifdef VTE_DEFAULT_ISO_8859_1
	vte_terminal_set_encoding(terminal, vte_table_narrow_encoding());
#else
	g_get_charset(&locale_encoding);
	vte_terminal_set_encoding(terminal, locale_encoding);
#endif
}

static void
vte_sequence_handler_utf_8_charset(VteTerminal *terminal,
				   const char *match,
				   GQuark match_quark,
				   GValueArray *params)
{
	vte_terminal_set_encoding(terminal, "UTF-8");
}

/* Device status reports. The possible reports are the cursor position and
 * whether or not we're okay. */
static void
vte_sequence_handler_device_status_report(VteTerminal *terminal,
					  const char *match,
					  GQuark match_quark,
					  GValueArray *params)
{
	GValue *value;
	VteScreen *screen;
	long param;
	char buf[LINE_MAX];

	screen = terminal->pvt->screen;

	if ((params != NULL) && (params->n_values > 0)) {
		value = g_value_array_get_nth(params, 0);
		param = g_value_get_long(value);
		switch (param) {
			case 5:
				/* Send a thumbs-up sequence. */
				snprintf(buf, sizeof(buf),
					 "%s%dn", VTE_CAP_CSI, 0);
				vte_terminal_feed_child(terminal,
							buf, strlen(buf));
				break;
			case 6:
				/* Send the cursor position. */
				snprintf(buf, sizeof(buf),
					 "%s%ld;%ldR", VTE_CAP_CSI,
					 screen->cursor_current.row + 1 -
					 screen->insert_delta,
					 screen->cursor_current.col + 1);
				vte_terminal_feed_child(terminal,
							buf, strlen(buf));
				break;
			default:
				break;
		}
	}
}

/* DEC-style device status reports. */
static void
vte_sequence_handler_dec_device_status_report(VteTerminal *terminal,
					      const char *match,
					      GQuark match_quark,
					      GValueArray *params)
{
	GValue *value;
	VteScreen *screen;
	long param;
	char buf[LINE_MAX];

	screen = terminal->pvt->screen;

	if ((params != NULL) && (params->n_values > 0)) {
		value = g_value_array_get_nth(params, 0);
		param = g_value_get_long(value);
		switch (param) {
			case 6:
				/* Send the cursor position. */
				snprintf(buf, sizeof(buf),
					 "%s?%ld;%ldR", VTE_CAP_CSI,
					 screen->cursor_current.row + 1 -
					 screen->insert_delta,
					 screen->cursor_current.col + 1);
				vte_terminal_feed_child(terminal,
							buf, strlen(buf));
				break;
			case 15:
				/* Send printer status -- 10 = ready,
				 * 11 = not ready.  We don't print. */
				snprintf(buf, sizeof(buf),
					 "%s?%dn", VTE_CAP_CSI, 11);
				vte_terminal_feed_child(terminal,
							buf, strlen(buf));
				break;
			case 25:
				/* Send UDK status -- 20 = locked,
				 * 21 = not locked.  I don't even know what
				 * that means, but punt anyway. */
				snprintf(buf, sizeof(buf),
					 "%s?%dn", VTE_CAP_CSI, 20);
				vte_terminal_feed_child(terminal,
							buf, strlen(buf));
				break;
			case 26:
				/* Send keyboard status.  50 = no locator. */
				snprintf(buf, sizeof(buf),
					 "%s?%dn", VTE_CAP_CSI, 50);
				vte_terminal_feed_child(terminal,
							buf, strlen(buf));
				break;
			default:
				break;
		}
	}
}

/* Restore a certain terminal attribute. */
static void
vte_sequence_handler_restore_mode(VteTerminal *terminal,
				  const char *match,
				  GQuark match_quark,
				  GValueArray *params)
{
	GValue *value;
	long setting;
	int i;
	if ((params == NULL) || (params->n_values == 0)) {
		return;
	}
	for (i = 0; i < params->n_values; i++) {
		value = g_value_array_get_nth(params, i);
		if (!G_VALUE_HOLDS_LONG(value)) {
			continue;
		}
		setting = g_value_get_long(value);
		vte_sequence_handler_decset_internal(terminal, setting,
						     TRUE, FALSE, FALSE);
	}
}

/* Save a certain terminal attribute. */
static void
vte_sequence_handler_save_mode(VteTerminal *terminal,
			       const char *match,
			       GQuark match_quark,
			       GValueArray *params)
{
	GValue *value;
	long setting;
	int i;
	if ((params == NULL) || (params->n_values == 0)) {
		return;
	}
	for (i = 0; i < params->n_values; i++) {
		value = g_value_array_get_nth(params, i);
		if (!G_VALUE_HOLDS_LONG(value)) {
			continue;
		}
		setting = g_value_get_long(value);
		vte_sequence_handler_decset_internal(terminal, setting,
						     FALSE, TRUE, FALSE);
	}
}

/* Perform a screen alignment test -- fill all visible cells with the
 * letter "E". */
static void
vte_sequence_handler_screen_alignment_test(VteTerminal *terminal,
					   const char *match,
					   GQuark match_quark,
					   GValueArray *params)
{
	long row;
	GArray *rowdata;
	VteScreen *screen;
	struct vte_charcell cell;

	screen = terminal->pvt->screen;

	for (row = terminal->pvt->screen->insert_delta;
	     row < terminal->pvt->screen->insert_delta + terminal->row_count;
	     row++) {
		/* Find this row. */
		while (vte_ring_next(screen->row_data) <= row) {
			rowdata = vte_new_row_data();
			vte_ring_append(screen->row_data, rowdata);
		}
		rowdata = vte_ring_index(screen->row_data, GArray*, row);
		/* Clear this row. */
		while (rowdata->len > 0) {
			g_array_remove_index(rowdata, rowdata->len - 1);
		}
		/* Fill this row. */
		cell = screen->defaults;
		cell.c = 'E';
		cell.fore = VTE_DEF_FG;
		cell.back = VTE_DEF_BG;
		cell.columns = 1;
		while (rowdata->len < terminal->column_count) {
			g_array_append_val(rowdata, cell);
		}
	}
	vte_invalidate_all(terminal);
}

/* Perform a soft reset. */
static void
vte_sequence_handler_soft_reset(VteTerminal *terminal,
				const char *match,
				GQuark match_quark,
				GValueArray *params)
{
	vte_terminal_reset(terminal, FALSE, FALSE);
}

/* Window manipulation control sequences.  Most of these are considered
 * bad ideas, but they're implemented as signals which the application
 * is free to ignore, so they're harmless. */
static void
vte_sequence_handler_window_manipulation(VteTerminal *terminal,
					 const char *match,
					 GQuark match_quark,
					 GValueArray *params)
{
	VteScreen *screen;
	GValue *value;
	GtkWidget *widget;
	Display *display;
	char buf[LINE_MAX];
	long param, arg1, arg2;
	guint width, height;
	int i;

	widget = GTK_WIDGET(terminal);
	screen = terminal->pvt->screen;

	for (i = 0; ((params != NULL) && (i < params->n_values)); i++) {
		arg1 = arg2 = -1;
		if (i + 1 < params->n_values) {
			value = g_value_array_get_nth(params, i + 1);
			if (G_VALUE_HOLDS_LONG(value)) {
				arg1 = g_value_get_long(value);
			}
		}
		if (i + 2 < params->n_values) {
			value = g_value_array_get_nth(params, i + 2);
			if (G_VALUE_HOLDS_LONG(value)) {
				arg2 = g_value_get_long(value);
			}
		}
		value = g_value_array_get_nth(params, i);
		if (!G_VALUE_HOLDS_LONG(value)) {
			continue;
		}
		param = g_value_get_long(value);
		switch (param) {
			case 1:
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_PARSE)) {
					fprintf(stderr, "Deiconifying window.\n");
				}
#endif
				vte_terminal_emit_deiconify_window(terminal);
				break;
			case 2:
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_PARSE)) {
					fprintf(stderr, "Iconifying window.\n");
				}
#endif
				vte_terminal_emit_iconify_window(terminal);
				break;
			case 3:
				if ((arg1 != -1) && (arg2 != -2)) {
#ifdef VTE_DEBUG
					if (vte_debug_on(VTE_DEBUG_PARSE)) {
						fprintf(stderr, "Moving window to %ld,%ld.\n", arg1, arg2);
					}
#endif
					vte_terminal_emit_move_window(terminal, arg1, arg2);
					i += 2;
				}
				break;
			case 4:
				if ((arg1 != -1) && (arg2 != -1)) {
#ifdef VTE_DEBUG
					if (vte_debug_on(VTE_DEBUG_PARSE)) {
						fprintf(stderr, "Resizing window (%ldx%ld pixels).\n",
							arg2, arg1);
					}
#endif
					vte_terminal_emit_resize_window(terminal,
									arg2,
									arg1);
					i += 2;
				}
				break;
			case 5:
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_PARSE)) {
					fprintf(stderr, "Raising window.\n");
				}
#endif
				vte_terminal_emit_raise_window(terminal);
				break;
			case 6:
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_PARSE)) {
					fprintf(stderr, "Lowering window.\n");
				}
#endif
				vte_terminal_emit_lower_window(terminal);
				break;
			case 7:
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_PARSE)) {
					fprintf(stderr, "Refreshing window.\n");
				}
#endif
				vte_invalidate_all(terminal);
				vte_terminal_emit_refresh_window(terminal);
				break;
			case 8:
				if ((arg1 != -1) && (arg2 != -1)) {
#ifdef VTE_DEBUG
					if (vte_debug_on(VTE_DEBUG_PARSE)) {
						fprintf(stderr, "Resizing window (%ld columns, %ld rows).\n",
							arg2, arg1);
					}
#endif
					vte_terminal_emit_resize_window(terminal,
									arg2 * terminal->char_width,
									arg1 * terminal->char_height);
					i += 2;
				}
				break;
			case 9:
				switch (arg1) {
					case 0:
#ifdef VTE_DEBUG
						if (vte_debug_on(VTE_DEBUG_PARSE)) {
							fprintf(stderr, "Restoring window.\n");
						}
#endif
						vte_terminal_emit_restore_window(terminal);
						break;
					case 1:
#ifdef VTE_DEBUG
						if (vte_debug_on(VTE_DEBUG_PARSE)) {
							fprintf(stderr, "Maximizing window.\n");
						}
#endif
						vte_terminal_emit_maximize_window(terminal);
						break;
					default:
						break;
				}
				i++;
				break;
			case 11:
				/* If we're unmapped, then we're iconified. */
				snprintf(buf, sizeof(buf),
					 "%s%dt", VTE_CAP_CSI,
					 1 + !GTK_WIDGET_MAPPED(widget));
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_PARSE)) {
					fprintf(stderr, "Reporting window state %s.\n",
						GTK_WIDGET_MAPPED(widget) ?
						"non-iconified" : "iconified");
				}
#endif
				vte_terminal_feed_child(terminal,
							buf, strlen(buf));
				break;
			case 13:
				/* Send window location, in pixels. */
				gdk_window_get_origin(widget->window,
						      &width, &height);
				snprintf(buf, sizeof(buf),
					 "%s%d;%dt", VTE_CAP_CSI,
					 width, height);
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_PARSE)) {
					fprintf(stderr, "Reporting window location"
						"(%d,%d).\n",
						width, height);
				}
#endif
				vte_terminal_feed_child(terminal,
							buf, strlen(buf));
				break;
			case 14:
				/* Send window size, in pixels. */
				gdk_drawable_get_size(widget->window,
						      &width, &height);
				snprintf(buf, sizeof(buf),
					 "%s%d;%dt", VTE_CAP_CSI,
					 height, width);
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_PARSE)) {
					fprintf(stderr, "Reporting window size "
						"(%dx%d).\n", width, height);
				}
#endif
				vte_terminal_feed_child(terminal,
							buf, strlen(buf));
				break;
			case 18:
				/* Send widget size, in cells. */
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_PARSE)) {
					fprintf(stderr, "Reporting widget size.\n");
				}
#endif
				snprintf(buf, sizeof(buf),
					 "%s%ld;%ldt", VTE_CAP_CSI,
					 terminal->row_count,
					 terminal->column_count);
				vte_terminal_feed_child(terminal,
							buf, strlen(buf));
				break;
			case 19:
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_PARSE)) {
					fprintf(stderr, "Reporting screen size.\n");
				}
#endif
				display = gdk_x11_drawable_get_xdisplay(widget->window);
				i = gdk_x11_get_default_screen();
				snprintf(buf, sizeof(buf),
					 "%s%ld;%ldt", VTE_CAP_CSI,
					 DisplayHeight(display, i) /
					 terminal->char_height,
					 DisplayWidth(display, i) /
					 terminal->char_width);
				vte_terminal_feed_child(terminal,
							buf, strlen(buf));
				break;
			case 20:
				/* Report the icon title. */
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_PARSE)) {
					fprintf(stderr, "Reporting icon title.\n");
				}
#endif
				snprintf(buf, sizeof(buf),
					 "%sL%s%s",
					 VTE_CAP_OSC,
					 terminal->icon_title ?
					 terminal->icon_title : "",
					 VTE_CAP_ST);
				vte_terminal_feed_child(terminal,
							buf, strlen(buf));
				break;
			case 21:
				/* Report the window title. */
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_PARSE)) {
					fprintf(stderr, "Reporting window title.\n");
				}
#endif
				snprintf(buf, sizeof(buf),
					 "%sL%s%s",
					 VTE_CAP_OSC,
					 terminal->window_title ?
					 terminal->window_title : "",
					 VTE_CAP_ST);
				vte_terminal_feed_child(terminal,
							buf, strlen(buf));
				break;
			default:
				if (param >= 24) {
#ifdef VTE_DEBUG
					if (vte_debug_on(VTE_DEBUG_PARSE)) {
						fprintf(stderr, "Resizing to %ld rows.\n",
							param);
					}
#endif
					/* Resize to the specified number of
					 * rows. */
					vte_terminal_emit_resize_window(terminal,
									terminal->column_count * terminal->char_width,
									param * terminal->char_height);
				}
				break;
		}
	}
}

/* Complain that we got an escape sequence that's actually a keystroke. */
static void
vte_sequence_handler_complain_key(VteTerminal *terminal,
				  const char *match,
				  GQuark match_quark,
				  GValueArray *params)
{
	g_warning(_("Got unexpected (key?) sequence `%s'."),
		  match ? match : "???");
}

/* The table of handlers.  Primarily used at initialization time. */
static struct {
	const char *code;
	VteTerminalSequenceHandler handler;
} vte_sequence_handlers[] = {
	{"!1", vte_sequence_handler_complain_key},
	{"!2", vte_sequence_handler_complain_key},
	{"!3", vte_sequence_handler_complain_key},

	{"#1", vte_sequence_handler_complain_key},
	{"#2", vte_sequence_handler_complain_key},
	{"#3", vte_sequence_handler_complain_key},
	{"#4", vte_sequence_handler_complain_key},

	{"%1", vte_sequence_handler_complain_key},
	{"%2", vte_sequence_handler_complain_key},
	{"%3", vte_sequence_handler_complain_key},
	{"%4", vte_sequence_handler_complain_key},
	{"%5", vte_sequence_handler_complain_key},
	{"%6", vte_sequence_handler_complain_key},
	{"%7", vte_sequence_handler_complain_key},
	{"%8", vte_sequence_handler_complain_key},
	{"%9", vte_sequence_handler_complain_key},
	{"%a", vte_sequence_handler_complain_key},
	{"%b", vte_sequence_handler_complain_key},
	{"%c", vte_sequence_handler_complain_key},
	{"%d", vte_sequence_handler_complain_key},
	{"%e", vte_sequence_handler_complain_key},
	{"%f", vte_sequence_handler_complain_key},
	{"%g", vte_sequence_handler_complain_key},
	{"%h", vte_sequence_handler_complain_key},
	{"%i", vte_sequence_handler_complain_key},
	{"%j", vte_sequence_handler_complain_key},

	{"&0", vte_sequence_handler_complain_key},
	{"&1", vte_sequence_handler_complain_key},
	{"&2", vte_sequence_handler_complain_key},
	{"&3", vte_sequence_handler_complain_key},
	{"&4", vte_sequence_handler_complain_key},
	{"&5", vte_sequence_handler_complain_key},
	{"&6", vte_sequence_handler_complain_key},
	{"&7", vte_sequence_handler_complain_key},
	{"&8", vte_sequence_handler_complain_key},
	{"&9", vte_sequence_handler_complain_key},

	{"*0", vte_sequence_handler_complain_key},
	{"*1", vte_sequence_handler_complain_key},
	{"*2", vte_sequence_handler_complain_key},
	{"*3", vte_sequence_handler_complain_key},
	{"*4", vte_sequence_handler_complain_key},
	{"*5", vte_sequence_handler_complain_key},
	{"*6", vte_sequence_handler_complain_key},
	{"*7", vte_sequence_handler_complain_key},
	{"*8", vte_sequence_handler_complain_key},
	{"*9", vte_sequence_handler_complain_key},

	{"@0", vte_sequence_handler_complain_key},
	{"@1", vte_sequence_handler_complain_key},
	{"@2", vte_sequence_handler_complain_key},
	{"@3", vte_sequence_handler_complain_key},
	{"@4", vte_sequence_handler_complain_key},
	{"@5", vte_sequence_handler_complain_key},
	{"@6", vte_sequence_handler_complain_key},
	{"@7", vte_sequence_handler_complain_key},
	{"@8", vte_sequence_handler_complain_key},
	{"@9", vte_sequence_handler_complain_key},

	{"al", vte_sequence_handler_al},
	{"AL", vte_sequence_handler_AL},
	{"ae", vte_sequence_handler_ae},
	{"as", vte_sequence_handler_as},

	{"bc", vte_sequence_handler_le},
	{"bl", vte_sequence_handler_bl},
	{"bt", vte_sequence_handler_bt},

	{"cb", vte_sequence_handler_cb},
	{"cc", vte_sequence_handler_noop},
	{"cd", vte_sequence_handler_cd},
	{"ce", vte_sequence_handler_ce},
	{"ch", vte_sequence_handler_ch},
	{"cl", vte_sequence_handler_cl},
	{"cm", vte_sequence_handler_cm},
	{"cr", vte_sequence_handler_cr},
	{"cs", vte_sequence_handler_cs},
	{"cS", vte_sequence_handler_cS},
	{"ct", vte_sequence_handler_ct},
	{"cv", vte_sequence_handler_cv},

	{"dc", vte_sequence_handler_dc},
	{"DC", vte_sequence_handler_DC},
	{"dl", vte_sequence_handler_dl},
	{"DL", vte_sequence_handler_DL},
	{"dm", vte_sequence_handler_noop},
	{"do", vte_sequence_handler_do},
	{"DO", vte_sequence_handler_DO},
	{"ds", NULL},

	{"eA", vte_sequence_handler_eA},
	{"ec", vte_sequence_handler_ec},
	{"ed", vte_sequence_handler_noop},
	{"ei", vte_sequence_handler_ei},

	{"ff", vte_sequence_handler_noop},
	{"fs", vte_sequence_handler_fs},
	{"F1", vte_sequence_handler_complain_key},
	{"F2", vte_sequence_handler_complain_key},
	{"F3", vte_sequence_handler_complain_key},
	{"F4", vte_sequence_handler_complain_key},
	{"F5", vte_sequence_handler_complain_key},
	{"F6", vte_sequence_handler_complain_key},
	{"F7", vte_sequence_handler_complain_key},
	{"F8", vte_sequence_handler_complain_key},
	{"F9", vte_sequence_handler_complain_key},
	{"FA", vte_sequence_handler_complain_key},
	{"FB", vte_sequence_handler_complain_key},
	{"FC", vte_sequence_handler_complain_key},
	{"FD", vte_sequence_handler_complain_key},
	{"FE", vte_sequence_handler_complain_key},
	{"FF", vte_sequence_handler_complain_key},
	{"FG", vte_sequence_handler_complain_key},
	{"FH", vte_sequence_handler_complain_key},
	{"FI", vte_sequence_handler_complain_key},
	{"FJ", vte_sequence_handler_complain_key},
	{"FK", vte_sequence_handler_complain_key},
	{"FL", vte_sequence_handler_complain_key},
	{"FM", vte_sequence_handler_complain_key},
	{"FN", vte_sequence_handler_complain_key},
	{"FO", vte_sequence_handler_complain_key},
	{"FP", vte_sequence_handler_complain_key},
	{"FQ", vte_sequence_handler_complain_key},
	{"FR", vte_sequence_handler_complain_key},
	{"FS", vte_sequence_handler_complain_key},
	{"FT", vte_sequence_handler_complain_key},
	{"FU", vte_sequence_handler_complain_key},
	{"FV", vte_sequence_handler_complain_key},
	{"FW", vte_sequence_handler_complain_key},
	{"FX", vte_sequence_handler_complain_key},
	{"FY", vte_sequence_handler_complain_key},
	{"FZ", vte_sequence_handler_complain_key},

	{"Fa", vte_sequence_handler_complain_key},
	{"Fb", vte_sequence_handler_complain_key},
	{"Fc", vte_sequence_handler_complain_key},
	{"Fd", vte_sequence_handler_complain_key},
	{"Fe", vte_sequence_handler_complain_key},
	{"Ff", vte_sequence_handler_complain_key},
	{"Fg", vte_sequence_handler_complain_key},
	{"Fh", vte_sequence_handler_complain_key},
	{"Fi", vte_sequence_handler_complain_key},
	{"Fj", vte_sequence_handler_complain_key},
	{"Fk", vte_sequence_handler_complain_key},
	{"Fl", vte_sequence_handler_complain_key},
	{"Fm", vte_sequence_handler_complain_key},
	{"Fn", vte_sequence_handler_complain_key},
	{"Fo", vte_sequence_handler_complain_key},
	{"Fp", vte_sequence_handler_complain_key},
	{"Fq", vte_sequence_handler_complain_key},
	{"Fr", vte_sequence_handler_complain_key},

	{"hd", NULL},
	{"ho", vte_sequence_handler_ho},
	{"hu", NULL},

	{"i1", NULL},
	{"i3", NULL},

	{"is", NULL},
	{"ic", vte_sequence_handler_ic},
	{"IC", vte_sequence_handler_IC},
	{"if", NULL},
	{"im", vte_sequence_handler_im},
	{"ip", NULL},
	{"iP", NULL},

	{"K1", vte_sequence_handler_complain_key},
	{"K2", vte_sequence_handler_complain_key},
	{"K3", vte_sequence_handler_complain_key},
	{"K4", vte_sequence_handler_complain_key},
	{"K5", vte_sequence_handler_complain_key},

	{"k0", vte_sequence_handler_complain_key},
	{"k1", vte_sequence_handler_complain_key},
	{"k2", vte_sequence_handler_complain_key},
	{"k3", vte_sequence_handler_complain_key},
	{"k4", vte_sequence_handler_complain_key},
	{"k5", vte_sequence_handler_complain_key},
	{"k6", vte_sequence_handler_complain_key},
	{"k7", vte_sequence_handler_complain_key},
	{"k8", vte_sequence_handler_complain_key},
	{"k9", vte_sequence_handler_complain_key},
	{"k;", vte_sequence_handler_complain_key},
	{"ka", vte_sequence_handler_complain_key},
	{"kA", vte_sequence_handler_complain_key},
	{"kb", vte_sequence_handler_kb},
	{"kB", vte_sequence_handler_complain_key},
	{"kC", vte_sequence_handler_complain_key},
	{"kd", vte_sequence_handler_complain_key},
	{"kD", vte_sequence_handler_complain_key},
	{"ke", vte_sequence_handler_ke},
	{"kE", vte_sequence_handler_complain_key},
	{"kF", vte_sequence_handler_complain_key},
	{"kh", vte_sequence_handler_complain_key},
	{"kH", vte_sequence_handler_complain_key},
	{"kI", vte_sequence_handler_complain_key},
	{"kl", vte_sequence_handler_complain_key},
	{"kL", vte_sequence_handler_complain_key},
	{"kM", vte_sequence_handler_complain_key},
	{"kN", vte_sequence_handler_complain_key},
	{"kP", vte_sequence_handler_complain_key},
	{"kr", vte_sequence_handler_complain_key},
	{"kR", vte_sequence_handler_complain_key},
	{"ks", vte_sequence_handler_ks},
	{"kS", vte_sequence_handler_complain_key},
	{"kt", vte_sequence_handler_complain_key},
	{"kT", vte_sequence_handler_complain_key},
	{"ku", vte_sequence_handler_complain_key},

	{"l0", NULL},
	{"l1", NULL},
	{"l2", NULL},
	{"l3", NULL},
	{"l4", NULL},
	{"l5", NULL},
	{"l6", NULL},
	{"l7", NULL},
	{"l8", NULL},
	{"l9", NULL},
	{"la", NULL},

	{"le", vte_sequence_handler_le},
	{"LE", vte_sequence_handler_LE},
	{"LF", NULL},
	{"ll", vte_sequence_handler_ll},
	{"LO", NULL},

	{"mb", vte_sequence_handler_mb},
	{"MC", NULL},
	{"md", vte_sequence_handler_md},
	{"me", vte_sequence_handler_me},
	{"mh", vte_sequence_handler_mh},
	{"mk", vte_sequence_handler_mk},
	{"ML", NULL},
	{"mm", NULL},
	{"mo", NULL},
	{"mp", vte_sequence_handler_mp},
	{"mr", vte_sequence_handler_mr},
	{"MR", NULL},

	{"nd", vte_sequence_handler_nd},
	{"nw", vte_sequence_handler_nw},

	{"pc", NULL},
	{"pf", NULL},
	{"pk", NULL},
	{"pl", NULL},
	{"pn", NULL},
	{"po", NULL},
	{"pO", NULL},
	{"ps", NULL},
	{"px", NULL},

	{"r1", NULL},
	{"r2", NULL},
	{"r3", NULL},

	{"..rp", NULL},
	{"RA", NULL},
	{"rc", vte_sequence_handler_rc},
	{"rf", NULL},
	{"RF", NULL},
	{"RI", vte_sequence_handler_RI},
	{"rp", NULL},
	{"rP", NULL},
	{"rs", NULL},
	{"RX", NULL},

	{"..sa", NULL},
	{"sa", NULL},
	{"SA", NULL},
	{"sc", vte_sequence_handler_sc},
	{"se", vte_sequence_handler_se},
	{"sf", vte_sequence_handler_sf},
	{"SF", vte_sequence_handler_SF},
	{"so", vte_sequence_handler_so},
	{"sr", vte_sequence_handler_sr},
	{"SR", vte_sequence_handler_SR},
	{"st", vte_sequence_handler_st},
	{"SX", NULL},

	{"ta", vte_sequence_handler_ta},
	{"te", vte_sequence_handler_noop},
	{"ti", vte_sequence_handler_noop},
	{"ts", vte_sequence_handler_ts},

	{"uc", vte_sequence_handler_uc},
	{"ue", vte_sequence_handler_ue},
	{"up", vte_sequence_handler_up},
	{"UP", vte_sequence_handler_UP},
	{"us", vte_sequence_handler_us},

	{"vb", vte_sequence_handler_vb},
	{"ve", vte_sequence_handler_ve},
	{"vi", vte_sequence_handler_vi},
	{"vs", vte_sequence_handler_vs},

	{"wi", NULL},

	{"XF", NULL},

	{"7-bit-controls", NULL},
	{"8-bit-controls", NULL},
	{"ansi-conformance-level-1", NULL},
	{"ansi-conformance-level-2", NULL},
	{"ansi-conformance-level-3", NULL},
	{"application-keypad", vte_sequence_handler_application_keypad},
	{"change-background-colors", NULL},
	{"change-color", NULL},
	{"change-cursor-colors", NULL},
	{"change-font-name", NULL},
	{"change-font-number", NULL},
	{"change-foreground-colors", NULL},
	{"change-highlight-colors", NULL},
	{"change-logfile", NULL},
	{"change-mouse-cursor-background-colors", NULL},
	{"change-mouse-cursor-foreground-colors", NULL},
	{"change-tek-background-colors", NULL},
	{"change-tek-foreground-colors", NULL},
	{"character-attributes", vte_sequence_handler_character_attributes},
	{"character-position-absolute", vte_sequence_handler_character_position_absolute},
	{"cursor-back-tab", vte_sequence_handler_bt},
	{"cursor-backward", vte_sequence_handler_LE},
	{"cursor-character-absolute", vte_sequence_handler_cursor_character_absolute},
	{"cursor-down", vte_sequence_handler_DO},
	{"cursor-forward-tabulation", vte_sequence_handler_ta},
	{"cursor-forward", vte_sequence_handler_RI},
	{"cursor-lower-left", vte_sequence_handler_cursor_lower_left},
	{"cursor-next-line", vte_sequence_handler_cursor_next_line},
	{"cursor-position", vte_sequence_handler_cursor_position},
	{"cursor-preceding-line", vte_sequence_handler_cursor_preceding_line},
	{"cursor-up", vte_sequence_handler_UP},
	{"dec-device-status-report", vte_sequence_handler_dec_device_status_report},
	{"dec-media-copy", NULL},
	{"decreset", vte_sequence_handler_decreset},
	{"decset", vte_sequence_handler_decset},
	{"delete-characters", vte_sequence_handler_DC},
	{"delete-lines", vte_sequence_handler_delete_lines},
	{"device-control-string", NULL},
	{"device-status-report", vte_sequence_handler_device_status_report},
	{"double-height-bottom-half", NULL},
	{"double-height-top-half", NULL},
	{"double-width", NULL},
	{"enable-filter-rectangle", NULL},
	{"enable-locator-reporting", NULL},
	{"end-of-guarded-area", NULL},
	{"erase-characters", vte_sequence_handler_erase_characters},
	{"erase-in-display", vte_sequence_handler_erase_in_display},
	{"erase-in-line", vte_sequence_handler_erase_in_line},
	{"full-reset", vte_sequence_handler_full_reset},
	{"horizontal-and-vertical-position", vte_sequence_handler_horizontal_and_vertical_position},
	{"index", vte_sequence_handler_index},
	{"initiate-hilite-mouse-tracking", NULL},
	{"insert-blank-characters", vte_sequence_handler_insert_blank_characters},
	{"insert-lines", vte_sequence_handler_insert_lines},
	{"invoke-g1-character-set-as-gr", NULL},
	{"invoke-g2-character-set-as-gr", NULL},
	{"invoke-g2-character-set", NULL},
	{"invoke-g3-character-set-as-gr", NULL},
	{"invoke-g3-character-set", NULL},
	{"iso8859-1-character-set", vte_sequence_handler_local_charset},
	{"line-position-absolute", vte_sequence_handler_line_position_absolute},
	{"media-copy", NULL},
	{"memory-lock", NULL},
	{"memory-unlock", NULL},
	{"next-line", vte_sequence_handler_next_line},
	{"normal-keypad", vte_sequence_handler_normal_keypad},
	{"repeat", NULL},
	{"request-locator-position", NULL},
	{"request-terminal-parameters", vte_sequence_handler_request_terminal_parameters},
	{"reset-mode", vte_sequence_handler_reset_mode},
	{"restore-cursor", vte_sequence_handler_rc},
	{"restore-mode", vte_sequence_handler_restore_mode},
	{"return-terminal-status", vte_sequence_handler_return_terminal_status},
	{"return-terminal-id", NULL},
	{"reverse-index", vte_sequence_handler_reverse_index},
	{"save-cursor", vte_sequence_handler_sc},
	{"save-mode", vte_sequence_handler_save_mode},
	{"screen-alignment-test", vte_sequence_handler_screen_alignment_test},
	{"scroll-down", NULL},
	{"scroll-up", NULL},
	{"select-character-protection", NULL},
	{"selective-erase-in-display", NULL},
	{"selective-erase-in-line", NULL},
	{"select-locator-events", NULL},
	{"send-primary-device-attributes", vte_sequence_handler_send_primary_device_attributes},
	{"send-secondary-device-attributes", vte_sequence_handler_send_secondary_device_attributes},
	{"set-conformance-level", NULL},
	{"set-icon-and-window-title", vte_sequence_handler_set_icon_and_window_title},
	{"set-icon-title", vte_sequence_handler_set_icon_title},
	{"set-mode", vte_sequence_handler_set_mode},
	{"set-scrolling-region", vte_sequence_handler_set_scrolling_region},
	{"set-window-title", vte_sequence_handler_set_window_title},
	{"single-shift-g2", NULL},
	{"single-shift-g3", NULL},
	{"single-width", NULL},
	{"soft-reset", vte_sequence_handler_soft_reset},
	{"start-of-guarded-area", NULL},
	{"tab-clear", vte_sequence_handler_tab_clear},
	{"tab-set", vte_sequence_handler_st},
	{"utf-8-character-set", vte_sequence_handler_utf_8_charset},
	{"window-manipulation", vte_sequence_handler_window_manipulation},
};

/* Create the basic widget.  This more or less creates and initializes a
 * GtkWidget and clears out the rest of the data which is specific to our
 * widget class. */
GtkWidget *
vte_terminal_new(void)
{
	return GTK_WIDGET(g_object_new(vte_terminal_get_type(), NULL));
}

/* Set up a palette entry with a more-or-less match for the requested color. */
static void
vte_terminal_set_color_internal(VteTerminal *terminal, int entry,
				const GdkColor *proposed)
{
	GtkWidget *widget;
	Display *display;
	GdkColormap *gcolormap;
	Colormap colormap;
	GdkVisual *gvisual;
	Visual *visual;
	GdkColor color;

	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	g_return_if_fail(entry < G_N_ELEMENTS(terminal->pvt->palette));

	/* Save the requested color. */
	terminal->pvt->palette[entry].red = proposed->red;
	terminal->pvt->palette[entry].green = proposed->green;
	terminal->pvt->palette[entry].blue = proposed->blue;

	/* If we're not realized yet, there's nothing else we can do. */
	widget = GTK_WIDGET(terminal);
	if (!GTK_WIDGET_REALIZED(widget)) {
		return;
	}

	/* Get X11 attributes used by GDK for the widget. */
	display = GDK_DISPLAY();
	gcolormap = gtk_widget_get_colormap(widget);
	colormap = gdk_x11_colormap_get_xcolormap(gcolormap);
	gvisual = gtk_widget_get_visual(widget);
	visual = gdk_x11_visual_get_xvisual(gvisual);

	/* Create a working copy of what we want, which GDK will
	 * adjust below when it fills in the pixel value. */
	color = *proposed;

	/* Get a GDK color. */
	gdk_rgb_find_color(gcolormap, &color); /* fills in pixel */
	terminal->pvt->palette[entry].red = color.red;
	terminal->pvt->palette[entry].green = color.green;
	terminal->pvt->palette[entry].blue = color.blue;
	terminal->pvt->palette[entry].pixel = color.pixel;

#ifdef HAVE_XFT
	/* If we're using Xft, we need to allocate a RenderColor, too. */
	if ((terminal->pvt->render_method == VteRenderXft1) ||
	    (terminal->pvt->render_method == VteRenderXft2)) {
		XRenderColor *rcolor;
		XftColor *ftcolor;

		rcolor = &terminal->pvt->palette[entry].rcolor;
		ftcolor = &terminal->pvt->palette[entry].ftcolor;

		/* Fill the render color in with what we got from GDK,
		 * hopefully so that they match. */
		rcolor->red = color.red;
		rcolor->green = color.green;
		rcolor->blue = color.blue;
		rcolor->alpha = 0xffff;

		/* FIXME this should probably use a color from the
		 * color cube. */
		g_return_if_fail(XftColorAllocValue(display, visual, colormap,
						    rcolor, ftcolor) != 0);
	}
#endif

	/* If we're setting the background color, set the background color
	 * on the widget as well. */
	if ((entry == VTE_DEF_BG)) {
		vte_terminal_setup_background(terminal, FALSE);
	}
}

static void
vte_terminal_generate_bold(const struct vte_palette_entry *foreground,
			   const struct vte_palette_entry *background,
			   double factor,
			   GdkColor *bold)
{
	double fy, fcb, fcr, by, bcb, bcr, r, g, b;
	g_return_if_fail(foreground != NULL);
	g_return_if_fail(background != NULL);
	g_return_if_fail(bold != NULL);
	fy =   0.2990 * foreground->red +
	       0.5870 * foreground->green +
	       0.1140 * foreground->blue;
	fcb = -0.1687 * foreground->red +
	      -0.3313 * foreground->green +
	       0.5000 * foreground->blue;
	fcr =  0.5000 * foreground->red +
	      -0.4187 * foreground->green +
	      -0.0813 * foreground->blue;
	by =   0.2990 * background->red +
	       0.5870 * background->green +
	       0.1140 * background->blue;
	bcb = -0.1687 * background->red +
	      -0.3313 * background->green +
	       0.5000 * background->blue;
	bcr =  0.5000 * background->red +
	      -0.4187 * background->green +
	      -0.0813 * background->blue;
	fy = (factor * fy) + ((1.0 - factor) * by);
	fcb = (factor * fcb) + ((1.0 - factor) * bcb);
	fcr = (factor * fcr) + ((1.0 - factor) * bcr);
	r = fy + 1.402 * fcr;
	g = fy + 0.34414 * fcb - 0.71414 * fcr;
	b = fy + 1.722 * fcb;
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Calculated bold (%d, %d, %d) = (%lf,%lf,%lf)",
			foreground->red, foreground->green, foreground->blue,
			r, g, b);
	}
#endif
	bold->red = CLAMP(r, 0, 0xffff);
	bold->green = CLAMP(g, 0, 0xffff);
	bold->blue = CLAMP(b, 0, 0xffff);
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "= (%04x,%04x,%04x).\n",
			bold->red, bold->green, bold->blue);
	}
#endif
}

/* Set the bold foreground color. */
void
vte_terminal_set_color_bold(VteTerminal *terminal, const GdkColor *bold)
{
	vte_terminal_set_color_internal(terminal, VTE_BOLD_FG, bold);
}

/* Set the foreground color. */
void
vte_terminal_set_color_foreground(VteTerminal *terminal,
				  const GdkColor *foreground)
{
	vte_terminal_set_color_internal(terminal, VTE_DEF_FG, foreground);
}

/* Set the background color. */
void
vte_terminal_set_color_background(VteTerminal *terminal,
				  const GdkColor *background)
{
	vte_terminal_set_color_internal(terminal, VTE_DEF_BG, background);
}

/* Set a given set of colors as the palette. */
void
vte_terminal_set_colors(VteTerminal *terminal,
			const GdkColor *foreground,
			const GdkColor *background,
			const GdkColor *palette,
			gssize palette_size)
{
	int i;
	GdkColor color;

	g_return_if_fail(VTE_IS_TERMINAL(terminal));

	g_return_if_fail(palette_size >= 0);
	g_return_if_fail((palette_size == 0) ||
			 (palette_size == 8) ||
			 (palette_size == 16) ||
			 (palette_size == G_N_ELEMENTS(terminal->pvt->palette)));

	/* Accept NULL as the default foreground and background colors if we
	 * got a palette. */
	if ((foreground == NULL) && (palette_size >= 8)) {
		foreground = &palette[7];
	}
	if ((background == NULL) && (palette_size >= 8)) {
		background = &palette[0];
	}

	memset(&color, 0, sizeof(color));

	/* Initialize each item in the palette if we got any entries to work
	 * with. */
	for (i = 0; (i < G_N_ELEMENTS(terminal->pvt->palette)); i++) {
		switch (i) {
			case VTE_DEF_FG:
				if (foreground != NULL) {
					color = *foreground;
				} else {
					color.red = 0xc000;
					color.blue = 0xc000;
					color.green = 0xc000;
				}
				break;
			case VTE_DEF_BG:
				if (background != NULL) {
					color = *background;
				} else {
					color.red = 0;
					color.blue = 0;
					color.green = 0;
				}
				break;
			case VTE_BOLD_FG:
				vte_terminal_generate_bold(&terminal->pvt->palette[VTE_DEF_FG],
							   &terminal->pvt->palette[VTE_DEF_BG],
							   1.8,
							   &color);
				break;
			case 0 + 0:
			case 0 + 1:
			case 0 + 2:
			case 0 + 3:
			case 0 + 4:
			case 0 + 5:
			case 0 + 6:
			case 0 + 7:
			case 8 + 0:
			case 8 + 1:
			case 8 + 2:
			case 8 + 3:
			case 8 + 4:
			case 8 + 5:
			case 8 + 6:
			case 8 + 7:
				color.blue = (i & 4) ? 0xc000 : 0;
				color.green = (i & 2) ? 0xc000 : 0;
				color.red = (i & 1) ? 0xc000 : 0;
				if (i > 8) {
					color.blue += 0x3fff;
					color.green += 0x3fff;
					color.red += 0x3fff;
				}
				break;
			default:
				g_assert_not_reached();
				break;
		}

		/* Override from the supplied palette if there is one. */
		if (i < palette_size) {
			color = palette[i];
		}

		/* Set up the color entry. */
		vte_terminal_set_color_internal(terminal, i, &color);
	}

	/* We may just have changed the default background color, so queue
	 * a repaint of the entire viewable area. */
	vte_invalidate_all(terminal);

	/* Track that we had a color palette set. */
	terminal->pvt->palette_initialized = TRUE;
}

/* Reset palette defaults for character colors. */
void
vte_terminal_set_default_colors(VteTerminal *terminal)
{
	vte_terminal_set_colors(terminal, NULL, NULL, NULL, 0);
}

/* Insert a single character into the stored data array. */
static void
vte_terminal_insert_char(GtkWidget *widget, gunichar c,
			 gboolean force_insert_mode)
{
	VteTerminal *terminal;
	GArray *array;
	struct vte_charcell cell, *pcell;
	int columns, i;
	long col;
	VteScreen *screen;
	gboolean insert;

	g_return_if_fail(widget != NULL);
	g_return_if_fail(VTE_IS_TERMINAL(widget));
	terminal = VTE_TERMINAL(widget);
	screen = terminal->pvt->screen;
	insert = screen->insert_mode || force_insert_mode;

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_IO) && vte_debug_on(VTE_DEBUG_PARSE)) {
		fprintf(stderr, "Inserting %ld %c (%d/%d)(%d), delta = %ld, ",
			(long)c,
			c < 256 ? c : ' ',
			screen->defaults.fore, screen->defaults.back,
			vte_unichar_width(c),
			(long)screen->insert_delta);
	}
#endif
	/* If this character is destined for the status line, save it. */
	if (terminal->pvt->screen->status_line) {
		g_string_append_unichar(terminal->pvt->screen->status_line_contents,
					c);
		vte_terminal_emit_status_line_changed(terminal);
		return;
	}

	/* Figure out how many columns this character should occupy. */
	columns = vte_unichar_width(c);
	if (columns < 0) {
		g_warning(_("Character 0x%x is undefined, allocating one "
			  "column."), c);
		columns = 1;
	}

	/* If we're autowrapping here, do it. */
	col = screen->cursor_current.col;
	if (col >= terminal->column_count) {
		if (terminal->pvt->flags.am) {
			/* Wrap. */
			screen->cursor_current.col = 0;
			screen->cursor_current.row++;
		} else {
			/* Don't wrap, stay at the rightmost column. */
			screen->cursor_current.col = terminal->column_count - 1;
		}
	}

	/* Make sure we have enough rows to hold this data. */
	vte_terminal_ensure_cursor(terminal, FALSE);

	/* Get a handle on the array for the insertion row. */
	array = vte_ring_index(screen->row_data,
			       GArray*,
			       screen->cursor_current.row);

	/* Insert the right number of columns. */
	for (i = 0; i < columns; i++) {
		col = screen->cursor_current.col;
		cell = screen->defaults;

		/* Make sure we have enough columns in this row. */
		if (array->len <= col) {
			/* Add enough cells to fill out the row to at least out
			 * to the insertion point. */
			while (array->len < col) {
				array = g_array_append_val(array, cell);
			}
			/* Add one more cell to the end of the line to get
			 * it into the column, and use it. */
			array = g_array_append_val(array, cell);
			pcell = &g_array_index(array,
					       struct vte_charcell,
					       col);
		} else {
			/* If we're in insert mode, insert a new cell here
			 * and use it. */
			if (insert) {
				g_array_insert_val(array, col, cell);
				pcell = &g_array_index(array,
						       struct vte_charcell,
						       col);
			} else {
				/* We're in overtype mode, so use the existing
				 * character. */
				pcell = &g_array_index(array,
						       struct vte_charcell,
						       col);
			}
		}

		/* Set the character cell's attributes to match the current
		 * defaults, preserving any previous contents. */
		cell = *pcell;
		*pcell = screen->defaults;
		pcell->c = cell.c;
		pcell->columns = cell.columns;

		/* Now set the character and column count. */
		if (i == 0) {
			if ((pcell->c != 0) &&
			    (c == '_') &&
			    (terminal->pvt->flags.ul)) {
				/* Handle overstrike-style underlining. */
				pcell->underline = 1;
			} else {
				/* Insert the character. */
				pcell->c = c;
				pcell->columns = columns;
			}
		} else {
			/* This is a continuation cell. */
			pcell->columns = 0;
		}

		/* Signal that this part of the window needs drawing. */
		if (insert) {
			vte_invalidate_cells(terminal,
					     col,
					     terminal->column_count - col,
					     screen->cursor_current.row,
					     2);
		} else {
			vte_invalidate_cells(terminal,
					     col, 1,
					     screen->cursor_current.row, 2);
		}

		/* And take a step to the to the right. */
		screen->cursor_current.col++;

		/* Make sure we're not getting random stuff past the right
		 * edge of the screen at this point, because the user can't
		 * see it. */
		while (array->len > terminal->column_count) {
			g_array_remove_index(array, array->len - 1);
		}
	}

	/* Make sure the location the cursor is on exists. */
	vte_terminal_ensure_cursor(terminal, FALSE);

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_IO) && vte_debug_on(VTE_DEBUG_PARSE)) {
		fprintf(stderr, "insertion delta => %ld.\n",
			(long)screen->insert_delta);
	}
#endif
}

#ifdef VTE_DEBUG
static void
display_control_sequence(const char *name, GValueArray *params)
{
	/* Display the control sequence with its parameters, to
	 * help me debug this thing.  I don't have all of the
	 * sequences implemented yet. */
	int i;
	long l;
	const char *s;
	const gunichar *w;
	GValue *value;
	fprintf(stderr, "%s(", name);
	if (params != NULL) {
		for (i = 0; i < params->n_values; i++) {
			value = g_value_array_get_nth(params, i);
			if (i > 0) {
				fprintf(stderr, ", ");
			}
			if (G_VALUE_HOLDS_LONG(value)) {
				l = g_value_get_long(value);
				fprintf(stderr, "%ld", l);
			} else
			if (G_VALUE_HOLDS_STRING(value)) {
				s = g_value_get_string(value);
				fprintf(stderr, "\"%s\"", s);
			} else
			if (G_VALUE_HOLDS_POINTER(value)) {
				w = g_value_get_pointer(value);
				fprintf(stderr, "\"%ls\"", w);
			}
		}
	}
	fprintf(stderr, ")\n");
}
#endif

/* Handle a terminal control sequence and its parameters. */
static void
vte_terminal_handle_sequence(GtkWidget *widget,
			     const char *match_s,
			     GQuark match,
			     GValueArray *params)
{
	VteTerminal *terminal;
	VteTerminalSequenceHandler handler;
	VteScreen *screen;
	struct vte_cursor_position position;

	g_return_if_fail(widget != NULL);
	g_return_if_fail(VTE_IS_TERMINAL(widget));
	terminal = VTE_TERMINAL(widget);
	screen = terminal->pvt->screen;

	/* This may generate multiple redraws, so freeze it while we do them. */
	if (GTK_WIDGET_REALIZED (widget)) {
		gdk_window_freeze_updates(widget->window);
	}

	/* Save the cursor's current position for future use. */
	position = screen->cursor_current;

	/* Find the handler for this control sequence. */
	handler = g_tree_lookup(terminal->pvt->sequences, GINT_TO_POINTER(match));
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_PARSE)) {
		display_control_sequence(match_s, params);
	}
#endif
	if (handler != NULL) {
		/* Let the handler handle it. */
		handler(terminal, match_s, match, params);
	} else {
		g_warning(_("No handler for control sequence `%s' defined."),
			  match_s);
	}

	/* If the cursor moved, then we need to redraw the cell in which
	 * it used to be. */
	if ((screen->cursor_current.col != position.col) ||
	    (screen->cursor_current.row != position.row)) {
		vte_invalidate_cells(terminal,
				     position.col, 1,
				     position.row, 1);
	}

	/* We probably need to update the cursor's new position, too. */
	vte_invalidate_cells(terminal,
			     screen->cursor_current.col, 1,
			     screen->cursor_current.row, 1);

	/* Let the updating begin. */
	if (GTK_WIDGET_REALIZED (widget)) {
		gdk_window_thaw_updates(widget->window);
	}
}

/* Catch a VteReaper child-exited signal, and if it matches the one we're
 * looking for, emit one of our own. */
static void
vte_terminal_catch_child_exited(VteReaper *reaper, guint pid, guint status,
				VteTerminal *data)
{
	VteTerminal *terminal;
	g_return_if_fail(VTE_IS_TERMINAL(data));
	terminal = VTE_TERMINAL(data);
	if (pid == terminal->pvt->pty_pid) {
		vte_terminal_emit_child_exited(terminal);
	}
}

/* Start up a command in a slave PTY. */
pid_t
vte_terminal_fork_command(VteTerminal *terminal, const char *command,
			  char **argv, char **envv)
{
	char **env_add;
	int i;
	pid_t pid;
	GtkWidget *widget;

	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), -1);
	widget = GTK_WIDGET(terminal);

	/* Start up the command and get the PTY of the master. */
	for (i = 0; (envv != NULL) && (envv[i] != NULL); i++) ;

	env_add = g_malloc0(sizeof(char*) * (i + 2));
	if (command == NULL) {
		command = terminal->pvt->shell;
	}

	env_add[0] = g_strdup_printf("TERM=%s", terminal->pvt->emulation);
	for (i = 0; (envv != NULL) && (envv[i] != NULL); i++) {
		env_add[i + 1] = g_strdup(envv[i]);
	}
	env_add[i + 1] = NULL;

	terminal->pvt->pty_master = vte_pty_open(&pid,
						 env_add,
						 command,
						 argv,
						 terminal->column_count,
						 terminal->row_count);

	for (i = 0; env_add[i] != NULL; i++) {
		g_free(env_add[i]);
	}
	g_free(env_add);

	/* If we started the process, set up to listen for its output. */
	if (pid != -1) {
		/* Set this as the child's pid. */
		terminal->pvt->pty_pid = pid;

		/* Catch a child-exited signal from the child pid. */
		g_signal_connect(G_OBJECT(vte_reaper_get()), "child-exited",
				 G_CALLBACK(vte_terminal_catch_child_exited),
				 terminal);

		/* Set the pty to be non-blocking. */
		i = fcntl(terminal->pvt->pty_master, F_GETFL);
		fcntl(terminal->pvt->pty_master, F_SETFL, i | O_NONBLOCK);

		/* Set the PTY size. */
		vte_terminal_set_size(terminal,
				      terminal->column_count,
				      terminal->row_count);
		if (GTK_WIDGET_REALIZED(widget)) {
			gtk_widget_queue_resize(widget);
		}

		/* Open a channel to listen for input on. */
		terminal->pvt->pty_input =
			g_io_channel_unix_new(terminal->pvt->pty_master);
		terminal->pvt->pty_input_source =
			g_io_add_watch_full(terminal->pvt->pty_input,
					    VTE_CHILD_INPUT_PRIORITY,
					    G_IO_IN | G_IO_HUP,
					    vte_terminal_io_read,
					    terminal,
					    NULL);
	}

	/* Return the pid to the caller. */
	return pid;
}

/* Handle an EOF from the client. */
static void
vte_terminal_eof(GIOChannel *channel, gpointer data)
{
	VteTerminal *terminal;

	g_return_if_fail(VTE_IS_TERMINAL(data));
	terminal = VTE_TERMINAL(data);

	/* Close the connections to the child -- note that the source channel
	 * has already been dereferenced. */
	if (channel == terminal->pvt->pty_input) {
		g_io_channel_unref(terminal->pvt->pty_input);
		terminal->pvt->pty_input = NULL;
		g_source_remove(terminal->pvt->pty_input_source);
		terminal->pvt->pty_input_source = -1;
	}

	/* Emit a signal that we read an EOF. */
	vte_terminal_emit_eof(terminal);
}

/* Reset the input method context. */
static void
vte_terminal_im_reset(VteTerminal *terminal)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	if (GTK_WIDGET_REALIZED(GTK_WIDGET(terminal))) {
		gtk_im_context_reset(terminal->pvt->im_context);
		if (terminal->pvt->im_preedit != NULL) {
			g_free(terminal->pvt->im_preedit);
			terminal->pvt->im_preedit = NULL;
		}
	}
}

/* Free a parameter array.  Most of the GValue elements can clean up after
 * themselves, but we're using gpointers to hold unicode character strings, and
 * we need to free those ourselves. */
static void
free_params_array(GValueArray *params)
{
	int i;
	GValue *value;
	gpointer ptr;
	if (params != NULL) {
		for (i = 0; i < params->n_values; i++) {
			value = g_value_array_get_nth(params, i);
			if (G_VALUE_HOLDS_POINTER(value)) {
				ptr = g_value_get_pointer(value);
				if (ptr != NULL) {
					g_free(ptr);
				}
				g_value_set_pointer(value, NULL);
			}
		}
		g_value_array_free(params);
	}
}

/* Process incoming data, first converting it to unicode characters, and then
 * processing control sequences. */
static gboolean
vte_terminal_process_incoming(gpointer data)
{
	GValueArray *params = NULL;
	VteTerminal *terminal;
	VteScreen *screen;
	struct vte_cursor_position cursor;
	struct vte_iso2022 *substitutions;
	gssize substitution_count;
	GtkWidget *widget;
	GdkRectangle rect;
	char *ibuf, *obuf, *obufptr, *ubuf, *ubufptr;
	gssize icount, ocount, ucount;
	gunichar *wbuf, c;
	int wcount, start;
	const char *match, *encoding;
	GIConv unconv;
	GQuark quark;
	const gunichar *next;
	gboolean leftovers, modified, again, bottom;

	g_return_val_if_fail(GTK_IS_WIDGET(data), FALSE);
	g_return_val_if_fail(VTE_IS_TERMINAL(data), FALSE);
	widget = GTK_WIDGET(data);
	terminal = VTE_TERMINAL(data);
	bottom = (terminal->pvt->screen->insert_delta ==
		  terminal->pvt->screen->scroll_delta);

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_IO)) {
		fprintf(stderr, "Handler processing %d bytes.\n",
			terminal->pvt->n_incoming);
	}
#endif

	/* We should only be called when there's data to process. */
	g_assert(terminal->pvt->n_incoming > 0);

	/* Try to convert the data into unicode characters. */
	ocount = sizeof(gunichar) * terminal->pvt->n_incoming;
	obuf = obufptr = g_malloc(ocount);
	icount = terminal->pvt->n_incoming;
	ibuf = terminal->pvt->incoming;

	/* Convert the data to unicode characters. */
	if (g_iconv(terminal->pvt->incoming_conv, &ibuf, &icount,
		    &obuf, &ocount) == -1) {
		/* No dice.  Try again when we have more data. */
		if ((errno == EILSEQ) && (terminal->pvt->n_incoming >= icount)) {
			/* Discard the offending byte. */
			start = terminal->pvt->n_incoming - icount;
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_IO)) {
				fprintf(stderr, "Error converting %ld incoming "
					"data bytes: %s, discarding byte %ld "
					"(0x%02x) and trying again.\n",
					(long) terminal->pvt->n_incoming,
					strerror(errno), start,
					terminal->pvt->incoming[start]);
			}
#endif
			terminal->pvt->incoming[start] = '?';
			/* Try again, before we try anything else. */
			g_free(obufptr);
			/* To pull this off we add ourselves as a higher
			 * priority idle handler, and cause this handler to
			 * be dropped. */
			terminal->pvt->processing_tag =
					g_idle_add_full(VTE_INPUT_RETRY_PRIORITY,
							vte_terminal_process_incoming,
							terminal,
						NULL);
			return FALSE;
		}
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_IO)) {
			fprintf(stderr, "Error converting %ld incoming data "
				"bytes: %s, leaving for later.\n",
				(long) terminal->pvt->n_incoming,
				strerror(errno));
		}
#endif
		terminal->pvt->processing = FALSE;
		terminal->pvt->processing_tag = -1;
		g_free(obufptr);
		return terminal->pvt->processing;
	}

	/* Store the current encoding. */
	encoding = terminal->pvt->encoding;

	/* Compute the number of unicode characters we got. */
	wcount = (obuf - obufptr) / sizeof(gunichar);
	wbuf = (gunichar*) obufptr;

	/* Perform ISO-2022 and XTerm national charset substitutions. */
	substitutions = vte_iso2022_copy(terminal->pvt->substitutions);
	substitution_count = vte_iso2022_substitute(substitutions,
						    wbuf, wcount, wbuf,
						    terminal->pvt->table);
	if (substitution_count < 0) {
		vte_iso2022_free(substitutions);
		g_free(obufptr);
		return terminal->pvt->processing;
	} else {
		vte_iso2022_free(terminal->pvt->substitutions);
		terminal->pvt->substitutions = substitutions;
		wcount = substitution_count;
	}

	/* Save the current cursor position. */
	screen = terminal->pvt->screen;
	cursor = screen->cursor_current;

	/* Try initial substrings. */
	start = 0;
	modified = leftovers = again = FALSE;
	while ((start < wcount) && !leftovers) {
		/* Try to match any control sequences. */
		vte_table_match(terminal->pvt->table,
			        &wbuf[start],
			        wcount - start,
			        &match,
			        &next,
			        &quark,
			        &params);
		/* We're in one of three possible situations now.
		 * First, the match string is a non-empty string and next
		 * points to the first character which isn't part of this
		 * sequence. */
		if ((match != NULL) && (match[0] != '\0')) {
			vte_invalidate_cursor_once(terminal);
			vte_terminal_handle_sequence(GTK_WIDGET(terminal),
						     match,
						     quark,
						     params);
			/* Skip over the proper number of unicode chars. */
			start = (next - wbuf);
			/* Check if the encoding's changed. If it has, we need
			 * to force our caller to call us again to parse the
			 * rest of the data. */
			if (strcmp(encoding, terminal->pvt->encoding)) {
				leftovers = TRUE;
			}
			modified = TRUE;
		} else
		/* Second, we have a NULL match, and next points the very
		 * next character in the buffer.  Insert the character we're
		 * which we're currently examining. */
		if (match == NULL) {
			c = wbuf[start];
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_PARSE)) {
				if (c > 255) {
					fprintf(stderr, "%ld\n", (long) c);
				} else {
					if (c > 127) {
						fprintf(stderr, "%ld = ",
							(long) c);
					}
					if (c < 32) {
						fprintf(stderr, "^%lc\n",
							(wint_t)c + 64);
					} else {
						fprintf(stderr, "`%lc'\n",
							(wint_t)c);
					}
				}
			}
#endif
			if (c != 0) {
				vte_terminal_insert_char(widget, c, FALSE);
			}
			modified = TRUE;
			start++;
		} else {
			/* Case three: the read broke in the middle of a
			 * control sequence, so we're undecided with no more
			 * data to consult. If we have data following the
			 * middle of the sequence, then it's just garbage data,
			 * and for compatibility, we should discard it. */
			if (wbuf + wcount > next) {
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_PARSE)) {
					fprintf(stderr, "Invalid control sequence, "
						"discarding %d characters.\n",
						next - (wbuf + start));
				}
#endif
				/* Discard. */
				start = next - wbuf + 1;
			} else {
				/* Pause processing and wait for more data. */
				leftovers = TRUE;
			}
		}
		/* Free any parameters we don't care about any more. */
		free_params_array(params);
		params = NULL;
	}

	if (leftovers) {
		/* There are leftovers, so convert them back to the terminal's
		 * old encoding and save them for later. */
		unconv = g_iconv_open(encoding, vte_table_wide_encoding());
		if (unconv != ((GIConv) -1)) {
			icount = sizeof(gunichar) * (wcount - start);
			ibuf = (char*) &wbuf[start];
			ucount = VTE_UTF8_BPC * (wcount - start) + 1;
			ubuf = ubufptr = g_malloc(ucount);
			if (g_iconv(unconv, &ibuf, &icount,
				    &ubuf, &ucount) != -1) {
				/* Store it. */
				if (terminal->pvt->incoming) {
					g_free(terminal->pvt->incoming);
				}
				terminal->pvt->incoming = ubufptr;
				terminal->pvt->n_incoming = ubuf - ubufptr;
				*ubuf = '\0';
				/* If we're doing this because the encoding
				 * was changed out from under us, we need to
				 * keep trying to process the incoming data. */
				if (strcmp(encoding, terminal->pvt->encoding)) {
					again = TRUE;
				}
			} else {
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_IO)) {
					fprintf(stderr, "Error unconverting %ld "
						"pending input bytes (%s), dropping.\n",
						(long) (sizeof(gunichar) * (wcount - start)),
						strerror(errno));
				}
#endif
				if (terminal->pvt->incoming) {
					g_free(terminal->pvt->incoming);
				}
				terminal->pvt->incoming = NULL;
				terminal->pvt->n_incoming = 0;
				g_free(ubufptr);
				again = FALSE;
			}
			g_iconv_close(unconv);
		} else {
			/* Discard the data, we can't use it. */
			if (terminal->pvt->incoming != NULL) {
				g_free(terminal->pvt->incoming);
			}
			terminal->pvt->incoming = NULL;
			terminal->pvt->n_incoming = 0;
			again = FALSE;
		}
	} else {
		/* No leftovers, clean out the data. */
		terminal->pvt->n_incoming = 0;
		g_free(terminal->pvt->incoming);
		terminal->pvt->incoming = NULL;
		again = FALSE;
	}
	g_free(obufptr);

	if (modified) {
		/* Keep the cursor on-screen if we scroll on output, or if
		 * we're currently at the bottom of the buffer. */
		vte_terminal_scroll_insertion(terminal);
		if (terminal->pvt->scroll_on_output || bottom) {
			vte_terminal_scroll_to_bottom(terminal);
		}

		/* The cursor moved, so force it to be redrawn. */
		vte_invalidate_cursor_once(terminal);

		/* Deselect any existing selection. */
		vte_terminal_deselect_all(terminal);
	}

	if (modified || (screen != terminal->pvt->screen)) {
		/* Signal that the visible contents changed. */
		vte_terminal_match_contents_clear(terminal);
		vte_terminal_emit_contents_changed(terminal);
	}

	if ((cursor.col != terminal->pvt->screen->cursor_current.col) ||
	    (cursor.row != terminal->pvt->screen->cursor_current.row)) {
		/* Signal that the cursor moved. */
		vte_terminal_emit_cursor_moved(terminal);
	}

	/* Tell the input method where the cursor is. */
	if (terminal->pvt->im_context) {
		rect.x = terminal->pvt->screen->cursor_current.col *
			 terminal->char_width;
		rect.width = terminal->char_width;
		rect.y = terminal->pvt->screen->cursor_current.row *
			terminal->char_height;
		rect.height = terminal->char_height;
		gtk_im_context_set_cursor_location(terminal->pvt->im_context, &rect);
	}

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_IO)) {
		fprintf(stderr, "%d bytes left to process.\n",
			terminal->pvt->n_incoming);
	}
#endif
	/* Decide if we're going to keep on processing data, and if not,
	 * note that our source tag is about to become invalid. */
	terminal->pvt->processing = again && (terminal->pvt->n_incoming > 0);
	if (terminal->pvt->processing == FALSE) {
		terminal->pvt->processing_tag = -1;
	}
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_IO)) {
		if (terminal->pvt->processing) {
			fprintf(stderr, "Leaving processing handler on.\n");
		} else {
			fprintf(stderr, "Turning processing handler off.\n");
		}
	}
#endif
	return terminal->pvt->processing;
}

/* Read and handle data from the child. */
static gboolean
vte_terminal_io_read(GIOChannel *channel,
		     GdkInputCondition condition,
		     gpointer data)
{
	VteTerminal *terminal;
	GtkWidget *widget;
	char *buf;
	gssize bufsize;
	int bcount, fd;
	gboolean empty, eof, leave_open = TRUE;

	g_return_val_if_fail(VTE_IS_TERMINAL(data), TRUE);
	widget = GTK_WIDGET(data);
	terminal = VTE_TERMINAL(data);

	/* Check that the channel is still open. */
	fd = g_io_channel_unix_get_fd(channel);

	/* Allocate a buffer to hold whatever data's available. */
	bufsize = terminal->pvt->n_incoming + 0x1000;
	buf = g_malloc0(bufsize);
	if (terminal->pvt->n_incoming > 0) {
		memcpy(buf, terminal->pvt->incoming, terminal->pvt->n_incoming);
	}
	empty = (terminal->pvt->n_incoming == 0);

	/* Read some more data in from this channel. */
	bcount = 0;
	if (condition & G_IO_IN) {
		bcount = read(fd, buf + terminal->pvt->n_incoming,
			      bufsize - terminal->pvt->n_incoming);
	}
	eof = FALSE;
	if (condition & G_IO_HUP) {
		eof = TRUE;
	}

	/* Catch errors. */
	leave_open = TRUE;
	switch (bcount) {
		case 0:
			/* EOF */
			eof = TRUE;
			break;
		case -1:
			switch (errno) {
				case EIO: /* Fake an EOF. */
					eof = TRUE;
					break;
				case EAGAIN:
				case EBUSY:
					leave_open = TRUE;
					break;
				default:
					g_warning(_("Error reading from child: "
						    "%s."), strerror(errno));
					leave_open = TRUE;
					break;
			}
			break;
		default:
			break;
	}

	/* If we got data, modify the pending buffer. */
	if (bcount >= 0) {
		if (terminal->pvt->incoming != NULL) {
			g_free(terminal->pvt->incoming);
		}
		terminal->pvt->incoming = buf;
		terminal->pvt->n_incoming += bcount;
	} else {
		g_free(buf);
	}

	/* If we have data to process, schedule some time to process it. */
	if (!terminal->pvt->processing && (terminal->pvt->n_incoming > 0)) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_IO)) {
			fprintf(stderr, "Queuing handler to process bytes.\n");
		}
#endif
		terminal->pvt->processing = TRUE;
		terminal->pvt->processing_tag =
				g_idle_add_full(VTE_INPUT_PRIORITY,
						vte_terminal_process_incoming,
						terminal,
						NULL);
	}

	/* If we detected an eof condition, signal one. */
	if (eof) {
		vte_terminal_eof(channel, terminal);
		leave_open = FALSE;
	}

	/* If there's more data coming, return TRUE, otherwise return FALSE. */
	return leave_open;
}

/* Render some UTF-8 text. */
void
vte_terminal_feed(VteTerminal *terminal, const char *data, gssize length)
{
	char *buf;
	gboolean empty;

	/* Allocate space for old and new data. */
	buf = g_malloc(terminal->pvt->n_incoming + length + 1);
	empty = (terminal->pvt->n_incoming == 0);

	/* If we got data, modify the pending buffer. */
	if (length >= 0) {
		if (terminal->pvt->n_incoming > 0) {
			memcpy(buf, terminal->pvt->incoming,
			       terminal->pvt->n_incoming);
			g_free(terminal->pvt->incoming);
		}
		memcpy(buf + terminal->pvt->n_incoming,
		       data, length);
		terminal->pvt->incoming = buf;
		terminal->pvt->n_incoming += length;
	} else {
		g_free(buf);
	}

	/* If we didn't have data before, but we do now, process it. */
	if (!terminal->pvt->processing && (terminal->pvt->n_incoming > 0)) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_IO)) {
			fprintf(stderr, "Queuing handler to process bytes.\n");
		}
#endif
		terminal->pvt->processing = TRUE;
		terminal->pvt->processing_tag =
				g_idle_add_full(VTE_INPUT_PRIORITY,
						vte_terminal_process_incoming,
						terminal,
						NULL);
	}
}

/* Send locally-encoded characters to the child. */
static gboolean
vte_terminal_io_write(GIOChannel *channel,
		      GdkInputCondition condition,
		      gpointer data)
{
	VteTerminal *terminal;
	gssize count;
	int fd;
	gboolean leave_open;

	g_return_val_if_fail(VTE_IS_TERMINAL(data), FALSE);
	terminal = VTE_TERMINAL(data);

	fd = g_io_channel_unix_get_fd(channel);

	count = write(fd, terminal->pvt->outgoing, terminal->pvt->n_outgoing);
	if (count != -1) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_IO)) {
			int i;
			for (i = 0; i < count; i++) {
				fprintf(stderr, "Wrote %c%c\n",
					terminal->pvt->outgoing[i] >= 32 ?
					' ' : '^',
					terminal->pvt->outgoing[i] >= 32 ?
					terminal->pvt->outgoing[i] :
					terminal->pvt->outgoing[i]  + 64);
			}
		}
#endif
		memmove(terminal->pvt->outgoing,
			terminal->pvt->outgoing + count,
			terminal->pvt->n_outgoing - count);
		terminal->pvt->n_outgoing -= count;
	}

	if (terminal->pvt->n_outgoing == 0) {
		if (channel == terminal->pvt->pty_output) {
			g_io_channel_unref(terminal->pvt->pty_output);
			terminal->pvt->pty_output = NULL;
			g_source_remove(terminal->pvt->pty_output_source);
			terminal->pvt->pty_output_source = -1;
		}
		leave_open = FALSE;
	} else {
		leave_open = TRUE;
	}

	return leave_open;
}

/* Convert some arbitrarily-encoded data to send to the child. */
static void
vte_terminal_send(VteTerminal *terminal, const char *encoding,
		  const void *data, gssize length)
{
	gssize icount, ocount;
	char *ibuf, *obuf, *obufptr;
	char *outgoing, *p;
	gssize n_outgoing;
	GIConv *conv;

	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	g_assert((strcmp(encoding, "UTF-8") == 0) ||
		 (strcmp(encoding, vte_table_wide_encoding()) == 0));

	conv = NULL;
	if (strcmp(encoding, "UTF-8") == 0) {
		conv = &terminal->pvt->outgoing_conv_utf8;
	}
	if (strcmp(encoding, vte_table_wide_encoding()) == 0) {
		conv = &terminal->pvt->outgoing_conv_wide;
	}
	g_assert(conv != NULL);
	g_assert(*conv != ((GIConv) -1));

	icount = length;
	ibuf = (char *) data;
	ocount = ((length + 1) * VTE_UTF8_BPC) + 1;
	obuf = obufptr = g_malloc0(ocount);

	if (g_iconv(*conv, &ibuf, &icount, &obuf, &ocount) == -1) {
		g_warning(_("Error (%s) converting data for child, dropping."),
			  strerror(errno));
	} else {
		n_outgoing = terminal->pvt->n_outgoing + (obuf - obufptr);
		outgoing = g_realloc(terminal->pvt->outgoing, n_outgoing);
		/* Move some data around. */
		memcpy(outgoing + terminal->pvt->n_outgoing,
		       obufptr, obuf - obufptr);
		/* Save the new outgoing buffer. */
		terminal->pvt->n_outgoing = n_outgoing;
		terminal->pvt->outgoing = outgoing;
		/* Convert newlines to carriage returns, which more software
		 * is able to cope with (cough, pico, cough). */
		p = terminal->pvt->outgoing;
		while ((p != NULL) && (p - outgoing < n_outgoing)) {
			p = memchr(p, '\n', n_outgoing - (p - outgoing));
			if (p != NULL) {
				*p = '\r';
				p++;
			}
		}
		/* If we need to start waiting for the child pty to become
		 * available for writing, set that up here. */
		if (terminal->pvt->pty_output == NULL) {
			terminal->pvt->pty_output =
				g_io_channel_unix_new(terminal->pvt->pty_master);
			terminal->pvt->pty_output_source =
				g_io_add_watch_full(terminal->pvt->pty_output,
						    VTE_CHILD_OUTPUT_PRIORITY,
						    G_IO_OUT,
						    vte_terminal_io_write,
						    terminal,
						    NULL);
		}
	}
	g_free(obufptr);
	return;
}

/* Send a chunk of UTF-8 text to the child. */
void
vte_terminal_feed_child(VteTerminal *terminal, const char *text, gssize length)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	if (length == ((gssize)-1)) {
		length = strlen(text);
	}
	vte_terminal_im_reset(terminal);
	vte_terminal_send(terminal, "UTF-8", text, length);
}

/* Send text from the input method to the child. */
static void
vte_terminal_im_commit(GtkIMContext *im_context, gchar *text, gpointer data)
{
	VteTerminal *terminal;

	g_return_if_fail(VTE_IS_TERMINAL(data));
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_EVENTS)) {
		fprintf(stderr, "Input method committed `%s'.\n", text);
	}
#endif
	terminal = VTE_TERMINAL(data);
	vte_terminal_feed_child(terminal, text, -1);
	/* Committed text was committed because the user pressed a key, so
	 * we need to obey the scroll-on-keystroke setting. */
	if (terminal->pvt->scroll_on_keystroke) {
		vte_terminal_scroll_to_bottom(terminal);
	}
}

/* We've started pre-editing. */
static void
vte_terminal_im_preedit_start(GtkIMContext *im_context, gpointer data)
{
	VteTerminal *terminal;

	g_return_if_fail(VTE_IS_TERMINAL(data));
	terminal = VTE_TERMINAL(data);
	g_return_if_fail(GTK_IS_IM_CONTEXT(im_context));

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_EVENTS)) {
		fprintf(stderr, "Input method pre-edit started.\n");
	}
#endif
}

/* We've stopped pre-editing. */
static void
vte_terminal_im_preedit_end(GtkIMContext *im_context, gpointer data)
{
	VteTerminal *terminal;

	g_return_if_fail(VTE_IS_TERMINAL(data));
	terminal = VTE_TERMINAL(data);
	g_return_if_fail(GTK_IS_IM_CONTEXT(im_context));

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_EVENTS)) {
		fprintf(stderr, "Input method pre-edit ended.\n");
	}
#endif
}

/* The pre-edit string changed. */
static void
vte_terminal_im_preedit_changed(GtkIMContext *im_context, gpointer data)
{
	gchar *str;
	PangoAttrList *attrs;
	VteTerminal *terminal;
	gint cursor;

	g_return_if_fail(VTE_IS_TERMINAL(data));
	terminal = VTE_TERMINAL(data);
	g_return_if_fail(GTK_IS_IM_CONTEXT(im_context));

	gtk_im_context_get_preedit_string(im_context, &str, &attrs, &cursor);
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_EVENTS)) {
		fprintf(stderr, "Input method pre-edit changed (%s,%d).\n",
			str, cursor);
	}
#endif

	vte_invalidate_cursor_once(terminal);

	pango_attr_list_unref(attrs);
	if (terminal->pvt->im_preedit != NULL) {
		g_free(terminal->pvt->im_preedit);
	}
	terminal->pvt->im_preedit = str;
	terminal->pvt->im_preedit_cursor = cursor;

	vte_invalidate_cursor_once(terminal);
}

/* Handle the toplevel being reconfigured. */
static gboolean
vte_terminal_configure_toplevel(GtkWidget *widget, GdkEventConfigure *event,
				gpointer data)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_EVENTS)) {
		fprintf(stderr, "Top level parent configured.\n");
	}
#endif
	g_return_val_if_fail(GTK_IS_WIDGET(widget), FALSE);
	g_return_val_if_fail(GTK_WIDGET_TOPLEVEL(widget), FALSE);
	g_return_val_if_fail(VTE_IS_TERMINAL(data), FALSE);

	/* In case we moved, queue a background image update. */
	if (VTE_TERMINAL(data)->pvt->bg_transparent) {
		vte_terminal_queue_background_update(VTE_TERMINAL(data));
	}

	/* In case we were resized, repaint everything, including any extra
	 * regions which no cell covers. */
	vte_invalidate_all(VTE_TERMINAL(data));

	return FALSE;
}

/* Handle a hierarchy-changed signal. */
static void
vte_terminal_hierarchy_changed(GtkWidget *widget, GtkWidget *old_toplevel,
			       gpointer data)
{
	VteTerminal *terminal;
	GtkWidget *toplevel;

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_EVENTS)) {
		fprintf(stderr, "Hierarchy changed.\n");
	}
#endif

	g_return_if_fail(VTE_IS_TERMINAL(widget));
	terminal = VTE_TERMINAL(widget);

	if (GTK_IS_WIDGET(old_toplevel)) {
		g_signal_handlers_disconnect_by_func(G_OBJECT(old_toplevel),
						     vte_terminal_configure_toplevel,
						     terminal);
	}

	toplevel = gtk_widget_get_toplevel(widget);
	if (GTK_IS_WIDGET(toplevel)) {
		g_signal_connect(G_OBJECT(toplevel), "configure-event",
				 G_CALLBACK(vte_terminal_configure_toplevel),
				 terminal);
	}
}

/* Handle a style-changed signal. */
static void
vte_terminal_style_changed(GtkWidget *widget, GtkStyle *style, gpointer data)
{
	VteTerminal *terminal;
	g_return_if_fail(VTE_IS_TERMINAL(widget));
	terminal = VTE_TERMINAL(widget);
	/* If the font we're using is the same as the old default, then we
	 * need to pick up the new default. */
	if (pango_font_description_equal(style->font_desc,
					 widget->style->font_desc) ||
	    (terminal->pvt->fontdesc == NULL)) {
		vte_terminal_set_font(terminal, NULL);
	}
}

static struct {
	gulong keyval;
	unsigned char *special;
	unsigned char *vt_ctrl_special;
} vte_keysym_map[] = {
	{GDK_F1,     "k1", "F3"},
	{GDK_KP_F1,  "k1", "F3"},
	{GDK_F2,     "k2", "F4"},
	{GDK_KP_F2,  "k2", "F4"},
	{GDK_F3,     "k3", "F5"},
	{GDK_KP_F3,  "k3", "F5"},
	{GDK_F4,     "k4", "F6"},
	{GDK_KP_F4,  "k4", "F6"},
	{GDK_F5,     "k5", "F7"},
	{GDK_F6,     "k6", "F8"},
	{GDK_F7,     "k7", "F9"},
	{GDK_F8,     "k8", "FA"},
	{GDK_F9,     "k9", "FB"},
	{GDK_F10,    "k;", "FC"},
	{GDK_F11,    "F1", NULL},
	{GDK_F12,    "F2", NULL},

	{GDK_F13,    "F3", NULL},
	{GDK_F14,    "F4", NULL},
	{GDK_F15,    "F5", NULL},
	{GDK_F16,    "F6", NULL},
	{GDK_F17,    "F7", NULL},
	{GDK_F18,    "F8", NULL},
	{GDK_F19,    "F9", NULL},
	{GDK_F20,    "FA", NULL},
	{GDK_F21,    "FB", NULL},
	{GDK_F22,    "FC", NULL},
	{GDK_F23,    "FD", NULL},
	{GDK_F24,    "FE", NULL},
	{GDK_F25,    "FF", NULL},
	{GDK_F26,    "FG", NULL},
	{GDK_F27,    "FH", NULL},
	{GDK_F28,    "FI", NULL},
	{GDK_F29,    "FJ", NULL},
	{GDK_F30,    "FK", NULL},
	{GDK_F31,    "FL", NULL},
	{GDK_F32,    "FM", NULL},
	{GDK_F33,    "FN", NULL},
	{GDK_F34,    "FO", NULL},
	{GDK_F35,    "FP", NULL},
};

/* Read and handle a keypress event. */
static gint
vte_terminal_key_press(GtkWidget *widget, GdkEventKey *event)
{
	VteTerminal *terminal;
	GdkModifierType modifiers;
	const PangoFontDescription *rofontdesc;
	PangoFontDescription *fontdesc;
	struct vte_termcap *termcap;
	const char *tterm;
	unsigned char *normal = NULL;
	gssize normal_length = 0;
	int i;
	unsigned char *special = NULL, *specialmods = NULL;
	struct termios tio;
	struct timeval tv;
	struct timezone tz;
	gboolean scrolled = FALSE, steal = FALSE, modifier = FALSE;

	g_return_val_if_fail(widget != NULL, FALSE);
	g_return_val_if_fail(VTE_IS_TERMINAL(widget), FALSE);
	terminal = VTE_TERMINAL(widget);

	/* If it's a keypress, record that we got the event, in case the
	 * input method takes the event from us. */
	if (event->type == GDK_KEY_PRESS) {
		if (gettimeofday(&tv, &tz) == 0) {
			terminal->pvt->last_keypress_time =
				(tv.tv_sec * 1000) + (tv.tv_usec / 1000);
		}
		/* Read the modifiers. */
		if (gdk_event_get_state((GdkEvent*)event,
					&modifiers) == FALSE) {
			modifiers = 0;
		}
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_EVENTS)) {
			fprintf(stderr, "Keypress, modifiers=%d, keyval=%d, "
				"string=`%s'.\n", modifiers, event->keyval,
				event->string);
		}
#endif
		/* Determine if this is just a modifier key. */
		switch (event->keyval) {
			case GDK_Alt_L:
			case GDK_Alt_R:
			case GDK_Caps_Lock:
			case GDK_Control_L:
			case GDK_Control_R:
			case GDK_Eisu_Shift:
			case GDK_Hyper_L:
			case GDK_Hyper_R:
			case GDK_ISO_First_Group_Lock:
			case GDK_ISO_Group_Lock:
			case GDK_ISO_Group_Shift:
			case GDK_ISO_Last_Group_Lock:
			case GDK_ISO_Level3_Lock:
			case GDK_ISO_Level3_Shift:
			case GDK_ISO_Lock:
			case GDK_ISO_Next_Group_Lock:
			case GDK_ISO_Prev_Group_Lock:
			case GDK_Kana_Lock:
			case GDK_Kana_Shift:
			case GDK_Meta_L:
			case GDK_Meta_R:
			case GDK_Num_Lock:
			case GDK_Scroll_Lock:
			case GDK_Shift_L:
			case GDK_Shift_Lock:
			case GDK_Shift_R:
			case GDK_Super_L:
			case GDK_Super_R:
				modifier = TRUE;
				break;
			default:
				modifier = FALSE;
				break;
		}
		/* Unless it's a modifier key, hide the pointer. */
		if (!modifier) {
			vte_terminal_set_pointer_visible(terminal, FALSE);
		}
		/* Determine if this is a key we want to steal. */
		switch (event->keyval) {
			case GDK_KP_Add:
			case GDK_KP_Subtract:
				if (modifiers & GDK_SHIFT_MASK) {
					steal = TRUE;
				}
				break;
			default:
				break;
		}
	}

	/* Let the input method at this one first. */
	if (!steal) {
		if (gtk_im_context_filter_keypress(terminal->pvt->im_context,
						   event)) {
			return TRUE;
		}
	}

	/* Now figure out what to send to the child. */
	if (event->type == GDK_KEY_PRESS) {
		/* Map the key to a sequence name if we can. */
		switch (event->keyval) {
			case GDK_BackSpace:
				switch (terminal->pvt->backspace_binding) {
					case VTE_ERASE_ASCII_BACKSPACE:
						normal = g_strdup("");
						normal_length = 1;
						break;
					case VTE_ERASE_ASCII_DELETE:
						normal = g_strdup("");
						normal_length = 1;
						break;
					case VTE_ERASE_DELETE_SEQUENCE:
						special = "kD";
						break;
					/* Use the tty's erase character. */
					case VTE_ERASE_AUTO:
					default:
						if (tcgetattr(terminal->pvt->pty_master,
							      &tio) != -1) {
							normal = g_strdup_printf("%c",
										 tio.c_cc[VERASE]);
							normal_length = 1;
						}
						break;
				}
				break;
			case GDK_KP_Delete:
			case GDK_Delete:
				switch (terminal->pvt->delete_binding) {
					case VTE_ERASE_ASCII_BACKSPACE:
						normal = g_strdup("");
						normal_length = 1;
						break;
					case VTE_ERASE_ASCII_DELETE:
						normal = g_strdup("");
						normal_length = 1;
						break;
					case VTE_ERASE_DELETE_SEQUENCE:
					case VTE_ERASE_AUTO:
					default:
						special = "kD";
						break;
				}
				break;
			case GDK_KP_Insert:
			case GDK_Insert:
				if (modifiers & GDK_SHIFT_MASK) {
					vte_terminal_paste(terminal,
							   GDK_SELECTION_PRIMARY);
				} else {
					special = "kI";
				}
				break;
			case GDK_KP_Home:
			case GDK_Home:
				special = "kh";
				break;
			case GDK_KP_End:
			case GDK_End:
				special = "@7";
				break;
			case GDK_F1:
			case GDK_F2:
			case GDK_F3:
			case GDK_F4:
			case GDK_F5:
			case GDK_F6:
			case GDK_F7:
			case GDK_F8:
			case GDK_F9:
			case GDK_F10:
			case GDK_F11:
			case GDK_F12:
			case GDK_F13:
			case GDK_F14:
			case GDK_F15:
			case GDK_F16:
			case GDK_F17:
			case GDK_F18:
			case GDK_F19:
			case GDK_F20:
			case GDK_F21:
			case GDK_F22:
			case GDK_F23:
			case GDK_F24:
			case GDK_F25:
			case GDK_F26:
			case GDK_F27:
			case GDK_F28:
			case GDK_F29:
			case GDK_F30:
			case GDK_F31:
			case GDK_F32:
			case GDK_F33:
			case GDK_F34:
			case GDK_F35:
				for (i = 0;
				     i < G_N_ELEMENTS(vte_keysym_map);
				     i++) {
					if (vte_keysym_map[i].keyval == event->keyval) {
						if (terminal->pvt->fkey == VTE_FKEY_VT220) {
							if ((modifiers & GDK_CONTROL_MASK) && vte_keysym_map[i].vt_ctrl_special) {
								special = vte_keysym_map[i].vt_ctrl_special;
							} else {
								special = vte_keysym_map[i].special;
							}
						}
						if (terminal->pvt->fkey == VTE_FKEY_SUNPC) {
							special = vte_keysym_map[i].special;
							i = 0;
							if (modifiers & GDK_CONTROL_MASK) {
								i += 4;
							}
							if (modifiers & GDK_MOD1_MASK) {
								i += 2;
							}
							if (modifiers & GDK_SHIFT_MASK) {
								i += 1;
							}
							if (i > 0) {
								specialmods = g_strdup_printf("%d", i + 1);
							}
						}
						break;
					}
				}
				break;
			/* Cursor keys. */
			case GDK_KP_Up:
			case GDK_Up:
				special = "ku";
				break;
			case GDK_KP_Down:
			case GDK_Down:
				special = "kd";
				break;
			case GDK_KP_Left:
			case GDK_Left:
				special = "kl";
				break;
			case GDK_KP_Right:
			case GDK_Right:
				special = "kr";
				break;
			case GDK_KP_Page_Up:
			case GDK_Page_Up:
				if (modifiers & GDK_SHIFT_MASK) {
					vte_terminal_scroll_pages(terminal, -1);
					scrolled = TRUE;
				} else {
					special = "kP";
				}
				break;
			case GDK_KP_Page_Down:
			case GDK_Page_Down:
				if (modifiers & GDK_SHIFT_MASK) {
					vte_terminal_scroll_pages(terminal, 1);
					scrolled = TRUE;
				} else {
					special = "kN";
				}
				break;
			case GDK_KP_Tab:
			case GDK_Tab:
				if (modifiers & GDK_SHIFT_MASK) {
					special = "kB";
				} else {
					normal = g_strdup("\t");
					normal_length = 1;
				}
				break;
			case GDK_KP_Space:
			case GDK_space:
				if (modifiers & GDK_CONTROL_MASK) {
					/* Ctrl-Space sends NUL?!?  Madness! */
					normal = g_strdup("");
					normal_length = 1;
				} else {
					normal = g_strdup(" ");
					normal_length = 1;
				}
				break;
			/* Let Shift +/- tweak the font, like XTerm does. */
			case GDK_KP_Add:
			case GDK_KP_Subtract:
				if ((modifiers & GDK_SHIFT_MASK) &&
				    terminal->pvt->xterm_font_tweak) {
					rofontdesc = vte_terminal_get_font(terminal);
					if (rofontdesc != NULL) {
						fontdesc = pango_font_description_copy(rofontdesc);
						i = pango_font_description_get_size(fontdesc);
						if (event->keyval == GDK_KP_Add) {
							i += PANGO_SCALE;
						}
						if (event->keyval == GDK_KP_Subtract) {
							i = MAX(PANGO_SCALE,
								i - PANGO_SCALE);
						}
#ifdef VTE_DEBUG
						if (vte_debug_on(VTE_DEBUG_MISC)) {
							fprintf(stderr, "Changing font size from %d to %d.\n",
								pango_font_description_get_size(fontdesc), i);
						}
#endif
						pango_font_description_set_size(fontdesc, i);
						vte_terminal_set_font(terminal, fontdesc);
						pango_font_description_free(fontdesc);
					}
#ifdef VTE_DEBUG
					if (vte_debug_on(VTE_DEBUG_MISC)) {
						if (rofontdesc == NULL) {
							fprintf(stderr, "Font can't be modified.\n");
						}
					}
#endif
					break;
				}
			/* The default is to just send the string. */
			default:
				if (event->string != NULL) {
					normal = g_strdup(event->string);
					normal_length = strlen(normal);
					if (modifiers & GDK_CONTROL_MASK) {
						/* Replace characters which have
						 * "control" counterparts with
						 * those counterparts. */
						for (i = 0;
						     i < normal_length;
						     i++) {
							if ((normal[i] > 64) &&
							    (normal[i] < 97)) {
								normal[i] ^= 0x40;
							}
						}
					}
				}
				break;
		}
		/* If we got normal characters, send them to the child. */
		if (normal != NULL) {
			if (terminal->pvt->alt_sends_escape &&
			    (normal_length > 0) &&
			    (modifiers & GDK_MOD1_MASK)) {
				vte_terminal_feed_child(terminal, "", 1);
			}
			vte_terminal_feed_child(terminal,
						normal, normal_length);
			g_free(normal);
		} else
		/* If the key maps to characters, send them to the child. */
		if (special != NULL) {
			termcap = terminal->pvt->termcap;
			tterm = terminal->pvt->emulation;
			normal = vte_termcap_find_string_length(termcap,
								tterm,
								special,
								&normal_length);
			special = g_strdup_printf(normal, 1);
			if (specialmods) {
				i = strlen(special);
				if ((i > 0) && (special[i - 1] == '~')) {
					/* Insert the modifier before the
					 * last character, which is '~'. */
					special = g_realloc(special,
							    i + strlen(specialmods) + 2);
					special[i - 1] = ';';
					strcpy(special + i, specialmods);
					strcat(special + i + strlen(specialmods), "~");
				}
				g_free(specialmods);
			}
			vte_terminal_feed_child(terminal,
						special, strlen(special));
			g_free(special);
			g_free(normal);
		}
		/* Keep the cursor on-screen. */
		if (!scrolled && !modifier &&
		    terminal->pvt->scroll_on_keystroke) {
			vte_terminal_scroll_to_bottom(terminal);
		}
		return TRUE;
	}
	return FALSE;
}

static gboolean
vte_terminal_key_release(GtkWidget *widget, GdkEventKey *event)
{
	VteTerminal *terminal;

	terminal = VTE_TERMINAL(widget);

	return gtk_im_context_filter_keypress(terminal->pvt->im_context, event);
}

/* Check if a particular character is part of a "word" or not. */
gboolean
vte_terminal_is_word_char(VteTerminal *terminal, gunichar c)
{
	int i;
	VteWordCharRange *range;
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), FALSE);
	if (terminal->pvt->word_chars == NULL) {
		return FALSE;
	}
	for (i = 0; i < terminal->pvt->word_chars->len; i++) {
		range = &g_array_index(terminal->pvt->word_chars,
				       VteWordCharRange,
				       i);
		if ((c >= range->start) && (c <= range->end)) {
			return TRUE;
		}
	}
	return FALSE;
}

/* Check if the characters in the given block are in the same class (word vs.
 * non-word characters). */
static gboolean
vte_uniform_class(VteTerminal *terminal, long row, long scol, long ecol)
{
	struct vte_charcell *pcell = NULL;
	long col;
	gboolean word_char;
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), FALSE);
	if ((pcell = vte_terminal_find_charcell(terminal, scol, row)) != NULL) {
		word_char = vte_terminal_is_word_char(terminal, pcell->c);
		for (col = scol + 1; col <= ecol; col++) {
			pcell = vte_terminal_find_charcell(terminal, col, row);
			if (pcell == NULL) {
				return FALSE;
			}
			if (word_char != vte_terminal_is_word_char(terminal,
								   pcell->c)) {
				return FALSE;
			}
		}
		return TRUE;
	}
	return FALSE;
}

static gboolean
vte_cell_is_between(long col, long row,
		    long acol, long arow, long bcol, long brow,
		    gboolean inclusive)
{
	long t;
	/* Sort endpoints on the same row properly. */
	if (arow == brow) {
		if (acol > bcol) {
			t = acol;
			acol = bcol;
			bcol = t;
		}
	} else
	if (arow > brow) {
		t = arow;
		arow = brow;
		brow = t;
		t = acol;
		acol = bcol;
		bcol = t;
	}
	/* No zero-length between allowed. */
	if ((row == arow) && (row == brow) && (col == acol) && (col == bcol)) {
		return FALSE;
	}
	/* A cell is between two points if it's on a line after the
	 * specified area starts, or before the line where it ends, 
	 * or any of the lines in between. */
	if ((row > arow) && (row < brow)) {
		return TRUE;
	} else
	/* It's also between the two points if they're on the same row
	 * the cell lies between the start and end columns (which may not
	 * be in the more obvious of two possible orders). */
	if ((row == arow) && (row == brow)) {
		if (col >= acol) {
			if (col < bcol) {
				return TRUE;
			} else
			if ((col == bcol) && inclusive) {
				return TRUE;
			}
		}
	} else
	/* It's also "between" if it's on the line where the area starts and
	 * at or after the start column, or on the line where the area ends and
	 * before the end column. */
	if ((row == arow) && (col >= acol)) {
		return TRUE;
	} else
	if (row == brow) {
		if (col < bcol) {
			return TRUE;
		} else
		if ((col == bcol) && inclusive) {
			return TRUE;
		}
	}
	return FALSE;
}

/* Check if a cell is selected or not. */
static gboolean
vte_cell_is_selected(VteTerminal *terminal, long col, long row)
{
	long scol, ecol;

	/* If there's nothing selected, it's an easy question to answer. */
	if (!terminal->pvt->has_selection) {
		return FALSE;
	}

	/* Sort the two columns, for the cases where the selection is
	 * entirely within a single line. */
	scol = MIN(terminal->pvt->selection_start.x,
		   terminal->pvt->selection_end.x);
	ecol = MAX(terminal->pvt->selection_start.x,
		   terminal->pvt->selection_end.x);

	switch (terminal->pvt->selection_type) {
		case selection_type_char:
			/* A cell is selected if it's between the start and
			 * endpoints of the selection. */
			if (vte_cell_is_between(col, row,
						terminal->pvt->selection_start.x,
						terminal->pvt->selection_start.y,
						terminal->pvt->selection_end.x,
						terminal->pvt->selection_end.y,
						FALSE)) {
				return TRUE;
			}
			break;
		case selection_type_word:
			/* A cell is selected if it's on the line where the
			 * selected area starts, or the line where it ends,
			 * or any of the lines in between. */
			if ((row > terminal->pvt->selection_start.y) &&
			    (row < terminal->pvt->selection_end.y)) {
				return TRUE;
			} else
			/* It's also selected if the selection is confined to
			 * one line and the character lies between the start
			 * and end columns (which may not be in the more obvious
			 * of two possible orders). */
			if ((terminal->pvt->selection_start.y == row) &&
			    (terminal->pvt->selection_end.y == row)) {
				if ((col >= scol) && (col <= ecol)) {
					return TRUE;
				} else
				/* If the character is before the beginning of
				 * the region, it's also selected if it and
				 * everything else in between belongs to the
				 * same character class. */
				if (col < scol) {
					if (vte_uniform_class(terminal,
							      row,
							      col,
							      scol)) {
						return TRUE;
					}
				} else
				if (col > ecol) {
					if (vte_uniform_class(terminal,
							      row,
							      ecol,
							      col)) {
						return TRUE;
					}
				}
			} else
			/* It's also selected if it's on the line where the
			 * selected area starts and it's after the start column,
			 * or on the line where the selection ends, after the
			 * last selected column. */
			if (row == terminal->pvt->selection_start.y) {
				if (col >= terminal->pvt->selection_start.x) {
					return TRUE;
				} else
				if (vte_uniform_class(terminal,
						      row,
						      col,
						      terminal->pvt->selection_start.x)) {
					return TRUE;
				}
			} else
			if (row == terminal->pvt->selection_end.y) {
				if (col < terminal->pvt->selection_end.x) {
					return TRUE;
				} else
				if (vte_uniform_class(terminal,
						      row,
						      terminal->pvt->selection_end.x,
						      col)) {
					return TRUE;
				}
			}
			break;
		case selection_type_line:
			/* A cell is selected if it's on the line where the
			 * selected area starts, or the line where it ends,
			 * or any of the lines in between. */
			if ((row >= terminal->pvt->selection_start.y) &&
			    (row <= terminal->pvt->selection_end.y)) {
				return TRUE;
			}
			break;
		default:
			break;
	}
	return FALSE;
}

/* Once we get text data, actually paste it in. */
static void
vte_terminal_paste_cb(GtkClipboard *clipboard, const gchar *text, gpointer data)
{
	VteTerminal *terminal;
	g_return_if_fail(VTE_IS_TERMINAL(data));
	terminal = VTE_TERMINAL(data);
	if (text != NULL) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_SELECTION)) {
			fprintf(stderr, "Pasting %d UTF-8 bytes.\n",
				strlen(text));
		}
#endif
		vte_terminal_im_reset(terminal);
		vte_terminal_send(terminal, "UTF-8", text, strlen(text));
	}
}

/* Send a button down or up notification. */
static void
vte_terminal_send_mouse_button_internal(VteTerminal *terminal,
					int button,
					double x, double y,
					GdkModifierType modifiers)
{
	unsigned char cb = 0, cx = 0, cy = 0;
	char buf[LINE_MAX];

	g_return_if_fail(VTE_IS_TERMINAL(terminal));

	/* Encode the button information in cb. */
	switch (button) {
		case 0:			/* Release/no buttons. */
			cb = 3;
			break;
		case 1:			/* Left. */
			cb = 0;
			break;
		case 2:			/* Middle. */
			cb = 1;
			break;
		case 3:			/* Right. */
			cb = 2;
			break;
		case 4:
			cb = 64;	/* Scroll up. FIXME: check */
			break;
		case 5:
			cb = 65;	/* Scroll down. FIXME: check */
			break;
	}
	cb += 32; /* 32 for normal */

	/* Encode the modifiers. */
	if (modifiers & GDK_SHIFT_MASK) {
		cb |= 4;
	}
	if (modifiers & GDK_MOD1_MASK) {
		cb |= 8;
	}
	if (modifiers & GDK_CONTROL_MASK) {
		cb |= 16;
	}

	/* Encode the cursor coordinates. */
	cx = 32 + 1 + (x / terminal->char_width);
	cy = 32 + 1 + (y / terminal->char_height);

	/* Send the event to the child. */
	snprintf(buf, sizeof(buf), "%sM%c%c%c", VTE_CAP_CSI, cb, cx, cy);
	vte_terminal_feed_child(terminal, buf, strlen(buf));
}

/* Send a mouse button click/release notification. */
static void
vte_terminal_send_mouse_button(VteTerminal *terminal, GdkEventButton *event)
{
	GdkModifierType modifiers;

	/* Read the modifiers. */
	if (gdk_event_get_state((GdkEvent*)event, &modifiers) == FALSE) {
		modifiers = 0;
	}

	/* Encode the parameters and send them to the app. */
	vte_terminal_send_mouse_button_internal(terminal,
						(event->type == GDK_BUTTON_PRESS) ?
						event->button : 0,
						event->x - VTE_PAD_WIDTH,
						event->y - VTE_PAD_WIDTH,
						modifiers);
}

/* Send a mouse motion notification. */
static void
vte_terminal_send_mouse_drag(VteTerminal *terminal, GdkEventMotion *event)
{
	unsigned char cb = 0, cx = 0, cy = 0;
	char buf[LINE_MAX];
	GdkModifierType modifiers;

	g_return_if_fail(VTE_IS_TERMINAL(terminal));

	/* First determine if we even want to send notification. */
	if (!terminal->pvt->mouse_cell_motion_tracking &&
	    !terminal->pvt->mouse_all_motion_tracking) {
		return;
	}
	if (terminal->pvt->mouse_cell_motion_tracking) {
		if (((event->x - VTE_PAD_WIDTH) / terminal->char_width ==
		     terminal->pvt->mouse_last_x / terminal->char_width) &&
		    ((event->y - VTE_PAD_WIDTH) / terminal->char_height ==
		     terminal->pvt->mouse_last_y / terminal->char_height)) {
			return;
		}
	}

	/* Read the modifiers. */
	if (gdk_event_get_state((GdkEvent*)event, &modifiers) == FALSE) {
		modifiers = 0;
	}

	/* Encode the modifiers. */
	if (modifiers & GDK_SHIFT_MASK) {
		cb |= 4;
	}
	if (modifiers & GDK_MOD1_MASK) {
		cb |= 8;
	}
	if (modifiers & GDK_CONTROL_MASK) {
		cb |= 16;
	}

	/* Encode which button we're being dragged with. */
	switch (terminal->pvt->mouse_last_button) {
		case 1:
			cb = 0;
			break;
		case 2:
			cb = 1;
			break;
		case 3:
			cb = 2;
			break;
		case 4:
			cb = 64;	/* FIXME: check */
			break;
		case 5:
			cb = 65;	/* FIXME: check */
			break;
	}
	cb += 64; /* 32 for normal, 32 for movement */

	/* Encode the cursor coordinates. */
	cx = 32 + 1 + ((event->x - VTE_PAD_WIDTH) / terminal->char_width);
	cy = 32 + 1 + ((event->y - VTE_PAD_WIDTH) / terminal->char_height);

	/* Send the event to the child. */
	snprintf(buf, sizeof(buf), "%sM%c%c%c", VTE_CAP_CSI, cb, cx, cy);
	vte_terminal_feed_child(terminal, buf, strlen(buf));
}

/* Clear all match hilites. */
static void
vte_terminal_match_hilite_clear(VteTerminal *terminal)
{
	long srow, scolumn, erow, ecolumn;
	srow = terminal->pvt->match_start.row;
	scolumn = terminal->pvt->match_start.column;
	erow = terminal->pvt->match_end.row;
	ecolumn = terminal->pvt->match_end.column;
	if ((srow != erow) || (scolumn != ecolumn)) {
		terminal->pvt->match_start.row = 0;
		terminal->pvt->match_start.column = 0;
		terminal->pvt->match_end.row = 0;
		terminal->pvt->match_end.column = 0;
		vte_invalidate_cells(terminal,
				     0,
				     terminal->column_count,
				     terminal->pvt->screen->scroll_delta + srow,
				     erow - srow + 1);
	}
}

/* Update the hilited text if the pointer has moved to a new character cell. */
static void
vte_terminal_match_hilite(VteTerminal *terminal, double x, double y)
{
	int start, end;
	long rows, rowe;
	char *match;
	struct vte_char_attributes *attr;
	VteScreen *screen;
	/* If the pointer hasn't moved to another character cell, then we
	 * need do nothing. */
	if ((x / terminal->char_width ==
	     terminal->pvt->mouse_last_x / terminal->char_width) &&
	    (y / terminal->char_height ==
	     terminal->pvt->mouse_last_y / terminal->char_height)) {
		return;
	}
	/* Check for matches. */
	match = vte_terminal_match_check_internal(terminal,
						  floor(x) / terminal->char_width,
						  floor(y) / terminal->char_height,
						  NULL,
						  &start,
						  &end);
	/* If there are no matches, repaint what we had matched before. */
	if (match == NULL) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_EVENTS)) {
			fprintf(stderr, "No matches.\n");
		}
#endif
		vte_terminal_match_hilite_clear(terminal);
	} else {
		screen = terminal->pvt->screen;
		/* Save the old hilite area. */
		rows = terminal->pvt->match_start.row;
		rowe = terminal->pvt->match_end.row;
		/* Read the new locations. */
		attr = &g_array_index(terminal->pvt->match_attributes,
				      struct vte_char_attributes,
				      start);
		terminal->pvt->match_start.row = attr->row;
		terminal->pvt->match_start.column = attr->column;
		attr = &g_array_index(terminal->pvt->match_attributes,
				      struct vte_char_attributes,
				      end);
		terminal->pvt->match_end.row = attr->row;
		terminal->pvt->match_end.column = attr->column;
		/* Repaint the newly-hilited area. */
		vte_invalidate_cells(terminal,
				     0,
				     terminal->column_count,
				     screen->scroll_delta +
				     terminal->pvt->match_start.row,
				     terminal->pvt->match_end.row -
				     terminal->pvt->match_start.row + 1);
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_EVENTS)) {
			fprintf(stderr, "Matched (%ld,%ld) to (%ld,%ld).\n",
				terminal->pvt->match_start.column,
				screen->scroll_delta +
				terminal->pvt->match_start.row,
				terminal->pvt->match_end.column,
				screen->scroll_delta +
				terminal->pvt->match_end.row);
		}
#endif
		/* Repaint what used to be hilited, if anything. */
		vte_invalidate_cells(terminal,
				     0,
				     terminal->column_count,
				     screen->scroll_delta + rows,
				     rowe - rows + 1);
	}
}

/* Recalculate the start- and endpoints of the selected text, using the
 * selection origin and "last" coordinate sets. */
static void
vte_terminal_selection_compute(VteTerminal *terminal)
{
	struct {
		long x, y;
	} origin, last, start, end;
	long delta, width, height;

	g_return_if_fail(VTE_IS_TERMINAL(terminal));

	width = terminal->char_width;
	height = terminal->char_height;
	origin.x = (terminal->pvt->selection_origin.x + width / 2) / width;
	origin.y = (terminal->pvt->selection_origin.y) / height;
	last.x = (terminal->pvt->selection_last.x + width / 2) / width;
	last.y = (terminal->pvt->selection_last.y) / height;
	start.x = start.y = end.x = end.y = 0;

	if (last.y > origin.y) {
		start.x = origin.x;
		start.y = origin.y;
		end.x = last.x;
		end.y = last.y;
	} else
	if (last.y < origin.y) {
		start.x = last.x;
		start.y = last.y;
		end.x = origin.x;
		end.y = origin.y;
	} else
	/* last.y == origin.y */
	if (last.x > origin.x) {
		start.x = origin.x;
		start.y = origin.y;
		end.x = last.x;
		end.y = last.y;
	} else {
		start.x = last.x;
		start.y = last.y;
		end.x = origin.x;
		end.y = origin.y;
	}

	delta = terminal->pvt->screen->scroll_delta;

	terminal->pvt->selection_start.x = start.x;
	terminal->pvt->selection_start.y = start.y + delta;
	terminal->pvt->selection_end.x = end.x;
	terminal->pvt->selection_end.y = end.y + delta;
}

/* Read and handle a motion event. */
static gint
vte_terminal_motion_notify(GtkWidget *widget, GdkEventMotion *event)
{
	VteTerminal *terminal;
	GdkModifierType modifiers;
	long top, height;

	g_return_val_if_fail(VTE_IS_TERMINAL(widget), FALSE);
	terminal = VTE_TERMINAL(widget);

	/* Show the cursor. */
	vte_terminal_set_pointer_visible(terminal, TRUE);

	/* Read the modifiers. */
	if (gdk_event_get_state((GdkEvent*)event, &modifiers) == FALSE) {
		modifiers = 0;
	}
	/* Handle a drag event if we're running a mouse-aware application. */
	if ((terminal->pvt->mouse_last_button != 0) &&
	    (terminal->pvt->mouse_send_xy_on_click ||
	     terminal->pvt->mouse_send_xy_on_button ||
	     terminal->pvt->mouse_hilite_tracking ||
	     terminal->pvt->mouse_cell_motion_tracking ||
	     terminal->pvt->mouse_all_motion_tracking) &&
	    ((modifiers & GDK_SHIFT_MASK) == 0)) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_EVENTS)) {
			fprintf(stderr, "Mousing drag.\n");
		}
#endif
		vte_terminal_send_mouse_drag(terminal, event);
	} else
	if (terminal->pvt->mouse_last_button == 1) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_EVENTS)) {
			fprintf(stderr, "Drag.\n");
		}
#endif
		/* If we delayed resetting selection, reset here. */
		if (terminal->pvt->start_selection) {
			vte_terminal_deselect_all(terminal);
			terminal->pvt->selection_origin.x =
				terminal->pvt->selection_delayed.x;
			terminal->pvt->selection_origin.y =
				terminal->pvt->selection_delayed.y;
			terminal->pvt->selection_type = selection_type_char;
		}
		terminal->pvt->has_selection = TRUE;

		top = MIN(terminal->pvt->selection_last.y,
			  event->y - VTE_PAD_WIDTH) /
		      terminal->char_height;
		height = (MAX(terminal->pvt->selection_last.y,
			      event->y - VTE_PAD_WIDTH) /
			  terminal->char_height) - top + 1;

		terminal->pvt->selection_last.x = event->x - VTE_PAD_WIDTH;
		terminal->pvt->selection_last.y = event->y - VTE_PAD_WIDTH;

		vte_terminal_selection_compute(terminal);

#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_EVENTS)) {
			fprintf(stderr, "selection is (%ld,%ld) to (%ld,%ld)\n",
				terminal->pvt->selection_start.x,
				terminal->pvt->selection_start.y,
				terminal->pvt->selection_end.x,
				terminal->pvt->selection_end.y);
			fprintf(stderr, "repainting rows %ld to %ld\n",
				top, top + height);
		}
#endif
		vte_invalidate_cells(terminal, 0, terminal->column_count,
				     top + terminal->pvt->screen->scroll_delta,
				     height);

		vte_terminal_emit_selection_changed (terminal);
	} else {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_EVENTS)) {
			fprintf(stderr, "Mouse move.\n");
		}
#endif
	}

	/* Hilite any matches. */
	vte_terminal_match_hilite(terminal,
				  event->x - VTE_PAD_WIDTH,
				  event->y - VTE_PAD_WIDTH);

	/* Save the pointer coordinates for later use. */
	terminal->pvt->mouse_last_x = event->x - VTE_PAD_WIDTH;
	terminal->pvt->mouse_last_y = event->y - VTE_PAD_WIDTH;

	return FALSE;
}

/* Note that the clipboard has cleared. */
static void
vte_terminal_clear_cb(GtkClipboard *clipboard, gpointer owner)
{
	VteTerminal *terminal;
	g_return_if_fail(VTE_IS_TERMINAL(owner));
	terminal = VTE_TERMINAL(owner);
	if (terminal->pvt->has_selection) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_SELECTION)) {
			fprintf(stderr, "Lost selection.\n",
				strlen(terminal->pvt->selection));
		}
#endif
		vte_terminal_deselect_all(terminal);
	}
}

/* Supply the selected text to the clipboard. */
static void
vte_terminal_copy_cb(GtkClipboard *clipboard, GtkSelectionData *data,
		     guint info, gpointer owner)
{
	VteTerminal *terminal;
	g_return_if_fail(VTE_IS_TERMINAL(owner));
	terminal = VTE_TERMINAL(owner);
	if (terminal->pvt->selection != NULL) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_SELECTION)) {
			int i;
			fprintf(stderr, "Setting selection (%d UTF-8 bytes.)\n",
				strlen(terminal->pvt->selection));
			for (i = 0; terminal->pvt->selection[i] != '\0'; i++) {
				fprintf(stderr, "0x%04x\n",
					terminal->pvt->selection[i]);
			}
		}
#endif
		gtk_selection_data_set_text(data, terminal->pvt->selection, -1);
	}
}

/* Extract a view of the widget as if we were going to copy it. */
char *
vte_terminal_get_text(VteTerminal *terminal,
		      gboolean(*is_selected)(VteTerminal *, long, long),
		      GArray *attributes)
{
	long x, y, spaces;
	VteScreen *screen;
	struct vte_charcell *pcell;
	GString *string;
	struct vte_char_attributes attr;

	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), NULL);
	g_return_val_if_fail(is_selected != NULL, NULL);
	screen = terminal->pvt->screen;

	string = g_string_new("");
	memset(&attr, 0, sizeof(attr));

	for (y = screen->scroll_delta;
	     y < terminal->row_count + screen->scroll_delta;
	     y++) {
		x = 0;
		spaces = 0;
		attr.row = y - screen->scroll_delta;
		do {
			pcell = vte_terminal_find_charcell(terminal, x, y);
			if (is_selected(terminal, x, y)) {
				if (pcell == NULL) {
					/* If there are no more cells on this
					 * line, and we've hit the right margin,
					 * add a newline. */
					if ((x < terminal->column_count - 1) ||
					    (spaces > 0)) {
						string = g_string_append_c(string, '\n');
					}
					break;
				} else
				if (pcell->columns == 0) {
					/* Ignore this padding cell. */
				} else
				if ((pcell->c == 0) ||
				    (g_unichar_isspace(pcell->c))) {
					/* Count this in case there's something
					 * to the right of it. */
					spaces++;
				} else {
					/* Use the attributes for this character. */
					attr.fore.red =
						terminal->pvt->palette[pcell->fore].red;
					attr.fore.green =
						terminal->pvt->palette[pcell->fore].green;
					attr.fore.blue =
						terminal->pvt->palette[pcell->fore].blue;
					attr.back.red =
						terminal->pvt->palette[pcell->back].red;
					attr.back.green =
						terminal->pvt->palette[pcell->back].green;
					attr.back.blue =
						terminal->pvt->palette[pcell->back].blue;
					attr.underline = pcell->underline;
					attr.alternate = pcell->alternate;
					attr.column = x;
					/* Stuff any saved spaces in. */
					while (spaces > 0) {
						string = g_string_append_c(string, ' ');
                                                spaces--;
					}
					/* Stuff the character in this cell. */
					string = g_string_append_unichar(string, pcell->c);
				}
			}
			/* If we added a character to the string, record its
			 * attributes, one per byte. */
			if (attributes) {
				while (attributes->len < string->len) {
					g_array_append_val(attributes, attr);
				}
			}
			x++;
		} while (pcell != NULL);
		/* If we broke out of the loop, there might be more characters
		 * with missing attributes. */
		if (attributes) {
			while (attributes->len < string->len) {
				g_array_append_val(attributes, attr);
			}
		}
	}
	if (attributes) {
		g_assert(string->len == attributes->len);
	}
	return g_string_free(string, FALSE);
}
/* Tell the caller where the cursor is, in screen coordinates. */
void
vte_terminal_get_cursor_position(VteTerminal *terminal,
				 long *column, long *row)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	*column = terminal->pvt->screen->cursor_current.col;
	*row    = terminal->pvt->screen->cursor_current.row -
		  terminal->pvt->screen->insert_delta;
}

/* Place the selected text onto the clipboard.  Do this asynchronously so that
 * we get notified when the selection we placed on the clipboard is replaced. */
static void
vte_terminal_copy(VteTerminal *terminal, GdkAtom board)
{
	GtkClipboard *clipboard;
	GtkTargetEntry targets[] = {
		{"UTF8_STRING", 0, 0},
		{"COMPOUND_TEXT", 0, 0},
		{"TEXT", 0, 0},
		{"STRING", 0, 0},
	};

	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	clipboard = gtk_clipboard_get(board);

	/* Chuck old selected text and retrieve the newly-selected text. */
	if (terminal->pvt->selection != NULL) {
		g_free(terminal->pvt->selection);
	}
	terminal->pvt->selection = vte_terminal_get_text(terminal,
							 vte_cell_is_selected,
							 NULL);

	/* Place the text on the clipboard. */
	if (terminal->pvt->selection != NULL) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_SELECTION)) {
			fprintf(stderr, "Assuming ownership of selection.\n");
		}
#endif
		gtk_clipboard_set_with_owner(clipboard,
					     targets,
					     G_N_ELEMENTS(targets),
					     vte_terminal_copy_cb,
					     vte_terminal_clear_cb,
					     G_OBJECT(terminal));
	}
}

/* Paste from the given clipboard. */
static void
vte_terminal_paste(VteTerminal *terminal, GdkAtom board)
{
	GtkClipboard *clipboard;
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	clipboard = gtk_clipboard_get(board);
	if (clipboard != NULL) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_SELECTION)) {
			fprintf(stderr, "Requesting clipboard contents.\n");
		}
#endif
		gtk_clipboard_request_text(clipboard,
					   vte_terminal_paste_cb,
					   terminal);
	}
}

/* Read and handle a pointing device buttonpress event. */
static gint
vte_terminal_button_press(GtkWidget *widget, GdkEventButton *event)
{
	VteTerminal *terminal;
	long height, width, delta;
	GdkModifierType modifiers;
	gboolean ret = FALSE;
	long cellx, celly;
	struct selection_event_coords *start, *end;

	g_return_val_if_fail(VTE_IS_TERMINAL(widget), FALSE);
	terminal = VTE_TERMINAL(widget);
	height = terminal->char_height;
	width = terminal->char_width;
	delta = terminal->pvt->screen->scroll_delta;
	vte_terminal_set_pointer_visible(terminal, TRUE);

	/* Read the modifiers. */
	if (gdk_event_get_state((GdkEvent*)event, &modifiers) == FALSE) {
		modifiers = 0;
	}

	/* Convert the event coordinates to cell coordinates. */
	cellx = (event->x - VTE_PAD_WIDTH) / width;
	celly = (event->y - VTE_PAD_WIDTH) / height;

	if (event->type == GDK_BUTTON_PRESS) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_EVENTS)) {
			char *match;
			int match_tag;
			fprintf(stderr, "Button %d pressed at (%lf,%lf).\n",
				event->button,
				event->x - VTE_PAD_WIDTH,
				event->y - VTE_PAD_WIDTH);
			fprintf(stderr, "Character cell (%lf,%lf).\n",
				cellx, celly);
			match = vte_terminal_match_check(terminal,
							 cellx,
							 celly,
							 &match_tag);
			if (match != NULL) {
				fprintf(stderr, "Matched string %d = \"%s\".\n",
					match_tag, match);
				g_free(match);
			}
		}
#endif
		/* If the child is handling mouse events, send it the event. */
		if ((terminal->pvt->mouse_send_xy_on_button ||
		     terminal->pvt->mouse_send_xy_on_click) &&
		    ((modifiers & GDK_SHIFT_MASK) == 0)) {
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_EVENTS)) {
				fprintf(stderr, "Sending click to child.\n");
			}
#endif
			vte_terminal_send_mouse_button(terminal, event);
		} else
		/* Handle this event ourselves. */
		if (event->button == 1) {
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_EVENTS)) {
				fprintf(stderr, "Handling click ourselves.\n");
			}
#endif
			if (!GTK_WIDGET_HAS_FOCUS(widget)) {
				gtk_widget_grab_focus(widget);
			}
			/* If the user didn't hold down shift, or if the click
			 * was in an already-selected cell, we deselect and
			 * start over. */
			if (((modifiers & GDK_SHIFT_MASK) == 0) ||
			    vte_cell_is_selected(terminal, cellx, celly)) {
				/* Start selection later. */
				terminal->pvt->start_selection = TRUE;
				terminal->pvt->selection_delayed.x =
					event->x - VTE_PAD_WIDTH;
				terminal->pvt->selection_delayed.y =
					event->y - VTE_PAD_WIDTH;
				ret = TRUE;
			} else {
				/* Don't restart selection later. */
				terminal->pvt->start_selection = FALSE;
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_EVENTS)) {
					fprintf(stderr, "Selection is "
						"(%ld,%ld) to (%ld,%ld).\n",
						terminal->pvt->selection_start.x,
						terminal->pvt->selection_start.y,
						terminal->pvt->selection_end.x,
						terminal->pvt->selection_end.y);
				}
#endif
				/* Extend the selection by moving either the
				 * origin or last pointer to the event's
				 * coordinates. */
				if ((terminal->pvt->selection_origin.y <
				     terminal->pvt->selection_last.y) ||
				    ((terminal->pvt->selection_origin.y ==
				      terminal->pvt->selection_last.y) &&
				     (terminal->pvt->selection_origin.x <
				      terminal->pvt->selection_last.x))) {
					/* The origin point is "before" the end
					 * point. */
					start = &terminal->pvt->selection_origin;
					end = &terminal->pvt->selection_last;
				} else {
					/* The end point is "before" the origin
					 * point. */
					end = &terminal->pvt->selection_origin;
					start = &terminal->pvt->selection_last;
				}
				/* Move the selection start- or endpoint. */
				if (((event->y - VTE_PAD_WIDTH) < start->y) ||
				    (((event->y - VTE_PAD_WIDTH) == start->y) &&
				     ((event->x - VTE_PAD_WIDTH) < start->x))) {
					/* The click was "before" the start
					 * point. */
					start->x = event->x - VTE_PAD_WIDTH;
					start->y = event->y - VTE_PAD_WIDTH;
				} else {
					/* The click was "after" the start
					 * point. */
					end->x = event->x - VTE_PAD_WIDTH;
					end->y = event->y - VTE_PAD_WIDTH;
				}
				/* Recalculate the selection area using the
				 * new origin and "last" coordinates. */
				vte_terminal_selection_compute(terminal);
				/* Redraw the newly-highlited rows. */
				vte_invalidate_cells(terminal,
						     0,
						     terminal->column_count,
						     terminal->pvt->selection_start.y,
						     terminal->pvt->selection_end.y -
						     terminal->pvt->selection_start.y + 1);

#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_EVENTS)) {
					fprintf(stderr, "Selection changed to "
						"(%ld,%ld) to (%ld,%ld).\n",
						terminal->pvt->selection_start.x,
						terminal->pvt->selection_start.y,
						terminal->pvt->selection_end.x,
						terminal->pvt->selection_end.y);
				}
#endif
				ret = TRUE;
			}
		} else
		/* Paste. */
		if (event->button == 2) {
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_EVENTS)) {
				fprintf(stderr, "Handling click ourselves.\n");
			}
#endif
			vte_terminal_paste(terminal, GDK_SELECTION_PRIMARY);
			ret = TRUE;
		}
	} else
	if (event->type == GDK_2BUTTON_PRESS) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_EVENTS)) {
			fprintf(stderr, "Button %d double-click at (%lf,%lf)\n",
				event->button,
				event->x - VTE_PAD_WIDTH,
				event->y - VTE_PAD_WIDTH);
		}
#endif
		if (event->button == 1) {
			if (!GTK_WIDGET_HAS_FOCUS(widget)) {
				gtk_widget_grab_focus(widget);
			}
			vte_terminal_deselect_all(terminal);
			terminal->pvt->has_selection = TRUE;
			terminal->pvt->selection_origin.x =
				event->x - VTE_PAD_WIDTH;
			terminal->pvt->selection_origin.y =
				event->y - VTE_PAD_WIDTH;
			terminal->pvt->selection_start.x = cellx;
			terminal->pvt->selection_start.y = celly + delta;
			terminal->pvt->selection_end =
			terminal->pvt->selection_start;
			terminal->pvt->selection_type = selection_type_word;
			vte_invalidate_cells(terminal,
					     0,
					     terminal->column_count,
					     terminal->pvt->selection_start.y,
					     1);
			ret = TRUE;
		}
	} else
	if (event->type == GDK_3BUTTON_PRESS) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_EVENTS)) {
			fprintf(stderr, "Button %d triple-click at (%lf,%lf).\n",
				event->button,
				event->x - VTE_PAD_WIDTH,
				event->y - VTE_PAD_WIDTH);
		}
#endif
		if (event->button == 1) {
			if (!GTK_WIDGET_HAS_FOCUS(widget)) {
				gtk_widget_grab_focus(widget);
			}
			vte_terminal_deselect_all(terminal);
			terminal->pvt->has_selection = TRUE;
			terminal->pvt->selection_origin.x =
				event->x - VTE_PAD_WIDTH;
			terminal->pvt->selection_origin.y =
				event->y - VTE_PAD_WIDTH;
			terminal->pvt->selection_start.x = cellx;
			terminal->pvt->selection_start.y = celly + delta;
			terminal->pvt->selection_end =
			terminal->pvt->selection_start;
			terminal->pvt->selection_type = selection_type_line;
			vte_invalidate_cells(terminal,
					     0,
					     terminal->column_count,
					     terminal->pvt->selection_start.y,
					     1);
			ret = TRUE;
		}
	}

	/* Hilite any matches. */
	vte_terminal_match_hilite(terminal,
				  event->x - VTE_PAD_WIDTH,
				  event->y - VTE_PAD_WIDTH);

	/* Save the pointer state for later use. */
	terminal->pvt->mouse_last_button = event->button;
	terminal->pvt->mouse_last_x = event->x - VTE_PAD_WIDTH;
	terminal->pvt->mouse_last_y = event->y - VTE_PAD_WIDTH;

	return ret;
}

/* Read and handle a pointing device buttonrelease event. */
static gint
vte_terminal_button_release(GtkWidget *widget, GdkEventButton *event)
{
	VteTerminal *terminal;
	GdkModifierType modifiers;

	g_return_val_if_fail(VTE_IS_TERMINAL(widget), FALSE);
	terminal = VTE_TERMINAL(widget);
	vte_terminal_set_pointer_visible(terminal, TRUE);

	if (event->type == GDK_BUTTON_RELEASE) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_EVENTS)) {
			fprintf(stderr, "Button %d released at (%lf,%lf).\n",
				event->button,
				event->x - VTE_PAD_WIDTH,
				event->y - VTE_PAD_WIDTH);
		}
#endif
		/* Read the modifiers. */
		if (gdk_event_get_state((GdkEvent*)event, &modifiers) == FALSE) {
			modifiers = 0;
		}
		if ((terminal->pvt->mouse_send_xy_on_button) &&
		    ((modifiers & GDK_SHIFT_MASK) == 0)) {
			vte_terminal_send_mouse_button(terminal, event);
		} else
		if (event->button == 1) {
			vte_terminal_copy(terminal, GDK_SELECTION_PRIMARY);
		}
	}

	/* Hilite any matches. */
	vte_terminal_match_hilite(terminal,
				  event->x - VTE_PAD_WIDTH,
				  event->y - VTE_PAD_WIDTH);

	/* Save the pointer state for later use. */
	terminal->pvt->mouse_last_button = 0;
	terminal->pvt->mouse_last_x = event->x - VTE_PAD_WIDTH;
	terminal->pvt->mouse_last_y = event->y - VTE_PAD_WIDTH;

	return FALSE;
}

/* Handle receiving or losing focus. */
static gint
vte_terminal_focus_in(GtkWidget *widget, GdkEventFocus *event)
{
	g_return_val_if_fail(GTK_IS_WIDGET(widget), 0);
	GTK_WIDGET_SET_FLAGS(widget, GTK_HAS_FOCUS);
	gtk_im_context_focus_in((VTE_TERMINAL(widget))->pvt->im_context);
	vte_invalidate_cursor_once(VTE_TERMINAL(widget));
	return TRUE;
}

static gint
vte_terminal_focus_out(GtkWidget *widget, GdkEventFocus *event)
{
	g_return_val_if_fail(GTK_WIDGET(widget), 0);
	GTK_WIDGET_UNSET_FLAGS(widget, GTK_HAS_FOCUS);
	gtk_im_context_focus_out((VTE_TERMINAL(widget))->pvt->im_context);
	vte_invalidate_cursor_once(VTE_TERMINAL(widget));
	return TRUE;
}

static void
vte_terminal_font_complain(const char *font,
			   char **missing_charset_list,
			   int missing_charset_count)
{
	int i;
	char *charsets, *tmp;
	if ((missing_charset_count > 0) && (missing_charset_list != NULL)) {
		charsets = NULL;
		for (i = 0; i < missing_charset_count; i++) {
			if (charsets == NULL) {
				tmp = g_strdup(missing_charset_list[i]);
			} else {
				tmp = g_strconcat(charsets, ", ",
						  missing_charset_list[i],
						  NULL);
				g_free(charsets);
			}
			charsets = tmp;
			tmp = NULL;
		}
		g_warning(_("Using fontset \"%s\", which is missing "
			    "these character sets: %s."), font, charsets);
		g_free(charsets);
	}
}

#ifdef HAVE_XFT
static int
xft_weight_from_pango_weight (int weight)
{
	/* cut-and-pasted from Pango */
	if (weight < (PANGO_WEIGHT_NORMAL + PANGO_WEIGHT_LIGHT) / 2)
		return XFT_WEIGHT_LIGHT;
	else if (weight < (PANGO_WEIGHT_NORMAL + 600) / 2)
		return XFT_WEIGHT_MEDIUM;
	else if (weight < (600 + PANGO_WEIGHT_BOLD) / 2)
		return XFT_WEIGHT_DEMIBOLD;
	else if (weight < (PANGO_WEIGHT_BOLD + PANGO_WEIGHT_ULTRABOLD) / 2)
		return XFT_WEIGHT_BOLD;
	else
		return XFT_WEIGHT_BLACK;
}

static int
xft_slant_from_pango_style (int style)
{
	switch (style) {
	case PANGO_STYLE_NORMAL:
		return XFT_SLANT_ROMAN;
		break;
	case PANGO_STYLE_ITALIC:
		return XFT_SLANT_ITALIC;
		break;
	case PANGO_STYLE_OBLIQUE:
		return XFT_SLANT_OBLIQUE;
		break;
	}

	return XFT_SLANT_ROMAN;
}

/* Create an Xft pattern from a Pango font description. */
static XftPattern *
xft_pattern_from_pango_font_desc(const PangoFontDescription *font_desc)
{
	XftPattern *pattern;
	const char *family = "mono";
	int pango_mask = 0;
	int weight, style;
	double size = 14.0;

	if (font_desc != NULL) {
		pango_mask = pango_font_description_get_set_fields (font_desc);
	}

	pattern = XftPatternCreate ();

	/* Set the family for the pattern, or use a sensible default. */
	if (pango_mask & PANGO_FONT_MASK_FAMILY) {
		family = pango_font_description_get_family (font_desc);
	}
	XftPatternAddString (pattern, XFT_FAMILY, family);

	/* Set the font size for the pattern, or use a sensible default. */
	if (pango_mask & PANGO_FONT_MASK_SIZE) {
		size = (double) pango_font_description_get_size (font_desc);
		size /= (double) PANGO_SCALE;
	}
	XftPatternAddDouble (pattern, XFT_SIZE, size);

	/* There aren'ty any fallbacks for these, so just omit them from the
	 * pattern if they're not set in the pango font. */
	if (pango_mask & PANGO_FONT_MASK_WEIGHT) {
		weight = pango_font_description_get_weight (font_desc);
		XftPatternAddInteger (pattern, XFT_WEIGHT,
				      xft_weight_from_pango_weight (weight));
	}
	if (pango_mask & PANGO_FONT_MASK_STYLE) {
		style = pango_font_description_get_style (font_desc);
		XftPatternAddInteger (pattern, XFT_SLANT,
				      xft_slant_from_pango_style (style));
	}

	return pattern;
}
#endif

static char *
xlfd_from_pango_font_description(GtkWidget *widget,
				 const PangoFontDescription *fontdesc)
{
	char *spec;
	PangoContext *context;
	PangoFont *font;
	PangoXSubfont *subfont_ids;
	PangoFontMap *fontmap;
	int *subfont_charsets, i, count;
	char *xlfd = NULL, *tmp, *subfont, *ret;
	char **exploded;
	char *encodings[] = {
		"iso10646-0",
		"iso10646-1",
		"ascii-0",
		"big5-0",
		"dos-437",
		"dos-737",
		"gb18030.2000-0",
		"gb18030.2000-1",
		"gb2312.1980-0",
		"iso8859-1",
		"iso8859-10",
		"iso8859-15",
		"iso8859-2",
		"iso8859-3",
		"iso8859-4",
		"iso8859-5",
		"iso8859-7",
		"iso8859-8",
		"iso8859-9",
		"jisx0201.1976-0",
		"jisx0208.1983-0",
		"jisx0208.1990-0",
		"jisx0208.1997-0",
		"jisx0212.1990-0",
		"jisx0213.2000-1",
		"jisx0213.2000-2",
		"koi8-r",
		"koi8-u",
		"koi8-ub",
		"misc-fontspecific",
	};

	g_return_val_if_fail(fontdesc != NULL, NULL);
	g_return_val_if_fail(GTK_IS_WIDGET(widget), NULL);

	context = pango_x_get_context(GDK_DISPLAY());
	if (context == NULL) {
		return g_strdup(VTE_X_FIXED);
	}

	fontmap = pango_x_font_map_for_display(GDK_DISPLAY());
	if (fontmap == NULL) {
		return g_strdup(VTE_X_FIXED);
	}

	font = pango_font_map_load_font(fontmap, context, fontdesc);
	if (font == NULL) {
		return g_strdup(VTE_X_FIXED);
	}

	count = pango_x_list_subfonts(font,
				      encodings, G_N_ELEMENTS(encodings),
				      &subfont_ids, &subfont_charsets);
	for (i = 0; i < count; i++) {
		subfont = pango_x_font_subfont_xlfd(font,
						    subfont_ids[i]);
		exploded = g_strsplit(subfont, "-", 0);
		if (exploded != NULL) {
			g_free(exploded[6]);
			exploded[6] = g_strdup("*");
			g_free(exploded[8]);
			exploded[8] = g_strdup("*");
			g_free(exploded[9]);
			exploded[9] = g_strdup("*");
			g_free(subfont);
			subfont = g_strjoinv("-", exploded);
			g_strfreev(exploded);
		}
		if (xlfd) {
			tmp = g_strconcat(xlfd, ",", subfont, NULL);
			g_free(xlfd);
			g_free(subfont);
			xlfd = tmp;
		} else {
			xlfd = subfont;
		}
	}

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		spec = pango_font_description_to_string(fontdesc);
		fprintf(stderr, "Converted PangoFontSpecification `%s' to "
			"xlfd `%s'.\n", spec, xlfd ? xlfd : "(null)");
		g_free(spec);
	}
#endif

	if (subfont_ids != NULL) {
		g_free(subfont_ids);
	}
	if (subfont_charsets != NULL) {
		g_free(subfont_charsets);
	}

	ret = strdup(xlfd);
	g_free(xlfd);
	return ret;
}

#ifdef HAVE_XFT
/* Convert an Xft pattern to a font name. */
static char *
vte_unparse_xft_pattern(XftPattern *pattern)
{
#ifdef HAVE_XFT2
	return FcNameUnparse(pattern);
#else /* !HAVE_XFT2 */
	char buf[256];
	if (!XftNameUnparse(pattern, buf, sizeof(buf)-1)) {
		buf[0] = '\0';
	}
	buf[sizeof(buf) - 1] = '\0';
	return strdup(buf);
#endif /* HAVE_XFT2 */
}
#endif /* HAVE_XFT */

/* A comparison function which helps sort quarks. */
static gint
vte_compare_direct(gconstpointer a, gconstpointer b)
{
	return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
}

/* Apply the changed metrics, and queue a resize if need be. */
static void
vte_terminal_apply_metrics(VteTerminal *terminal,
			   gint width, gint height, gint ascent, gint descent)
{
	gboolean resize = FALSE, cresize = FALSE;

	/* Sanity check for broken font changes. */
	width = MAX(width, 1);
	height = MAX(height, 2);
	ascent = MAX(ascent, 1);
	descent = MAX(descent, 1);

	/* Change settings, and keep track of when we've changed anything. */
	if (width != terminal->char_width) {
		resize = cresize = TRUE;
		terminal->char_width = width;
	}
	if (height != terminal->char_height) {
		resize = cresize = TRUE;
		terminal->char_height = height;
	}
	if (ascent != terminal->char_ascent) {
		resize = TRUE;
		terminal->char_ascent = ascent;
	}
	if (descent != terminal->char_descent) {
		resize = TRUE;
		terminal->char_descent = descent;
	}
	/* Queue a resize if anything's changed. */
	if (resize) {
		if (GTK_WIDGET_REALIZED(GTK_WIDGET(terminal))) {
			gtk_widget_queue_resize(GTK_WIDGET(terminal));
		}
	}
	/* Emit a signal that the font changed. */
	if (cresize) {
		vte_terminal_emit_char_size_changed(terminal,
						    terminal->char_width,
						    terminal->char_height);
	}
	/* Repaint. */
	vte_invalidate_all(terminal);
}

#ifdef HAVE_XFT2
/* Handle notification that Xft-related GTK settings have changed by resetting
 * the font using the new settings. */
static void
vte_xft_changed_cb(GtkSettings *settings, GParamSpec *spec,
		   VteTerminal *terminal)
{
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Xft settings changed.\n");
	}
#endif
	vte_terminal_set_font(terminal, terminal->pvt->fontdesc);
}

/* Add default specifiers to the pattern which incorporate the current Xft
 * settings. */
static void
vte_default_substitute(VteTerminal *terminal, FcPattern *pattern)
{
	GtkSettings *settings;
	GObjectClass *klass;
	XftResult result;
	gboolean found;
	int i = -1;
	double d = -1;
	int antialias = -1, hinting = -1, dpi = -1;
	char *rgba = NULL, *hintstyle = NULL;

	settings = gtk_widget_get_settings(GTK_WIDGET(terminal));
	if (settings == NULL) {
		return;
	}

	/* Check that the properties we're looking at are defined. */
	klass = G_OBJECT_CLASS(GTK_SETTINGS_GET_CLASS(settings));
	if (g_object_class_find_property(klass, "gtk-xft-antialias") == NULL) {
		return;
	}

	/* If this is our first time in here, start listening for changes
	 * to the Xft settings. */
	if (terminal->pvt->connected_settings == NULL) {
		terminal->pvt->connected_settings = settings;
		g_signal_connect(G_OBJECT(settings),
				 "notify::gtk-xft-antialias",
				 G_CALLBACK(vte_xft_changed_cb), terminal);
		g_signal_connect(G_OBJECT(settings),
				 "notify::gtk-xft-hinting",
				 G_CALLBACK(vte_xft_changed_cb), terminal);
		g_signal_connect(G_OBJECT(settings),
				 "notify::gtk-xft-hintstyle",
				 G_CALLBACK(vte_xft_changed_cb), terminal);
		g_signal_connect(G_OBJECT(settings),
				 "notify::gtk-xft-rgba",
				 G_CALLBACK(vte_xft_changed_cb), terminal);
		g_signal_connect(G_OBJECT(settings),
				 "notify::gtk-xft-dpi",
				 G_CALLBACK(vte_xft_changed_cb), terminal);
	}

	/* Read the settings. */
	g_object_get(G_OBJECT(settings),
		     "gtk-xft-antialias", &antialias,
		     "gtk-xft-hinting", &hinting,
		     "gtk-xft-hintstyle", &hintstyle,
		     "gtk-xft-rgba", &rgba,
		     "gtk-xft-dpi", &dpi,
		     NULL);

	/* First get and set the settings Xft1 "knows" about. */
	if (antialias >= 0) {
		result = FcPatternGetBool(pattern, FC_ANTIALIAS, 0, &i);
		if (result == FcResultNoMatch) {
			FcPatternAddBool(pattern, FC_ANTIALIAS, antialias > 0);
		}
	}

	if (rgba != NULL) {
		result = FcPatternGetInteger(pattern, FC_RGBA, 0, &i);
		if (result == FcResultNoMatch) {
			i = FC_RGBA_NONE;
			found = TRUE;
			if (strcmp(rgba, "none") == 0) {
				i = FC_RGBA_NONE;
			} else
			if (strcmp(rgba, "rgb") == 0) {
				i = FC_RGBA_RGB;
			} else
			if (strcmp(rgba, "bgr") == 0) {
				i = FC_RGBA_BGR;
			} else
			if (strcmp(rgba, "vrgb") == 0) {
				i = FC_RGBA_VRGB;
			} else
			if (strcmp(rgba, "vbgr") == 0) {
				i = FC_RGBA_VBGR;
			} else {
				found = FALSE;
			}
			if (found) {
				FcPatternAddInteger(pattern, FC_RGBA, i);
			}
		}
	}

	if (dpi >= 0) {
		result = FcPatternGetDouble(pattern, FC_DPI, 0, &d);
		if (result == FcResultNoMatch) {
			FcPatternAddDouble(pattern, FC_DPI, dpi / 1024.0);
		}
	}

	if (hinting >= 0) {
		result = FcPatternGetBool(pattern, FC_HINTING, 0, &i);
		if (result == FcResultNoMatch) {
			FcPatternAddBool(pattern, FC_HINTING, hinting > 0);
		}
	}

	if (hintstyle != NULL) {
		result = FcPatternGetInteger(pattern, FC_HINT_STYLE, 0, &i);
		if (result == FcResultNoMatch) {
			i = FC_HINT_NONE;
			found = TRUE;
			if (strcmp(hintstyle, "hintnone") == 0) {
				i = FC_HINT_NONE;
			} else
			if (strcmp(hintstyle, "hintslight") == 0) {
				i = FC_HINT_SLIGHT;
			} else
			if (strcmp(hintstyle, "hintmedium") == 0) {
				i = FC_HINT_MEDIUM;
			} else
			if (strcmp(hintstyle, "hintfull") == 0) {
				i = FC_HINT_FULL;
			} else {
				found = FALSE;
			}
			if (found) {
				FcPatternAddInteger(pattern, FC_HINT_STYLE, i);
			}
		}
	}
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		FcPatternPrint(pattern);
	}
#endif
	if (rgba != NULL) {
		g_free(rgba);
	}
	if (hintstyle != NULL) {
		g_free(hintstyle);
	}
}

/* Find a font which matches the request, figuring in FontConfig settings. */
static FcPattern *
vte_font_match(VteTerminal *terminal, FcPattern *pattern, FcResult *result)
{
	FcPattern *spec, *match;
	Display *display;
	int screen;

	spec = FcPatternDuplicate(pattern);
	if (spec == NULL) {
		return NULL;
	}

	display = GDK_DISPLAY();
	screen = gdk_x11_get_default_screen();

	FcConfigSubstitute(NULL, spec, FcMatchPattern);
	vte_default_substitute(terminal, spec);
	FcDefaultSubstitute(spec);

	match = FcFontMatch(NULL, spec, result);

	FcPatternDestroy(spec);
	return match;
}
#endif

#ifdef HAVE_XFT
/* Ensure that an Xft font is loaded and metrics are known. */
static void
vte_terminal_open_font_xft(VteTerminal *terminal)
{
	XftFont *new_font;
	XftPattern *pattern;
	XftPattern *matched_pattern;
	XftResult result;
	XGlyphInfo glyph_info;
	gint width, height, ascent, descent;
	gboolean need_destroy = FALSE;
	char *name;

	/* Simple case -- we already loaded the font. */
	if (terminal->pvt->ftfont != NULL) {
		return;
	}

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Opening Xft font.\n");
	}
#endif
	/* Map the font description to an Xft pattern. */
	pattern = xft_pattern_from_pango_font_desc(terminal->pvt->fontdesc);

	/* Xft is on a lot of crack here - it fills in "result" when it
	 * feels like it, and leaves it uninitialized the rest of the
	 * time.  Whether it's filled in is impossible to determine
	 * afaict.  We don't care about its value anyhow.  */
	result = 0xffff; /* some bogus value to help in debugging */
#ifdef HAVE_XFT2
	matched_pattern = vte_font_match(terminal, pattern, &result);
#else
	matched_pattern = XftFontMatch(GDK_DISPLAY(),
				       gdk_x11_get_default_screen(),
				       pattern, &result);
#endif
	/* Keep track of whether or not we need to destroy this pattern. */
	if (matched_pattern != NULL) {
		need_destroy = TRUE;
	}

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		if (matched_pattern != NULL) {
			name = vte_unparse_xft_pattern(matched_pattern);
			fprintf(stderr, "Matched pattern \"%s\".\n", name);
			free(name);
		}
		switch (result) {
			case XftResultMatch:
			       fprintf(stderr, "matched.\n");
			       break;
			case XftResultNoMatch:
			       fprintf(stderr, "no match.\n");
			       break;
			case XftResultTypeMismatch:
			       fprintf(stderr, "type mismatch.\n");
			       break;
			case XftResultNoId:
			       fprintf(stderr, "no ID.\n");
			       break;
			default:
			       fprintf(stderr, "undefined/bogus result.\n");
			       break;
		}
	}
#endif

	if (matched_pattern != NULL) {
		/* More Xft crackrock - it appears to "adopt" matched_pattern
		 * as new_font->pattern; whether it does this reliably or not,
		 * or does another unpredictable bogosity like the "result"
		 * field above, I don't know.  */
		new_font = XftFontOpenPattern(GDK_DISPLAY(), matched_pattern);
		need_destroy = FALSE;
	} else {
		new_font = NULL;
	}

	if (new_font == NULL) {
		name = vte_unparse_xft_pattern(matched_pattern);
		g_warning(_("Failed to load Xft font pattern \"%s\", "
			    "falling back to default font."), name);
		free(name);
		/* Try to use the default font. */
		new_font = XftFontOpen(GDK_DISPLAY(),
				       gdk_x11_get_default_screen(),
				       XFT_FAMILY, XftTypeString,
				       "monospace",
				       XFT_SIZE, XftTypeDouble, 12.0,
				       0);
	}
	if (new_font == NULL) {
		g_warning(_("Failed to load default Xft font."));
	}

	g_assert(pattern != new_font->pattern);
	XftPatternDestroy(pattern);
	if (need_destroy) {
		XftPatternDestroy(matched_pattern);
	}

	if (new_font) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC)) {
			name = vte_unparse_xft_pattern(new_font->pattern);
			fprintf(stderr, "Opened new font `%s'.\n", name);
			free(name);
		}
#endif
		terminal->pvt->ftfont = new_font;
	}

	/* Read the metrics for the new font, if one was loaded. */
	if (terminal->pvt->ftfont != NULL) {
		ascent = terminal->pvt->ftfont->ascent;
		descent = terminal->pvt->ftfont->descent;
		memset(&glyph_info, 0, sizeof(glyph_info));
		XftTextExtents8(GDK_DISPLAY(), terminal->pvt->ftfont,
				VTE_REPRESENTATIVE_CHARACTERS,
				strlen(VTE_REPRESENTATIVE_CHARACTERS),
				&glyph_info);
		width = howmany(glyph_info.width,
				strlen(VTE_REPRESENTATIVE_CHARACTERS));
		height = MAX(terminal->pvt->ftfont->height, (ascent + descent));
		if (height == 0) {
			height = glyph_info.height;
		}
		vte_terminal_apply_metrics(terminal,
					   width, height,
					   ascent, descent);
	}
}
static void
vte_terminal_close_font_xft(VteTerminal *terminal)
{
	if (terminal->pvt->ftfont != NULL) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC)) {
			fprintf(stderr, "Closing Xft font.\n");
		}
#endif
		XftFontClose(GDK_DISPLAY(), terminal->pvt->ftfont);
		terminal->pvt->ftfont = NULL;
	}
}
#endif

/* Ensure that an Xlib font is loaded. */
static void
vte_terminal_open_font_xlib(VteTerminal *terminal)
{
	char *xlfds;
	long width, height, ascent, descent;
	XFontStruct **font_struct_list, font_struct;
	XRectangle ink, logical;
	char **missing_charset_list = NULL, *def_string = NULL;
	int missing_charset_count = 0;
	char **font_name_list = NULL;

	/* Simple case -- we already loaded the font. */
	if (terminal->pvt->fontset != NULL) {
		return;
	}

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Opening Xlib font.\n");
	}
#endif
	xlfds = xlfd_from_pango_font_description(GTK_WIDGET(terminal),
						 terminal->pvt->fontdesc);
	if (xlfds == NULL) {
		xlfds = strdup(VTE_X_FIXED);
	}
	/* Open the font set. */
	terminal->pvt->fontset = XCreateFontSet(GDK_DISPLAY(),
						xlfds,
						&missing_charset_list,
						&missing_charset_count,
						&def_string);
	if (terminal->pvt->fontset != NULL) {
		vte_terminal_font_complain(xlfds,
					   missing_charset_list,
					   missing_charset_count);
	} else {
		g_warning(_("Failed to load font set \"%s\", "
			    "falling back to default font."), xlfds);
		if (missing_charset_list != NULL) {
			XFreeStringList(missing_charset_list);
			missing_charset_list = NULL;
		}
		terminal->pvt->fontset = XCreateFontSet(GDK_DISPLAY(),
							VTE_X_FIXED,
							&missing_charset_list,
							&missing_charset_count,
							&def_string);
		if (terminal->pvt->fontset == NULL) {
			g_warning(_("Failed to load default font, "
				    "crashing or behaving abnormally."));
		} else {
			vte_terminal_font_complain(xlfds,
						   missing_charset_list,
						   missing_charset_count);
		}
	}
	if (missing_charset_list != NULL) {
		XFreeStringList(missing_charset_list);
		missing_charset_list = NULL;
	}
	free(xlfds);
	xlfds = NULL;
	g_return_if_fail(terminal->pvt->fontset != NULL);

	/* Read the font metrics. */
	XmbTextExtents(terminal->pvt->fontset,
		       VTE_REPRESENTATIVE_CHARACTERS,
		       strlen(VTE_REPRESENTATIVE_CHARACTERS),
		       &ink, &logical);
	width = logical.width / strlen(VTE_REPRESENTATIVE_CHARACTERS);
	height = logical.height;
	ascent = height;
	descent = 0;
	if (XFontsOfFontSet(terminal->pvt->fontset,
			    &font_struct_list,
			    &font_name_list)) {
		if (font_struct_list) {
			if (font_struct_list[0]) {
				font_struct = font_struct_list[0][0];
				ascent = font_struct.max_bounds.ascent;
				descent = font_struct.max_bounds.descent;
				height = ascent + descent;
			}
		}
		font_struct_list = NULL;
		font_name_list = NULL;
	}
	xlfds = NULL;

	/* Save the new font metrics. */
	vte_terminal_apply_metrics(terminal, width, height, ascent, descent);
}

/* Free the Xlib font. */
static void
vte_terminal_close_font_xlib(VteTerminal *terminal)
{
	if (terminal->pvt->fontset != NULL) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC)) {
			fprintf(stderr, "Closing Xlib font.\n");
		}
#endif
		XFreeFontSet(GDK_DISPLAY(), terminal->pvt->fontset);
		terminal->pvt->fontset = NULL;
	}
}

/* Ensure that a Pango font's metrics are known. */
static void
vte_terminal_open_font_pango(VteTerminal *terminal)
{
	PangoFontDescription *desc = NULL;
	PangoContext *context = NULL;
	PangoFontMetrics *metrics = NULL;
	PangoLanguage *lang = NULL;
	PangoLayout *layout = NULL;
	PangoRectangle ink, logical;
	gint height, width, ascent, descent;

	if (terminal->pvt->pcontext != NULL) {
		return;
	}
	terminal->pvt->pcontext = vte_terminal_get_pango_context(terminal);
	context = terminal->pvt->pcontext;
	desc = terminal->pvt->fontdesc;

	/* Load a font using this description and read its metrics to find
	 * the ascent and descent. */
	if ((context != NULL) && (desc != NULL)) {
		lang = pango_context_get_language(context);
		metrics = pango_context_get_metrics(context, desc, lang);
		ascent = pango_font_metrics_get_ascent(metrics);
		descent = pango_font_metrics_get_descent(metrics);
		pango_font_metrics_unref(metrics);
		metrics = NULL;

		/* Create a layout object to get a width estimate. */
		layout = pango_layout_new(context);
		pango_layout_set_font_description(layout, desc);
		pango_layout_set_text(layout,
				      VTE_REPRESENTATIVE_CHARACTERS,
				      strlen(VTE_REPRESENTATIVE_CHARACTERS));
		pango_layout_get_extents(layout, &ink, &logical);
		width = howmany(logical.width, PANGO_SCALE);
		width = howmany(width, strlen(VTE_REPRESENTATIVE_CHARACTERS));
		height = howmany(logical.height, PANGO_SCALE);
		g_object_unref(G_OBJECT(layout));
		layout = NULL;

		/* Change the metrics. */
		vte_terminal_apply_metrics(terminal,
					   width, height,
					   ascent, descent);
	}
}
static void
vte_terminal_close_font_pango(VteTerminal *terminal)
{
	if (terminal->pvt->pcontext != NULL) {
		vte_terminal_maybe_unref_pango_context(terminal,
						       terminal->pvt->pcontext);
		terminal->pvt->pcontext = NULL;
	}
}

/* Ensure that the font's metrics are known. */
static void
vte_terminal_open_font(VteTerminal *terminal)
{
	switch (terminal->pvt->render_method) {
#ifdef HAVE_XFT
	case VteRenderXft2:
	case VteRenderXft1:
		vte_terminal_open_font_xft(terminal);
		break;
#endif
	case VteRenderPango:
		vte_terminal_open_font_pango(terminal);
		break;
	case VteRenderXlib:
	default:
		vte_terminal_open_font_xlib(terminal);
	}
}
static void
vte_terminal_close_font(VteTerminal *terminal)
{
	vte_terminal_close_font_xlib(terminal);
	vte_terminal_close_font_pango(terminal);
#ifdef HAVE_XFT
	vte_terminal_close_font_xft(terminal);
#endif
}

/* Set the fontset used for rendering text into the widget. */
void
vte_terminal_set_font(VteTerminal *terminal,
		      const PangoFontDescription *font_desc)
{
	GtkWidget *widget;

	g_return_if_fail(terminal != NULL);
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	widget = GTK_WIDGET(terminal);

	/* Destroy the font padding records. */
	if (terminal->pvt->fontpaddingl != NULL) {
		g_tree_destroy(terminal->pvt->fontpaddingl);
	}
	terminal->pvt->fontpaddingl = g_tree_new(vte_compare_direct);
	if (terminal->pvt->fontpaddingr != NULL) {
		g_tree_destroy(terminal->pvt->fontpaddingr);
	}
	terminal->pvt->fontpaddingr = g_tree_new(vte_compare_direct);

	/* Create an owned font description. */
	if (font_desc != NULL) {
		font_desc = pango_font_description_copy(font_desc);
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC)) {
			if (font_desc) {
				char *tmp;
				tmp = pango_font_description_to_string(font_desc);
				fprintf(stderr, "Using pango font \"%s\".\n", tmp);
				g_free (tmp);
			}
		}
#endif
	} else {
		gtk_widget_ensure_style(widget);
		font_desc =
			pango_font_description_copy(widget->style->font_desc);
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC)) {
			fprintf(stderr, "Using default pango font.\n");
		}
#endif
	}

	/* Save the new font description. */
	if (terminal->pvt->fontdesc != NULL) {
		pango_font_description_free(terminal->pvt->fontdesc);
	}
	terminal->pvt->fontdesc = (PangoFontDescription*) font_desc;

	/* Free the older fonts and load the new ones. */
	vte_terminal_close_font(terminal);
	vte_terminal_open_font(terminal);
}

void
vte_terminal_set_font_from_string(VteTerminal *terminal, const char *name)
{
	PangoFontDescription *font_desc;
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	g_return_if_fail(name != NULL);
	g_return_if_fail(strlen(name) > 0);

	font_desc = pango_font_description_from_string(name);
	vte_terminal_set_font(terminal, font_desc);
	pango_font_description_free(font_desc);
}

const PangoFontDescription *
vte_terminal_get_font(VteTerminal *terminal)
{
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), NULL);
	return terminal->pvt->fontdesc;
}

/* Read and refresh our perception of the size of the PTY. */
static void
vte_terminal_refresh_size(VteTerminal *terminal)
{
	int rows, columns;
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	if (terminal->pvt->pty_master != -1) {
		/* Use an ioctl to read the size of the terminal. */
		if (vte_pty_get_size(terminal->pvt->pty_master, &columns, &rows) != 0) {
			g_warning(_("Error reading PTY size, using defaults: "
				    "%s."), strerror(errno));
		} else {
			terminal->row_count = rows;
			terminal->column_count = columns;
		}
	}
}

/* Set the size of the PTY. */
void
vte_terminal_set_size(VteTerminal *terminal, long columns, long rows)
{
	struct winsize size;
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Setting PTY size to %dx%d.\n", columns, rows);
	}
#endif
	if (terminal->pvt->pty_master != -1) {
		memset(&size, 0, sizeof(size));
		size.ws_row = rows;
		size.ws_col = columns;
		/* Try to set the terminal size. */
		if (vte_pty_set_size(terminal->pvt->pty_master, columns, rows) != 0) {
			g_warning(_("Error setting PTY size: %s."),
				    strerror(errno));
		}
	} else {
		terminal->row_count = rows;
		terminal->column_count = columns;
	}
	/* Read the terminal size, in case something went awry. */
	vte_terminal_refresh_size(terminal);
}

/* Redraw the widget. */
static void
vte_handle_scroll(VteTerminal *terminal)
{
	long dy, adj;
	GtkWidget *widget;
	VteScreen *screen;
	/* Sanity checks. */
	g_return_if_fail(GTK_IS_WIDGET(terminal));
	widget = GTK_WIDGET(terminal);
	screen = terminal->pvt->screen;
	if (GTK_WIDGET_REALIZED(widget) == FALSE) {
		return;
	}
	/* This may generate multiple redraws, so freeze it while we do them. */
	gdk_window_freeze_updates(widget->window);

	/* Read the new adjustment value and save the difference. */
	adj = floor(gtk_adjustment_get_value(terminal->adjustment));
	dy = screen->scroll_delta - adj;
	screen->scroll_delta = adj;
	if (dy != 0) {
		vte_terminal_scroll_region(terminal, screen->scroll_delta,
					   terminal->row_count, dy);
	}

	/* Let the refreshing begin. */
	gdk_window_thaw_updates(widget->window);
}

/* Set the adjustment objects used by the terminal widget. */
static void
vte_terminal_set_scroll_adjustment(VteTerminal *terminal,
				   GtkAdjustment *adjustment)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	if (adjustment != NULL) {
		/* Add a reference to the new adjustment object. */
		g_object_ref(adjustment);
		/* Get rid of the old adjustment object. */
		if (terminal->adjustment != NULL) {
			/* Disconnect our signal handlers from this object. */
			g_signal_handlers_disconnect_by_func(terminal->adjustment,
							     G_CALLBACK(vte_handle_scroll),
							     terminal);
			g_object_unref(terminal->adjustment);
		}
		/* Set the new adjustment object. */
		terminal->adjustment = adjustment;
		g_signal_connect_swapped(terminal->adjustment,
					 "value_changed",
					 G_CALLBACK(vte_handle_scroll),
					 terminal);
		g_signal_connect_swapped(terminal->adjustment,
					 "changed",
					 G_CALLBACK(vte_handle_scroll),
					 terminal);
	}
}

/* Set the type of terminal we're emulating. */
void
vte_terminal_set_emulation(VteTerminal *terminal, const char *emulation)
{
	const char *code, *value;
	gboolean found_cr = FALSE, found_lf = FALSE;
	char *stripped;
	gssize stripped_length;
	int columns, rows;
	GQuark quark;
	char *tmp;
	int i;

	/* Set the emulation type, for reference. */
	if (emulation == NULL) {
		emulation = VTE_DEFAULT_EMULATION;
	}
	quark = g_quark_from_string(emulation);
	terminal->pvt->emulation = g_quark_to_string(quark);
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Setting emulation to `%s'...", emulation);
	}
#endif
	/* Find and read the right termcap file. */
	vte_terminal_set_termcap(terminal, NULL, FALSE);

	/* Create a table to hold the control sequences. */
	if (terminal->pvt->table != NULL) {
		vte_table_free(terminal->pvt->table);
	}
	terminal->pvt->table = vte_table_new();

	/* Create a tree to hold the handlers. */
	if (terminal->pvt->sequences) {
		g_tree_destroy(terminal->pvt->sequences);
	}
	terminal->pvt->sequences = g_tree_new(vte_compare_direct);
	for (i = 0; i < G_N_ELEMENTS(vte_sequence_handlers); i++) {
		if (vte_sequence_handlers[i].handler != NULL) {
			code = vte_sequence_handlers[i].code;
			g_tree_insert(terminal->pvt->sequences,
				      GINT_TO_POINTER(g_quark_from_string(code)),
				      vte_sequence_handlers[i].handler);
		}
	}

	/* Load the known capability strings from the termcap structure into
	 * the table for recognition. */
	for (i = 0;
	     vte_terminal_capability_strings[i].capability != NULL;
	     i++) {
		if (vte_terminal_capability_strings[i].key) {
			continue;
		}
		code = vte_terminal_capability_strings[i].capability;
		tmp = vte_termcap_find_string(terminal->pvt->termcap,
					      terminal->pvt->emulation,
					      code);
		if ((tmp != NULL) && (tmp[0] != '\0')) {
			vte_termcap_strip(tmp, &stripped, &stripped_length);
			vte_table_add(terminal->pvt->table,
				      stripped, stripped_length,
				      code,
				      0);
			if (stripped[0] == '\r') {
				found_cr = TRUE;
			} else
			if (stripped[0] == '\n') {
				if ((strcmp(code, "sf") == 0) ||
				    (strcmp(code, "do") == 0)) {
					found_lf = TRUE;
				}
			}
			g_free(stripped);
		}
		g_free(tmp);
	}

	/* Add emulator-specific sequences. */
	if (strstr(emulation, "xterm") || strstr(emulation, "dtterm")) {
		/* Add all of the xterm-specific stuff. */
		for (i = 0;
		     vte_xterm_capability_strings[i].value != NULL;
		     i++) {
			code = vte_xterm_capability_strings[i].code;
			value = vte_xterm_capability_strings[i].value;
			vte_termcap_strip(code, &stripped, &stripped_length);
			vte_table_add(terminal->pvt->table,
				     stripped, stripped_length,
				     value, 0);
			g_free(stripped);
		}
	}

	/* Always define cr and lf. */
	if (!found_cr) {
		vte_table_add(terminal->pvt->table, "\r", 1, "cr", 0);
	}
	if (!found_lf) {
		vte_table_add(terminal->pvt->table, "\n", 1, "sf", 0);
	}

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Trie contents:\n");
		vte_table_print(terminal->pvt->table);
		fprintf(stderr, "\n");
	}
#endif

	/* Read emulation flags. */
	terminal->pvt->flags.am = vte_termcap_find_boolean(terminal->pvt->termcap,
							   terminal->pvt->emulation,
							   "am");
	terminal->pvt->flags.bw = vte_termcap_find_boolean(terminal->pvt->termcap,
							   terminal->pvt->emulation,
							   "bw");
	terminal->pvt->flags.ul = vte_termcap_find_boolean(terminal->pvt->termcap,
							   terminal->pvt->emulation,
							   "ul");

	/* Resize to the given default. */
	columns = vte_termcap_find_numeric(terminal->pvt->termcap,
					   terminal->pvt->emulation,
					   "co");
	rows = vte_termcap_find_numeric(terminal->pvt->termcap,
					terminal->pvt->emulation,
					"li");
	terminal->pvt->default_column_count = columns;
	terminal->pvt->default_row_count = rows;

	/* Notify observers that we changed our emulation. */
	vte_terminal_emit_emulation_changed(terminal);
}

const char *
vte_terminal_get_emulation(VteTerminal *terminal)
{
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), NULL);
	return terminal->pvt->emulation;
}

/* Set the path to the termcap file we read, and read it in. */
static void
vte_terminal_set_termcap(VteTerminal *terminal, const char *path,
			 gboolean reset)
{
	struct stat st;
	char path_default[PATH_MAX];

	if (path == NULL) {
		snprintf(path_default, sizeof(path_default),
			 DATADIR "/" PACKAGE "/termcap/%s",
			 terminal->pvt->emulation ?
			 terminal->pvt->emulation : VTE_DEFAULT_EMULATION);
		if (stat(path_default, &st) == 0) {
			path = path_default;
		} else {
			path = "/etc/termcap";
		}
	}
	terminal->pvt->termcap_path = g_quark_to_string(g_quark_from_string(path));
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Loading termcap `%s'...",
			terminal->pvt->termcap_path);
	}
#endif
	if (terminal->pvt->termcap) {
		vte_termcap_free(terminal->pvt->termcap);
	}
	terminal->pvt->termcap = vte_termcap_new(path);
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "\n");
	}
#endif
	if (reset) {
		vte_terminal_set_emulation(terminal, terminal->pvt->emulation);
	}
}

static void
vte_terminal_reset_rowdata(VteRing **ring, long lines)
{
	VteRing *new_ring;
	GArray *row;
	long i, next;

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Sizing scrollback buffer to %ld lines.\n",
			lines);
	}
#endif
	if (*ring && (vte_ring_max(*ring) == lines)) {
		return;
	}
	new_ring = vte_ring_new(lines, vte_free_row_data, NULL);
	if (*ring) {
		next = vte_ring_next(*ring);
		for (i = vte_ring_delta(*ring); i < next; i++) {
			row = vte_ring_index(*ring, GArray*, i);
			vte_ring_append(new_ring, row);
		}
		vte_ring_free(*ring, FALSE);
	}
	*ring = new_ring;
}

/* Initialize the terminal widget after the base widget stuff is initialized.
 * We need to create a new psuedo-terminal pair, read in the termcap file, and
 * set ourselves up to do the interpretation of sequences. */
static void
vte_terminal_init(VteTerminal *terminal, gpointer *klass)
{
	struct _VteTerminalPrivate *pvt;
	GtkWidget *widget;
	struct passwd *pwd;
	GtkAdjustment *adjustment;
	struct timezone tz;
	struct timeval tv;
	enum VteRenderMethod render_max;

	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	widget = GTK_WIDGET(terminal);
	GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_FOCUS);

	/* Set up public-facing members. */

	/* Set an adjustment for the application to use to control scrolling. */
	adjustment = GTK_ADJUSTMENT(gtk_adjustment_new(0, 0, 0, 0, 0, 0));
	vte_terminal_set_scroll_adjustment(terminal, adjustment);

	/* Initialize the default titles. */
	terminal->window_title = NULL;
	terminal->icon_title = NULL;

	/* Initialize private data. */
	pvt = terminal->pvt = g_malloc0(sizeof(*terminal->pvt));

	/* Load the termcap data and set up the emulation. */
	pvt->termcap = NULL;
	pvt->table = NULL;
	pvt->termcap_path = NULL;
	memset(&pvt->flags, 0, sizeof(pvt->flags));
	pvt->flags.am = FALSE;
	pvt->flags.bw = FALSE;
	pvt->flags.ul = FALSE;
	pvt->keypad = VTE_KEYPAD_NORMAL;
	pvt->fkey = VTE_FKEY_VT220;
	pvt->dec_saved = g_hash_table_new(g_direct_hash, g_direct_equal);
	pvt->default_column_count = 80;
	pvt->default_row_count = 24;
	vte_terminal_set_termcap(terminal, NULL, FALSE);
	vte_terminal_set_emulation(terminal, NULL);
	vte_terminal_set_size(terminal,
			      pvt->default_column_count,
			      pvt->default_row_count);

	/* Determine what the user's shell is. */
	if (pvt->shell == NULL) {
		pwd = getpwuid(getuid());
		if (pwd != NULL) {
			pvt->shell = pwd->pw_shell;
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_MISC)) {
				fprintf(stderr, "Using user's shell (%s).\n",
					pvt->shell);
			}
#endif
		}
	}
	if (pvt->shell == NULL) {
		pvt->shell = "/bin/sh";
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC)) {
			fprintf(stderr, "Using default shell (%s).\n",
				pvt->shell);
		}
#endif
	}
	pvt->shell = g_quark_to_string(g_quark_from_string(pvt->shell));
	pvt->pty_master = -1;
	pvt->pty_input = NULL;
	pvt->pty_input_source = -1;
	pvt->pty_output = NULL;
	pvt->pty_output_source = -1;
	pvt->pty_pid = -1;

	/* Set up I/O encodings. */
	pvt->encoding = NULL;
	pvt->substitutions = vte_iso2022_new();
	pvt->incoming = NULL;
	pvt->n_incoming = 0;
	pvt->processing = FALSE;
	pvt->processing_tag = -1;
	pvt->outgoing = NULL;
	pvt->n_outgoing = 0;
	pvt->incoming_conv = (GIConv) -1;
	pvt->outgoing_conv_wide = (GIConv) -1;
	pvt->outgoing_conv_utf8 = (GIConv) -1;
	vte_terminal_set_encoding(terminal, NULL);
	g_assert(terminal->pvt->encoding != NULL);

	/* Initialize the screens and histories. */
	pvt->alternate_screen.row_data = NULL;
	vte_terminal_reset_rowdata(&pvt->alternate_screen.row_data,
				   pvt->scrollback_lines);
	pvt->alternate_screen.cursor_current.row = 0;
	pvt->alternate_screen.cursor_current.col = 0;
	pvt->alternate_screen.cursor_saved.row = 0;
	pvt->alternate_screen.cursor_saved.col = 0;
	pvt->alternate_screen.insert_delta = 0;
	pvt->alternate_screen.scroll_delta = 0;
	pvt->alternate_screen.insert_mode = FALSE;
	pvt->alternate_screen.reverse_mode = FALSE;
	pvt->alternate_screen.status_line = FALSE;
	pvt->alternate_screen.status_line_contents = g_string_new("");
	pvt->screen = &terminal->pvt->alternate_screen;
	vte_terminal_set_default_attributes(terminal);

	pvt->normal_screen.row_data = NULL;
	vte_terminal_reset_rowdata(&pvt->normal_screen.row_data,
				   pvt->scrollback_lines);
	pvt->normal_screen.cursor_current.row = 0;
	pvt->normal_screen.cursor_current.col = 0;
	pvt->normal_screen.cursor_saved.row = 0;
	pvt->normal_screen.cursor_saved.col = 0;
	pvt->normal_screen.insert_delta = 0;
	pvt->normal_screen.scroll_delta = 0;
	pvt->normal_screen.insert_mode = FALSE;
	pvt->normal_screen.reverse_mode = FALSE;
	pvt->normal_screen.status_line = FALSE;
	pvt->normal_screen.status_line_contents = g_string_new("");
	pvt->screen = &terminal->pvt->normal_screen;
	vte_terminal_set_default_attributes(terminal);

	/* Selection info. */
	pvt->word_chars = NULL;
	pvt->has_selection = FALSE;
	pvt->start_selection = FALSE;
	pvt->selection = NULL;
	pvt->selection_start.x = 0;
	pvt->selection_start.y = 0;
	pvt->selection_end.x = 0;
	pvt->selection_end.y = 0;
	vte_terminal_set_word_chars(terminal, "-a-zA-Z0-9");

	/* Miscellaneous options. */
	vte_terminal_set_backspace_binding(terminal, VTE_ERASE_AUTO);
	vte_terminal_set_delete_binding(terminal, VTE_ERASE_AUTO);
	pvt->alt_sends_escape = TRUE;
	pvt->audible_bell = TRUE;
	pvt->visible_bell = FALSE;
	pvt->xterm_font_tweak = FALSE;
	pvt->tabstops = NULL;
	vte_terminal_set_default_tabstops(terminal);

	/* Scrolling options. */
	pvt->scroll_on_output = FALSE;
	pvt->scroll_on_keystroke = TRUE;
	pvt->scrollback_lines = VTE_SCROLLBACK_MIN;
	vte_terminal_set_scrollback_lines(terminal,
					  terminal->pvt->scrollback_lines);

	/* Cursor blinking. */
	pvt->cursor_blinks = FALSE;
	pvt->cursor_blink_tag = -1;
	pvt->cursor_visible = TRUE;

	/* Input options. */
	if (gettimeofday(&tv, &tz) == 0) {
		pvt->last_keypress_time = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
	} else {
		pvt->last_keypress_time = 0;
	}
	pvt->mouse_send_xy_on_click = FALSE;
	pvt->mouse_send_xy_on_button = FALSE;
	pvt->mouse_hilite_tracking = FALSE;
	pvt->mouse_cell_motion_tracking = FALSE;
	pvt->mouse_all_motion_tracking = FALSE;
	pvt->mouse_last_button = 0;
	pvt->mouse_last_x = 0;
	pvt->mouse_last_y = 0;
	pvt->mouse_autohide = FALSE;

	/* Matching data. */
	pvt->match_contents = NULL;
	pvt->match_attributes = NULL;
	pvt->match_regexes = g_array_new(FALSE, TRUE,
					 sizeof(struct vte_match_regex));
	pvt->match_start.row = 0;
	pvt->match_start.column = 0;
	pvt->match_end = pvt->match_start;

	/* Server-side rendering data.  Try everything. */
	pvt->palette_initialized = FALSE;
	memset(&pvt->palette, 0, sizeof(pvt->palette));
	pvt->fontset = NULL;
	pvt->fontpaddingl = NULL;
	pvt->fontpaddingr = NULL;
	render_max = VteRenderPango;
#ifdef HAVE_XFT
	pvt->ftfont = NULL;
	render_max = VteRenderXft1;
#ifdef HAVE_XFT2
	/* GTK+ with Xft1-only = 2.0.  If we have fontconfig, it's either a
	 * devel version with fontconfig support or 2.2 or later. */
	render_max = VteRenderXft2;
#endif
#endif
	/* Let debugging users have some influence on how we render text. */
	if ((render_max == VteRenderXft2) &&
	    (getenv("VTE_USE_XFT2") != NULL)) {
		if (atol(getenv("VTE_USE_XFT2")) == 0) {
			render_max = VteRenderXft1;
		}
	}
	if ((render_max >= VteRenderXft1) &&
	    (getenv("VTE_USE_XFT") != NULL)) {
		if (atol(getenv("VTE_USE_XFT")) == 0) {
			render_max = VteRenderPango;
		}
	}
	if ((render_max >= VteRenderXft1) &&
	    (getenv("GDK_USE_XFT") != NULL)) {
		if (atol(getenv("VTE_USE_XFT")) == 0) {
			render_max = VteRenderPango;
		}
	}
	if ((render_max == VteRenderPango) &&
	    (getenv("VTE_USE_PANGO") != NULL)) {
		if (atol(getenv("VTE_USE_PANGO")) == 0) {
			render_max = VteRenderXlib;
		}
	}
	pvt->render_method = render_max;

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		switch (pvt->render_method) {
		case VteRenderXft2:
#ifdef HAVE_XFT2
			fprintf(stderr, "Using Xft2.\n");
			break;
#endif
		case VteRenderXft1:
			fprintf(stderr, "Using Xft1.\n");
			break;
		case VteRenderPango:
			fprintf(stderr, "Using Pango.\n");
			break;
		case VteRenderXlib:
		default:
			fprintf(stderr, "Using Xlib fonts.\n");
		}
	}
#endif

	/* The font description. */
	pvt->fontdesc = NULL;
	gtk_widget_ensure_style(widget);
	vte_terminal_set_font(terminal, NULL);

	/* Input method support. */
	pvt->im_context = NULL;
	pvt->im_preedit = NULL;
	pvt->im_preedit_cursor = 0;

	/* Our accessible peer. */
	pvt->accessible = NULL;

	/* Settings we're monitoring. */
	pvt->connected_settings = NULL;

	/* Set up background information. */
	pvt->bg_transparent = FALSE;
	pvt->bg_transparent_update_pending = FALSE;
	pvt->bg_transparent_update_tag = -1;
	pvt->bg_transparent_atom = 0;
	pvt->bg_transparent_window = NULL;
	pvt->bg_transparent_image = NULL;
	pvt->bg_saturation = 0.4 * VTE_SATURATION_MAX;
	pvt->bg_image = NULL;

	/* Listen for hierarchy change notifications. */
	g_signal_connect(G_OBJECT(terminal), "hierarchy-changed",
			 G_CALLBACK(vte_terminal_hierarchy_changed),
			 NULL);

	/* Listen for style changes. */
	g_signal_connect(G_OBJECT(terminal), "style-set",
			 G_CALLBACK(vte_terminal_style_changed),
			 NULL);

	/* Mapping trees. */
	pvt->unichar_wc_map = g_tree_new(vte_compare_direct);
}

/* Tell GTK+ how much space we need. */
static void
vte_terminal_size_request(GtkWidget *widget, GtkRequisition *requisition)
{
	VteTerminal *terminal;

	g_return_if_fail(widget != NULL);
	g_return_if_fail(VTE_IS_TERMINAL(widget));
	terminal = VTE_TERMINAL(widget);

	if (terminal->pvt->pty_master != -1) {
		vte_terminal_refresh_size(terminal);
		requisition->width = terminal->char_width *
				     terminal->column_count;
		requisition->height = terminal->char_height *
				      terminal->row_count;
	} else {
		requisition->width = terminal->char_width *
				     terminal->pvt->default_column_count;
		requisition->height = terminal->char_height *
				      terminal->pvt->default_row_count;
	}

	requisition->width += VTE_PAD_WIDTH * 2;
	requisition->height += VTE_PAD_WIDTH * 2;

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Size request is %dx%d.\n",
			requisition->width, requisition->height);
	}
#endif
}

/* Accept a given size from GTK+. */
static void
vte_terminal_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
{
	VteTerminal *terminal;
	glong width, height;

	g_return_if_fail(widget != NULL);
	g_return_if_fail(VTE_IS_TERMINAL(widget));

	terminal = VTE_TERMINAL(widget);

	width = (allocation->width - (2 * VTE_PAD_WIDTH)) /
		terminal->char_width;
	height = (allocation->height - (2 * VTE_PAD_WIDTH)) /
		 terminal->char_height;

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Sizing window to %dx%d (%ldx%ld).\n",
			allocation->width, allocation->height,
			width, height);
	}
#endif

	/* Set our allocation to match the structure. */
	widget->allocation = *allocation;

	/* Set the size of the pseudo-terminal. */
	vte_terminal_set_size(terminal, width, height);

	/* Adjust scrollback buffers to ensure that they're big enough. */
	vte_terminal_set_scrollback_lines(terminal,
					  MAX(terminal->pvt->scrollback_lines,
					      height));

	/* Resize the GDK window. */
	if (widget->window != NULL) {
		gdk_window_move_resize(widget->window,
				       allocation->x,
				       allocation->y,
				       allocation->width,
				       allocation->height);
		vte_terminal_queue_background_update(terminal);
	}

	/* Adjust the adjustments. */
	vte_terminal_adjust_adjustments(terminal);
	vte_invalidate_all(terminal);
}

/* The window is being destroyed. */
static void
vte_terminal_unrealize(GtkWidget *widget)
{
	VteTerminal *terminal;
	Display *display;
	GdkColormap *gcolormap;
	Colormap colormap;
	GdkVisual *gvisual;
	Visual *visual;
	int i;

	g_return_if_fail(widget != NULL);
	g_return_if_fail(VTE_IS_TERMINAL(widget));
	terminal = VTE_TERMINAL(widget);

	/* Shut down accessibility. */
	if (terminal->pvt->accessible != NULL) {
		g_object_unref(G_OBJECT(terminal->pvt->accessible));
		terminal->pvt->accessible = NULL;
	}

	/* Deallocate the cursors. */
	gdk_cursor_unref(terminal->pvt->mouse_default_cursor);
	terminal->pvt->mouse_default_cursor = NULL;
	gdk_cursor_unref(terminal->pvt->mouse_mousing_cursor);
	terminal->pvt->mouse_mousing_cursor = NULL;
	gdk_cursor_unref(terminal->pvt->mouse_inviso_cursor);
	terminal->pvt->mouse_inviso_cursor = NULL;

	/* Shut down input methods. */
	g_object_unref(G_OBJECT(terminal->pvt->im_context));
	terminal->pvt->im_context = NULL;

#ifdef HAVE_XFT
	/* Clean up after Xft. */
	display = gdk_x11_drawable_get_xdisplay(widget->window);
	gvisual = gtk_widget_get_visual(widget);
	visual = gdk_x11_visual_get_xvisual(gvisual);
	gcolormap = gtk_widget_get_colormap(widget);
	colormap = gdk_x11_colormap_get_xcolormap(gcolormap);
	for (i = 0; i < G_N_ELEMENTS(terminal->pvt->palette); i++) {
		XftColorFree(display,
			     visual,
			     colormap,
			     &terminal->pvt->palette[i].ftcolor);
	}
#endif

	/* Clean up after Pango. */
	if (terminal->pvt->fontpaddingl != NULL) {
		g_tree_destroy(terminal->pvt->fontpaddingl);
		terminal->pvt->fontpaddingl = NULL;
	}
	if (terminal->pvt->fontpaddingr != NULL) {
		g_tree_destroy(terminal->pvt->fontpaddingr);
		terminal->pvt->fontpaddingr = NULL;
	}

	/* Unload fonts. */
	vte_terminal_close_font(terminal);

	/* Disconnect any filters which might be watching for X window
	 * pixmap changes. */
	if (terminal->pvt->bg_transparent) {
		gdk_window_remove_filter(terminal->pvt->bg_transparent_window,
					 vte_terminal_filter_property_changes,
					 terminal);
	}
	gdk_window_remove_filter(widget->window,
				 vte_terminal_filter_property_changes,
				 terminal);

	/* Unmap the widget if it hasn't been already. */
	if (GTK_WIDGET_MAPPED(widget)) {
		gtk_widget_unmap(widget);
	}

	/* Remove the GDK window. */
	if (widget->window != NULL) {
		gdk_window_destroy(widget->window);
		widget->window = NULL;
	}

	/* Remove the blink timeout function. */
	if (terminal->pvt->cursor_blink_tag != -1) {
		g_source_remove(terminal->pvt->cursor_blink_tag);
	}

	/* Mark that we no longer have a GDK window. */
	GTK_WIDGET_UNSET_FLAGS(widget, GTK_REALIZED);
}

/* Perform final cleanups for the widget before it's freed. */
static void
vte_terminal_finalize(GObject *object)
{
	VteTerminal *terminal;
	GtkWidget *toplevel;
	GObjectClass *object_class;
	GtkWidgetClass *widget_class;
	GtkClipboard *clipboard;
	struct vte_match_regex *regex;
	int i;

	g_return_if_fail(VTE_IS_TERMINAL(object));
	terminal = VTE_TERMINAL(object);
	object_class = G_OBJECT_GET_CLASS(G_OBJECT(object));
	widget_class = g_type_class_peek(GTK_TYPE_WIDGET);

	/* The unichar->wchar_t map. */
	if (terminal->pvt->unichar_wc_map != NULL) {
		g_tree_destroy(terminal->pvt->unichar_wc_map);
		terminal->pvt->unichar_wc_map = NULL;
	}

	/* The NLS maps. */
	if (terminal->pvt->substitutions != NULL) {
		vte_iso2022_free(terminal->pvt->substitutions);
		terminal->pvt->substitutions = NULL;
	}

	/* Free background info. */
	if (terminal->pvt->bg_image != NULL) {
		g_object_unref(G_OBJECT(terminal->pvt->bg_image));
		terminal->pvt->bg_image = NULL;
	}
	if (terminal->pvt->bg_transparent_image != NULL) {
		g_object_unref(G_OBJECT(terminal->pvt->bg_transparent_image));
		terminal->pvt->bg_transparent_image = NULL;
	}
	if (terminal->pvt->bg_transparent_image != NULL) {
		g_object_unref(G_OBJECT(terminal->pvt->bg_transparent_image));
		terminal->pvt->bg_transparent_image = NULL;
	}
	if (terminal->pvt->bg_transparent_update_tag != -1) {
		g_source_remove(terminal->pvt->bg_transparent_update_tag);
		terminal->pvt->bg_transparent_update_tag = -1;
	}

#ifdef HAVE_XFT2
	/* Disconnect from settings changes. */
	if (terminal->pvt->connected_settings) {
		g_signal_handlers_disconnect_by_func(G_OBJECT(terminal->pvt->connected_settings),
						     vte_xft_changed_cb,
						     terminal);
		terminal->pvt->connected_settings = NULL;
	}
#endif

	/* Free the fonts if we still have some loaded. */
	vte_terminal_close_font(terminal);

	/* Free the font description. */
	if (terminal->pvt->fontdesc != NULL) {
		pango_font_description_free(terminal->pvt->fontdesc);
		terminal->pvt->fontdesc = NULL;
	}

	/* Free matching data. */
	if (terminal->pvt->match_attributes != NULL) {
		g_array_free(terminal->pvt->match_attributes, TRUE);
		terminal->pvt->match_attributes = NULL;
	}
	if (terminal->pvt->match_contents != NULL) {
		g_free(terminal->pvt->match_contents);
		terminal->pvt->match_contents = NULL;
	}
	if (terminal->pvt->match_regexes != NULL) {
		for (i = 0; i < terminal->pvt->match_regexes->len; i++) {
			regex = &g_array_index(terminal->pvt->match_regexes,
					       struct vte_match_regex,
					       i);
			regfree(&regex->reg);
		}
		g_array_free(terminal->pvt->match_regexes, TRUE);
		terminal->pvt->match_regexes = NULL;
	}

	/* Disconnect from toplevel window configure events. */
	toplevel = gtk_widget_get_toplevel(GTK_WIDGET(object));
	if ((toplevel != NULL) && (G_OBJECT(toplevel) != G_OBJECT(object))) {
		g_signal_handlers_disconnect_by_func(toplevel,
						     vte_terminal_configure_toplevel,
						     terminal);
	}

	/* Tabstop information. */
	if (terminal->pvt->tabstops != NULL) {
		g_hash_table_destroy(terminal->pvt->tabstops);
		terminal->pvt->tabstops = NULL;
	}

	/* Free any selected text, but if we currently own the selection,
	 * throw the text onto the clipboard without an owner so that it
	 * doesn't just disappear. */
	if (terminal->pvt->selection != NULL) {
		clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
		if (gtk_clipboard_get_owner(clipboard) == G_OBJECT(terminal)) {
			gtk_clipboard_set_text(clipboard,
					       terminal->pvt->selection,
					       -1);
		}
		g_free(terminal->pvt->selection);
		terminal->pvt->selection = NULL;
	}
	if (terminal->pvt->word_chars != NULL) {
		g_array_free(terminal->pvt->word_chars, TRUE);
		terminal->pvt->word_chars = NULL;
	}

	/* Clear the output histories. */
	vte_ring_free(terminal->pvt->normal_screen.row_data, TRUE);
	terminal->pvt->normal_screen.row_data = NULL;
	vte_ring_free(terminal->pvt->alternate_screen.row_data, TRUE);
	terminal->pvt->alternate_screen.row_data = NULL;

	/* Clear the status lines. */
	terminal->pvt->normal_screen.status_line = FALSE;
	g_string_free(terminal->pvt->normal_screen.status_line_contents,
		      TRUE);
	terminal->pvt->alternate_screen.status_line = FALSE;
	g_string_free(terminal->pvt->alternate_screen.status_line_contents,
		      TRUE);

	/* Free conversion descriptors. */
	if (terminal->pvt->incoming_conv != ((GIConv) -1)) {
		g_iconv_close(terminal->pvt->incoming_conv);
	}
	terminal->pvt->incoming_conv = ((GIConv) -1);
	if (terminal->pvt->outgoing_conv_wide != ((GIConv) -1)) {
		g_iconv_close(terminal->pvt->outgoing_conv_wide);
	}
	terminal->pvt->outgoing_conv_wide = ((GIConv) -1);
	if (terminal->pvt->outgoing_conv_utf8 != ((GIConv) -1)) {
		g_iconv_close(terminal->pvt->outgoing_conv_utf8);
	}
	terminal->pvt->outgoing_conv_utf8 = ((GIConv) -1);

	/* Stop listening for child-exited signals. */
	g_signal_handlers_disconnect_by_func(vte_reaper_get(),
					     vte_terminal_catch_child_exited,
					     terminal);

	/* Stop processing input. */
	if (terminal->pvt->processing_tag != -1) {
		g_source_remove(terminal->pvt->processing_tag);
		terminal->pvt->processing_tag = -1;
	}

	/* Discard any pending data. */
	if (terminal->pvt->incoming != NULL) {
		g_free(terminal->pvt->incoming);
	}
	terminal->pvt->incoming = NULL;
	terminal->pvt->n_incoming = 0;

	/* Stop the child and stop watching for input from the child. */
	if (terminal->pvt->pty_pid > 0) {
		kill(-terminal->pvt->pty_pid, SIGHUP);
	}
	terminal->pvt->pty_pid = 0;
	if (terminal->pvt->pty_input != NULL) {
		g_io_channel_unref(terminal->pvt->pty_input);
		terminal->pvt->pty_input = NULL;
		g_source_remove(terminal->pvt->pty_input_source);
		terminal->pvt->pty_input_source = -1;
	}
	if (terminal->pvt->pty_output != NULL) {
		g_io_channel_unref(terminal->pvt->pty_output);
		terminal->pvt->pty_output = NULL;
		g_source_remove(terminal->pvt->pty_output_source);
		terminal->pvt->pty_output_source = -1;
	}
	close(terminal->pvt->pty_master);
	terminal->pvt->pty_master = -1;

	/* Clear some of our strings. */
	terminal->pvt->shell = NULL;

	/* Remove hash tables. */
	if (terminal->pvt->dec_saved != NULL) {
		g_hash_table_destroy(terminal->pvt->dec_saved);
		terminal->pvt->dec_saved = NULL;
	}

	/* Clean up emulation structures. */
	memset(&terminal->pvt->flags, 0, sizeof(terminal->pvt->flags));
	g_tree_destroy(terminal->pvt->sequences);
	terminal->pvt->sequences= NULL;
	terminal->pvt->emulation = NULL;
	terminal->pvt->termcap_path = NULL;
	if (terminal->pvt->table != NULL) {
		vte_table_free(terminal->pvt->table);
		terminal->pvt->table = NULL;
	}
	vte_termcap_free(terminal->pvt->termcap);
	terminal->pvt->termcap = NULL;

	/* Free public-facing data. */
	if (terminal->window_title != NULL) {
		g_free(terminal->window_title);
		terminal->window_title = NULL;
	}
	if (terminal->icon_title != NULL) {
		g_free(terminal->icon_title);
		terminal->icon_title = NULL;
	}
	if (terminal->adjustment != NULL) {
		g_object_unref(terminal->adjustment);
		terminal->adjustment = NULL;
	}

	/* Call the inherited finalize() method. */
	if (G_OBJECT_CLASS(widget_class)->finalize) {
		(G_OBJECT_CLASS(widget_class))->finalize(object);
	}
}

/* Handle realizing the widget.  Most of this is copy-paste from GGAD. */
static void
vte_terminal_realize(GtkWidget *widget)
{
	VteTerminal *terminal = NULL;
	GdkWindowAttr attributes;
	GdkPixmap *pixmap;
	GdkColor black = {0,}, color;
	int attributes_mask = 0, i;

	g_return_if_fail(widget != NULL);
	g_return_if_fail(VTE_IS_TERMINAL(widget));
	terminal = VTE_TERMINAL(widget);

	/* Create a GDK window for the widget. */
	attributes.window_type = GDK_WINDOW_CHILD;
	attributes.x = 0;
	attributes.y = 0;
	attributes.width = widget->allocation.width;
	attributes.height = widget->allocation.height;
	attributes.wclass = GDK_INPUT_OUTPUT;
	attributes.visual = gtk_widget_get_visual(widget);
	attributes.colormap = gtk_widget_get_colormap(widget);
	attributes.event_mask = gtk_widget_get_events(widget) |
				GDK_EXPOSURE_MASK |
				GDK_BUTTON_PRESS_MASK |
				GDK_BUTTON_RELEASE_MASK |
				GDK_POINTER_MOTION_MASK |
				GDK_BUTTON1_MOTION_MASK |
				GDK_KEY_PRESS_MASK |
				GDK_KEY_RELEASE_MASK;
	attributes.cursor = terminal->pvt->mouse_default_cursor;
	attributes_mask = GDK_WA_X |
			  GDK_WA_Y |
			  GDK_WA_VISUAL |
			  GDK_WA_COLORMAP |
			  GDK_WA_CURSOR;
	widget->window = gdk_window_new(gtk_widget_get_parent_window(widget),
					&attributes,
					attributes_mask);
	gdk_window_move_resize(widget->window,
			       widget->allocation.x,
			       widget->allocation.y,
			       widget->allocation.width,
			       widget->allocation.height);
	gdk_window_set_user_data(widget->window, widget);
	gdk_window_show(widget->window);

	/* Set up the desired palette. */
	if (!terminal->pvt->palette_initialized) {
		vte_terminal_set_default_colors(terminal);
	}

	/* Set the realized flag. */
	GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED);

	/* Add a filter to watch for property changes. */
	gdk_window_add_filter(widget->window,
			      vte_terminal_filter_property_changes,
			      terminal);

	/* Actually load the font. */
	vte_terminal_set_font(terminal, terminal->pvt->fontdesc);

	/* Allocate colors. */
	for (i = 0; i < G_N_ELEMENTS(terminal->pvt->palette); i++) {
		color.red = terminal->pvt->palette[i].red;
		color.green = terminal->pvt->palette[i].green;
		color.blue = terminal->pvt->palette[i].blue;
		color.pixel = 0;
		vte_terminal_set_color_internal(terminal, i, &color);
	}

	/* Set up the background. */
	vte_terminal_setup_background(terminal, TRUE);

	/* Setup cursor blink */
	terminal->pvt->cursor_blink_tag = g_timeout_add_full(G_PRIORITY_LOW,
							     0,
							     vte_invalidate_cursor_periodic,
							     terminal,
							     NULL);

	/* Set up input method support.  FIXME: do we need to handle the
	 * "retrieve-surrounding" and "delete-surrounding" events? */
	if (terminal->pvt->im_context != NULL) {
		g_object_unref(G_OBJECT(terminal->pvt->im_context));
		terminal->pvt->im_context = NULL;
	}
	terminal->pvt->im_context = gtk_im_multicontext_new();
	gtk_im_context_set_client_window(terminal->pvt->im_context,
					 widget->window);
	g_signal_connect(G_OBJECT(terminal->pvt->im_context), "commit",
			 GTK_SIGNAL_FUNC(vte_terminal_im_commit), terminal);
	g_signal_connect(G_OBJECT(terminal->pvt->im_context), "preedit-start",
			 GTK_SIGNAL_FUNC(vte_terminal_im_preedit_start),
			 terminal);
	g_signal_connect(G_OBJECT(terminal->pvt->im_context), "preedit-changed",
			 GTK_SIGNAL_FUNC(vte_terminal_im_preedit_changed),
			 terminal);
	g_signal_connect(G_OBJECT(terminal->pvt->im_context), "preedit-end",
			 GTK_SIGNAL_FUNC(vte_terminal_im_preedit_end),
			 terminal);
	gtk_im_context_set_use_preedit(terminal->pvt->im_context, TRUE);

	/* Create the stock cursors. */
	terminal->pvt->mouse_default_cursor =
		gdk_cursor_new(VTE_DEFAULT_CURSOR);
	terminal->pvt->mouse_mousing_cursor =
		gdk_cursor_new(VTE_MOUSING_CURSOR);

	/* Create our invisible cursor. */
	pixmap = gdk_pixmap_new(widget->window, 1, 1, 1);
	terminal->pvt->mouse_inviso_cursor =
		gdk_cursor_new_from_pixmap(pixmap, pixmap,
					   &black, &black, 0, 0);
	g_object_unref(G_OBJECT(pixmap));

	/* Grab input focus. */
	gtk_widget_grab_focus(widget);
}

static void
vte_terminal_determine_colors(VteTerminal *terminal,
			      const struct vte_charcell *cell, gboolean reverse,
			      int *fore, int *back)
{
	/* Determine what the foreground and background colors for rendering
	 * text should be. */
	if (reverse ^ ((cell != NULL) && (cell->reverse))) {
		*fore = cell ? cell->back : VTE_DEF_BG;
		*back = cell ? cell->fore : VTE_DEF_FG;
	} else {
		*fore = cell ? cell->fore : VTE_DEF_FG;
		*back = cell ? cell->back : VTE_DEF_BG;
	}

	/* Handle invisible, bold, and standout text by adjusting colors. */
	if (cell && cell->invisible) {
		*fore = *back;
	}
	if (cell && cell->bold) {
		if (*fore == VTE_DEF_FG) {
			*fore = VTE_BOLD_FG;
		} else
		if ((*fore != VTE_DEF_BG) && (*fore < VTE_COLOR_SET_SIZE)) {
			*fore += VTE_COLOR_BRIGHT_OFFSET;
		}
	}
	if (cell && cell->standout) {
		if (*back < VTE_COLOR_SET_SIZE) {
			*back += VTE_COLOR_BRIGHT_OFFSET;
		}
	}
}

#if HAVE_XFT
/* Try to map some common characters which are frequently missing from fonts
 * to others which look the same and may be there. */
static XftChar32
vte_terminal_xft_remap_char(Display *display, XftFont *font, XftChar32 orig)
{
	XftChar32 new;

	if (XftGlyphExists(display, font, orig)) {
		return orig;
	}

	switch (orig) {
		case 0:			/* NUL */
		case 0x00A0:		/* NO-BREAK SPACE */
			new = 0x0020;	/* SPACE */
			break;
		case 0x2010:		/* HYPHEN */
		case 0x2011:		/* NON-BREAKING HYPHEN */
		case 0x2012:		/* FIGURE DASH */
		case 0x2013:		/* EN DASH */
		case 0x2014:		/* EM DASH */
		case 0x2212:		/* MINUS SIGN */
			new = 0x002D;	/* HYPHEN-MINUS */
			break;
		default:
			return orig;
	}

	if (XftGlyphExists(display, font, new)) {
		return new;
	} else {
		return orig;
	}
}
#endif

/* Check if a unicode character is actually a graphic character we draw
 * ourselves to handle cases where fonts don't have glyphs for them. */
static gboolean
vte_unichar_isgraphic(gunichar c)
{
	switch (c) {
		case 0x2500: /* horizontal line */
		case 0x2502: /* vertical line */
		case 0x250c: /* upleft corner */
		case 0x2510: /* upright corner */
		case 0x2514: /* downleft corner */
		case 0x2518: /* downright corner */
		case 0x2524: /* right t */
		case 0x251c: /* left t */
		case 0x2534: /* up tee */
		case 0x252c: /* down tee */
		case 0x253c: /* cross */
		case 0x2592: /* checkerboard */
		case 0x25c6: /* diamond */
		case 0x00b0: /* degree */
		case 0x00b1: /* plus/minus */
		case 0x00b7: /* bullet */
		case 0x2190: /* left arrow */
		case 0x2192: /* right arrow */
		case 0x2193: /* down arrow */
		case 0x2191: /* up arrow */
		case 0x25ae: /* block */
			return TRUE;
			break;
		default:
			break;
	}
	return FALSE;
}

/* Draw the graphic representation of an alternate font graphics character. */
static void
vte_terminal_draw_graphic(VteTerminal *terminal, gunichar c,
			  gint fore, gint back, gboolean draw_default_bg,
			  gint x, gint y, gint column_width, gint row_height,
			  Display *display,
			  GdkDrawable *gdrawable, Drawable drawable,
			  GdkGC *ggc, GC gc)
{
	XPoint diamond[4];
	gint xcenter, xright, ycenter, ybottom, i, j, draw;

	x += VTE_PAD_WIDTH;
	y += VTE_PAD_WIDTH;

	/* If this is a unicode special graphics character, map it to one of
	 * the characters we know how to draw. */
	switch (c) {
		case 0x2500: /* horizontal line */
			c = 'q';
			break;
		case 0x2502: /* vertical line */
			c = 'x';
			break;
		case 0x250c: /* upleft corner */
			c = 'l';
			break;
		case 0x2510: /* upright corner */
			c = 'k';
			break;
		case 0x2514: /* downleft corner */
			c = 'm';
			break;
		case 0x2518: /* downright corner */
			c = 'j';
			break;
		case 0x2524: /* right t */
			c = 'u';
			break;
		case 0x251c: /* left t */
			c = 't';
			break;
		case 0x2534: /* up tee */
			c = 'w';
			break;
		case 0x252c: /* down tee */
			c = 'v';
			break;
		case 0x253c: /* cross */
			c = 'n';
			break;
		case 0x2592: /* checkerboard */
			c = 'a';
			break;
		case 0x25c6: /* diamond */
			c = 96;
			break;
		case 0x00b0: /* degree */
			c = 'f';
			break;
		case 0x00b1: /* plus/minus */
			c = 'g';
			break;
		case 0x00b7: /* bullet */
			c = 127;
			break;
		case 0x2190: /* left arrow */
		case 0x2192: /* right arrow */
		case 0x2193: /* down arrow */
		case 0x2191: /* up arrow */
		case 0x25ae: /* block */
		default:
			break;
	}

	xright = x + column_width;
	ybottom = y + row_height;
	xcenter = (x + xright) / 2;
	ycenter = (y + ybottom) / 2;

	if ((back != VTE_DEF_BG) || draw_default_bg) {
		XSetForeground(display, gc, terminal->pvt->palette[back].pixel);
		XFillRectangle(display, drawable, gc,
			       x, y,
			       column_width, row_height);
	}
	XSetForeground(display, gc, terminal->pvt->palette[fore].pixel);
	switch (c) {
		case 95:
			/* drawing a blank */
			break;
		case 96:
			/* diamond */
			diamond[0].x = xcenter;
			diamond[0].y = y + 1;
			diamond[1].x = xright - 1;
			diamond[1].y = ycenter;
			diamond[2].x = xcenter;
			diamond[2].y = ybottom - 1;
			diamond[3].x = x + 1;
			diamond[3].y = ycenter;
			XFillPolygon(display, drawable, gc,
				     diamond, 4,
				     Convex, CoordModeOrigin);
			break;
		case 97:  /* a */
			for (i = x; i <= xright; i++) {
				draw = ((i - x) & 1) == 0;
				for (j = y; j <= ybottom; j++) {
					if (draw) {
						XDrawPoint(display,
							   drawable,
							   gc, i, j);
					}
					draw = !draw;
				}
			}
			break;
		case 98:  /* b */
			xcenter--;
			ycenter--;
			xright--;
			ybottom--;
			/* H */
			XDrawLine(display, drawable, gc,
				  x, y,
				  x, ycenter);
			XDrawLine(display, drawable, gc,
				  xcenter, y,
				  xcenter, ycenter);
			XDrawLine(display, drawable, gc,
				  x, (y + ycenter) / 2,
				  xcenter, (y + ycenter) / 2);
			/* T */
			XDrawLine(display, drawable, gc,
				  xcenter, ycenter,
				  xright - 1, ycenter);
			XDrawLine(display, drawable, gc,
				  (xcenter + xright) / 2, ycenter,
				  (xcenter + xright) / 2, ybottom - 1);
			break;
		case 99:  /* c */
			xcenter--;
			ycenter--;
			xright--;
			ybottom--;
			/* F */
			XDrawLine(display, drawable, gc,
				  x, y,
				  x, ycenter);
			XDrawLine(display, drawable, gc,
				  x, y,
				  xcenter, y);
			XDrawLine(display, drawable, gc,
				  x, (y + ycenter) / 2,
				  xcenter, (y + ycenter) / 2);
			/* F */
			XDrawLine(display, drawable, gc,
				  xcenter, ycenter,
				  xcenter, ybottom - 1);
			XDrawLine(display, drawable, gc,
				  xcenter, ycenter,
				  xright - 1, ycenter);
			XDrawLine(display, drawable, gc,
				  xcenter, (ycenter + ybottom) / 2,
				  xright - 1, (ycenter + ybottom) / 2);
			break;
		case 100: /* d */
			xcenter--;
			ycenter--;
			xright--;
			ybottom--;
			/* C */
			XDrawLine(display, drawable, gc,
				  x, y,
				  x, ycenter);
			XDrawLine(display, drawable, gc,
				  x, y,
				  xcenter, y);
			XDrawLine(display, drawable, gc,
				  x, ycenter,
				  xcenter, ycenter);
			/* R */
			XDrawLine(display, drawable, gc,
				  xcenter, ycenter,
				  xcenter, ybottom - 1);
			XDrawLine(display, drawable, gc,
				  xcenter, ycenter,
				  xright - 1, ycenter);
			XDrawLine(display, drawable, gc,
				  xright - 1, ycenter,
				  xright - 1, (ycenter + ybottom) / 2);
			XDrawLine(display, drawable, gc,
				  xright - 1, (ycenter + ybottom) / 2,
				  xcenter, (ycenter + ybottom) / 2);
			XDrawLine(display, drawable, gc,
				  xcenter, (ycenter + ybottom) / 2,
				  xright - 1, ybottom - 1);
			break;
		case 101: /* e */
			xcenter--;
			ycenter--;
			xright--;
			ybottom--;
			/* L */
			XDrawLine(display, drawable, gc,
				  x, y,
				  x, ycenter);
			XDrawLine(display, drawable, gc,
				  x, ycenter,
				  xcenter, ycenter);
			/* F */
			XDrawLine(display, drawable, gc,
				  xcenter, ycenter,
				  xcenter, ybottom - 1);
			XDrawLine(display, drawable, gc,
				  xcenter, ycenter,
				  xright - 1, ycenter);
			XDrawLine(display, drawable, gc,
				  xcenter, (ycenter + ybottom) / 2,
				  xright - 1, (ycenter + ybottom) / 2);
			break;
		case 102: /* f */
			/* litle circle */
			diamond[0].x = xcenter - 1;
			diamond[0].y = ycenter;
			diamond[1].x = xcenter;
			diamond[1].y = ycenter - 1;
			diamond[2].x = xcenter + 1;
			diamond[2].y = ycenter;
			diamond[3].x = xcenter;
			diamond[3].y = ycenter + 1;
			XFillPolygon(display, drawable, gc,
				     diamond, 4,
				     Convex, CoordModeOrigin);
			break;
		case 103: /* g */
			xcenter--;
			ycenter--;
			xright--;
			ybottom--;
			/* +/- */
			XDrawLine(display, drawable, gc,
				  xcenter, (y + ycenter) / 2,
				  xcenter, (ycenter + ybottom) / 2);
			XDrawLine(display, drawable, gc,
				  (x + xcenter) / 2, ycenter,
				  (xcenter + xright) / 2, ycenter);
			XDrawLine(display, drawable, gc,
				  (x + xcenter) / 2,
				  (ycenter + ybottom) / 2,
				  (xcenter + xright) / 2,
				  (ycenter + ybottom) / 2);
			break;
		case 104: /* h */
			xcenter--;
			ycenter--;
			xright--;
			ybottom--;
			/* N */
			XDrawLine(display, drawable, gc,
				  x, y,
				  x, ycenter);
			XDrawLine(display, drawable, gc,
				  x, y,
				  xcenter, ycenter);
			XDrawLine(display, drawable, gc,
				  xcenter, y,
				  xcenter, ycenter);
			/* L */
			XDrawLine(display, drawable, gc,
				  xcenter, ycenter,
				  xcenter, ybottom - 1);
			XDrawLine(display, drawable, gc,
				  xcenter, ybottom - 1,
				  xright - 1, ybottom - 1);
			break;
		case 105: /* i */
			xcenter--;
			ycenter--;
			xright--;
			ybottom--;
			/* V */
			XDrawLine(display, drawable, gc,
				  x, y,
				  (x + xcenter) / 2, ycenter);
			XDrawLine(display, drawable, gc,
				  (x + xcenter) / 2, ycenter,
				  xcenter, y);
			/* T */
			XDrawLine(display, drawable, gc,
				  xcenter, ycenter,
				  xright - 1, ycenter);
			XDrawLine(display, drawable, gc,
				  (xcenter + xright) / 2, ycenter,
				  (xcenter + xright) / 2, ybottom - 1);
			break;
		case 106: /* j */
			XFillRectangle(display,
				       drawable,
				       gc,
				       x,
				       ycenter,
				       xcenter - x + VTE_LINE_WIDTH,
				       VTE_LINE_WIDTH);
			XFillRectangle(display,
				       drawable,
				       gc,
				       xcenter,
				       y,
				       VTE_LINE_WIDTH,
				       ycenter - y + VTE_LINE_WIDTH);
			break;
		case 107: /* k */
			XFillRectangle(display,
				       drawable,
				       gc,
				       x,
				       ycenter,
				       xcenter - x + VTE_LINE_WIDTH,
				       VTE_LINE_WIDTH);
			XFillRectangle(display,
				       drawable,
				       gc,
				       xcenter,
				       ycenter,
				       VTE_LINE_WIDTH,
				       ybottom - ycenter);
			break;
		case 108: /* l */
			XFillRectangle(display,
				       drawable,
				       gc,
				       xcenter,
				       ycenter,
				       xright - xcenter,
				       VTE_LINE_WIDTH);
			XFillRectangle(display,
				       drawable,
				       gc,
				       xcenter,
				       ycenter,
				       VTE_LINE_WIDTH,
				       ybottom - ycenter);
			break;
		case 109: /* m */
			XFillRectangle(display,
				       drawable,
				       gc,
				       xcenter,
				       ycenter,
				       xright - xcenter,
				       VTE_LINE_WIDTH);
			XFillRectangle(display,
				       drawable,
				       gc,
				       xcenter,
				       y,
				       VTE_LINE_WIDTH,
				       ycenter - y + VTE_LINE_WIDTH);
			break;
		case 110: /* n */
			XFillRectangle(display,
				       drawable,
				       gc,
				       xcenter,
				       y,
				       VTE_LINE_WIDTH,
				       row_height);
			XFillRectangle(display,
				       drawable,
				       gc,
				       x,
				       ycenter,
				       column_width,
				       VTE_LINE_WIDTH);
			break;
		case 111: /* o */
			XFillRectangle(display,
				       drawable,
				       gc,
				       x,
				       y,
				       column_width,
				       VTE_LINE_WIDTH);
			break;
		case 112: /* p */
			XFillRectangle(display,
				       drawable,
				       gc,
				       x,
				       (y + ycenter) / 2,
				       column_width,
				       VTE_LINE_WIDTH);
			break;
		case 113: /* q */
			XFillRectangle(display,
				       drawable,
				       gc,
				       x,
				       ycenter,
				       column_width,
				       VTE_LINE_WIDTH);
			break;
		case 114: /* r */
			XFillRectangle(display,
				       drawable,
				       gc,
				       x,
				       (ycenter + ybottom) / 2,
				       column_width,
				       VTE_LINE_WIDTH);
			break;
		case 115: /* s */
			XFillRectangle(display,
				       drawable,
				       gc,
				       x,
				       ybottom,
				       column_width,
				       VTE_LINE_WIDTH);
			break;
		case 116: /* t */
			XFillRectangle(display,
				       drawable,
				       gc,
				       xcenter,
				       y,
				       VTE_LINE_WIDTH,
				       row_height);
			XFillRectangle(display,
				       drawable,
				       gc,
				       xcenter,
				       ycenter,
				       xright - xcenter,
				       VTE_LINE_WIDTH);
			break;
		case 117: /* u */
			XFillRectangle(display,
				       drawable,
				       gc,
				       xcenter,
				       y,
				       VTE_LINE_WIDTH,
				       row_height);
			XFillRectangle(display,
				       drawable,
				       gc,
				       x,
				       ycenter,
				       xcenter - x + VTE_LINE_WIDTH,
				       VTE_LINE_WIDTH);
			break;
		case 118: /* v */
			XFillRectangle(display,
				       drawable,
				       gc,
				       xcenter,
				       y,
				       VTE_LINE_WIDTH,
				       ycenter - y + VTE_LINE_WIDTH);
			XFillRectangle(display,
				       drawable,
				       gc,
				       x,
				       ycenter,
				       column_width,
				       VTE_LINE_WIDTH);
			break;
		case 119: /* w */
			XFillRectangle(display,
				       drawable,
				       gc,
				       xcenter,
				       ycenter,
				       VTE_LINE_WIDTH,
				       ybottom - ycenter);
			XFillRectangle(display,
				       drawable,
				       gc,
				       x,
				       ycenter,
				       column_width,
				       VTE_LINE_WIDTH);
			break;
		case 120: /* x */
			XFillRectangle(display,
				       drawable,
				       gc,
				       xcenter,
				       y,
				       VTE_LINE_WIDTH,
				       row_height);
			break;
		case 121: /* y */
			xcenter--;
			ycenter--;
			xright--;
			ybottom--;
			/* <= */
			XDrawLine(display, drawable, gc,
				  xright - 1, y,
				  x, (y + ycenter) / 2);
			XDrawLine(display, drawable, gc,
				  x, (y + ycenter) / 2,
				  xright - 1, ycenter);
			XDrawLine(display, drawable, gc,
				  x, ycenter,
				  xright - 1, (ycenter + ybottom) / 2);
			break;
		case 122: /* z */
			xcenter--;
			ycenter--;
			xright--;
			ybottom--;
			/* >= */
			XDrawLine(display, drawable, gc,
				  x, y,
				  xright - 1, (y + ycenter) / 2);
			XDrawLine(display, drawable, gc,
				  xright - 1, (y + ycenter) / 2,
				  x, ycenter);
			XDrawLine(display, drawable, gc,
				  xright - 1, ycenter,
				  x, (ycenter + ybottom) / 2);
			break;
		case 123: /* pi */
			xcenter--;
			ycenter--;
			xright--;
			ybottom--;
			XDrawLine(display, drawable, gc,
				  (x + xcenter) / 2 - 1,
				  (y + ycenter) / 2,
				  (xright + xcenter) / 2 + 1,
				  (y + ycenter) / 2);
			XDrawLine(display, drawable, gc,
				  (x + xcenter) / 2,
				  (y + ycenter) / 2,
				  (x + xcenter) / 2,
				  (ybottom + ycenter) / 2);
			XDrawLine(display, drawable, gc,
				  (xright + xcenter) / 2,
				  (y + ycenter) / 2,
				  (xright + xcenter) / 2,
				  (ybottom + ycenter) / 2);
			break;
		case 124:
			xcenter--;
			ycenter--;
			xright--;
			ybottom--;
			/* != */
			XDrawLine(display, drawable, gc,
				  (x + xcenter) / 2 - 1, ycenter,
				  (xright + xcenter) / 2 + 1, ycenter);
			XDrawLine(display, drawable, gc,
				  (x + xcenter) / 2 - 1,
				  (ybottom + ycenter) / 2,
				  (xright + xcenter) / 2 + 1,
				  (ybottom + ycenter) / 2);
			XDrawLine(display, drawable, gc,
				  xright - 1, y + 1,
				  x + 1, ybottom - 1);
			break;
		case 125:
			xcenter--;
			ycenter--;
			xright--;
			ybottom--;
			/* British pound.  An "L" with a hyphen. */
			XDrawLine(display, drawable, gc,
				  (x + xcenter) / 2,
				  (y + ycenter) / 2,
				  (x + xcenter) / 2,
				  (ycenter + ybottom) / 2);
			XDrawLine(display, drawable, gc,
				  (x + xcenter) / 2,
				  (ycenter + ybottom) / 2,
				  (xcenter + xright) / 2,
				  (ycenter + ybottom) / 2);
			XDrawLine(display, drawable, gc,
				  x, ycenter,
				  xcenter + 1, ycenter);
			break;
		case 126:
			xcenter--;
			ycenter--;
			xright--;
			ybottom--;
			/* short hyphen? */
			XDrawLine(display, drawable, gc,
				  xcenter - 1, ycenter,
				  xcenter + 1, ycenter);
			break;
		case 127:
			xcenter--;
			ycenter--;
			xright--;
			ybottom--;
			/* A "delete" symbol I saw somewhere. */
			XDrawLine(display, drawable, gc,
				  x, ycenter,
				  xcenter, y);
			XDrawLine(display, drawable, gc,
				  xcenter, y,
				  xright - 1, ycenter);
			XDrawLine(display, drawable, gc,
				  xright - 1, ycenter,
				  xright - 1, ybottom - 1);
			XDrawLine(display, drawable, gc,
				  xright - 1, ybottom - 1,
				  x, ybottom - 1);
			XDrawLine(display, drawable, gc,
				  x, ybottom - 1,
				  x, ycenter);
			break;
		default:
			break;
	}
}

/* Calculate how much padding needs to be placed to either side of a character
 * to make sure it renders into the center of its cell. */
static void
vte_terminal_compute_padding(VteTerminal *terminal, Display *display,
			     gunichar c)
{
	int columns, pad = 0, rpad = 0, width;
	char utf8_buf[VTE_UTF8_BPC];
	GtkWidget *widget;
	PangoLayout *layout;
	PangoRectangle pink, plogical;
	XRectangle xink, xlogical;
	wchar_t wc;
#ifdef HAVE_XFT
	XGlyphInfo extents;
#endif
	/* Check how many columns this character uses up. */
	columns = g_unichar_iswide(c) ? 2 : 1;
	switch (terminal->pvt->render_method) {
#ifdef HAVE_XFT
	/* Ask Xft. */
	case VteRenderXft2:
	case VteRenderXft1:
		XftTextExtents32(display, terminal->pvt->ftfont,
				 &c, 1, &extents);
		pad = ((columns * terminal->char_width) - extents.xOff) / 2;
		rpad = ((columns * terminal->char_width) - extents.xOff) - pad;
		break;
#endif
	/* Ask Pango. */
	case VteRenderPango:
		widget = GTK_WIDGET(terminal);
		layout = pango_layout_new(terminal->pvt->pcontext);
		pango_layout_set_font_description(layout,
						  terminal->pvt->fontdesc);
		pango_layout_set_text(layout, utf8_buf,
				      g_unichar_to_utf8(c, utf8_buf));
		pango_layout_get_extents(layout, &pink, &plogical);
		width = howmany(plogical.width, PANGO_SCALE);
		g_object_unref(G_OBJECT(layout));
		pad = ((columns * terminal->char_width) - width) / 2;
		rpad = ((columns * terminal->char_width) - width) - pad;
		break;
	case VteRenderXlib:
	default:
		/* Ask Xlib. */
		wc = vte_wc_from_unichar(terminal, c);
		XwcTextExtents(terminal->pvt->fontset, &wc, 1,
			       &xink, &xlogical);
		pad = ((columns * terminal->char_width) - xlogical.width) / 2;
		rpad = ((columns * terminal->char_width) - xlogical.width) - pad;
	}
	/* Sanitize possibly-negative padding values and save them. */
	pad = MAX(0, pad);
	if (pad == 0) {
		pad = -1;
	}
	g_tree_insert(terminal->pvt->fontpaddingl,
		      GINT_TO_POINTER(c), GINT_TO_POINTER(pad));
	rpad = MAX(0, rpad);
	if (rpad == 0) {
		rpad = -1;
	}
	g_tree_insert(terminal->pvt->fontpaddingr,
		      GINT_TO_POINTER(c), GINT_TO_POINTER(rpad));
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC) && 0) {
		fprintf(stderr, "Padding for %d is %d/%d/%d.\n",
			c, pad, rpad, terminal->char_width);
	}
#endif
}
static int
vte_terminal_get_char_padding(VteTerminal *terminal, Display *display,
			      gunichar c)
{
	int pad;
	/* NUL gets no padding. */
	if (c == 0) {
		return 0;
	}
	/* Look up the cached value if there is one. */
	pad = GPOINTER_TO_INT(g_tree_lookup(terminal->pvt->fontpaddingl,
					    GINT_TO_POINTER(c)));
	/* If it's non-zero, clamp it. */
	if (pad != 0) {
		return CLAMP(pad, 0, terminal->char_width);
	}
	/* Compute the padding and try again. */
	vte_terminal_compute_padding(terminal, display, c);
	pad = GPOINTER_TO_INT(g_tree_lookup(terminal->pvt->fontpaddingl,
					    GINT_TO_POINTER(c)));
	return CLAMP(pad, 0, terminal->char_width);
}
static int
vte_terminal_get_char_padding_right(VteTerminal *terminal, Display *display,
				    gunichar c)
{
	int pad;
	/* NUL gets no padding. */
	if (c == 0) {
		return 0;
	}
	/* Look up the cached value if there is one. */
	pad = GPOINTER_TO_INT(g_tree_lookup(terminal->pvt->fontpaddingr,
					    GINT_TO_POINTER(c)));
	/* If it's non-zero, clamp it. */
	if (pad != 0) {
		return CLAMP(pad, 0, terminal->char_width);
	}
	/* Compute the padding and try again. */
	vte_terminal_compute_padding(terminal, display, c);
	pad = GPOINTER_TO_INT(g_tree_lookup(terminal->pvt->fontpaddingr,
					    GINT_TO_POINTER(c)));
	return CLAMP(pad, 0, terminal->char_width);
}

/* Draw a string of characters with similar attributes. */
static void
vte_terminal_draw_cells(VteTerminal *terminal,
			struct vte_draw_item *items, gssize n,
			gint fore, gint back, gboolean draw_default_bg,
			gboolean underline, gboolean hilite, gboolean boxed,
			gint x, gint y, gint x_offs, gint y_offs,
			gint ascent, gboolean monospaced,
			gint column_width, gint row_height,
			Display *display,
			GdkDrawable *gdrawable,
			Drawable drawable,
			Colormap colormap,
			Visual *visual,
			GdkGC *ggc,
			GC gc,
#ifdef HAVE_XFT
			XftDraw *ftdraw,
#endif
			PangoLayout *layout)
{
	int i;
	gint columns = 0;
	struct vte_palette_entry *fg, *bg;
	GdkColor color;

#ifdef HAVE_XFT2
	XftCharSpec *ftcharspecs;
#endif
#ifdef HAVE_XFT
	XftChar32 ftchar;
#endif
	gunichar c;
	char utf8_buf[VTE_UTF8_BPC];

	wchar_t wc;
	XwcTextItem textitem;

	fg = &terminal->pvt->palette[fore];
	bg = &terminal->pvt->palette[back];
	x += VTE_PAD_WIDTH;
	y += VTE_PAD_WIDTH;

	switch (terminal->pvt->render_method) {
	case VteRenderXft2:
#ifdef HAVE_XFT
#ifdef HAVE_XFT2
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC) && 0) {
			fprintf(stderr, "Rendering with Xft2.\n");
		}
#endif
		/* Set up the draw request. */
		ftcharspecs = g_malloc(sizeof(XftCharSpec) * n);
		for (i =  columns = 0; i < n; i++) {
			c = items[i].c ? items[i].c : ' ';
			ftcharspecs[i].ucs4 = vte_terminal_xft_remap_char(display,
									  terminal->pvt->ftfont,
									  c);
			ftcharspecs[i].x = x + (columns * column_width) +
					   items[i].xpad;
			ftcharspecs[i].y = y + ascent;
			columns += g_unichar_iswide(c) ? 2 : 1;
		}
		if (ftdraw != NULL) {
			/* Draw the background rectangle. */
			if ((back != VTE_DEF_BG) || draw_default_bg) {
				XftDrawRect(ftdraw, &bg->ftcolor, x, y,
					    columns * column_width, row_height);
			}
			/* Draw the text. */
			XftDrawCharSpec(ftdraw, &fg->ftcolor,
					terminal->pvt->ftfont,
					ftcharspecs, n);
		}
		/* Clean up. */
		g_free(ftcharspecs);
		break;
#endif
	case VteRenderXft1:
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC) && 0) {
			fprintf(stderr, "Rendering with Xft1.\n");
		}
#endif
		/* Set up the draw request. */
		for (i = columns = 0; i < n; i++) {
			c = items[i].c ? items[i].c : ' ';
			columns += g_unichar_iswide(c) ? 2 : 1;
		}
		/* Draw the background rectangle. */
		if ((back != VTE_DEF_BG) || draw_default_bg) {
			XftDrawRect(ftdraw, &bg->ftcolor, x, y,
				    columns * column_width, row_height);
		}
		/* Draw the text. */
		for (i = columns = 0; i < n; i++) {
			c = items[i].c ? items[i].c : ' ';
			ftchar = vte_terminal_xft_remap_char(display,
							     terminal->pvt->ftfont,
							     c);
			XftDrawString32(ftdraw, &fg->ftcolor,
					terminal->pvt->ftfont,
					x + (columns * column_width) +
					items[i].xpad,
					y + ascent,
					&ftchar, 1);
			columns += g_unichar_iswide(c) ? 2 : 1;
		}
		break;
#endif
	case VteRenderPango:
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC) && 0) {
			fprintf(stderr, "Rendering with Pango.\n");
		}
#endif
		/* Draw the background. */
		if ((back != VTE_DEF_BG) || draw_default_bg) {
			for (i = columns = 0; i < n; i++) {
				c = items[i].c ? items[i].c : ' ';
				columns += g_unichar_iswide(c) ? 2 : 1;
			}
#ifdef VTE_PREFER_PANGOX
			XSetForeground(display, gc, bg->pixel);
			XFillRectangle(display, drawable, gc,
				       x, y,
				       columns * column_width, row_height);
#else
			color.red = terminal->pvt->palette[back].red;
			color.blue = terminal->pvt->palette[back].blue;
			color.green = terminal->pvt->palette[back].green;
			color.pixel = terminal->pvt->palette[back].pixel;
			gdk_gc_set_foreground(ggc, &color);
			gdk_draw_rectangle(gdrawable,
					   ggc,
					   TRUE,
					   x + x_offs, y + y_offs,
					   columns * column_width, row_height);
#endif
		}
		/* Draw the text in a monospaced manner. */
		color.red = terminal->pvt->palette[fore].red;
		color.blue = terminal->pvt->palette[fore].blue;
		color.green = terminal->pvt->palette[fore].green;
		color.pixel = terminal->pvt->palette[fore].pixel;
		gdk_gc_set_foreground(ggc, &color);
		for (i = columns = 0; (layout != NULL) && (i < n); i++) {
			c = items[i].c ? items[i].c : ' ';
			pango_layout_set_text(layout, utf8_buf,
					      g_unichar_to_utf8(c, utf8_buf));
#ifdef VTE_PREFER_PANGOX
			XSetForeground(display, gc, fg->pixel);
			pango_x_render_layout(display,
					      drawable,
					      gc,
					      layout,
					      x + (columns * column_width) +
					      items[i].xpad,
					      y);
#else
			gdk_draw_layout(gdrawable, ggc,
					x + (columns * column_width) +
					items[i].xpad + x_offs,
					y + y_offs,
					layout);
#endif
			columns += g_unichar_iswide(c) ? 2 : 1;
		}
		break;
	case VteRenderXlib:
	default:
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC) && 0) {
			fprintf(stderr, "Rendering with Xlib.\n");
		}
#endif
		/* Draw the background. */
		if ((back != VTE_DEF_BG) || draw_default_bg) {
			for (i = columns = 0; i < n; i++) {
				c = items[i].c ? items[i].c : ' ';
				columns += g_unichar_iswide(c) ? 2 : 1;
			}
			XSetForeground(display, gc, bg->pixel);
			XFillRectangle(display, drawable, gc,
				       x, y,
				       columns * column_width, row_height);
		}
		/* Create a separate draw item for each character. */
		XSetForeground(display, gc, fg->pixel);
		textitem.nchars = 1;
		textitem.font_set = terminal->pvt->fontset;
		for (i = columns = 0; i < n; i++) {
			c = items[i].c ? items[i].c : ' ';
			wc = vte_wc_from_unichar(terminal, c);
			textitem.chars = &wc;
			textitem.delta = items[i].xpad;
			XwcDrawText(display, drawable, gc,
				    x + (columns * column_width) +
				    items[i].xpad,
				    y + ascent, &textitem, 1);
			columns += g_unichar_iswide(c) ? 2 : 1;
		}
	}

	/* Draw whatever SFX are required. */
	if (underline) {
		XSetForeground(display, gc, fg->pixel);
		XDrawLine(display, drawable, gc,
			  x, y + row_height - 2,
			  x + (columns * column_width) - 1, y + row_height - 2);
	}
	if (hilite) {
		XSetForeground(display, gc, fg->pixel);
		XDrawLine(display, drawable, gc,
			  x, y + row_height - 1,
			  x + (columns * column_width) - 1, y + row_height - 1);
	}
	if (boxed) {
		XSetForeground(display, gc, fg->pixel);
		XDrawRectangle(display, drawable, gc,
			       x, y,
			       MAX(0, (columns * column_width) - 1),
			       MAX(0, row_height - 1));
	}
}

static gboolean
vte_terminal_get_blink_state(VteTerminal *terminal)
{
	struct timezone tz;
	struct timeval tv;
	gint blink_cycle = 1000;
	GtkSettings *settings;
	time_t daytime;
	gboolean blink;
	GtkWidget *widget;

	/* Determine if blinking text should be shown. */
	if (terminal->pvt->cursor_blinks) {
		if (gettimeofday(&tv, &tz) == 0) {
			widget = GTK_WIDGET(terminal);
			settings = gtk_widget_get_settings(widget);
			if (G_IS_OBJECT(settings)) {
				g_object_get(G_OBJECT(settings),
					     "gtk-cursor-blink-time",
					     &blink_cycle, NULL);
			}
			daytime = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
			if (daytime >= terminal->pvt->last_keypress_time) {
				daytime -= terminal->pvt->last_keypress_time;
			}
			daytime = daytime % blink_cycle;
			blink = daytime < (blink_cycle / 2);
		} else {
			blink = TRUE;
		}
	} else {
		blink = TRUE;
	}
	return blink;
}

/* Paint the contents of a given row at the given location. */
static void
vte_terminal_draw_row(VteTerminal *terminal,
		      VteScreen *screen,
		      gint row,
		      gint column, gint column_count,
		      gint x, gint y,
		      gint x_offs, gint y_offs,
		      gint ascent, gboolean monospaced,
		      gint column_width, gint row_height,
		      Display *display,
		      GdkDrawable *gdrawable,
		      Drawable drawable,
		      Colormap colormap,
		      Visual *visual,
		      GdkGC *ggc,
		      GC gc,
#ifdef HAVE_XFT
		      XftDraw *ftdraw,
#endif
		      PangoLayout *layout)
{
	GArray *items;
	int i, j, fore, nfore, back, nback;
	gboolean underline, nunderline, hilite, nhilite, reverse;
	struct vte_draw_item item;
	struct vte_charcell *cell;

	/* Allocate an array to hold draw requests. */
	items = g_array_new(FALSE, FALSE, sizeof(struct vte_draw_item));

	/* Find groups of characters with identical attributes and bundle
	 * them together. */
	i = column;

	/* Back up in case this is a multicolumn character. */
	cell = vte_terminal_find_charcell(terminal, i, row);
	if ((cell != NULL) && (cell->columns == 0) && (i > 0)) {
		cell = vte_terminal_find_charcell(terminal, i - 1, row);
		column--;
		column_count++;
	}
	/* Walk the line. */
	while (i < column + column_count) {
		/* Get the character cell's contents. */
		cell = vte_terminal_find_charcell(terminal, i, row);
		/* Find the colors for this cell. */
		reverse = vte_cell_is_selected(terminal, i, row);
		vte_terminal_determine_colors(terminal, cell, reverse,
					      &fore, &back);
		underline = (cell != NULL) ? (cell->underline != 0) : FALSE;
		if (terminal->pvt->match_contents != NULL) {
			hilite = vte_cell_is_between(i, row - screen->scroll_delta,
						     terminal->pvt->match_start.column,
						     terminal->pvt->match_start.row,
						     terminal->pvt->match_end.column,
						     terminal->pvt->match_end.row,
						     TRUE);
		} else {
			hilite = FALSE;
		}

		/* If this is a graphics character, draw it locally. */
		if ((cell != NULL) &&
		    (cell->alternate || vte_unichar_isgraphic(cell->c))) {
			item.c = cell ? cell->c : ' ';
			vte_terminal_draw_graphic(terminal, cell->c, fore, back,
						  FALSE,
						  x +
						  ((i - column) * column_width),
						  y,
						  column_width,
						  row_height,
						  display,
						  gdrawable,
						  drawable,
						  ggc,
						  gc);
			i++;
			continue;
		}

		/* Add this cell to the draw list. */
		item.c = cell ? cell->c : ' ';
		item.xpad = vte_terminal_get_char_padding(terminal,
							  display,
							  item.c);
		g_array_append_val(items, item);

		/* Now find out how many cells have the same attributes. */
		for (j = i + 1;
		     (j < column + column_count) &&
		     (j - i < VTE_XFT_HARD_LIMIT);
		     j++) {
			/* Don't render fragments of multicolumn characters. */
			cell = vte_terminal_find_charcell(terminal, j, row);
			if ((cell != NULL) && (cell->columns == 0)) {
				continue;
			}
			if ((cell != NULL) && (cell->alternate)) {
				break;
			}
			if ((cell != NULL) && vte_unichar_isgraphic(cell->c)) {
				break;
			}
			/* Resolve attributes to colors where possible and
			 * compare visual attributes to the first character
			 * in this chunk. */
			reverse = vte_cell_is_selected(terminal, j, row);
			vte_terminal_determine_colors(terminal, cell, reverse,
						      &nfore, &nback);
			if ((nfore != fore) || (nback != back)) {
				break;
			}
			nunderline = (cell != NULL) ?
				     (cell->underline != 0) :
				     FALSE;
			if (nunderline != underline) {
				break;
			}
			if (terminal->pvt->match_contents != NULL) {
				nhilite = vte_cell_is_between(j, row - screen->scroll_delta,
							      terminal->pvt->match_start.column,
							      terminal->pvt->match_start.row,
							      terminal->pvt->match_end.column,
							      terminal->pvt->match_end.row,
							      TRUE);
			} else {
				nhilite = FALSE;
			}
			if (nhilite != hilite) {
				break;
			}
			/* Add this cell to the draw list. */
			item.c = cell ? cell->c : ' ';
			item.xpad = vte_terminal_get_char_padding(terminal,
								  display,
								  item.c);
			g_array_append_val(items, item);
		}
		/* Draw the cells. */
		vte_terminal_draw_cells(terminal,
					(struct vte_draw_item*) items->data,
					items->len,
					fore, back, FALSE,
					underline, hilite, FALSE,
					x + ((i - column) * column_width),
					y,
					x_offs,
					y_offs,
					ascent, monospaced,
					column_width, row_height,
					display, gdrawable, drawable,
					colormap, visual, ggc, gc,
#ifdef HAVE_XFT
					ftdraw,
#endif
					layout);
		g_array_set_size(items, 0);
		/* We'll need to continue at the first cell which didn't
		 * match the first one in this set. */
		i = j;
	}

	/* Clean up. */
	g_array_free(items, TRUE);
}

/* Draw the widget. */
static void
vte_terminal_paint(GtkWidget *widget, GdkRectangle *area)
{
	VteTerminal *terminal = NULL;
	PangoLayout *layout = NULL;
	VteScreen *screen;
	Display *display;
	GdkDrawable *gdrawable;
	Drawable drawable;
	GdkColormap *gcolormap;
	Colormap colormap;
	GdkVisual *gvisual;
	Visual *visual;
	GdkGC *ggc;
	GC gc;
	struct vte_charcell *cell;
	struct vte_draw_item item, *items;
	int row, drow, col, row_stop, col_stop, x_offs = 0, y_offs = 0, columns;
	char *preedit;
	long width, height, ascent, descent, delta;
	int i, len, fore, back;
	gboolean blink, underline, hilite, monospaced;
#ifdef HAVE_XFT
	XftDraw *ftdraw = NULL;
#endif

	/* Make a few sanity checks. */
	g_return_if_fail(widget != NULL);
	g_return_if_fail(VTE_IS_TERMINAL(widget));
	g_return_if_fail(area != NULL);
	terminal = VTE_TERMINAL(widget);

	/* Get going. */
	screen = terminal->pvt->screen;

	/* Get the X11 structures we need for the drawing area. */
	gdk_window_get_internal_paint_info(widget->window, &gdrawable,
					   &x_offs, &y_offs);
	display = gdk_x11_drawable_get_xdisplay(gdrawable);
	drawable = gdk_x11_drawable_get_xid(gdrawable);
	gcolormap = gdk_drawable_get_colormap(widget->window);
	colormap = gdk_x11_colormap_get_xcolormap(gcolormap);
	gvisual = gtk_widget_get_visual(widget);
	visual = gdk_x11_visual_get_xvisual(gvisual);

	/* Reset the GDK drawable to the buffered version. */
	gdrawable = widget->window;

	switch (terminal->pvt->render_method) {
#ifdef HAVE_XFT
	case VteRenderXft2:
	case VteRenderXft1:
		ftdraw = XftDrawCreate(display, drawable, visual, colormap);
		if (ftdraw == NULL) {
			g_warning(_("Error allocating draw, disabling Xft."));
			return;
		}
		break;
#endif
	case VteRenderPango:
		if (terminal->pvt->pcontext == NULL) {
			g_warning(_("Error allocating context, "
				    "disabling Pango."));
			return;
		}
		layout = pango_layout_new(terminal->pvt->pcontext);
		if (layout == NULL) {
			g_warning(_("Error allocating layout, "
				    "disabling Pango."));
			return;
		}
		pango_layout_set_font_description(layout,
						  terminal->pvt->fontdesc);
		break;
	case VteRenderXlib:
	default:
		/* do nothing */
		break;
	}

	gc = XCreateGC(display, drawable, 0, NULL);
	ggc = gdk_gc_new(gdrawable);

	/* Keep local copies of rendering information. */
	width = terminal->char_width;
	height = terminal->char_height;
	ascent = terminal->char_ascent;
	descent = terminal->char_descent;
	delta = screen->scroll_delta;

	monospaced =
		(vte_terminal_get_char_padding(terminal, display,
					       VTE_REPRESENTATIVE_WIDER_CHARACTER) == 0) &&
		(vte_terminal_get_char_padding(terminal, display,
					       VTE_REPRESENTATIVE_NARROWER_CHARACTER) == 0);

	/* Now we're ready to draw the text.  Iterate over the rows we
	 * need to draw. */
	row = (area->y - VTE_PAD_WIDTH) / height;
	row_stop = ((area->y - VTE_PAD_WIDTH) + area->height + height - 1) / height;
	while (row < row_stop) {
		col = (area->x - VTE_PAD_WIDTH) / width;
		col_stop = howmany((area->x - VTE_PAD_WIDTH) + area->width,
				   width);
		vte_terminal_draw_row(terminal,
				      screen,
				      row + delta,
				      col,
				      col_stop - col,
				      col * width - x_offs,
				      row * height - y_offs,
				      x_offs, y_offs,
				      ascent, monospaced,
				      terminal->char_width,
				      terminal->char_height,
				      display, gdrawable, drawable,
				      colormap, visual, ggc, gc,
#ifdef HAVE_XFT
				      ftdraw,
#endif
				      layout);
		row++;
	}

	if (terminal->pvt->cursor_visible) {
		/* Get the location of the cursor. */
		col = screen->cursor_current.col;
		if (terminal->pvt->im_preedit != NULL) {
			preedit = terminal->pvt->im_preedit;
			for (i = 0; i < terminal->pvt->im_preedit_cursor; i++) {
				col += vte_unichar_width(g_utf8_get_char(preedit));
				preedit = g_utf8_next_char(preedit);
			}
		}
		drow = screen->cursor_current.row;
		row = drow - delta;

		/* Find the character "under" the cursor. */
		cell = vte_terminal_find_charcell(terminal, col, drow);
		if ((cell != NULL) && (cell->columns == 0)) {
			col--;
			cell = vte_terminal_find_charcell(terminal, col, drow);
		}

		/* Draw the cursor. */
		if (GTK_WIDGET_HAS_FOCUS(GTK_WIDGET(terminal))) {
			blink = vte_terminal_get_blink_state(terminal);
			vte_terminal_determine_colors(terminal, cell, blink,
						      &fore, &back);
			if ((cell != NULL) &&
			    (cell->alternate || vte_unichar_isgraphic(cell->c))) {
				vte_terminal_draw_graphic(terminal,
							  cell->c, fore, back,
							  TRUE,
							  col * width - x_offs,
							  row * height - y_offs,
							  terminal->char_width,
							  terminal->char_height,
							  display,
							  gdrawable,
							  drawable,
							  ggc,
							  gc);
			} else {
				item.c = cell ? cell->c : ' ';
				item.xpad = vte_terminal_get_char_padding(terminal,
									  display,
									  item.c);
				underline = cell ? (cell->underline != 0) : FALSE;
				hilite = FALSE;
				vte_terminal_draw_cells(terminal,
							&item, 1,
							fore, back, TRUE,
							underline, hilite, FALSE,
							col * width - x_offs,
							row * height - y_offs,
							x_offs,
							y_offs,
							ascent, monospaced,
							terminal->char_width,
							terminal->char_height,
							display, gdrawable, drawable,
							colormap, visual, ggc, gc,
#ifdef HAVE_XFT
							ftdraw,
#endif
							layout);
			}
		} else {
			/* Determine how wide the cursor is. */
			columns = 1;
			if ((cell != NULL) && (cell->columns > 1)) {
				columns = cell->columns;
			}
			/* Draw it as a hollow rectangle. */
			fore = cell ? cell->fore : VTE_DEF_FG;
			XSetForeground(display, gc,
				       terminal->pvt->palette[fore].pixel);
			XDrawRectangle(display, drawable, gc,
				       col * width - x_offs + VTE_PAD_WIDTH,
				       row * height - y_offs + VTE_PAD_WIDTH,
				       columns * width - 1,
				       height - 1);
		}
	}

	/* Draw the pre-edit string (if one exists) over the cursor. */
	if (terminal->pvt->im_preedit) {
		drow = screen->cursor_current.row;
		row = screen->cursor_current.row - delta;

		/* If the pre-edit string won't fit on the screen, skip initial
		 * characters until it does. */
		preedit = terminal->pvt->im_preedit;
		len = g_utf8_strlen(preedit, -1);
		col = screen->cursor_current.col;
		while (((col + len) > terminal->column_count) && (len > 0)) {
			preedit = g_utf8_next_char(preedit);
			len = g_utf8_strlen(preedit, -1);
		}
		col = screen->cursor_current.col;

		/* Draw the preedit string, boxed. */
		if (len > 0) {
			items = g_malloc(sizeof(struct vte_draw_item) * len);
			for (i = columns = 0; i < len; i++) {
				items[i].c = g_utf8_get_char(preedit);
				items[i].xpad = vte_terminal_get_char_padding(terminal,
									      display,
									      item.c);
				columns += g_unichar_iswide(items[i].c) ? 2 : 1;
				preedit = g_utf8_next_char(preedit);
			}
			fore = screen->defaults.fore;
			back = screen->defaults.back;
			XSetForeground(display, gc,
				       terminal->pvt->palette[back].pixel);
			XFillRectangle(display, drawable, gc,
				       col * width - x_offs + VTE_PAD_WIDTH,
				       row * height - y_offs + VTE_PAD_WIDTH,
				       columns * terminal->char_width,
				       terminal->char_height);
			vte_terminal_draw_cells(terminal,
						items, len,
						screen->defaults.fore,
						screen->defaults.back,
						FALSE,
						FALSE, FALSE, TRUE,
						col * width - x_offs,
						row * height - y_offs,
						x_offs,
						y_offs,
						ascent, monospaced,
						terminal->char_width,
						terminal->char_height,
						display, gdrawable, drawable,
						colormap, visual, ggc, gc,
#ifdef HAVE_XFT
						ftdraw,
#endif
						layout);
			g_free(items);
		}
	}

	/* Done with various structures. */
#ifdef HAVE_XFT
	if (ftdraw != NULL) {
		XftDrawDestroy(ftdraw);
	}
#endif
	if (layout != NULL) {
		g_object_unref(G_OBJECT(layout));
	}
	g_object_unref(G_OBJECT(ggc));
	XFreeGC(display, gc);
}

/* Handle an expose event by painting the exposed area. */
static gint
vte_terminal_expose(GtkWidget *widget, GdkEventExpose *event)
{
	g_return_val_if_fail(VTE_IS_TERMINAL(widget), 0);
	if (event->window == widget->window) {
		if ((GTK_WIDGET_REALIZED(widget) &&
		    (GTK_WIDGET_DRAWABLE(widget) &&
		    (gdk_window_get_state(widget->window) !=
		     GDK_VISIBILITY_FULLY_OBSCURED)))) {
			vte_terminal_paint(widget, &event->area);
		}
	} else {
		g_assert_not_reached();
	}
	return TRUE;
}

/* Handle a scroll event. */
static gboolean
vte_terminal_scroll(GtkWidget *widget, GdkEventScroll *event)
{
	GtkAdjustment *adj;
	VteTerminal *terminal;
	gdouble new_value;
	GdkModifierType modifiers;
	int button;

	g_return_val_if_fail(VTE_IS_TERMINAL(widget), FALSE);
	terminal = VTE_TERMINAL(widget);

	/* Read the modifiers. */
	if (gdk_event_get_state((GdkEvent*)event, &modifiers) == FALSE) {
		modifiers = 0;
	}

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_EVENTS)) {
		switch (event->direction) {
			case GDK_SCROLL_UP:
				fprintf(stderr, "Scroll up.\n");
				break;
			case GDK_SCROLL_DOWN:
				fprintf(stderr, "Scroll down.\n");
				break;
			default:
				break;
		}
	}
#endif

	/* If we're running a mouse-aware application, map the scroll event
	 * to a button press on buttons four and five. */
	if (terminal->pvt->mouse_send_xy_on_click ||
	    terminal->pvt->mouse_send_xy_on_button ||
	    terminal->pvt->mouse_hilite_tracking ||
	    terminal->pvt->mouse_cell_motion_tracking ||
	    terminal->pvt->mouse_all_motion_tracking) {
		switch (event->direction) {
			case GDK_SCROLL_UP:
				button = 4;
				break;
			case GDK_SCROLL_DOWN:
				button = 5;
				break;
			default:
				button = 0;
				break;
		}
		if (button != 0) {
			/* Encode the parameters and send them to the app. */
			vte_terminal_send_mouse_button_internal(terminal,
								button,
								event->x - VTE_PAD_WIDTH,
								event->y - VTE_PAD_WIDTH,
								modifiers);
			return TRUE;
		}
	}

	/* Perform a history scroll. */
	adj = (VTE_TERMINAL(widget))->adjustment;

	switch (event->direction) {
		case GDK_SCROLL_UP:
			new_value = adj->value - adj->page_increment / 2;
			break;
		case GDK_SCROLL_DOWN:
			new_value = adj->value + adj->page_increment / 2;
			break;
		default:
			return FALSE;
	}

	new_value = CLAMP(new_value, adj->lower, adj->upper - adj->page_size);
	gtk_adjustment_set_value(adj, new_value);

	return TRUE;
}

/* Create a new accessible object associated with ourselves, and return
 * it to the caller. */
static AtkObject *
vte_terminal_get_accessible(GtkWidget *widget)
{
	AtkObject *access;
	VteTerminal *terminal;
	g_return_val_if_fail(VTE_IS_TERMINAL(widget), NULL);
	terminal = VTE_TERMINAL(widget);
	if (terminal->pvt->accessible != NULL) {
		access = terminal->pvt->accessible;
	} else {
		access = vte_terminal_accessible_new(terminal);
		terminal->pvt->accessible = access;
	}
	return access;
}

/* Initialize methods. */
static void
vte_terminal_class_init(VteTerminalClass *klass, gconstpointer data)
{
	GObjectClass *gobject_class;
	GtkWidgetClass *widget_class;

	bindtextdomain(PACKAGE, LOCALEDIR);

	gobject_class = G_OBJECT_CLASS(klass);
	widget_class = GTK_WIDGET_CLASS(klass);

	/* Override some of the default handlers. */
	gobject_class->finalize = vte_terminal_finalize;
	widget_class->realize = vte_terminal_realize;
	widget_class->scroll_event = vte_terminal_scroll;
	widget_class->expose_event = vte_terminal_expose;
	widget_class->key_press_event = vte_terminal_key_press;
	widget_class->key_release_event = vte_terminal_key_release;
	widget_class->button_press_event = vte_terminal_button_press;
	widget_class->button_release_event = vte_terminal_button_release;
	widget_class->motion_notify_event = vte_terminal_motion_notify;
	/* widget_class->focus_in_event = vte_terminal_focus_in; */
	/* widget_class->focus_out_event = vte_terminal_focus_out; */
	widget_class->unrealize = vte_terminal_unrealize;
	widget_class->size_request = vte_terminal_size_request;
	widget_class->size_allocate = vte_terminal_size_allocate;
	widget_class->get_accessible = vte_terminal_get_accessible;

	/* Register some signals of our own. */
	klass->eof_signal =
		g_signal_new("eof",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->child_exited_signal =
		g_signal_new("child-exited",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->window_title_changed_signal =
		g_signal_new("window-title-changed",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->icon_title_changed_signal =
		g_signal_new("icon-title-changed",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->encoding_changed_signal =
		g_signal_new("encoding-changed",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->emulation_changed_signal =
		g_signal_new("emulation-changed",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->char_size_changed_signal =
		g_signal_new("char-size-changed",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__UINT_UINT,
			     G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_UINT);
	klass->selection_changed_signal =
		g_signal_new ("selection-changed",
			      G_OBJECT_CLASS_TYPE(klass),
			      G_SIGNAL_RUN_LAST,
			      0,
			      NULL,
			      NULL,
			      _vte_marshal_VOID__VOID,
			      G_TYPE_NONE, 0);
	klass->contents_changed_signal =
		g_signal_new("contents-changed",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->cursor_moved_signal =
		g_signal_new("cursor-moved",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->deiconify_window_signal =
		g_signal_new("deiconify-window",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->iconify_window_signal =
		g_signal_new("iconify-window",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->raise_window_signal =
		g_signal_new("raise-window",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->lower_window_signal =
		g_signal_new("lower-window",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->refresh_window_signal =
		g_signal_new("refresh-window",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->restore_window_signal =
		g_signal_new("restore-window",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->maximize_window_signal =
		g_signal_new("maximize-window",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);
	klass->resize_window_signal =
		g_signal_new("resize-window",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__UINT_UINT,
			     G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_UINT);
	klass->move_window_signal =
		g_signal_new("move-window",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__UINT_UINT,
			     G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_UINT);
	klass->status_line_changed_signal =
		g_signal_new("status-line-changed",
			     G_OBJECT_CLASS_TYPE(klass),
			     G_SIGNAL_RUN_LAST,
			     0,
			     NULL,
			     NULL,
			     _vte_marshal_VOID__VOID,
			     G_TYPE_NONE, 0);

	/* Try to determine some acceptable encoding names. */
	if (vte_table_narrow_encoding() == NULL) {
		g_error("Don't know how to read ISO-8859-1 data!");
	}
	if (vte_table_wide_encoding() == NULL) {
		g_error("Don't know how to read native-endian unicode data!");
	}

#ifdef VTE_DEBUG
	/* Turn on debugging if we were asked to. */
	if (getenv("VTE_DEBUG_FLAGS") != NULL) {
		vte_debug_parse_string(getenv("VTE_DEBUG_FLAGS"));
	}
#endif
}

GtkType
vte_terminal_get_type(void)
{
	static GtkType terminal_type = 0;
	static const GTypeInfo terminal_info = {
		sizeof(VteTerminalClass),
		(GBaseInitFunc)NULL,
		(GBaseFinalizeFunc)NULL,

		(GClassInitFunc)vte_terminal_class_init,
		(GClassFinalizeFunc)NULL,
		(gconstpointer)NULL,

		sizeof(VteTerminal),
		0,
		(GInstanceInitFunc)vte_terminal_init,

		(GTypeValueTable*)NULL,
	};

	if (terminal_type == 0) {
		terminal_type = g_type_register_static(GTK_TYPE_WIDGET,
						       "VteTerminal",
						       &terminal_info,
						       0);
	}

	return terminal_type;
}

/* External access functions. */
void
vte_terminal_set_audible_bell(VteTerminal *terminal, gboolean audible)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	terminal->pvt->audible_bell = audible;
}
gboolean
vte_terminal_get_audible_bell(VteTerminal *terminal)
{
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), FALSE);
	return terminal->pvt->audible_bell;
}

void
vte_terminal_set_visible_bell(VteTerminal *terminal, gboolean visible)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	terminal->pvt->visible_bell = visible;
}
gboolean
vte_terminal_get_visible_bell(VteTerminal *terminal)
{
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), FALSE);
	return terminal->pvt->visible_bell;
}

void
vte_terminal_set_scroll_on_output(VteTerminal *terminal, gboolean scroll)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	terminal->pvt->scroll_on_output = scroll;
}

void
vte_terminal_set_scroll_on_keystroke(VteTerminal *terminal, gboolean scroll)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	terminal->pvt->scroll_on_keystroke = scroll;
}

void
vte_terminal_copy_clipboard(VteTerminal *terminal)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	vte_terminal_copy(terminal, GDK_SELECTION_CLIPBOARD);
}

void
vte_terminal_paste_clipboard(VteTerminal *terminal)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	vte_terminal_paste(terminal, GDK_SELECTION_CLIPBOARD);
}

/* Append the menu items for our input method context to the given shell. */
void
vte_terminal_im_append_menuitems(VteTerminal *terminal, GtkMenuShell *menushell)
{
	GtkIMMulticontext *context;
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	g_return_if_fail(GTK_WIDGET_REALIZED(GTK_WIDGET((terminal))));
	context = GTK_IM_MULTICONTEXT(terminal->pvt->im_context);
	gtk_im_multicontext_append_menuitems(context, menushell);
}

/* Set up whatever background we want. */
static void
vte_terminal_setup_background(VteTerminal *terminal,
			      gboolean refresh_transparent)
{
	long i, pixel_count;
	GtkWidget *widget;
	guchar *pixels, *oldpixels;
	GdkColormap *colormap = NULL;
	GdkPixbuf *pixbuf = NULL;
	GdkPixmap *pixmap = NULL;
	GdkBitmap *bitmap = NULL;
	GdkColor bgcolor;
	GdkWindow *window = NULL;
	GdkAtom atom, prop_type;
	Pixmap *prop_data = NULL;

	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	widget = GTK_WIDGET(terminal);
	if (!GTK_WIDGET_REALIZED(widget)) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC)) {
			fprintf(stderr, "Can not set background image without "
				"window.\n");
		}
#endif
		return;
	}

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Setting up background image.\n");
	}
#endif

	/* Set the default background color. */
	bgcolor.red = terminal->pvt->palette[VTE_DEF_BG].red;
	bgcolor.green = terminal->pvt->palette[VTE_DEF_BG].green;
	bgcolor.blue = terminal->pvt->palette[VTE_DEF_BG].blue;
	bgcolor.pixel = terminal->pvt->palette[VTE_DEF_BG].pixel;
	gdk_window_set_background(widget->window, &bgcolor);

	if (terminal->pvt->bg_transparent) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC)) {
			fprintf(stderr, "Setting up background transparent.\n");
		}
#endif
		/* If we don't have a root pixmap, try to fetch one regardless
		 * of what the caller told us to do. */
		if (terminal->pvt->bg_transparent_image == NULL) {
			refresh_transparent = TRUE;
		}
		/* If we need a new copy of the desktop, get it. */
		if (refresh_transparent) {
			guint width, height, pwidth, pheight;

#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_MISC)) {
				fprintf(stderr, "Fetching new background "
					"pixmap.\n");
			}
#endif
			gdk_error_trap_push();

			/* Retrieve the window and its property which
			 * we're watching. */
			window = terminal->pvt->bg_transparent_window;
			atom = terminal->pvt->bg_transparent_atom;
			prop_data = NULL;

			/* Read the pixmap property off of the window. */
			gdk_property_get(window, atom, 0, 0, 10, FALSE,
					 &prop_type, NULL, NULL,
					 (guchar**)&prop_data);

			/* If we got something, try to create a pixmap we
			 * can mess with. */
			pixbuf = NULL;
			if ((prop_type == GDK_TARGET_PIXMAP) &&
			    (prop_data != NULL) &&
			    (prop_data[0] != 0)) {
				/* Create a pixmap from the window we're
				 * watching, which is foreign because we
				 * didn't create it. */
				gdk_drawable_get_size(window, &width, &height);
				pixmap = gdk_pixmap_foreign_new(prop_data[0]);
				/* If we got a pixmap, create a pixbuf for
				 * us to work with. */
				if (GDK_IS_PIXMAP(pixmap)) {
					gdk_drawable_get_size(GDK_DRAWABLE(pixmap), &pwidth, &pheight);
					colormap = gdk_drawable_get_colormap(window);
					pixbuf = gdk_pixbuf_get_from_drawable(NULL,
									      pixmap,
									      colormap,
									      0, 0,
									      0, 0,
									      MIN(width, pwidth),
									      MIN(pheight, height));
					/* Get rid of the pixmap. */
					g_object_unref(G_OBJECT(pixmap));
					pixmap = NULL;
				}
			}
			if (prop_data != NULL) {
				g_free(prop_data);
			}
                        gdk_flush();
			gdk_error_trap_pop();

			/* Get rid of any previous snapshot we've got, and
			 * save the new one in its place. */
			if (GDK_IS_PIXBUF(terminal->pvt->bg_transparent_image)) {
				g_object_unref(G_OBJECT(terminal->pvt->bg_transparent_image));
			}
			terminal->pvt->bg_transparent_image = pixbuf;
			pixbuf = NULL;
		}

		/* Get a copy of the root image which we can manipulate. */
		if (GDK_IS_PIXBUF(terminal->pvt->bg_transparent_image)) {
			pixbuf = gdk_pixbuf_copy(terminal->pvt->bg_transparent_image);
		}

		/* Rotate the copy of the image left or up to compensate for
		 * our window not having the same origin. */
		if (GDK_IS_PIXBUF(pixbuf)) {
			guint width, height;
			gint x, y;

			width = gdk_pixbuf_get_width(pixbuf);
			height = gdk_pixbuf_get_height(pixbuf);

			/* Determine how far we should shift the origin. */
			gdk_window_get_origin(widget->window, &x, &y);
			while (x < 0) {
				x += width;
			}
			while (y < 0) {
				y += height;
			}
			x %= width;
			y %= height;

			/* Copy the picture data. */
			oldpixels = gdk_pixbuf_get_pixels(pixbuf);
			pixels = g_malloc(height *
					  gdk_pixbuf_get_rowstride(pixbuf) *
					  2);
			memcpy(pixels,
			       oldpixels,
			       gdk_pixbuf_get_rowstride(pixbuf) * height);
			memcpy(pixels +
			       gdk_pixbuf_get_rowstride(pixbuf) * height,
			       oldpixels,
			       gdk_pixbuf_get_rowstride(pixbuf) * height);
			memcpy(oldpixels,
			       pixels + gdk_pixbuf_get_rowstride(pixbuf) * y +
			       (gdk_pixbuf_get_bits_per_sample(pixbuf) *
				gdk_pixbuf_get_n_channels(pixbuf) * x) / 8,
			       gdk_pixbuf_get_rowstride(pixbuf) * height);
			g_free(pixels);
		}
	} else
	if (GDK_IS_PIXBUF(terminal->pvt->bg_image)) {
		/* If we need to desaturate the image, create a copy we can
		 * safely modify.  Otherwise just ref the one we were passed. */
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC)) {
			fprintf(stderr, "Applying new background pixbuf.\n");
		}
#endif
		if (terminal->pvt->bg_saturation != VTE_SATURATION_MAX) {
			pixbuf = gdk_pixbuf_copy(terminal->pvt->bg_image);
		} else {
			pixbuf = terminal->pvt->bg_image;
			g_object_ref(G_OBJECT(pixbuf));
		}
	}

	/* Desaturate the image if we need to. */
	if (GDK_IS_PIXBUF(pixbuf)) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC)) {
			fprintf(stderr, "Desaturating background.\n");
		}
#endif
		if (terminal->pvt->bg_saturation != VTE_SATURATION_MAX) {
			pixels = gdk_pixbuf_get_pixels(pixbuf);
			pixel_count = gdk_pixbuf_get_height(pixbuf) *
				      gdk_pixbuf_get_rowstride(pixbuf);
			for (i = 0; i < pixel_count; i++) {
				pixels[i] = pixels[i]
					    * terminal->pvt->bg_saturation
					    / VTE_SATURATION_MAX;
			}
		}
	}

	if (GDK_IS_PIXBUF(pixbuf)) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC)) {
			fprintf(stderr, "Setting final background.\n");
		}
#endif
		/* Render the modified image into a pixmap/bitmap pair. */
		colormap = gdk_drawable_get_colormap(widget->window);
		gdk_pixbuf_render_pixmap_and_mask_for_colormap(pixbuf,
							       colormap,
							       &pixmap,
							       &bitmap,
							       0);

		/* Get rid of the pixbuf, which is no longer useful. */
		g_object_unref(G_OBJECT(pixbuf));
		pixbuf = NULL;

		/* Set the pixmap as the window background, and then get unref
		 * it (the drawable should keep a ref). */
		if (GDK_IS_PIXMAP(pixmap)) {
			/* Set the pixmap as the window background. */
			gdk_window_set_back_pixmap(widget->window,
						   pixmap,
						   FALSE);
			g_object_unref(G_OBJECT(pixmap));
			pixmap = NULL;
		}
		if (GDK_IS_DRAWABLE(bitmap)) {
			g_object_unref(G_OBJECT(bitmap));
			bitmap = NULL;
		}
	}

	/* Force a redraw for everything. */
	vte_invalidate_all(terminal);
}

void
vte_terminal_set_background_saturation(VteTerminal *terminal, double saturation)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	terminal->pvt->bg_saturation = saturation * VTE_SATURATION_MAX;
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Setting background saturation to %ld/%ld.\n",
			terminal->pvt->bg_saturation,
			(long) VTE_SATURATION_MAX);
	}
#endif
	vte_terminal_queue_background_update(terminal);
}

/* Set up the background, grabbing a new copy of the transparency background,
 * if possible. */
static gboolean
vte_terminal_update_transparent(gpointer data)
{
	VteTerminal *terminal;
	g_return_val_if_fail(VTE_IS_TERMINAL(data), FALSE);
	terminal = VTE_TERMINAL(data);
	if (terminal->pvt->bg_transparent_update_pending) {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_EVENTS)) {
			fprintf(stderr, "Starting background update.\n");
		}
#endif
		vte_terminal_setup_background(terminal, TRUE);
		terminal->pvt->bg_transparent_update_pending = FALSE;
		terminal->pvt->bg_transparent_update_tag = -1;
	}
	return FALSE;
}

/* Queue an update of the background image, to be done as soon as we can
 * get to it.  Just bail if there's already an update pending, so that if
 * opaque move tables to screw us, we don't end up with an insane backlog
 * of updates after the user finishes moving us. */
static void
vte_terminal_queue_background_update(VteTerminal *terminal)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	if (!terminal->pvt->bg_transparent_update_pending) {
		terminal->pvt->bg_transparent_update_pending = TRUE;
		terminal->pvt->bg_transparent_update_tag =
				g_idle_add_full(VTE_FX_PRIORITY,
						vte_terminal_update_transparent,
						terminal,
						NULL);
	} else {
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_EVENTS)) {
			fprintf(stderr, "Skipping background update.\n");
		}
#endif
	}
}

/* Watch for property change events. */
static GdkFilterReturn
vte_terminal_filter_property_changes(GdkXEvent *xevent, GdkEvent *event,
				     gpointer data)
{
	VteTerminal *terminal;
	GdkWindow *window;
	XEvent *xev;
	GdkAtom atom;

	xev = (XEvent*) xevent;

	/* If we aren't realized, then we have no need for this information. */
	if (VTE_IS_TERMINAL(data) && GTK_WIDGET_REALIZED(GTK_WIDGET(data))) {
		terminal = VTE_TERMINAL(data);
	} else {
		return GDK_FILTER_CONTINUE;
	}

	/* We only care about property changes to the pixmap ID on the root
	 * window, so we should ignore everything else. */
	switch (xev->type) {
	case PropertyNotify:
#ifdef VTE_DEBUG
		if (vte_debug_on(VTE_DEBUG_MISC)) {
			fprintf(stderr, "Property changed.\n");
		}
#endif
		atom = terminal->pvt->bg_transparent_atom;
		if (xev->xproperty.atom == gdk_x11_atom_to_xatom(atom)) {
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_MISC)) {
				fprintf(stderr, "Property atom matches.\n");
			}
#endif
			window = terminal->pvt->bg_transparent_window;
			if (xev->xproperty.window == GDK_DRAWABLE_XID(window)) {
#ifdef VTE_DEBUG
				if (vte_debug_on(VTE_DEBUG_MISC)) {
					fprintf(stderr, "Property window "
						"matches.\n");
				}
#endif
				/* The attribute we care about changed in the
				 * window we care about, so update the
				 * background image to the new snapshot. */
				vte_terminal_queue_background_update(terminal);
			}
		}
	}
	return GDK_FILTER_CONTINUE;
}

/* Turn background "transparency" on or off. */
void
vte_terminal_set_background_transparent(VteTerminal *terminal, gboolean setting)
{
	GdkWindow *window;
	GdkAtom atom;

	g_return_if_fail(VTE_IS_TERMINAL(terminal));
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Turning background transparency %s.\n",
			setting ? "on" : "off");
	}
#endif
	terminal->pvt->bg_transparent = setting;

	/* To be "transparent", we treat the _XROOTPMAP_ID attribute of the
	 * root window as a picture of what's beneath us, and use that as
	 * the background.  It's a little tricky because we need to "scroll"
	 * the image to match our window position. */
	window = gdk_get_default_root_window();
	if (setting) {
		/* Get the window and property name we'll be watching for
		 * changes in. */
		atom = gdk_atom_intern("_XROOTPMAP_ID", TRUE);
		terminal->pvt->bg_transparent_window = window;
		terminal->pvt->bg_transparent_atom = atom;
		/* Add a filter to watch for this property changing. */
		gdk_window_add_filter(window,
				      vte_terminal_filter_property_changes,
				      terminal);
		gdk_window_set_events(window,
				      gdk_window_get_events(window) |
				      GDK_PROPERTY_CHANGE_MASK);
		/* Remove a background image, if we have one. */
		if (GDK_IS_PIXBUF(terminal->pvt->bg_image)) {
			g_object_unref(G_OBJECT(terminal->pvt->bg_image));
			terminal->pvt->bg_image = NULL;
		}
	} else {
		/* Remove the watch filter in case it was added before. */
		gdk_window_remove_filter(window,
					 vte_terminal_filter_property_changes,
					 terminal);
	}
	/* Update the background. */
	vte_terminal_queue_background_update(terminal);
}

void
vte_terminal_set_background_image(VteTerminal *terminal, GdkPixbuf *image)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));

#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "%s background image.\n",
			GDK_IS_PIXBUF(image) ? "Setting" : "Clearing");
	}
#endif

	/* Get a ref to the new image if there is one.  Do it here just in
	 * case we're actually given the same one we're already using. */
	if (GDK_IS_PIXBUF(image)) {
		g_object_ref(G_OBJECT(image));
	}

	/* Unref the previous background image. */
	if (GDK_IS_PIXBUF(terminal->pvt->bg_image)) {
		g_object_unref(G_OBJECT(terminal->pvt->bg_image));
	}

	/* Set the new background. */
	terminal->pvt->bg_image = image;

	/* Turn off transparency and finish setting things up. */
	if (terminal->pvt->bg_transparent) {
		vte_terminal_set_background_transparent(terminal, FALSE);
	}
	vte_terminal_queue_background_update(terminal);
}

/* Set the background image using just a file.  It's more efficient for a
 * caller to pass us an already-desaturated pixbuf if we've got multiple
 * instances going, but this is handy for the single-widget case. */
void
vte_terminal_set_background_image_file(VteTerminal *terminal, const char *path)
{
	GdkPixbuf *image;
	GError *error = NULL;
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	g_return_if_fail(path != NULL);
	g_return_if_fail(strlen(path) > 0);
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_MISC)) {
		fprintf(stderr, "Loading background image from `%s'.\n", path);
	}
#endif
	image = gdk_pixbuf_new_from_file(path, &error);
	if ((image != NULL) && (error == NULL)) {
		vte_terminal_set_background_image(terminal, image);
		g_object_unref(G_OBJECT(image));
	} else {
		/* Set "no image" as the background. */
		vte_terminal_set_background_image(terminal, NULL);
		/* FIXME: do something better with the error. */
		g_error_free(error);
	}
}

/* Check if we're the current owner of the clipboard. */
gboolean
vte_terminal_get_has_selection(VteTerminal *terminal)
{
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), FALSE);
	return terminal->pvt->has_selection;
}

/* Tell the caller if we're [planning on] using Xft for rendering. */
gboolean
vte_terminal_get_using_xft(VteTerminal *terminal)
{
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), FALSE);
	return (terminal->pvt->render_method == VteRenderXft2) ||
	       (terminal->pvt->render_method == VteRenderXft1);
}

/* Toggle the cursor blink setting. */
void
vte_terminal_set_cursor_blinks(VteTerminal *terminal, gboolean blink)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	terminal->pvt->cursor_blinks = blink;
}

/* Set the length of the scrollback buffers. */
void
vte_terminal_set_scrollback_lines(VteTerminal *terminal, long lines)
{
	long old_next = 0, new_next = 0, delta;
	VteScreen *screens[2];
	int i;

	g_return_if_fail(VTE_IS_TERMINAL(terminal));

	/* We require a minimum buffer size. */
	lines = MAX(lines, VTE_SCROLLBACK_MIN);
	lines = MAX(lines, terminal->row_count);

	/* We need to resize both scrollback buffers, and this beats copying
	 * and pasting the same code twice. */
	screens[0] = &terminal->pvt->normal_screen;
	screens[1] = &terminal->pvt->alternate_screen;

	/* We want to do the same thing to both screens, so we use a loop
	 * to avoid cut/paste madness. */
	for (i = 0; i < G_N_ELEMENTS(screens); i++) {
		/* Resize the buffers, but keep track of where the last data
		 * in the buffer is so that we can compensate for it being
		 * moved.  We track the end of the data instead of the start
		 * so that the visible portion of the buffer doesn't change. */
		old_next = 0;
		if (screens[i]->row_data != NULL) {
			old_next = vte_ring_next(screens[i]->row_data);
		}
		/* The main screen gets the full scrollback buffer, but the
		 * alternate screen isn't allowed to scroll at all. */
		if (screens[i] == &terminal->pvt->alternate_screen) {
			vte_terminal_reset_rowdata(&screens[i]->row_data,
						   terminal->row_count);
		} else {
			vte_terminal_reset_rowdata(&screens[i]->row_data,
						   lines);
		}
		new_next = vte_ring_next(screens[i]->row_data);
		/* Adjust the scrolling delta by the difference of the two --
		 * this should keep the same lines in the same places on the
		 * screen. */
		delta = MAX(0, new_next - old_next);
		screens[i]->cursor_current.row += delta;
		screens[i]->scroll_delta += delta;
		screens[i]->insert_delta += delta;
	}
	terminal->pvt->scrollback_lines = lines;

	/* Adjust the scrollbars to the new locations. */
	vte_terminal_adjust_adjustments(terminal);
	vte_invalidate_all(terminal);
}

/* Set the list of characters we consider to be parts of words.  Everything
 * else will be a non-word character, and we'll use transitions between the
 * two sets when doing selection-by-words. */
void
vte_terminal_set_word_chars(VteTerminal *terminal, const char *spec)
{
	GIConv conv;
	gunichar *wbuf;
	char *ibuf, *ibufptr, *obuf, *obufptr;
	gssize ilen, olen;
	VteWordCharRange range;
	int i;

	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	/* Allocate a new range array. */
	if (terminal->pvt->word_chars != NULL) {
		g_array_free(terminal->pvt->word_chars, TRUE);
	}
	terminal->pvt->word_chars = g_array_new(FALSE, TRUE,
						sizeof(VteWordCharRange));
	/* Convert the spec from UTF-8 to a string of gunichars . */
	conv = g_iconv_open(vte_table_wide_encoding(), "UTF-8");
	if (conv == ((GIConv) -1)) {
		/* Aaargh.  We're screwed. */
		g_warning(_("g_iconv_open() failed setting word characters"));
		return;
	}
	ilen = strlen(spec);
	ibuf = ibufptr = g_strdup(spec);
	olen = (ilen + 1) * sizeof(gunichar);
	obuf = obufptr = g_malloc0(sizeof(gunichar) * (strlen(spec) + 1));
	wbuf = (gunichar*) obuf;
	wbuf[ilen] = '\0';
	g_iconv(conv, &ibuf, &ilen, &obuf, &olen);
	g_iconv_close(conv);
	for (i = 0; i < ((obuf - obufptr) / sizeof(gunichar)); i++) {
		/* The hyphen character. */
		if (wbuf[i] == '-') {
			range.start = wbuf[i];
			range.end = wbuf[i];
			g_array_append_val(terminal->pvt->word_chars, range);
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_MISC)) {
				fprintf(stderr, "Word charset includes hyphen.\n");
			}
#endif
			continue;
		}
		/* A single character, not the start of a range. */
		if ((wbuf[i] != '-') && (wbuf[i + 1] != '-')) {
			range.start = wbuf[i];
			range.end = wbuf[i];
			g_array_append_val(terminal->pvt->word_chars, range);
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_MISC)) {
				fprintf(stderr, "Word charset includes `%lc'.\n",
					(wint_t) wbuf[i]);
			}
#endif
			continue;
		}
		/* The start of a range. */
		if ((wbuf[i] != '-') &&
		    (wbuf[i + 1] == '-') &&
		    (wbuf[i + 2] != '-') &&
		    (wbuf[i + 2] != 0)) {
			range.start = wbuf[i];
			range.end = wbuf[i + 2];
			g_array_append_val(terminal->pvt->word_chars, range);
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_MISC)) {
				fprintf(stderr, "Word charset includes range from "
					"`%lc' to `%lc'.\n", (wint_t) wbuf[i],
					(wint_t) wbuf[i + 2]);
			}
#endif
			i += 2;
			continue;
		}
	}
	g_free(ibufptr);
	g_free(obufptr);
}

void
vte_terminal_set_backspace_binding(VteTerminal *terminal,
				   VteTerminalEraseBinding binding)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	/* FIXME: should we set the pty mode to match? */
	terminal->pvt->backspace_binding = binding;
}

void
vte_terminal_set_delete_binding(VteTerminal *terminal,
				VteTerminalEraseBinding binding)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	terminal->pvt->delete_binding = binding;
}

void
vte_terminal_set_mouse_autohide(VteTerminal *terminal, gboolean setting)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	terminal->pvt->mouse_autohide = setting;
}

gboolean
vte_terminal_get_mouse_autohide(VteTerminal *terminal)
{
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), FALSE);
	return terminal->pvt->mouse_autohide;
}

void
vte_terminal_reset(VteTerminal *terminal, gboolean full, gboolean clear_history)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	/* Ditch any pending input data. */
	if (terminal->pvt->incoming) {
		g_free(terminal->pvt->incoming);
	}
	terminal->pvt->incoming = NULL;
	terminal->pvt->n_incoming = 0;
	if (terminal->pvt->processing) {
		g_source_remove(terminal->pvt->processing_tag);
		terminal->pvt->processing_tag = -1;
		terminal->pvt->processing = FALSE;
	}
	/* Reset charset substitution state. */
	if (terminal->pvt->substitutions != NULL) {
		vte_iso2022_free(terminal->pvt->substitutions);
	}
	terminal->pvt->substitutions = vte_iso2022_new();
	/* Reset appkeypad state. */
	terminal->pvt->keypad = VTE_KEYPAD_NORMAL;
	/* Reset saved settings. */
	if (terminal->pvt->dec_saved != NULL) {
		g_hash_table_destroy(terminal->pvt->dec_saved);
		terminal->pvt->dec_saved = g_hash_table_new(g_direct_hash,
							    g_direct_equal);
	}
	/* Reset the color palette. */
	/* vte_terminal_set_default_colors(terminal); */
	/* Reset the default attributes.  Reset the alternate attribute because
	 * it's not a real attribute, but we need to treat it as one here. */
	terminal->pvt->screen = &terminal->pvt->alternate_screen;
	vte_terminal_set_default_attributes(terminal);
	terminal->pvt->screen->defaults.alternate = FALSE;
	terminal->pvt->screen = &terminal->pvt->normal_screen;
	vte_terminal_set_default_attributes(terminal);
	terminal->pvt->screen->defaults.alternate = FALSE;
	/* Clear the scrollback buffers and reset the cursors. */
	if (clear_history) {
		vte_ring_free(terminal->pvt->normal_screen.row_data, TRUE);
		terminal->pvt->normal_screen.row_data =
			vte_ring_new(terminal->pvt->scrollback_lines,
				     vte_free_row_data, NULL);
		vte_ring_free(terminal->pvt->alternate_screen.row_data, TRUE);
		terminal->pvt->alternate_screen.row_data =
			vte_ring_new(terminal->pvt->scrollback_lines,
				     vte_free_row_data, NULL);
		terminal->pvt->normal_screen.cursor_saved.row = 0;
		terminal->pvt->normal_screen.cursor_saved.col = 0;
		terminal->pvt->normal_screen.cursor_current.row = 0;
		terminal->pvt->normal_screen.cursor_current.col = 0;
		terminal->pvt->alternate_screen.cursor_saved.row = 0;
		terminal->pvt->alternate_screen.cursor_saved.col = 0;
		terminal->pvt->alternate_screen.cursor_current.row = 0;
		terminal->pvt->alternate_screen.cursor_current.col = 0;
	}
	/* Clear the status lines. */
	terminal->pvt->normal_screen.status_line = FALSE;
	if (terminal->pvt->normal_screen.status_line_contents != NULL) {
		g_string_free(terminal->pvt->normal_screen.status_line_contents,
			      TRUE);
	}
	terminal->pvt->normal_screen.status_line_contents = g_string_new("");
	terminal->pvt->alternate_screen.status_line = FALSE;
	if (terminal->pvt->alternate_screen.status_line_contents != NULL) {
		g_string_free(terminal->pvt->alternate_screen.status_line_contents,
			      TRUE);
	}
	terminal->pvt->alternate_screen.status_line_contents = g_string_new("");
	/* Do more stuff we refer to as a "full" reset. */
	if (full) {
		vte_terminal_set_default_tabstops(terminal);
	}
	/* Reset restricted scrolling regions, leave insert mode, make
	 * the cursor visible again. */
	terminal->pvt->normal_screen.scrolling_restricted = FALSE;
	terminal->pvt->normal_screen.insert_mode = FALSE;
	terminal->pvt->normal_screen.reverse_mode = FALSE;
	terminal->pvt->alternate_screen.scrolling_restricted = FALSE;
	terminal->pvt->alternate_screen.insert_mode = FALSE;
	terminal->pvt->alternate_screen.reverse_mode = FALSE;
	terminal->pvt->cursor_visible = TRUE;
	/* Reset the input and output buffers. */
	if (terminal->pvt->n_incoming > 0) {
		terminal->pvt->n_incoming = 0;
		g_free(terminal->pvt->incoming);
		terminal->pvt->incoming = NULL;
	}
	if (terminal->pvt->n_outgoing > 0) {
		terminal->pvt->n_outgoing = 0;
		g_free(terminal->pvt->outgoing);
		terminal->pvt->outgoing = NULL;
	}
	/* Reset the encoding. */
	vte_terminal_set_encoding(terminal, NULL);
	g_assert(terminal->pvt->encoding != NULL);
	/* Reset selection. */
	vte_terminal_deselect_all(terminal);
	/* Reset mouse motion events. */
	terminal->pvt->mouse_send_xy_on_click = FALSE;
	terminal->pvt->mouse_send_xy_on_button = FALSE;
	terminal->pvt->mouse_hilite_tracking = FALSE;
	terminal->pvt->mouse_cell_motion_tracking = FALSE;
	terminal->pvt->mouse_all_motion_tracking = FALSE;
	terminal->pvt->mouse_last_button = 0;
	terminal->pvt->mouse_last_x = 0;
	terminal->pvt->mouse_last_y = 0;
	/* Cause everything to be redrawn (or cleared). */
	vte_terminal_scroll_to_bottom(terminal);
	vte_invalidate_all(terminal);
}

const char *
vte_terminal_get_status_line(VteTerminal *terminal)
{
	g_return_val_if_fail(VTE_IS_TERMINAL(terminal), NULL);
	return terminal->pvt->screen->status_line_contents->str;
}

void
vte_terminal_get_padding(VteTerminal *terminal, int *xpad, int *ypad)
{
	g_return_if_fail(VTE_IS_TERMINAL(terminal));
	g_return_if_fail(xpad != NULL);
	g_return_if_fail(ypad != NULL);
	*xpad = 2 * VTE_PAD_WIDTH;
	*ypad = 2 * VTE_PAD_WIDTH;
}