summaryrefslogtreecommitdiff
path: root/pico/display.c
blob: 705dae109eeef3b13066e20b455d7be32770af88 (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
#if	!defined(lint) && !defined(DOS)
static char rcsid[] = "$Id: display.c 1025 2008-04-08 22:59:38Z hubert@u.washington.edu $";
#endif

/*
 * ========================================================================
 * Copyright 2006-2008 University of Washington
 * Copyright 2013-2020 Eduardo Chappa
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * ========================================================================
 *
 * Program:	Display functions
 *
 */

/*
 * The functions in this file handle redisplay. There are two halves, the
 * ones that update the virtual display screen, and the ones that make the
 * physical display screen the same as the virtual display screen. These
 * functions use hints that are left in the windows by the commands.
 *
 */

#include	"../c-client/mail.h"
#include	"../c-client/utf8.h"

#ifdef _WINDOWS
/* wingdi.h uses ERROR (!) and we aren't using the c-client ERROR so... */
#undef ERROR
#endif

#include	"headers.h"
#include	"../pith/charconv/filesys.h"
#include	"../pith/charconv/utf8.h"


void     vtmove(int, int);
void     vtputc(CELL);
void     vteeol(void);
void     updateline(int, CELL *, CELL *, short *, int);
void     updatelinecolor(int, CELL *, CELL *, short *, int);
void     updext(void);
void     mlputi(int, int);
void     pprints(int, int);
void     mlputli(long, int);
void     showCompTitle(void);
int      nlforw(void);
int      dumbroot(int, int);
int      dumblroot(long, int);
unsigned cellwidth_ptr_to_ptr(CELL *pstart, CELL *pend);
unsigned vcellwidth_a_to_b(int row, int a, int b);
int	window_signature_block(WINDOW *wp);
#ifdef _WINDOWS
void    pico_config_menu_items (KEYMENU *);
int     update_scroll (void);
#endif /* _WINDOWS */


/*
 * Standard pico keymenus...
 */
static KEYMENU menu_pico[] = {
    {"^G", N_("Get Help"), KS_SCREENHELP},	{"^O", N_("WriteOut"), KS_SAVEFILE},
    {"^R", N_("Read File"), KS_READFILE},	{"^Y", N_("Prev Pg"), KS_PREVPAGE},
    {"^K", N_("Cut Text"), KS_NONE},	{"^C", N_("Cur Pos"), KS_CURPOSITION},
    {"^X", N_("Exit"), KS_EXIT},		{"^J", N_("Justify"), KS_JUSTIFY},
    {"^W", N_("Where is"), KS_WHEREIS},	{"^V", N_("Next Pg"), KS_NEXTPAGE},
    {"^U", NULL, KS_NONE},
#ifdef	SPELLER
    {"^T", N_("To Spell"), KS_SPELLCHK}
#else
    {"^D", N_("Del Char"), KS_NONE}
#endif
};
#define	UNCUT_KEY	10


static KEYMENU menu_compose[] = {
    {"^G", N_("Get Help"), KS_SCREENHELP},	{"^X", NULL, KS_SEND},
    {"^R", N_("Read File"), KS_READFILE},	{"^Y", N_("Prev Pg"), KS_PREVPAGE},
    {"^K", N_("Cut Text"), KS_NONE},	{"^O", N_("Postpone"), KS_POSTPONE},
    /* TRANSLATORS: Justify is to reformat a paragraph automatically */
    {"^C", N_("Cancel"), KS_CANCEL},	{"^J", N_("Justify"), KS_JUSTIFY},
    {NULL, NULL, KS_NONE},		{"^V", N_("Next Pg"), KS_NEXTPAGE},
    {"^U", NULL, KS_NONE},
#ifdef	SPELLER
    {"^T", N_("To Spell"), KS_SPELLCHK}
#else
    {"^D", N_("Del Char"), KS_NONE}
#endif
};
#define	EXIT_KEY	1
#define	PSTPN_KEY	5
#define	WHERE_KEY	8


/*
 * Definition's for pico's modeline
 */
#define	PICO_TITLE	"  UW PICO %s"
#define	PICO_MOD_MSG	"Modified"
#define	PICO_NEWBUF_MSG	"New Buffer"

#define WFDEBUG 0                       /* Window flag debug. */

#define VFCHG   0x0001                  /* Changed flag			*/
#define	VFEXT	0x0002			/* extended (beyond column 80)	*/
#define VFSIG	0x0004			/* in signature block		*/

int     vtrow   = 0;                    /* Row location of SW cursor */
int     vtcol   = 0;                    /* Column location of SW cursor */
int     vtind   = 0;                    /* Index into row array of SW cursor */
int     ttrow   = FARAWAY;              /* Row location of HW cursor */
int     ttcol   = FARAWAY;              /* Column location of HW cursor */
int	lbound	= 0;			/* leftmost column of current line
					   being displayed */

VIDEO   **vscreen;                      /* Virtual screen. */
VIDEO   **pscreen;                      /* Physical screen. */


/*
 * Initialize the data structures used by the display code. The edge vectors
 * used to access the screens are set up. The operating system's terminal I/O
 * channel is set up. All the other things get initialized at compile time.
 * The original window has "WFCHG" set, so that it will get completely
 * redrawn on the first call to "update".
 */
int
vtinit(void)
{
    int i, j;
    VIDEO *vp;
    CELL   ac;

    ac.c = ' ';
    ac.a = 0;

    if(Pmaster == NULL)
      vtterminalinfo(gmode & MDTCAPWINS);

    (*term.t_open)();

    (*term.t_rev)(FALSE);
    vscreen = (VIDEO **) malloc((term.t_nrow+1)*sizeof(VIDEO *));
    memset(vscreen, 0, (term.t_nrow+1)*sizeof(VIDEO *));
    if (vscreen == NULL){
	emlwrite("Allocating memory for virtual display failed.", NULL);
        return(FALSE);
    }

    pscreen = (VIDEO **) malloc((term.t_nrow+1)*sizeof(VIDEO *));
    memset(pscreen, 0, (term.t_nrow+1)*sizeof(VIDEO *));
    if (pscreen == NULL){
	free((void *)vscreen);
	emlwrite("Allocating memory for physical display failed.", NULL);
        return(FALSE);
    }


    for (i = 0; i <= term.t_nrow; ++i) {
        vp = (VIDEO *) malloc(sizeof(VIDEO)+(term.t_ncol*sizeof(CELL)));

        if (vp == NULL){
	    free((void *)vscreen);
	    free((void *)pscreen);
	    emlwrite("Allocating memory for virtual display lines failed.",
		     NULL);
            return(FALSE);
	}
	else
	  for(j = 0; j < term.t_ncol; j++)
	    vp->v_text[j] = ac;

	vp->v_flag = 0;
	vp->v_length = 0;
        vscreen[i] = vp;

        vp = (VIDEO *) malloc(sizeof(VIDEO)+(term.t_ncol*sizeof(CELL)));

        if (vp == NULL){
            free((void *)vscreen[i]);
	    while(--i >= 0){
		free((void *)vscreen[i]);
		free((void *)pscreen[i]);
	    }

	    free((void *)vscreen);
	    free((void *)pscreen);
	    emlwrite("Allocating memory for physical display lines failed.",
		     NULL);
            return(FALSE);
	}
	else
	  for(j = 0; j < term.t_ncol; j++)
	    vp->v_text[j] = ac;

	vp->v_flag = 0;
	vp->v_length = 0;
        pscreen[i] = vp;
    }

    return(TRUE);
}

int
vtterminalinfo(int termcap_wins)
{
    return((term.t_terminalinfo) ? (*term.t_terminalinfo)(termcap_wins)
				 : (Pmaster ? 0 : TRUE));
}


/*
 * Clean up the virtual terminal system, in anticipation for a return to the
 * operating system. Move down to the last line and clear it out (the next
 * system prompt will be written in the line). Shut down the channel to the
 * terminal.
 */
void
vttidy(void)
{
    movecursor(term.t_nrow-1, 0);
    peeol();
    movecursor(term.t_nrow, 0);
    peeol();
    (*term.t_close)();
}


/*
 * Set the virtual cursor to the specified row and column on the virtual
 * screen. There is no checking for nonsense values; this might be a good
 * idea during the early stages.
 */
void
vtmove(int row, int col)
{
    vtrow = row;
    vtcol = col;

    if(vtcol < 0)
      vtind = -1;
    else if(vtcol == 0)
      vtind = vtcol;
    else{
	/*
	 * This is unused so don't worry about it.
	 */
	assert(0);
    }
}


/*
 * Write a character to the virtual screen. The virtual row and column are
 * updated. If the line is too long put a "$" in the last column. This routine
 * only puts printing characters into the virtual terminal buffers. Only
 * column overflow is checked.
 */
void
vtputc(CELL c)
{
    VIDEO   *vp;
    CELL     ac;
    int      w;

    vp = vscreen[vtrow];
    ac.c = ' ';
    ac.a = c.a;
    ac.d = c.d;

    if (vtcol >= term.t_ncol) {
	/*
	 * What's this supposed to be doing? This sets vtcol
	 * to the even multiple of 8 >= vtcol. Why are we doing that?
	 * Must make tab work correctly.
	 *               24 -> 24
	 *               25 -> 32
	 *               ...
	 *               31 -> 32
	 *               32 -> 32
	 *               33 -> 40
	 */
        vtcol = (vtcol + 0x07) & ~0x07;
	ac.c = '$';

	/*
	 * If we get to here that means that there must be characters
	 * past the right hand edge, so we want to put a $ character
	 * in the last visible character. It would be nice to replace
	 * the last visible character by a double-$ if it is double-width
	 * but we aren't doing that because we'd have to add up the widths
	 * starting at the left hand margin each time through.
	 */
	if(vtind > 0 && vtind <= term.t_ncol)
          vp->v_text[vtind-1] = ac;
    }
    else if (c.c == '\t') {
        do {
            vtputc(ac);
	}
        while (((vtcol + (vtrow==currow ? lbound : 0)) & 0x07) != 0 && vtcol < term.t_ncol);
    }
    else if (ISCONTROL(c.c)){
	ac.c = '^';
        vtputc(ac);
	ac.c = ((c.c & 0x7f) | 0x40);
        vtputc(ac);
    }
    else{

	/*
	 * Have to worry about what happens if we skip over 0
	 * with a double-width character. There may be a better
	 * place to be setting vtind, or maybe we could make do
	 * without it.
	 */

	w = wcellwidth((UCS) c.c);
	w = (w >= 0 ? w : 1);

	if(vtcol == 0 || (vtcol < 0 && vtcol + w == 1)){
	    vtind = 0;
	    if(vtcol < 0)
	      vtcol = 0;
	}

	/*
	 * Double-width character overlaps right edge.
	 * Replace it with a $.
	 */
	if(vtcol + w > term.t_ncol){
	    ac.c = '$';
	    c = ac;
	    w = 1;
	}

	if(vtind >= 0 && vtind < term.t_ncol)
	  vp->v_text[vtind++] = c;

	vtcol += w;
    }
}


/*
 * Erase from the end of the software cursor to the end of the line on which
 * the software cursor is located.
 */
void
vteeol(void)
{
    register VIDEO      *vp;
    CELL     c;

    c.c = ' ';
    c.a = 0;
    vp = vscreen[vtrow];

    if(vtind >= 0)
      while (vtind < term.t_ncol)
        vp->v_text[vtind++] = c;

    vtcol = term.t_ncol;
}

int
window_signature_block(WINDOW *wp)
{
  LINE *lp, *llp;
  int in_sig, is_sig_start;
  int change = 0;

  llp = wp->w_linep;
  lp = lforw(wp->w_bufp->b_linep);

  do {
    in_sig = lback(lp) == wp->w_bufp->b_linep ? 0 : lback(lp)->l_sig;
    if(in_sig == 0){
       if(llength(lp) == 3){
	 if(lgetc(lp, 0).c == '-' 
	     && lgetc(lp, 1).c == '-' 
	     && lgetc(lp, 2).c == ' '){
	   in_sig = 1; 
	   is_sig_start = 1;
	 }
       }
    } else {
	if(lisblank(lp))
	   if(is_sig_start == 0) in_sig = 0;
	is_sig_start = 0;
    }
    if(lp->l_sig != in_sig)
      change++;
    lp->l_sig = in_sig;
    lp = lforw(lp);
  } while(lp != wp->w_bufp->b_linep);
  wp->w_linep = llp;
  return change;
}


/*
 * Make sure that the display is right. This is a three part process. First,
 * scan through all of the windows looking for dirty ones. Check the framing,
 * and refresh the screen. Second, make sure that "currow" and "curcol" are
 * correct for the current window. Third, make the virtual and physical
 * screens the same.
 */
void
update(void)
{
    LINE   *lp;
    WINDOW *wp;
    VIDEO  *vp1;
    VIDEO  *vp2;
    int     i;
    int     j;
    int     scroll = 0;
    int     repaint= 0;
    int	    quoted;
    CELL	     c;
    PCOLORS *pcolors = Pmaster && Pmaster->colors ? Pmaster->colors : Pcolors;

#if	TYPEAH
    if (typahead())
	return;
#endif

#ifdef _WINDOWS
    /* This tells our MS Windows module to not bother updating the
     * cursor position while a massive screen update is in progress.
     */
    mswin_beginupdate ();
#endif

/*
 * BUG: setting and unsetting whole region at a time is dumb.  fix this.
 */
    if(curwp->w_markp){
	unmarkbuffer();
	markregion(1);
    }

    wp = wheadp;

    while (wp != NULL){
        /* Look at any window with update flags set on. */

	if(pcolors && (repaint = window_signature_block(wp))){
	   sgarbf = TRUE;
	   wp->w_flag |= WFEDIT | WFHARD;
	}
        if (wp->w_flag != 0){
            /* If not force reframe, check the framing. */

            if ((wp->w_flag & WFFORCE) == 0){
                lp = wp->w_linep;

                for (i = 0; i < wp->w_ntrows; ++i){
                    if (lp == wp->w_dotp)
		      goto out;

                    if (lp == wp->w_bufp->b_linep)
		      break;

                    lp = lforw(lp);
		}
	    }

            /* Not acceptable, better compute a new value for the line at the
             * top of the window. Then set the "WFHARD" flag to force full
             * redraw.
             */
            i = wp->w_force;

            if (i > 0){
                --i;

                if (i >= wp->w_ntrows)
                  i = wp->w_ntrows-1;
	    }
            else if (i < 0){
                i += wp->w_ntrows;

                if (i < 0)
		  i = 0;
	    }
            else if(TERM_OPTIMIZE){
		/* 
		 * find dotp, if its been moved just above or below the 
		 * window, use scrollxxx() to facilitate quick redisplay...
		 */
		lp = lforw(wp->w_dotp);
		if(lp != wp->w_dotp){
		    if(lp == wp->w_linep && lp != wp->w_bufp->b_linep){
			scroll = 1;
		    }
		    else {
			lp = wp->w_linep;
			for(j=0;j < wp->w_ntrows; ++j){
			    if(lp != wp->w_bufp->b_linep)
			      lp = lforw(lp);
			    else
			      break;
			}
			if(lp == wp->w_dotp && j == wp->w_ntrows)
			  scroll = 2;
		    }
		}
		j = i = wp->w_ntrows/2;
	    }
	    else
	      i = wp->w_ntrows/2;

            lp = wp->w_dotp;

            while (i != 0 && lback(lp) != wp->w_bufp->b_linep){
                --i;
                lp = lback(lp);
	    }

	    /*
	     * this is supposed to speed things up by using tcap sequences
	     * to efficiently scroll the terminal screen.  the thinking here
	     * is that its much faster to update pscreen[] than to actually
	     * write the stuff to the screen...
	     */
	    if(TERM_OPTIMIZE){
		switch(scroll){
		  case 1:			/* scroll text down */
		    j = j-i+1;			/* add one for dot line */
			/* 
			 * do we scroll down the header as well?  Well, only 
			 * if we're not editing the header, we've backed up 
			 * to the top, and the composer is not being 
			 * displayed...
			 */
		    if(Pmaster && Pmaster->headents && !ComposerEditing 
		       && (lback(lp) == wp->w_bufp->b_linep)
		       && (ComposerTopLine == COMPOSER_TOP_LINE))
		      j += entry_line(1000, TRUE); /* Never > 1000 headers */

		    scrolldown(wp, -1, j);
		    break;
		  case 2:			/* scroll text up */
		    j = wp->w_ntrows - (j-i);	/* we chose new top line! */
		    if(Pmaster && j){
			/* 
			 * do we scroll down the header as well?  Well, only 
			 * if we're not editing the header, we've backed up 
			 * to the top, and the composer is not being 
			 * displayed...
			 */
			if(!ComposerEditing 
			   && (ComposerTopLine != COMPOSER_TOP_LINE))
			  scrollup(wp, COMPOSER_TOP_LINE, 
				   j+entry_line(1000, TRUE));
			else
			  scrollup(wp, -1, j);
		    }
		    else
		      scrollup(wp, -1, j);
		    break;
		    default :
		      break;
		}
	    }

            wp->w_linep = lp;
            wp->w_flag |= WFHARD;       /* Force full. */
out:
	    /*
	     * if the line at the top of the page is the top line
	     * in the body, show the header...
	     */
	    if(Pmaster && Pmaster->headents && !ComposerEditing){
		if(lback(wp->w_linep) == wp->w_bufp->b_linep){
		    if(ComposerTopLine == COMPOSER_TOP_LINE){
			i = term.t_nrow - 2 - term.t_mrow - HeaderLen();
			if(i > 0 && nlforw() >= i) {	/* room for header ? */
			    if((i = nlforw()/2) == 0 && term.t_nrow&1)
			      i = 1;
			    while(wp->w_linep != wp->w_bufp->b_linep && i--)
			      wp->w_linep = lforw(wp->w_linep);
			    
			}
			else
			  ToggleHeader(1);
		    }
		}
		else{
		    if(ComposerTopLine != COMPOSER_TOP_LINE)
		      ToggleHeader(0);		/* hide it ! */
		}
	    }

            /* Try to use reduced update. Mode line update has its own special
             * flag. The fast update is used if the only thing to do is within
             * the line editing.
             */
            lp = wp->w_linep;
            i = wp->w_toprow;

            if ((wp->w_flag & ~WFMODE) == WFEDIT){
                while (lp != wp->w_dotp){
                    ++i;
                    lp = lforw(lp);
		}
		vscreen[i]->v_flag |= (lp->l_sig ? VFSIG : 0)| VFCHG;
		/* compute physical length of line in screen */
		vscreen[i]->v_length = 0;
		for (j = 0; vscreen[i]->v_length < term.t_ncol
			    && j < llength(lp); ++j){
		    c = lgetc(lp, j);
		    if(c.c == '\t'){
		       vscreen[i]->v_length |= 0x07;
		       vscreen[i]->v_length++;
		    }
		    else if(ISCONTROL(c.c)){
		       vscreen[i]->v_length += 2;
		    }
		    else{
		       int w;

		       w = wcellwidth((UCS) c.c);
		       vscreen[i]->v_length += (w >= 0 ? w : 1);
		    }
		}
                vtmove(i, 0);

                for (j = 0; j < llength(lp); ++j)
                    vtputc(lgetc(lp, j));
                vteeol();
	    }
	    else if ((wp->w_flag & (WFEDIT | WFHARD)) != 0){
                while (i < wp->w_toprow+wp->w_ntrows){
                    vscreen[i]->v_flag |= (lp->l_sig ? VFSIG : 0 )| VFCHG;
		    /* compute physical length of line in screen */
		    vscreen[i]->v_length = 0;
		    for (j = 0; vscreen[i]->v_length < term.t_ncol
			    && j < llength(lp); ++j){
		        c = lgetc(lp, j);
		        if(c.c == '\t'){
		           vscreen[i]->v_length |= 0x07;
		           vscreen[i]->v_length++;
		        }
		        else if(ISCONTROL(c.c)){
		           vscreen[i]->v_length += 2;
		        }
		        else{
		           int w;

			   w = wcellwidth((UCS) c.c);
		           vscreen[i]->v_length += (w >= 0 ? w : 1);
		       }
		    }
                    vtmove(i, 0);

		    /* if line has been changed */
                    if (lp != wp->w_bufp->b_linep){
                        for (j = 0; j < llength(lp); ++j)
                            vtputc(lgetc(lp, j));

                        lp = lforw(lp);
		    }

                    vteeol();
                    ++i;
		}
	    }
#if ~WFDEBUG
            if ((wp->w_flag&WFMODE) != 0)
                modeline(wp);

            wp->w_flag  = 0;
            wp->w_force = 0;
#endif
	}
#if WFDEBUG
        modeline(wp);
        wp->w_flag =  0;
        wp->w_force = 0;
#endif

	/* and onward to the next window */
        wp = wp->w_wndp;
    }

    /* Always recompute the row and column number of the hardware cursor. This
     * is the only update for simple moves.
     */
    lp = curwp->w_linep;
    currow = curwp->w_toprow;

    while (lp != curwp->w_dotp){
        ++currow;
        lp = lforw(lp);
    }

    curcol = 0;
    i = 0;

    while (i < curwp->w_doto){
	c = lgetc(lp, i++);

        if(c.c == '\t'){
            curcol |= 0x07;
	    ++curcol;
	}
        else if(ISCONTROL(c.c)){
            curcol += 2;
	}
	else{
	    int w;

	    w = wcellwidth((UCS) c.c);
	    curcol += (w >= 0 ? w : 1);
	}
    }

    if (curcol >= term.t_ncol) { 		/* extended line. */
	/* flag we are extended and changed */
	vscreen[currow]->v_flag |= VFEXT | VFCHG;
	updext();				/* and output extended line */
    } else
      lbound = 0;				/* not extended line */

    /* make sure no lines need to be de-extended because the cursor is
     * no longer on them 
     */

    wp = wheadp;

    while (wp != NULL) {
	lp = wp->w_linep;
	i = wp->w_toprow;

	while (i < wp->w_toprow + wp->w_ntrows) {
	    if (vscreen[i]->v_flag & VFEXT) {
		/* always flag extended lines as changed */
		vscreen[i]->v_flag |= VFCHG;
		if ((wp != curwp) || (lp != wp->w_dotp) ||
		    (curcol < term.t_ncol)) {
		    vtmove(i, 0);
		    for (j = 0; j < llength(lp); ++j)
		      vtputc(lgetc(lp, j));
		    vteeol();

		    /* this line no longer is extended */
		    vscreen[i]->v_flag &= ~VFEXT;
		}
	    }
	    lp = lforw(lp);
	    ++i;
	}
	/* and onward to the next window */
        wp = wp->w_wndp;
    }

    /* Special hacking if the screen is garbage. Clear the hardware screen,
     * and update your copy to agree with it. Set all the virtual screen
     * change bits, to force a full update.
     */

    if (sgarbf != FALSE){
	if(Pmaster){
	    int rv;
       
	    showCompTitle();

	    if(ComposerTopLine != COMPOSER_TOP_LINE){
		UpdateHeader(0);		/* arrange things */
		PaintHeader(COMPOSER_TOP_LINE, TRUE);
	    }

	    /*
	     * since we're using only a portion of the screen and only 
	     * one buffer, only clear enough screen for the current window
	     * which is to say the *only* window.
	     */
	    for(i=wheadp->w_toprow;i<=term.t_nrow; i++){
		movecursor(i, 0);
		peeol();
		vscreen[i]->v_flag |= VFCHG;
	    }
	    rv = (*Pmaster->showmsg)('X' & 0x1f);	/* ctrl-L */
	    ttresize();
	    picosigs();		/* restore altered handlers */
	    if(rv)		/* Did showmsg corrupt the display? */
	      PaintBody(0);	/* Yes, repaint */
	    movecursor(wheadp->w_toprow, 0);
	}
	else{
	    c.c = ' ';
	    c.a = 0;
	    for (i = 0; i < term.t_nrow-term.t_mrow; i++){
		vscreen[i]->v_flag |= VFCHG;
		vp1 = pscreen[i];
		for (j = 0; j < term.t_ncol; j++)
		  vp1->v_text[j] = c;
		if(sgarbf == FALSE){
		   movecursor(i, 0);
		   term.t_eeol();
		}
	    }
	    if(sgarbf != FALSE){
	      movecursor(0, 0);	               /* Erase the screen. */
	      (*term.t_eeop)();
	    }
	}

        sgarbf = FALSE;				/* Erase-page clears */
        mpresf = FALSE;				/* the message area. */

	if(Pmaster)
	  modeline(curwp);
	else
	  sgarbk = TRUE;			/* fix the keyhelp as well...*/
    }

    /* Make sure that the physical and virtual displays agree. Unlike before,
     * the "updateline" code is only called with a line that has been updated
     * for sure.
     */
    if(Pmaster)
      i = curwp->w_toprow;
    else
      i = 0;

    if (term.t_nrow > term.t_mrow)
       c.c = term.t_nrow - term.t_mrow;
    else
       c.c = 0;

    for (; i < (int)c.c; ++i){

        vp1 = vscreen[i];

	/* for each line that needs to be updated, or that needs its
	   reverse video status changed, call the line updater	*/
	j = vp1->v_flag;
        if (j & VFCHG){

#if	TYPEAH
	    if (typahead()){
#ifdef _WINDOWS
		mswin_endupdate ();
#endif
	        return;
	    }
#endif
            vp2 = pscreen[i];

            updateline(i, &vp1->v_text[0], &vp2->v_text[0], &vp1->v_flag, vp1->v_length);
	}
    }

    if(Pmaster == NULL){

	if(sgarbk != FALSE){
	    if(term.t_mrow > 0){
		movecursor(term.t_nrow-1, 0);
		peeol();
		movecursor(term.t_nrow, 0);
		peeol();
	    }

	    if(lastflag&CFFILL){
		/* TRANSLATORS: UnJustify means undo the previous
		   Justify command. */
		menu_pico[UNCUT_KEY].label = N_("UnJustify");
		if(!(lastflag&CFFLBF)){
		    emlwrite(_("Can now UnJustify!"), NULL);
		    mpresf = FARAWAY;	/* remove this after next keystroke! */
		}
	    }
	    else
	      menu_pico[UNCUT_KEY].label = N_("UnCut Text");

	    wkeyhelp(menu_pico);
	    sgarbk = FALSE;
        }
    }

    if(lastflag&CFFLBF){
	emlwrite(_("Can now UnJustify!"), NULL);
	mpresf = FARAWAY;  /* remove this after next keystroke! */
    }

    /* Finally, update the hardware cursor and flush out buffers. */

    movecursor(currow, curcol - lbound);
#ifdef _WINDOWS
    mswin_endupdate ();

    /* 
     * Update the scroll bars.  This function is where curbp->b_linecnt
     * is really managed.  See update_scroll.
     */
    update_scroll ();
#endif
    (*term.t_flush)();
}


/* updext - update the extended line which the cursor is currently
 *	    on at a column greater than the terminal width. The line
 *	    will be scrolled right or left to let the user see where
 *	    the cursor is
 */
void
updext(void)
{
    int   rcursor;		/* real cursor location */
    LINE *lp;			/* pointer to current line */
    int   j;			/* index into line */
    int   w = 0;
    int   ww;

    /*
     * Calculate what column the real cursor will end up in.
     * The cursor will be in the rcursor'th column. So if we're
     * counting columns 0 1 2 3 and rcursor is 8, then rcursor
     * will be over cell 7.
     *
     * What this effectively does is to scroll the screen as we're
     * moving to the right when the cursor first passes off the
     * screen's right edge. It would be nice if it did the same
     * thing coming back to the left. Instead, in order that the
     * screen's display depends only on the curcol and not on
     * how we got there, the screen scrolls when we pass the
     * t_margin column. It's also kind of funky that you can't
     * see the character under the $ but you can delete it.
     */
    rcursor = ((curcol - term.t_ncol) % (term.t_ncol - term.t_margin + 1)) + term.t_margin;
    lbound = curcol - rcursor + 1;

    /*
     * Make sure lbound is set so that a double-width character does
     * not straddle the boundary. If it does, move over one cell.
     */
    lp = curwp->w_dotp;			/* line to output */
    for (j=0; j<llength(lp) && w < lbound; ++j){
	ww = wcellwidth((UCS) lgetc(lp, j).c);
	w += (ww >= 0 ? ww : 1);
    }

    if(w > lbound)
      lbound = w;


    /* scan through the line outputting characters to the virtual screen
     * once we reach the left edge
     */
    vtmove(currow, -lbound);		/* start scanning offscreen */
    for (j=0; j<llength(lp); ++j)	/* until the end-of-line */
      vtputc(lgetc(lp, j));

    /* truncate the virtual line */
    vteeol();

    /* and put a '$' in column 1, may have to adjust curcol */
    w = wcellwidth((UCS) vscreen[currow]->v_text[0].c);
    vscreen[currow]->v_text[0].c = '$';
    vscreen[currow]->v_text[0].a = 0;
    if(w == 2){
	/*
	 * We want to put $ in the first two columns so that it
	 * takes up the right amount of space, but that means we
	 * have to scoot the real characters over one slot.
	 */
	for (j = term.t_ncol-1; j >= 2; --j)
	  vscreen[currow]->v_text[j] = vscreen[currow]->v_text[j-1];

	vscreen[currow]->v_text[1].c = '$';
	vscreen[currow]->v_text[1].a = 0;
    }
}

/* update line color, to be executed to update lines when color is on */
void
updatelinecolor (int row, CELL vline[], CELL pline[], short *flags, int len)
{
    CELL *cp1, *cp2, *cp3, *cp4, *cp5, *cp6, *cp7;
    int   nbflag;		/* non-blanks to the right flag? */
    int   cleartoeol = 0;
    int   in_quote, quote_found = 0, level;
    PCOLORS *pcolors = Pmaster && Pmaster->colors ? Pmaster->colors : Pcolors;
    COLOR_PAIR *qcolor = NULL, *lastc = NULL, *pcolor = NULL;
    int first = 1, lastattr = -1, change = 0;

    if(pcolors == NULL){
      updateline(row, vline, pline, flags, len);
      return;
    }

    nbflag = FALSE;
    lastc = pico_get_cur_color();

    /* set up pointers to virtual and physical lines */
    cp1 = &vline[0];
    cp2 = &pline[0];
    cp3 = &vline[term.t_ncol];
    cp4 = &pline[term.t_ncol];

    if(cellwidth_ptr_to_ptr(cp1, cp3) == cellwidth_ptr_to_ptr(cp2, cp4))
      while (cp3 != cp1 && cp3[-1].c == cp4[-1].c && cp3[-1].a == cp4[-1].a) {
	--cp3;
	--cp4;
	if (cp3[0].c != ' ' || cp3[0].a != 0)	/* Note if any nonblank */
	  nbflag = TRUE;			/* in right match. */
      }

    cp5 = cp3;

    if (nbflag == FALSE && TERM_EOLEXIST) {	/* Erase to EOL ? */
	while (cp5 != cp1 && cp5[-1].c == ' ' && cp5[-1].a == 0)
	  --cp5;

	if (cp3-cp5 <= 3)		/* Use only if erase is */
	  cp5 = cp3;			/* fewer characters. */
    }

    /* go to start of line */
    movecursor(row, 0);

    if(cp1 != cp5){
	int w1, w2;

	w1 = cellwidth_ptr_to_ptr(cp1, cp3);
	w2 = cellwidth_ptr_to_ptr(cp2, cp2 + (cp3-cp1));

	if(w1 < w2 || (nbflag && w1 != w2)){
	    if(TERM_EOLEXIST){
		if(nbflag){
		    /*
		     * Draw all of the characters starting with cp1
		     * until we get to all spaces, then clear to the end of
		     * line from there. Watch out we don't run over the
		     * right hand edge, which shouldn't happen.
		     *
		     * Set cp5 to the first of the repeating spaces.
		     */
		    cp5 = &vline[term.t_ncol];
		    while (cp5 != cp1 && cp5[-1].c == ' ' && cp5[-1].a == 0)
		      --cp5;
		}

		/*
		 * In the !nbflag case we want spaces from cp5 on.
		 * Setting cp3 to something different from cp5 triggers
		 * the clear to end of line below.
		 */
		if(cellwidth_ptr_to_ptr(&vline[0], cp5) < term.t_ncol)
		  cleartoeol++;
	    }
	    else{
		int w;

		/*
		 * No peeol so draw all the way to the edge whether they
		 * are spaces or not.
		 */
		cp3 = &vline[0];
		for(w = 0; w < term.t_ncol; cp3++){
		    int ww;

		    ww = wcellwidth((UCS) cp3->c);
		    w += (ww >= 0 ? ww : 1);
		}

		cp5 = cp3;
	    }
	}
    }

    if(row != 0 && len < term.t_ncol)
      cp5 = cp1 + len;

    in_quote = 1;
    level = -1;
    while (cp1 != cp5){		/* Ordinary. */
	int ww;

	if(lastattr < 0){
	    lastattr = cp1->a;
	    change = 0;
	}
	else 
	    change = lastattr != cp1->a;
	if(first != 0){
	  first = 0;
	  if(row == 0)
	     pico_set_colorp(pcolors->tbcp, PSC_NONE);
	  else if(row < term.t_nrow - 2)
	     pcolor = (*flags & VFSIG) ? pcolors->sbcp : pcolors->ntcp;
	}
	if(cp1->c != '>' && cp1->c != ' ')
	   in_quote = 0;
	else if (in_quote && cp1->c == '>' && pcolors != NULL)
	   level = (level + 1) % 3;
	if(level >= 0){
	   if(level == 0) pcolor = pcolors->qlcp;
	   else if(level == 1) pcolor = pcolors->qllcp;
	   else if(level == 2) pcolor = pcolors->qlllcp;
	}
	if(cp1->a == 1)
	   pcolor = pcolors->rtcp;	/* pcolor = proposed color */
	if(change == 0)
	  pico_set_colorp(pcolor, PSC_NONE);
	else
	  (*term.t_rev)(cp1->a);	/* set inverse for this char */

	if(change == 0)
	   (*term.t_rev)(cp1->a);	/* set inverse for this char */
	(*term.t_putchar)(cp1->c);

	ww = wcellwidth((UCS) cp1->c);
	ttcol += (ww >= 0 ? ww : 1);

	*cp2++ = *cp1++;
    }

    if (lastc){
	(void)pico_set_colorp(lastc, PSC_NONE);
	free_color_pair(&lastc);
    }

    (*term.t_rev)(0);			/* turn off inverse anyway! */

    if (cp5 != cp3 || cleartoeol)	/* Erase. */
	peeol();

    *flags &= ~(VFCHG|VFSIG);			/* flag this line is changed */
}



/*
 * Update a single line. This does not know how to use insert or delete
 * character sequences; we are using VT52 functionality. Update the physical
 * row and column variables.
 */
void
updateline(int row,			/* row on screen */
	   CELL vline[],		/* what we want it to end up as */
	   CELL pline[],		/* what it looks like now       */
	   short *flags,
	   int len)
{
    CELL *cp1, *cp2, *cp3, *cp4, *cp5, *cp6, *cp7;
    int   display = TRUE;
    int   nbflag;		/* non-blanks to the right flag? */
    int   cleartoeol = 0;

    if(row < 0 || row > term.t_nrow)
      return;

    if((Pmaster && Pmaster->colors) || Pcolors){
      updatelinecolor(row, vline, pline, flags, len);
      return;
    }

    /* set up pointers to virtual and physical lines */
    cp1 = &vline[0];
    cp2 = &pline[0];
    cp3 = &vline[term.t_ncol];

    /* advance past any common chars at the left */
    while (cp1 != cp3 && cp1[0].c == cp2[0].c && cp1[0].a == cp2[0].a) {
	++cp1;
	++cp2;
    }

/* This can still happen, even though we only call this routine on changed
 * lines. A hard update is always done when a line splits, a massive
 * change is done, or a buffer is displayed twice. This optimizes out most
 * of the excess updating. A lot of computes are used, but these tend to
 * be hard operations that do a lot of update, so I don't really care.
 */
    /* if both lines are the same, no update needs to be done */
    if (cp1 == cp3){
	*flags &= ~VFCHG;			/* mark it clean */
	return;
    }

    /* find out if there is a match on the right */
    nbflag = FALSE;
    cp3 = &vline[term.t_ncol];
    cp4 = &pline[term.t_ncol];

    if(cellwidth_ptr_to_ptr(cp1, cp3) == cellwidth_ptr_to_ptr(cp2, cp4))
      while (cp3[-1].c == cp4[-1].c && cp3[-1].a == cp4[-1].a) {
	--cp3;
	--cp4;
	if (cp3[0].c != ' ' || cp3[0].a != 0)	/* Note if any nonblank */
	  nbflag = TRUE;			/* in right match. */
      }

    cp5 = cp3;

    if (nbflag == FALSE && TERM_EOLEXIST) {	/* Erase to EOL ? */
	while (cp5 != cp1 && cp5[-1].c == ' ' && cp5[-1].a == 0)
	  --cp5;

	if (cp3-cp5 <= 3)		/* Use only if erase is */
	  cp5 = cp3;			/* fewer characters. */
    }

    /* go to start of differences */
    movecursor(row, cellwidth_ptr_to_ptr(&vline[0], cp1));

    if (!nbflag) {				/* use insert or del char? */
	cp6 = cp3;
	cp7 = cp4;

	if(TERM_INSCHAR
	   &&(cp7!=cp2 && cp6[0].c==cp7[-1].c && cp6[0].a==cp7[-1].a)){
	    while (cp7 != cp2 && cp6[0].c==cp7[-1].c && cp6[0].a==cp7[-1].a){
		--cp7;
		--cp6;
	    }

	    if (cp7==cp2 && cp4-cp2 > 3){
		int ww;

		(*term.t_rev)(cp1->a);	/* set inverse for this char */
		o_insert((UCS) cp1->c);  /* insert the char */
		ww = wcellwidth((UCS) cp1->c);
		ttcol += (ww >= 0 ? ww : 1);
		display = FALSE;        /* only do it once!! */
	    }
	}
	else if(TERM_DELCHAR && cp3 != cp1 && cp7[0].c == cp6[-1].c
		&& cp7[0].a == cp6[-1].a){
	    while (cp6 != cp1 && cp7[0].c==cp6[-1].c && cp7[0].a==cp6[-1].a){
		--cp7;
		--cp6;
	    }

	    if (cp6==cp1 && cp5-cp6 > 3){
		int w;

		w = wcellwidth((UCS) cp7[0].c);
		w = (w >= 0 ? w : 1);
		while(w-- > 0)		/* in case double-width char */
		  o_delete();		/* delete the char */
		display = FALSE;        /* only do it once!! */
	    }
	}
    }

    if(cp1 != cp5 && display){
	int w1, w2;

	/*
	 * If we need to copy characters from cp1 to cp2 and
	 * we need to display them, then we have to worry about
	 * the characters that we are replacing being of a different
	 * width than the new characters, else the display may be
	 * messed up.
	 *
	 * If the new width (w1) is less than the old width, that means
	 * we will leave behind some old remnants if we aren't careful.
	 * If the new width is larger than the old width, we have to
	 * make sure we draw the characters all the way to the end
	 * in order to get it right. Take advantage of clear to end
	 * of line if we have it.
	 */
	w1 = cellwidth_ptr_to_ptr(cp1, cp3);
	w2 = cellwidth_ptr_to_ptr(cp2, cp2 + (cp3-cp1));

	if(w1 < w2 || (nbflag && w1 != w2)){
	    if(TERM_EOLEXIST){
		if(nbflag){
		    /*
		     * Draw all of the characters starting with cp1
		     * until we get to all spaces, then clear to the end of
		     * line from there. Watch out we don't run over the
		     * right hand edge, which shouldn't happen.
		     *
		     * Set cp5 to the first of the repeating spaces.
		     */
		    cp5 = &vline[term.t_ncol];
		    while (cp5 != cp1 && cp5[-1].c == ' ' && cp5[-1].a == 0)
		      --cp5;
		}

		/*
		 * In the !nbflag case we want spaces from cp5 on.
		 * Setting cp3 to something different from cp5 triggers
		 * the clear to end of line below.
		 */
		if(cellwidth_ptr_to_ptr(&vline[0], cp5) < term.t_ncol)
		  cleartoeol++;
	    }
	    else{
		int w;

		/*
		 * No peeol so draw all the way to the edge whether they
		 * are spaces or not.
		 */
		cp3 = &vline[0];
		for(w = 0; w < term.t_ncol; cp3++){
		    int ww;

		    ww = wcellwidth((UCS) cp3->c);
		    w += (ww >= 0 ? ww : 1);
		}

		cp5 = cp3;
	    }
	}
    }

    while (cp1 != cp5) {		/* Ordinary. */
	int ww;

	if(display){
	    (*term.t_rev)(cp1->a);	/* set inverse for this char */
	    (*term.t_putchar)(cp1->c);
	}

	ww = wcellwidth((UCS) cp1->c);
	ttcol += (ww >= 0 ? ww : 1);

	*cp2++ = *cp1++;
    }

    (*term.t_rev)(0);			/* turn off inverse anyway! */

    if (cp5 != cp3 || cleartoeol) {	/* Erase. */
	if(display)
	  peeol();
	else
	  while (cp1 != cp3)
	    *cp2++ = *cp1++;
    }

    *flags &= ~VFCHG;			/* flag this line is changed */
}


/*
 * Redisplay the mode line for the window pointed to by the "wp". This is the
 * only routine that has any idea of how the modeline is formatted. You can
 * change the modeline format by hacking at this routine. Called by "update"
 * any time there is a dirty window.
 */
void
modeline(WINDOW *wp)
{
    if(Pmaster){
        if(ComposerEditing)
	  ShowPrompt();
	else{
	    menu_compose[EXIT_KEY].label  = (Pmaster->headents)
					      ? N_("Send") :N_("Exit");
	    menu_compose[PSTPN_KEY].name  = (Pmaster->headents)
					      ? "^O" : NULL;
	    menu_compose[PSTPN_KEY].label = (Pmaster->headents)
					      ? N_("Postpone") : NULL;
	    menu_compose[WHERE_KEY].name  = (Pmaster->alt_ed) ? "^_" : "^W";
	    menu_compose[WHERE_KEY].label = (Pmaster->alt_ed) ? N_("Alt Edit") 
							      : N_("Where is");
	    KS_OSDATASET(&menu_compose[WHERE_KEY],
			 (Pmaster->alt_ed) ? KS_ALTEDITOR : KS_WHEREIS);
	    menu_compose[UNCUT_KEY].label = (thisflag&CFFILL) ? N_("UnJustify")
							      : N_("UnCut Text");
	    wkeyhelp(menu_compose);
	}
    }
    else{
	BUFFER  *bp;
	char     t1[NLINE], t2[NLINE], t3[NLINE], tline[NLINE];
	int      w1, w2, w3, w1_to_2, w2_to_3, w3_to_r;
	UCS     *ucs;

	vtmove(1, 0);
	vteeol();
	vscreen[0]->v_flag |= VFCHG; /* Redraw next time. */
	vtmove(0, 0);		/* Seek to right line. */

	snprintf(t1, sizeof(t1), PICO_TITLE, version);	/* write version */

	bp = wp->w_bufp;
	if(bp->b_fname[0])				/* File name? */
	  snprintf(t2, sizeof(t2), "File: %s", bp->b_fname);
        else{
	    strncpy(t2, PICO_NEWBUF_MSG, sizeof(t2));
	    t2[sizeof(t2)-1] = '\0';
	}

	if(bp->b_flag&BFCHG){				/* "MOD" if changed. */
	    strncpy(t3, PICO_MOD_MSG, sizeof(t3));
	    t3[sizeof(t3)-1] = '\0';
	}
	else
	  t3[0] = '\0';

#define ALLOFTHEM (w1+w1_to_2+w2+w2_to_3+w3+w3_to_r)
#define ALLBUTSPACE (w1+w2+w3+w3_to_r)

	w1 = utf8_width(t1);
	w2 = utf8_width(t2);
	w3 = utf8_width(t3);
	w1_to_2 = w2_to_3 = 1;		/* min values for separation */
	w3_to_r = 2;

	if(ALLOFTHEM <= term.t_ncol){	/* everything fits */
	  w1_to_2 = (term.t_ncol - ALLBUTSPACE)/2;
	  w2_to_3 = term.t_ncol - (ALLBUTSPACE + w1_to_2);
	}
	else{
	  w1 = 2;
	  w1_to_2 = 0;
	  if(ALLOFTHEM <= term.t_ncol)
	    w2_to_3 = term.t_ncol - (ALLBUTSPACE + w1_to_2);
	  else{
	    w1 = w1_to_2 = w3_to_r = 0;
	    if(ALLOFTHEM <= term.t_ncol)
	      w2_to_3 = term.t_ncol - (ALLBUTSPACE + w1_to_2);
	    else{
	      if(bp->b_fname[0]){
	        snprintf(t2, sizeof(t2), "%s", bp->b_fname);
	        w2 = utf8_width(t2);
	      }

	      if(ALLOFTHEM <= term.t_ncol)
	        w2_to_3 = term.t_ncol - (ALLBUTSPACE + w1_to_2);
	      else{
	        w2 = 8;
	        if(bp->b_fname[0] && ALLOFTHEM <= term.t_ncol){
	          /* reduce size of file */
		  w2 = term.t_ncol - (ALLOFTHEM - w2);
		  t2[0] = t2[1] = t2[2] = '.';
		  utf8_to_width_rhs(t2+3, bp->b_fname, sizeof(t2)-3, w2-3);
		  w2 = utf8_width(t2);
	        }
	        else
	          w2 = utf8_width(t2);

	        if(ALLOFTHEM <= term.t_ncol)
	          w2_to_3 = term.t_ncol - (ALLBUTSPACE + w1_to_2);
	        else{
	          w1 = w1_to_2 = w2 = w2_to_3 = w3_to_r = 0;
	          if(ALLOFTHEM <= term.t_ncol)
	            w2_to_3 = term.t_ncol - ALLBUTSPACE;
		  else
		    w3 = 0;
	        }
	      }
	    }
	  }
	}

	utf8_snprintf(tline, sizeof(tline),
		      "%*.*w%*.*w%*.*w%*.*w%*.*w%*.*w",
		      w1, w1, t1,
		      w1_to_2, w1_to_2, "",
		      w2, w2, t2,
		      w2_to_3, w2_to_3, "",
		      w3, w3, t3,
		      w3_to_r, w3_to_r, "");

	ucs = NULL;
	if(utf8_width(tline) <= term.t_ncol)
	  ucs = utf8_to_ucs4_cpystr(tline);

	if(ucs){
	    UCS *ucsp;
	    CELL     c;

	    c.a = 1;
	    ucsp = ucs;
	    while((c.c = CELLMASK & *ucsp++))
	      vtputc(c);

	    fs_give((void **) &ucs);
	}
    }
}



/*
 * Send a command to the terminal to move the hardware cursor to row "row"
 * and column "col". The row and column arguments are origin 0. Optimize out
 * random calls. Update "ttrow" and "ttcol".
 */
void
movecursor(int row, int col)
{
    if (row!=ttrow || col!=ttcol) {
        ttrow = row;
        ttcol = col;
        (*term.t_move)(MIN(MAX(row,0),term.t_nrow), MIN(MAX(col,0),term.t_ncol-1));
    }
}


/*
 * Erase any sense we have of the cursor's HW location...
 */
void
clearcursor(void)
{
    ttrow = ttcol = FARAWAY;
}

void
get_cursor(int *row, int *col)
{
    if(row)
      *row = ttrow;
    if(col)
      *col = ttcol;
}


/*
 * Erase the message line. This is a special routine because the message line
 * is not considered to be part of the virtual screen. It always works
 * immediately; the terminal buffer is flushed via a call to the flusher.
 */
void
mlerase(void)
{
    if (term.t_nrow < term.t_mrow)
      return;

    movecursor(term.t_nrow - term.t_mrow, 0);
    (*term.t_rev)(0);
    if (TERM_EOLEXIST == TRUE)
      peeol();
    else{
	if(ttrow == term.t_nrow){
	  while(ttcol++ < term.t_ncol-1)
	    (*term.t_putchar)(' ');
	}
	else{
	  while(ttcol++ < term.t_ncol)		/* track's ttcol */
	    (*term.t_putchar)(' ');
	}
    }

    (*term.t_flush)();
    mpresf = FALSE;
}

/* returns the chosen dictionary. If one was already chosen
 * return that one 
 */
char *
speller_choice(char **sp_list, int *choice)
{
    int ch_dict = -1;
    int cnt;

    if(sp_list == NULL || sp_list[0] == NULL || sp_list[0][0] == '\0')
      return NULL;

    if(choice && *choice >= 0)
      return sp_list[*choice];

    for(cnt = 0; sp_list[cnt] != NULL && sp_list[cnt][0] != '\0'; cnt++)
	;

    if(cnt > 10)		/* only the first 10 dictionaries */
	cnt = 10;

    if(cnt == 1)		/* only one dictionary? choose it! */
        ch_dict = 0;

    if(ch_dict > cnt - 1)	/* choose again in case something changed */
	ch_dict = -1;

    if(ch_dict < 0){		/* not a choice yet? do one now! */
	UCS buf[128];
	int i;
	char *utf8_prompt;
	UCS  *ucs4_prompt;
	EXTRAKEYS    menu_dictionary[] = {
		{"0", NULL, '0'},
		{"1", NULL, '1'},
		{"2", NULL, '2'},
		{"3", NULL, '3'},
		{"4", NULL, '4'},
		{"5", NULL, '5'},
		{"6", NULL, '6'},
		{"7", NULL, '7'},
		{"8", NULL, '8'},
		{"9", NULL, '9'}
	};

	for(i = 0; i < cnt; i++)
	   menu_dictionary[i].label = sp_list[i];

	if(cnt < 10)
	  menu_dictionary[cnt].name = NULL;

	buf[0] = '\0';
	/* write the prompt in utf8, and let internal functions translate it to ucs4 */
	ucs4_prompt = utf8_to_ucs4_cpystr(_("Choose Dictionary: "));

	i = mlchoose(ucs4_prompt, menu_dictionary);

	if(i >= '0' && i <= '9')
	  ch_dict = i - '0';
	
	if (i == -2) /* user cancelled */
		ch_dict = -2;

	if(ucs4_prompt)
	   fs_give((void **)&ucs4_prompt);
  }
  else ch_dict = -1;

  if(choice)
     *choice = ch_dict;

  return  ch_dict >= 0 ? sp_list[ch_dict] : NULL;
}   

/* just like mlreplyd, but user cannot fill a prompt */
int
mlchoose(UCS *prompt, EXTRAKEYS *extras)
{
    UCS      c;
    UCS      buf[NLINE];
    int      i;
    int      changed = FALSE;
    int      return_val = 0;
    KEYMENU  menu_choose[12];
    COLOR_PAIR *lastc = NULL;

    for(i = 0; i < 12; i++){
	menu_choose[i].name = NULL;
	KS_OSDATASET(&menu_choose[i], KS_NONE);
    }

    menu_choose[0].name = "^G";
    menu_choose[0].label = N_("Get Help");
    KS_OSDATASET(&menu_choose[0], KS_SCREENHELP);

    menu_choose[6].name = "^C";
    menu_choose[6].label = N_("Cancel");
    KS_OSDATASET(&menu_choose[6], KS_NONE);

    for(i = 0; i < 10; i++){
	if((i % 2) == 0){
	  menu_choose[i / 2 + 1].name = extras[i].name;
	  menu_choose[i / 2 + 1].label = extras[i].label;
	}
	else{
	  menu_choose[(i + 13) / 2].name = extras[i].name;
	  menu_choose[(i + 13) / 2].label = extras[i].label;
	}
    }
    wkeyhelp(menu_choose);		/* paint generic menu */
    sgarbk = TRUE;			/* mark menu dirty */
    if(Pmaster && curwp)
      curwp->w_flag |= WFMODE;

    ucs4_strncpy(buf, prompt, NLINE);
    buf[NLINE-1] = '\0';
    mlwrite(buf, NULL);
    if(Pmaster && Pmaster->colors && Pmaster->colors->prcp
       && pico_is_good_colorpair(Pmaster->colors->prcp)){
	lastc = pico_get_cur_color();
	(void) pico_set_colorp(Pmaster->colors->prcp, PSC_NONE);
    }
    else
      (*term.t_rev)(1);

    return_val = -1;
    while(1){
	c = GetKey();
	for(i = 0; i < 10 && extras[i].name != NULL && extras[i].key != c; i++)
	   ;
	if(i < 10 && extras[i].name)
	   return_val = c;
	else switch(c){
	  case (CTRL|'C') :		/* Bail out! */
	  case F2         :
	    pputs_utf8(_("Cancel"), 1);
	    return_val = -2;
	  break;

	  case (CTRL|'G') :
	    if(term.t_mrow == 0 && km_popped == 0){
		movecursor(term.t_nrow-2, 0);
		peeol();
		term.t_mrow = 2;
		if(lastc){
		    (void) pico_set_colorp(lastc, PSC_NONE);
		    free_color_pair(&lastc);
		}
		else
		  (*term.t_rev)(0);

		wkeyhelp(menu_choose);		/* paint generic menu */
		mlwrite(buf, NULL);
		if(Pmaster && Pmaster->colors && Pmaster->colors->prcp
		   && pico_is_good_colorpair(Pmaster->colors->prcp)){
		    lastc = pico_get_cur_color();
		    (void) pico_set_colorp(Pmaster->colors->prcp, PSC_NONE);
		}
		else
		  (*term.t_rev)(1);

		sgarbk = TRUE;			/* mark menu dirty */
		km_popped++;
		break;
	    }
	    /* else fall through */

	  default:
	    (*term.t_beep)();
	  case NODATA :
	    break;
	}

	(*term.t_flush)();
	if (return_val != -1){ /* abort sets rv = -2, other return values are positive */
	    if(lastc){
		(void) pico_set_colorp(lastc, PSC_NONE);
		free_color_pair(&lastc);
	    }
	    else
	      (*term.t_rev)(0);

	    if(km_popped){
		term.t_mrow = 0;
		movecursor(term.t_nrow, 0);
		peeol();
		sgarbf = 1;
		km_popped = 0;
	    }

	    return(return_val);
	}
    }
}


int
mlyesno_utf8(char *utf8prompt, int dflt)
{
    int  ret;
    UCS *prompt;

    prompt = utf8_to_ucs4_cpystr(utf8prompt ? utf8prompt : "");

    ret = mlyesno(prompt, dflt);

    if(prompt)
      fs_give((void **) &prompt);

    return(ret);
}


/*
 * Ask a yes or no question in the message line. Return either TRUE, FALSE, or
 * ABORT. The ABORT status is returned if the user bumps out of the question
 * with a ^G. if d >= 0, d is the default answer returned. Otherwise there
 * is no default.
 */
int
mlyesno(UCS *prompt, int dflt)
{
    int     rv;
    UCS     buf[NLINE], lbuf[10];
    KEYMENU menu_yesno[12];
    COLOR_PAIR *lastc = NULL;
    PCOLORS *pcolors = Pmaster && Pmaster->colors ? Pmaster->colors : Pcolors;

#ifdef _WINDOWS
    if (mswin_usedialog ()) 
      switch (mswin_yesno (prompt)) {
	default:
	case 0:		return (ABORT);
	case 1:		return (TRUE);
	case 2:		return (FALSE);
      }
#endif  

    for(rv = 0; rv < 12; rv++){
	menu_yesno[rv].name = NULL;
	KS_OSDATASET(&menu_yesno[rv], KS_NONE);
    }

    menu_yesno[1].name  = "Y";
    menu_yesno[1].label = (dflt == TRUE) ? "[" N_("Yes") "]" : N_("Yes");
    menu_yesno[6].name  = "^C";
    menu_yesno[6].label = N_("Cancel");
    menu_yesno[7].name  = "N";
    menu_yesno[7].label = (dflt == FALSE) ? "[" N_("No") "]" : N_("No");
    wkeyhelp(menu_yesno);		/* paint generic menu */
    sgarbk = TRUE;			/* mark menu dirty */
    if(Pmaster && curwp)
      curwp->w_flag |= WFMODE;

    ucs4_strncpy(buf, prompt, NLINE);
    buf[NLINE-1] = '\0';
    lbuf[0] = ' '; lbuf[1] = '?'; lbuf[2] = ' '; lbuf[3] = '\0';
    ucs4_strncat(buf, lbuf, NLINE - ucs4_strlen(buf) - 1);
    buf[NLINE-1] = '\0';
    mlwrite(buf, NULL);
    if(pcolors && pcolors->prcp
       && pico_is_good_colorpair(pcolors->prcp)){
	lastc = pico_get_cur_color();
	(void) pico_set_colorp(pcolors->prcp, PSC_NONE);
    } else 
      (*term.t_rev)(1);

    rv = -1;
    while(1){
	switch(GetKey()){
	  case (CTRL|'M') :		/* default */
	    if(dflt >= 0){
		pputs_utf8((dflt) ? _("Yes") : _("No"), 1);
		rv = dflt;
	    }
	    else
	      (*term.t_beep)();

	    break;

	  case (CTRL|'C') :		/* Bail out! */
	  case F2         :
	    pputs_utf8(_("ABORT"), 1);
	    rv = ABORT;
	    break;

	  case 'y' :
	  case 'Y' :
	  case F3  :
	    pputs_utf8(_("Yes"), 1);
	    rv = TRUE;
	    break;

	  case 'n' :
	  case 'N' :
	  case F4  :
	    pputs_utf8(_("No"), 1);
	    rv = FALSE;
	    break;

	  case (CTRL|'G') :
	    if(term.t_mrow == 0 && km_popped == 0){
		movecursor(term.t_nrow-2, 0);
		peeol();
		term.t_mrow = 2;
		if(lastc){
		    (void) pico_set_colorp(lastc, PSC_NONE);
		    free_color_pair(&lastc);
		}
		else
		  (*term.t_rev)(0);

		wkeyhelp(menu_yesno);		/* paint generic menu */
		mlwrite(buf, NULL);
		if(pcolors && pcolors->prcp
		       && pico_is_good_colorpair(pcolors->prcp)){
		   lastc = pico_get_cur_color();
		   (void) pico_set_colorp(pcolors->prcp, PSC_NONE);
		}
		else
		  (*term.t_rev)(1);

		sgarbk = TRUE;			/* mark menu dirty */
		km_popped++;
		break;
	    }
	    /* else fall through */

	  default:
	    (*term.t_beep)();
	  case NODATA :
	    break;
	}

	(*term.t_flush)();
	if(rv != -1){
	    if(lastc){
		(void) pico_set_colorp(lastc, PSC_NONE);
		free_color_pair(&lastc);
	    }
	    else
	      (*term.t_rev)(0);

	    if(km_popped){
		term.t_mrow = 0;
		movecursor(term.t_nrow, 0);
		peeol();
		sgarbf = 1;
		km_popped = 0;
	    }

	    return(rv);
	}
    }
}


/*
 * Write a prompt into the message line, then read back a response. Keep
 * track of the physical position of the cursor. If we are in a keyboard
 * macro throw the prompt away, and return the remembered response. This
 * lets macros run at full speed. The reply is always terminated by a carriage
 * return. Handle erase, kill, and abort keys.
 */
int
mlreply_utf8(char *utf8prompt, char *utf8buf, int nbuf, int flg, EXTRAKEYS *extras)
{
    return(mlreplyd_utf8(utf8prompt, utf8buf, nbuf, flg|QDEFLT, extras));
}


int
mlreply(UCS *prompt, UCS *buf, int nbuf, int flg, EXTRAKEYS *extras)
{
    return(mlreplyd(prompt, buf, nbuf, flg|QDEFLT, extras));
}


/*
 * function key mappings
 */
static UCS rfkm[12][2] = {
    { F1,  (CTRL|'G')},
    { F2,  (CTRL|'C')},
    { F3,  0 },
    { F4,  0 },
    { F5,  0 },
    { F6,  0 },
    { F7,  0 },
    { F8,  0 },
    { F9,  0 },
    { F10, 0 },
    { F11, 0 },
    { F12, 0 }
};


int
mlreplyd_utf8(char *utf8prompt, char *utf8buf, int nbuf, int flg, EXTRAKEYS *extras)
{
    int  ret;
    UCS   *b, *buf;
    char  *utf8;
    UCS   *prompt;

    buf = (UCS *) fs_get(nbuf * sizeof(*b));
    b = utf8_to_ucs4_cpystr(utf8buf);
    if(b){
	ucs4_strncpy(buf, b, nbuf);
	buf[nbuf-1] = '\0';
	fs_give((void **) &b);
    }

    prompt = utf8_to_ucs4_cpystr(utf8prompt ? utf8prompt : "");

    ret = mlreplyd(prompt, buf, nbuf, flg, extras);

    utf8 = ucs4_to_utf8_cpystr(buf);
    if(utf8){
	strncpy(utf8buf, utf8, nbuf);
	utf8buf[nbuf-1] = '\0';
	fs_give((void **) &utf8);
    }

    if(buf)
      fs_give((void **) &buf);

    if(prompt)
      fs_give((void **) &prompt);

    return(ret);
}


void
writeachar(UCS ucs)
{
    pputc(ucs, 0);
}


/*
 * mlreplyd - write the prompt to the message line along with a default
 *	      answer already typed in.  Carriage return accepts the
 *	      default.  answer returned in buf which also holds the initial
 *            default, nbuf is its length, def set means use default value.
 *	      In order to be able to eliminate keys from a menu, EXTRAKEYS
 *	      always has size 10.
 */
int
mlreplyd(UCS *prompt, UCS *buf, int nbuf, int flg, EXTRAKEYS *extras)
{
    UCS      c;				/* current char       */
    UCS     *b;				/* pointer in buf     */
    int      i, j;
    int      plen;
    int      changed = FALSE;
    int      return_val = 0;
    KEYMENU  menu_mlreply[12];
    UCS	     extra_v[12];
    struct   display_line dline;
    COLOR_PAIR *lastc = NULL;
    PCOLORS *pcolors = Pmaster && Pmaster->colors ? Pmaster->colors : Pcolors;

#ifdef _WINDOWS
    if(mswin_usedialog()){
	MDlgButton		btn_list[12];
	LPTSTR                  free_names[12];
	LPTSTR                  free_labels[12];
	int			i, j;

	memset(&free_names, 0, sizeof(LPTSTR) * 12);
	memset(&free_labels, 0, sizeof(LPTSTR) * 12);
	memset(&btn_list, 0, sizeof (MDlgButton) * 12);
	j = 0;
	for(i = 0; extras && extras[i].name != NULL; ++i) {
	    if(extras[i].label[0] != '\0') {
		if((extras[i].key & CTRL) == CTRL) 
		  btn_list[j].ch = (extras[i].key & ~CTRL) - '@';
		else
		  btn_list[j].ch = extras[i].key;

		btn_list[j].rval = extras[i].key;
		free_names[j] = utf8_to_lptstr(extras[i].name);
		btn_list[j].name = free_names[j];
		free_labels[j] = utf8_to_lptstr(extras[i].label);
		btn_list[j].label = free_labels[j];
		j++;
	    }
	}

	btn_list[j].ch = -1;

	return_val = mswin_dialog(prompt, buf, nbuf, ((flg&QDEFLT) > 0), 
			    FALSE, btn_list, NULL, 0);

	if(return_val == 3)
	  return_val = HELPCH;

	for(i = 0; i < 12; i++){
	    if(free_names[i])
	      fs_give((void **) &free_names[i]);
	    if(free_labels[i])
	      fs_give((void **) &free_labels[i]);
	}

	return(return_val);
    }
#endif

    memset(&menu_mlreply, 0, 12*sizeof(KEYMENU));
    menu_mlreply[0].name = "^G";
    menu_mlreply[0].label = N_("Get Help");
    KS_OSDATASET(&menu_mlreply[0], KS_SCREENHELP);
    for(j = 0, i = 1; i < 6; i++){	/* insert odd extras */
	menu_mlreply[i].name = NULL;
	KS_OSDATASET(&menu_mlreply[i], KS_NONE);
	rfkm[2*i][1] = 0;
	if(extras){
	    j = 2*(i-1);
	    if(extras[j].name){
		rfkm[2*i][1]	      = extras[j].key;
		menu_mlreply[i].name  = extras[j].name;
		menu_mlreply[i].label = extras[j].label;
		KS_OSDATASET(&menu_mlreply[i], KS_OSDATAGET(&extras[j]));
	    }
	}
    }

    menu_mlreply[6].name = "^C";
    menu_mlreply[6].label = N_("Cancel");
    KS_OSDATASET(&menu_mlreply[6], KS_NONE);
    for(j = 0, i = 7; i < 12; i++){	/* insert even extras */
	menu_mlreply[i].name = NULL;
	rfkm[2*(i-6)+1][1] = 0;
	if(extras){
	    j = 2*(i-6) - 1;
	    if(extras[j].name){
		rfkm[2*(i-6)+1][1]    = extras[j].key;
		menu_mlreply[i].name  = extras[j].name;
		menu_mlreply[i].label = extras[j].label;
		KS_OSDATASET(&menu_mlreply[i], KS_OSDATAGET(&extras[j]));
	    }
	}
    }

    /* set up what to watch for and return values */
    memset(extra_v, 0, sizeof(extra_v));
    for(i = 0, j = 0; i < 12 && extras && extras[i].name; i++)
      extra_v[j++] = extras[i].key;

    plen = mlwrite(prompt, NULL);		/* paint prompt */

    if(!(flg&QDEFLT))
      *buf = '\0';

    dline.vused = ucs4_strlen(buf);
    dline.dwid  = term.t_ncol - plen;
    dline.row   = term.t_nrow - term.t_mrow;
    dline.col   = plen;

    dline.dlen  = 2 * dline.dwid + 100;

    dline.dl    = (UCS *) fs_get(dline.dlen * sizeof(UCS));
    dline.olddl = (UCS *) fs_get(dline.dlen * sizeof(UCS));
    memset(dline.dl,    0, dline.dlen * sizeof(UCS));
    memset(dline.olddl, 0, dline.dlen * sizeof(UCS));

    dline.movecursor = movecursor;
    dline.writechar  = writeachar;

    dline.vl    = buf;
    dline.vlen  = nbuf-1;
    dline.vbase = 0;

    b = &buf[(flg & QBOBUF) ? 0 : ucs4_strlen(buf)];
    
    wkeyhelp(menu_mlreply);		/* paint generic menu */

    sgarbk = 1;				/* mark menu dirty */

    if(pcolors && pcolors->prcp
       && pico_is_good_colorpair(pcolors->prcp)){
       lastc = pico_get_cur_color();
       (void) pico_set_colorp(pcolors->prcp, PSC_NONE);
    }
    else
      (*term.t_rev)(1);

    for(;;){

	line_paint(b-buf, &dline, NULL);
	(*term.t_flush)();

#ifdef	MOUSE
	mouse_in_content(KEY_MOUSE, -1, -1, 0x5, 0);
	register_mfunc(mouse_in_content, 
		       term.t_nrow - term.t_mrow, plen,
		       term.t_nrow - term.t_mrow, term.t_ncol-1);
#endif
#ifdef	_WINDOWS
	mswin_allowpaste(MSWIN_PASTE_LINE);
#endif
	while((c = GetKey()) == NODATA)
	  ;

#ifdef	MOUSE
	clear_mfunc(mouse_in_content);
#endif
#ifdef	_WINDOWS
	mswin_allowpaste(MSWIN_PASTE_DISABLE);
#endif

	switch(c = normalize_cmd(c, rfkm, 1)){
	  case (CTRL|'A') :			/* CTRL-A beginning     */
	  case KEY_HOME :
	    b = buf;
	    continue;

	  case (CTRL|'B') :			/* CTRL-B back a char   */
	  case KEY_LEFT:
	    if(b <= buf)
	      (*term.t_beep)();
	    else
	      b--;

	    continue;

	  case (CTRL|'C') :			/* CTRL-C abort		*/
	    pputs_utf8(_("ABORT"), 1);
	    ctrlg(FALSE, 0);
	    return_val = ABORT;
	    goto ret;

	  case (CTRL|'E') :			/* CTRL-E end of line   */
	  case KEY_END :
	    b = &buf[ucs4_strlen(buf)];
	    continue;

	  case (CTRL|'F') :			/* CTRL-F forward a char*/
	  case KEY_RIGHT :
	    if(*b == '\0')
	      (*term.t_beep)();
	    else
	      b++;

	    continue;

	  case (CTRL|'G') :			/* CTRL-G help		*/
	    if(term.t_mrow == 0 && km_popped == 0){
		movecursor(term.t_nrow-2, 0);
		peeol();
		sgarbk = 1;			/* mark menu dirty */
		km_popped++;
		term.t_mrow = 2;
		if(lastc){
		    (void) pico_set_colorp(lastc, PSC_NONE);
		    free_color_pair(&lastc);
		}
		else
		  (*term.t_rev)(0);

		wkeyhelp(menu_mlreply);		/* paint generic menu */
		plen = mlwrite(prompt, NULL);		/* paint prompt */
		if(pcolors && pcolors->prcp
		   && pico_is_good_colorpair(pcolors->prcp)){
		   lastc = pico_get_cur_color();
		   (void) pico_set_colorp(pcolors->prcp, PSC_NONE);
		}
		else
		  (*term.t_rev)(1);

		pputs(buf, 1);
		break;
	    }

	    pputs_utf8(_("HELP"), 1);
	    return_val = HELPCH;
	    goto ret;

	  case (CTRL|'H') :			/* CTRL-H backspace	*/
	  case 0x7f :				/*        rubout	*/
	    if (b <= buf){
	      (*term.t_beep)();
	      break;
	    }
	    else
	      b--;

	  case (CTRL|'D') :			/* CTRL-D delete char   */
	  case KEY_DEL :
	    if (!*b){
	      (*term.t_beep)();
	      break;
	    }

	    changed=TRUE;
	    i = 0;
	    dline.vused--;
	    do					/* blat out left char   */
	      b[i] = b[i+1];
	    while(b[i++] != '\0');
	    break;

	  case (CTRL|'L') :			/* CTRL-L redraw	*/
	    return_val = (CTRL|'L');
	    goto ret;

	  case (CTRL|'K') :			/* CTRL-K kill line	*/
	    changed=TRUE;
	    buf[0] = '\0';
	    dline.vused = 0;
	    b = buf;
	    break;

	  case F1 :				/* sort of same thing */
	    return_val = HELPCH;
	    goto ret;

	  case (CTRL|'M') :			/*        newline       */
	    return_val = changed;
	    goto ret;

#ifdef	MOUSE
	  case KEY_MOUSE :
	    {
	      MOUSEPRESS mp;

	      mouse_get_last (NULL, &mp);

	      /* The clicked line have anything special on it? */
	      switch(mp.button){
		case M_BUTTON_LEFT :			/* position cursor */
		  mp.col -= plen;			/* normalize column */
		  if(mp.col >= 0 && mp.col <= ucs4_strlen(buf))
		    b = buf + mp.col;

		  break;

		case M_BUTTON_RIGHT :
#ifdef	_WINDOWS
		  mswin_allowpaste(MSWIN_PASTE_LINE);
		  mswin_paste_popup();
		  mswin_allowpaste(MSWIN_PASTE_DISABLE);
		  break;
#endif

		case M_BUTTON_MIDDLE :			/* NO-OP for now */
		default:				/* just ignore */
		  break;
	      }
	    }

	    continue;
#endif

	  default : 

	    /* look for match in extra_v */
	    for(i = 0; i < 12; i++)
	      if(c && c == extra_v[i]){
		  return_val = c;
		  goto ret;
	      }

	    changed=TRUE;

	    if(c & (CTRL | FUNC)){		/* bag ctrl_special chars */
		(*term.t_beep)();
	    }
	    else{
		i = ucs4_strlen(b);
		if(flg&QNODQT){	                /* reject double quotes? */
		    if(c == '"'){
			(*term.t_beep)();
			continue;
		    }
		}

		if(dline.vused >= nbuf-1){
		    (*term.t_beep)();
		    continue;
		}

		do				/* blat out left char   */
		  b[i+1] = b[i];
		while(i-- > 0);

		dline.vused++;
		*b++ = c;
	    }
	}
    }

ret:
    if(lastc){
	(void) pico_set_colorp(lastc, PSC_NONE);
	free_color_pair(&lastc);
    }
    else
      (*term.t_rev)(0);

    (*term.t_flush)();

    if(km_popped){
	term.t_mrow = 0;
	movecursor(term.t_nrow, 0);
	peeol();
	sgarbf = 1;
	km_popped = 0;
    }

    if(dline.dl)
      fs_give((void **) &dline.dl);

    if(dline.olddl)
      fs_give((void **) &dline.olddl);

    return(return_val);
}


void
emlwwrite(char *utf8message, EML *eml)
{
  (*term.t_beep)();
   emlwrite(utf8message, eml);
}

void
emlwrite(char *utf8message, EML *eml)
{
    UCS *message;

    message = utf8_to_ucs4_cpystr(utf8message ? utf8message : "");

    emlwrite_ucs4(message, eml);

    if(message)
      fs_give((void **) &message);
}


/*
 * emlwrite() - write the message string to the error half of the screen
 *              center justified.  much like mlwrite (which is still used
 *              to paint the line for prompts and such), except it center
 *              the text.
 */
void
emlwrite_ucs4(UCS *message, EML *eml) 
{
    UCS  *bufp, *ap;
    int   width;
    COLOR_PAIR *lastc = NULL;
    PCOLORS *pcolors = Pmaster && Pmaster->colors ? Pmaster->colors : Pcolors;

    mlerase();

    if(!(message && *message) || term.t_nrow < 2)	
      return;    /* nothing to write or no space to write, bag it */

    bufp = message;

    width = ucs4_str_width(message);

    /*
     * next, figure out where the to move the cursor so the message 
     * comes out centered
     */
    if((ap=ucs4_strchr(message, '%')) != NULL){
	width -= 2;
	switch(ap[1]){
	  case '%':
	  case 'c':
	    width += (eml && eml->c) ? wcellwidth(eml->c) : 1;
	    break;
	  case 'd':
	    width += dumbroot(eml ? eml->d : 0, 10);
	    break;
	  case 'D':
	    width += dumblroot(eml ? eml->l : 0L, 10);
	    break;
	  case 'o':
	    width += dumbroot(eml ? eml->d : 0, 8);
	    break;
	  case 'x':
	    width += dumbroot(eml ? eml->d : 0, 16);
	    break;
	  case 's':				/* string arg is UTF-8 */
            width += (eml && eml->s) ? utf8_width(eml->s) : 2;
	    break;
	}
    }

    if(width+4 <= term.t_ncol)
      movecursor(term.t_nrow-term.t_mrow, (term.t_ncol - (width + 4))/2);
    else
      movecursor(term.t_nrow-term.t_mrow, 0);

    if(pcolors && pcolors->stcp
       && pico_is_good_colorpair(pcolors->stcp)){
	   lastc = pico_get_cur_color();
	   (void) pico_set_colorp(pcolors->stcp, PSC_NONE);
    }
    else
      (*term.t_rev)(1);

    pputs_utf8("[ ", 1);
    while (*bufp != '\0' && ttcol < term.t_ncol-2){
	if(*bufp == '\007')
	  (*term.t_beep)();
	else if(*bufp == '%'){
	    switch(*++bufp){
	      case 'c':
		if(eml && eml->c)
		  pputc(eml->c, 0);
		else {
		    pputs_utf8("%c", 0);
		}
		break;
	      case 'd':
		mlputi(eml ? eml->d : 0, 10);
		break;
	      case 'D':
		mlputli(eml ? eml->l : 0L, 10);
		break;
	      case 'o':
		mlputi(eml ? eml->d : 0, 16);
		break;
	      case 'x':
		mlputi(eml ? eml->d : 0, 8);
		break;
	      case 's':
		pputs_utf8((eml && eml->s) ? eml->s : "%s", 0);
		break;
	      case '%':
	      default:
		pputc(*bufp, 0);
		break;
	    }
	}
	else
	  pputc(*bufp, 0);
	bufp++;
    }

    pputs_utf8(" ]", 1);

    if(lastc){
	(void) pico_set_colorp(lastc, PSC_NONE);
	free_color_pair(&lastc);
    }
    else
      (*term.t_rev)(0);

    (*term.t_flush)();

    mpresf = TRUE;
}


int
mlwrite_utf8(char *utf8fmt, void *arg)
{
    UCS  *fmt;
    int   ret;

    fmt = utf8_to_ucs4_cpystr(utf8fmt ? utf8fmt : "");
    ret = mlwrite(fmt, arg);
    if(fmt)
      fs_give((void **) &fmt);

    return(ret);
}


/*
 * Write a message into the message line. Keep track of the physical cursor
 * position. A small class of printf like format items is handled. Assumes the
 * stack grows down; this assumption is made by the "++" in the argument scan
 * loop. Set the "message line" flag TRUE.
 */
int
mlwrite(UCS *fmt, void *arg)
{
    int   ret, ww;
    UCS   c;
    char *ap;
    COLOR_PAIR *lastc = NULL;
    PCOLORS *pcolors = Pmaster && Pmaster->colors ? Pmaster->colors : Pcolors;

    /*
     * the idea is to only highlight if there is something to show
     */
    mlerase();
    movecursor(ttrow, 0);

    if(pcolors && pcolors->prcp
       && pico_is_good_colorpair(pcolors->prcp)){
	   lastc = pico_get_cur_color();
	   (void) pico_set_colorp(pcolors->prcp, PSC_NONE);
    }
    else
      (*term.t_rev)(1);

    ap = (char *) &arg;

    while ((c = *fmt++) != 0) {
        if (c != '%') {
	    pputc(c, 1);
	}
        else {
            c = *fmt++;
            switch (c){
	      case 'd':
		mlputi(*(int *)ap, 10);
		ap += sizeof(int);
		break;

	      case 'o':
		mlputi(*(int *)ap,  8);
		ap += sizeof(int);
		break;

	      case 'x':
		mlputi(*(int *)ap, 16);
		ap += sizeof(int);
		break;

	      case 'D':
		mlputli(*(long *)ap, 10);
		ap += sizeof(long);
		break;

	      case 's':
		pputs_utf8(*(char **)ap, 1);
		ap += sizeof(char *);
		break;

              default:
		pputc(c, 1);
		ww = wcellwidth(c);
		ttcol += (ww >= 0 ? ww : 1);
	    }
	}
    }

    ret = ttcol;
    while(ttcol < term.t_ncol)
      pputc(' ', 0);

    movecursor(term.t_nrow - term.t_mrow, ret);

    if(lastc){
	(void) pico_set_colorp(lastc, PSC_NONE);
	free_color_pair(&lastc);
    }
    else
      (*term.t_rev)(0);

    (*term.t_flush)();
    mpresf = TRUE;

    return(ret);
}


/*
 * Write out an integer, in the specified radix. Update the physical cursor
 * position. This will not handle any negative numbers; maybe it should.
 */
void
mlputi(int i, int r)
{
    register int q;
    static char hexdigits[] = "0123456789ABCDEF";

    if (i < 0){
        i = -i;
	pputc('-', 1);
    }

    q = i/r;

    if (q != 0)
      mlputi(q, r);

    pputc(hexdigits[i%r], 1);
}


/*
 * do the same except as a long integer.
 */
void
mlputli(long l, int r)
{
    register long q;

    if (l < 0){
        l = -l;
        pputc('-', 1);
    }

    q = l/r;

    if (q != 0)
      mlputli(q, r);

    pputc((int)(l%r)+'0', 1);
}


void
unknown_command(UCS c)
{
    char  buf[10], ch, *s;
    EML   eml;

    buf[0] = '\0';
    s = buf;

    if(!c){
	/* fall through */
    }
    else if(c & CTRL && c >= (CTRL|'@') && c <= (CTRL|'_')){
	ch = c - (CTRL|'@') + '@';
	snprintf(s, sizeof(buf), "^%c", ch);
    }
    else
     switch(c){
      case ' '       : s = "SPACE";		break;
      case '\033'    : s = "ESC";		break;
      case '\177'    : s = "DEL";		break;
      case ctrl('I') : s = "TAB";		break;
      case ctrl('J') : s = "LINEFEED";		break;
      case ctrl('M') : s = "RETURN";		break;
      case ctrl('Q') : s = "XON";		break;
      case ctrl('S') : s = "XOFF";		break;
      case KEY_UP    : s = "Up Arrow";		break;
      case KEY_DOWN  : s = "Down Arrow";	break;
      case KEY_RIGHT : s = "Right Arrow";	break;
      case KEY_LEFT  : s = "Left Arrow";	break;
      case CTRL|KEY_UP    : s = "Ctrl-Up Arrow";	break;
      case CTRL|KEY_DOWN  : s = "Ctrl-Down Arrow";	break;
      case CTRL|KEY_RIGHT : s = "Ctrl-Right Arrow";	break;
      case CTRL|KEY_LEFT  : s = "Ctrl-Left Arrow";	break;
      case KEY_PGUP  : s = "Prev Page";		break;
      case KEY_PGDN  : s = "Next Page";		break;
      case KEY_HOME  : s = "Home";		break;
      case KEY_END   : s = "End";		break;
      case KEY_DEL   : s = "Delete";		break; /* Not necessary DEL! */
      case F1	     :
      case F2	     :
      case F3	     :
      case F4	     :
      case F5	     :
      case F6	     :
      case F7	     :
      case F8	     :
      case F9	     :
      case F10	     :
      case F11	     :
      case F12	     :
        snprintf(s, sizeof(buf), "F%ld", (long) (c - PF1 + 1));
	break;

      default:
	if(c < CTRL)
	  utf8_put((unsigned char *) s, (unsigned long) c);

	break;
     }

    eml.s = s;
    emlwrite("Unknown Command: %s", &eml);
    (*term.t_beep)();
}


/*
 * scrolldown - use stuff to efficiently move blocks of text on the
 *              display, and update the pscreen array to reflect those
 *              moves...
 *
 *        wp is the window to move in
 *        r  is the row at which to begin scrolling
 *        n  is the number of lines to scrol
 */
void
scrolldown(WINDOW *wp, int r, int n)
{
#ifdef	TERMCAP
    register int i;
    register int l;
    register VIDEO *vp1;
    register VIDEO *vp2;

    if(!n)
      return;

    if(r < 0){
	r = wp->w_toprow;
	l = wp->w_ntrows;
    }
    else{
	if(r > wp->w_toprow)
	    vscreen[r-1]->v_flag |= VFCHG;
	l = wp->w_toprow+wp->w_ntrows-r;
    }

    o_scrolldown(r, n);

    for(i=l-n-1; i >=  0; i--){
	vp1 = pscreen[r+i]; 
	vp2 = pscreen[r+i+n];
	memcpy(vp2, vp1, term.t_ncol * sizeof(CELL));
    }
    pprints(r+n-1, r);
    ttrow = FARAWAY;
    ttcol = FARAWAY;
#endif /* TERMCAP */
}


/*
 * scrollup - use tcap stuff to efficiently move blocks of text on the
 *            display, and update the pscreen array to reflect those
 *            moves...
 */
void
scrollup(WINDOW *wp, int r, int n)
{
#ifdef	TERMCAP
    register int i;
    register VIDEO *vp1;
    register VIDEO *vp2;

    if(!n)
      return;

    if(r < 0)
      r = wp->w_toprow;

    o_scrollup(r, n);

    i = 0;
    while(1){
	if(Pmaster){
	    if(!(r+i+n < wp->w_toprow+wp->w_ntrows))
	      break;
	}
	else{
	    if(!((i < wp->w_ntrows-n)&&(r+i+n < wp->w_toprow+wp->w_ntrows)))
	      break;
	}
	vp1 = pscreen[r+i+n]; 
	vp2 = pscreen[r+i];
	memcpy(vp2, vp1, term.t_ncol * sizeof(CELL));
	i++;
    }
    pprints(wp->w_toprow+wp->w_ntrows-n, wp->w_toprow+wp->w_ntrows-1);
    ttrow = FARAWAY;
    ttcol = FARAWAY;
#endif /* TERMCAP */
}


/*
 * print spaces in the physical screen starting from row abs(n) working in
 * either the positive or negative direction (depending on sign of n).
 */
void
pprints(int x, int y)
{
    register int i;
    register int j;

    if(x < y){
	for(i = x;i <= y; ++i){
	    for(j = 0; j < term.t_ncol; j++){
		pscreen[i]->v_text[j].c = ' ';
		pscreen[i]->v_text[j].a = 0;
	    }
        }
    }
    else{
	for(i = x;i >= y; --i){
	    for(j = 0; j < term.t_ncol; j++){
		pscreen[i]->v_text[j].c = ' ';
		pscreen[i]->v_text[j].a = 0;
	    }
        }
    }
    ttrow = y;
    ttcol = 0;
}


/*
 * doton - return the physical line number that the dot is on in the
 *         current window, and by side effect the number of lines remaining
 */
int
doton(int *r, unsigned *chs)
{
    register int  i = 0;
    register LINE *lp = curwp->w_linep;
    int      l = -1;

    assert(r != NULL && chs != NULL);

    *chs = 0;
    while(i++ < curwp->w_ntrows){
	if(lp == curwp->w_dotp)
	  l = i-1;
	lp = lforw(lp);
	if(lp == curwp->w_bufp->b_linep){
	    i++;
	    break;
	}
	if(l >= 0)
	  (*chs) += llength(lp);
    }
    *r = i - l - term.t_mrow;
    return(l+curwp->w_toprow);
}



/*
 * resize_pico - given new window dimensions, allocate new resources
 */
int
resize_pico(int row, int col)
{
    int old_nrow, old_ncol;
    register int i;
    register VIDEO *vp;

    old_nrow = term.t_nrow;
    old_ncol = term.t_ncol;

    term.t_nrow = row;
    term.t_ncol = col;

    if (old_ncol == term.t_ncol && old_nrow == term.t_nrow)
      return(TRUE);

    if(curwp){
	curwp->w_toprow = 2;
	curwp->w_ntrows = term.t_nrow - curwp->w_toprow - term.t_mrow;
    }

    if(Pmaster){
	fillcol = Pmaster->fillcolumn;
	(*Pmaster->resize)();
    }
    else if(userfillcol > 0)
      fillcol = userfillcol;
    else
      fillcol = term.t_ncol - 6;	       /* we control the fill column */

    /* 
     * free unused screen space ...
     */
    for(i=term.t_nrow+1; i <= old_nrow; ++i){
	free((char *) vscreen[i]);
	free((char *) pscreen[i]);
    }

    /* 
     * realloc new space for screen ...
     */
    if((vscreen=(VIDEO **)realloc(vscreen,(term.t_nrow+1)*sizeof(VIDEO *))) == NULL){
	if(Pmaster)
	  return(-1);
	else
	  exit(1);
    }

    if((pscreen=(VIDEO **)realloc(pscreen,(term.t_nrow+1)*sizeof(VIDEO *))) == NULL){
	if(Pmaster)
	  return(-1);
	else
	  exit(1);
    }

    for (i = 0; i <= term.t_nrow; ++i) {
	if(i <= old_nrow)
	  vp = (VIDEO *) realloc(vscreen[i], sizeof(VIDEO)+(term.t_ncol*sizeof(CELL)));
	else
	  vp = (VIDEO *) malloc(sizeof(VIDEO)+(term.t_ncol*sizeof(CELL)));

	if (vp == NULL)
	  exit(1);
	vp->v_flag = VFCHG;
	vscreen[i] = vp;
	if(old_ncol < term.t_ncol){  /* don't let any garbage in */
	    vtrow = i;
	    vtcol = (i < old_nrow) ? old_ncol : 0;
	    vteeol();
	}

	if(i <= old_nrow)
	  vp = (VIDEO *) realloc(pscreen[i], sizeof(VIDEO)+(term.t_ncol*sizeof(CELL)));
	else
	  vp = (VIDEO *) malloc(sizeof(VIDEO)+(term.t_ncol*sizeof(CELL)));

	if (vp == NULL)
	  exit(1);

	vp->v_flag = VFCHG;
	pscreen[i] = vp;
    }

    if(!ResizeBrowser()){
	if(Pmaster && Pmaster->headents){
	    ResizeHeader();
	}
	else{
	    curwp->w_flag |= (WFHARD | WFMODE);
	    pico_refresh(0, 1);                /* redraw whole enchilada. */
	    update();                          /* do it */
	}
    }

    return(TRUE);
}

void
redraw_pico_for_callback(void)
{
    pico_refresh(0, 1);
    update();
}


/*
 * showCompTitle - display the anchor line passed in from pine
 */
void
showCompTitle(void)
{
    if(Pmaster){
	UCS *bufp;
	extern   UCS *pico_anchor;
	COLOR_PAIR *lastc = NULL;

	if((bufp = pico_anchor) == NULL)
	  return;
	
	movecursor(COMPOSER_TITLE_LINE, 0);
	if (Pmaster->colors && Pmaster->colors->tbcp &&
	    pico_is_good_colorpair(Pmaster->colors->tbcp)){
	  lastc = pico_get_cur_color();
	  (void)pico_set_colorp(Pmaster->colors->tbcp, PSC_NONE);
	}
	else
	  (*term.t_rev)(1);   

	while (ttcol < term.t_ncol)
	  if(*bufp != '\0')
	    pputc(*bufp++, 1);
          else
	    pputc(' ', 1);

	if (lastc){
	  (void)pico_set_colorp(lastc, PSC_NONE);
	  free_color_pair(&lastc);
	}
	else
	  (*term.t_rev)(0);

	movecursor(COMPOSER_TITLE_LINE + 1, 0);
	peeol();
    }
}



/*
 * zotdisplay - blast malloc'd space created for display maps
 */
void
zotdisplay(void)
{
    register int i;

    for (i = 0; i <= term.t_nrow; ++i){		/* free screens */
	free((char *) vscreen[i]);
	free((char *) pscreen[i]);
    }

    free((char *) vscreen);
    free((char *) pscreen);
}



/*
 * nlforw() - returns the number of lines from the top to the dot
 */
int
nlforw(void)
{
    register int  i = 0;
    register LINE *lp = curwp->w_linep;
    
    while(lp != curwp->w_dotp){
	lp = lforw(lp);
	i++;
    }
    return(i);
}



/*
 * pputc - output the given char, keep track of it on the physical screen
 *	   array, and keep track of the cursor
 */
void
pputc(UCS c,				/* char to write */
      int a)				/* and its attribute */
{
    int ind, width, printable_ascii = 0;

    /*
     * This is necessary but not sufficient to allow us to draw. Note that
     * ttrow runs from 0 to t_nrow (so total number of rows is t_nrow+1)
     * ttcol runs from 0 to t_ncol-1 (so total number of cols is t_ncol)
     */
    if((ttcol >= 0 && ttcol < term.t_ncol) && (ttrow >= 0 && ttrow <= term.t_nrow)){

	/*
	 * Width is the number of screen columns a character will occupy.
	 */
	if(c < 0x80 && isprint(c)){
	    printable_ascii++;
	    width = 1;
	}
	else
	  width = wcellwidth(c);

	if(width < 0)
	  width = 1;		/* will be a '?' */

	if(ttcol + width <= term.t_ncol){	/* it fits */
	    /*
	     * Some terminals scroll when you write in the lower right corner
	     * of the screen, so don't write there.
	     */
	    if(!(ttrow == term.t_nrow && ttcol+width == term.t_ncol)){
		(*term.t_putchar)(c);			/* write it */
		ind = index_from_col(ttrow, ttcol);
		pscreen[ttrow]->v_text[ind].c = c;	/* keep track of it */
		pscreen[ttrow]->v_text[ind].a = a;	/* keep track of it */
	    }
	}
	else{
	    /*
	     * Character overlaps right edge of screen. Hopefully the higher
	     * layers will prevent this but we're making sure.
	     *
	     * We may want to do something like writing a space character
	     * into the cells that are on the screen. We'll see.
	     */
	}

	ttcol = MIN(term.t_ncol, ttcol+width);
    }
}


/*
 * pputs - print a string and keep track of the cursor
 */
void
pputs(UCS *s,				/* string to write */
      int a)				/* and its attribute */
{
    while (*s != '\0')
      pputc(*s++, a);
}


void
pputs_utf8(char *s, int a)
{
    UCS *ucsstr = NULL;

    if(s && *s){
	ucsstr = utf8_to_ucs4_cpystr(s);
	if(ucsstr){
	    pputs(ucsstr, a);
	    fs_give((void **) &ucsstr);
	}
    }
}


/*
 * peeol - physical screen array erase to end of the line.  remember to
 *	   track the cursor.
 */
void
peeol(void)
{
    int  i, width = 0, ww;
    CELL cl;

    if(ttrow < 0 || ttrow > term.t_nrow)
      return;

    cl.c = ' ';
    cl.a = 0;

    /*
     * Don't clear if we think we are sitting past the last column,
     * that erases the last column if we just wrote it.
     */
    if(ttcol < term.t_ncol)
      (*term.t_eeol)();

    /*
     * Because the characters are variable width it's a little tricky
     * to erase the rest of the line. What we do is add up the
     * widths of the characters until we reach ttcol
     * then set the rest to the space character.
     */
    for(i = 0; i < term.t_ncol && width < ttcol; i++){
	ww = wcellwidth((UCS) pscreen[ttrow]->v_text[i].c);
	width += (ww >= 0 ? ww : 1);
    }

    while(i < term.t_ncol)
      pscreen[ttrow]->v_text[i++] = cl;
}


/*
 * pscr - return the character cell on the physical screen map on the 
 *        given line, l, and offset, o.
 */
CELL *
pscr(int l, int o)
{
    if((l >= 0 && l <= term.t_nrow) && (o >= 0 && o < term.t_ncol))
      return(&(pscreen[l]->v_text[o]));
    else
      return(NULL);
}


/*
 * pclear() - clear the physical screen from row x through row y (inclusive)
 *            row is zero origin, min row = 0 max row = t_nrow
 *            Clear whole screen      -- pclear(0, term.t_nrow)
 *            Clear bottom two rows   -- pclear(term.t_nrow-1, term.t_nrow)
 *            Clear bottom three rows -- pclear(term.t_nrow-2, term.t_nrow)
 */
void
pclear(int x, int y)
{
    register int i;

    x = MIN(MAX(0, x), term.t_nrow);
    y = MIN(MAX(0, y), term.t_nrow);

    for(i=x; i <= y; i++){
	movecursor(i, 0);
	peeol();
    }
}


/*
 * dumbroot - just get close 
 */
int
dumbroot(int x, int b)
{
    if(x < b)
      return(1);
    else
      return(dumbroot(x/b, b) + 1);
}


/*
 * dumblroot - just get close 
 */
int
dumblroot(long x, int b)
{
    if(x < b)
      return(1);
    else
      return(dumblroot(x/b, b) + 1);
}


/*
 * pinsertc - use optimized insert, fixing physical screen map.
 *            returns true if char written, false otherwise
 */
int
pinsert(CELL c)
{
    int   i, ind = 0, ww;
    CELL *p;

    if(ttrow < 0 || ttrow > term.t_nrow)
      return(0);

    if(o_insert((UCS) c.c)){		/* if we've got it, use it! */
	p = pscreen[ttrow]->v_text;	/* then clean up physical screen */

	ind = index_from_col(ttrow, ttcol);

	for(i = term.t_ncol-1; i > ind; i--)
	  p[i] = p[i-1];		/* shift right */

	p[ind] = c;			/* insert new char */

	ww = wcellwidth((UCS) c.c);
	ttcol += (ww >= 0 ? ww : 1);
	
	return(1);
    }

    return(0);
}


/*
 * pdel - use optimized delete to rub out the current char and
 *        fix the physical screen array.
 *        returns true if optimized the delete, false otherwise
 */
int
pdel(void)
{
    int   i, ind = 0, w;
    CELL *p;

    if(ttrow < 0 || ttrow > term.t_nrow)
      return(0);

    if(TERM_DELCHAR){			/* if we've got it, use it! */
	p = pscreen[ttrow]->v_text;
	ind = index_from_col(ttrow, ttcol);

	if(ind > 0){
	    --ind;
	    w = wcellwidth((UCS) p[ind].c);
	    w = (w >= 0 ? w : 1);
	    ttcol -= w;

	    for(i = 0; i < w; i++){
		(*term.t_putchar)('\b'); 	/* move left a char */
		o_delete();			/* and delete it */
	    }

	    /* then clean up physical screen */
	    for(i=ind; i < term.t_ncol-1; i++)
	      p[i] = p[i+1];

	    p[i].c = ' ';
	    p[i].a = 0;
	}
	
	return(1);
    }

    return(0);
}



/*
 * wstripe - write out the given string at the given location, and reverse
 *           video on flagged characters.  Does the same thing as pine's
 *           stripe.
 *
 * I believe this needs to be fixed to work with non-ascii utf8pmt, but maybe
 * only if you want to put the tildes before multi-byte chars.
 */
void
wstripe(int line, int column, char *utf8pmt, int key)
{
    UCS  *ucs4pmt, *u;
    int  i = 0, col = 0;
    int  j = 0;
    int  l, ww;
    COLOR_PAIR *lastc = NULL;
    COLOR_PAIR *kncp = NULL;
    COLOR_PAIR *klcp = NULL;

    if(line < 0 || line > term.t_nrow)
      return;

    if (Pmaster && Pmaster->colors){
      if(pico_is_good_colorpair(Pmaster->colors->klcp))
        klcp = Pmaster->colors->klcp;

      if(klcp && pico_is_good_colorpair(Pmaster->colors->kncp))
        kncp = Pmaster->colors->kncp;
    }
    else if(Pcolors){
       klcp = Pcolors->klcp;
       kncp = Pcolors->kncp;
    }

    lastc = pico_get_cur_color();
    ucs4pmt = utf8_to_ucs4_cpystr(utf8pmt);
    l = ucs4_strlen(ucs4pmt);
    while(1){
	if(i >= term.t_ncol || col >= term.t_ncol || j >= l){
	  if(lastc) free_color_pair(&lastc);
	  if(ucs4pmt) fs_give((void **) &ucs4pmt);
	  return;				/* equal strings */
	}

	if(ucs4pmt[j] == (UCS) key)
	  j++;

	if (pscr(line, i) == NULL){
	  if(lastc) free_color_pair(&lastc);
	  if(ucs4pmt) fs_give((void **) &ucs4pmt);
	  return;
	}
	
	if(pscr(line, i)->c != ucs4pmt[j]){
	    if(j >= 1 && ucs4pmt[j-1] == (UCS) key)
 	      j--;
	    break;
	}

	ww = wcellwidth((UCS) pscr(line, i)->c);
	col += (ww >= 0 ? ww : 1);
	j++;
	i++;
    }

    movecursor(line, column+col);
    if(klcp) (void)pico_set_colorp(klcp, PSC_NONE);
    u = &ucs4pmt[j];
    do{
	if(*u == (UCS) key){
	    u++;
	    if(kncp)
	      (void)pico_set_colorp(kncp, PSC_NONE);
	    else
	      (void)(*term.t_rev)(1);

	    pputc(*u, 1);
	    if(kncp)
	      (void)pico_set_colorp(klcp, PSC_NONE);
	    else
	      (void)(*term.t_rev)(0);
	}
	else{
	    pputc(*u, 0);
	}
    }    
    while(*++u != '\0');

    if(ucs4pmt)
      fs_give((void **) &ucs4pmt);

    peeol();
    if (lastc){
      (void)pico_set_colorp(lastc, PSC_NONE);
      free_color_pair(&lastc);
    }
    (*term.t_flush)();
}



/*
 *  wkeyhelp - paint list of possible commands on the bottom
 *             of the display (yet another pine clone)
 *  NOTE: function key mode is handled here since all the labels
 *        are the same...
 *
 *    The KEYMENU definitions have names and labels defined as UTF-8 strings,
 *    and wstripe expects UTF-8.
 */
void
wkeyhelp(KEYMENU *keymenu)
{
    char *obufp, *p, fkey[4];
    char  linebuf[2*NLINE];	/* "2" is for space for invert tokens */
    int   row, slot, tspace, adjusted_tspace, nspace[6], index, n;
#ifdef	MOUSE
    char  nbuf[NLINE];
#endif

#ifdef _WINDOWS
    pico_config_menu_items (keymenu);
#endif

    if(term.t_mrow == 0)
      return;

    if(term.t_nrow < 1)
      return;

    /*
     * Calculate amount of space for the names column by column...
     */
    for(index = 0; index < 6; index++)
      if(!(gmode&MDFKEY)){
	  nspace[index] = (keymenu[index].name)
			    ? utf8_width(keymenu[index].name) : 0;
	  if(keymenu[index+6].name 
	     && (n = utf8_width(keymenu[index+6].name)) > nspace[index])
	    nspace[index] = n;

	  nspace[index]++;
      }
      else
	nspace[index] = (index < 4) ? 3 : 4;

    tspace = term.t_ncol/6;		/* total space for each item */

    /*
     * Avoid writing in bottom right corner so we won't scroll screens that
     * scroll when you do that. The way this is setup, we won't do that
     * unless the number of columns is evenly divisible by 6.
     */
    adjusted_tspace = (6 * tspace == term.t_ncol) ? tspace - 1 : tspace;

    index  = 0;
    for(row = 0; row <= 1; row++){
	linebuf[0] = '\0';
	obufp = &linebuf[0];
	for(slot = 0; slot < 6; slot++){
	    if(keymenu[index].name && keymenu[index].label){
		size_t l;
		char this_label[200], tmp_label[200];

		if(keymenu[index].label[0] == '[' && keymenu[index].label[(l=strlen(keymenu[index].label))-1] == ']' && l > 2){
		    strncpy(tmp_label, &keymenu[index].label[1], MIN(sizeof(tmp_label),l-2));
		    tmp_label[MIN(sizeof(tmp_label)-1,l-2)] = '\0';
		    snprintf(this_label, sizeof(this_label), "[%s]", _(tmp_label));
	        }
		else
		  strncpy(this_label, _(keymenu[index].label), sizeof(this_label));

		this_label[sizeof(this_label)-1] = '\0';

		if(gmode&MDFKEY){
		    p = fkey;
		    snprintf(fkey, sizeof(fkey), "F%d", (2 * slot) + row + 1);
		}
		else
		  p = keymenu[index].name;
#ifdef	MOUSE
		snprintf(nbuf, sizeof(nbuf), "%.*s %s", nspace[slot], p, this_label);
		register_key(index,
			     (gmode&MDFKEY) ? F1 + (2 * slot) + row:
			     (keymenu[index].name[0] == '^')
			       ? (CTRL | keymenu[index].name[1])
			       : (keymenu[index].name[0] == 'S'
				  && !strcmp(keymenu[index].name, "Spc"))
				   ? ' '
				   : keymenu[index].name[0],
			     nbuf, invert_label,
			     term.t_nrow - 1 + row, (slot * tspace),
			     strlen(nbuf),
			     (Pmaster && Pmaster->colors) 
			       ? Pmaster->colors->kncp: NULL,
			     (Pmaster && Pmaster->colors) 
			       ? Pmaster->colors->klcp: NULL);
#endif

		n = nspace[slot];
		while(p && *p && n--){
		    *obufp++ = '~';	/* insert "invert" token */
		    *obufp++ = *p++;
		}

		while(n-- > 0)
		  *obufp++ = ' ';

		p = this_label;
		n = ((slot == 5 && row == 1) ? adjusted_tspace
					     : tspace) - nspace[slot];
		while(p && *p && n-- > 0)
		  *obufp++ = *p++;

		while(n-- > 0)
		  *obufp++ = ' ';
	    }
	    else{
		n = (slot == 5 && row == 1) ? adjusted_tspace : tspace;
		while(n--)
		  *obufp++ = ' ';

#ifdef	MOUSE
		register_key(index, NODATA, "", NULL, 0, 0, 0, NULL, NULL);
#endif
	    }

	    *obufp = '\0';
	    index++;
	}

	wstripe(term.t_nrow - 1 + row, 0, linebuf, '~');
    }
}


/*
 * This returns the screen width between pstart (inclusive) and
 * pend (exclusive) where the pointers point into an array of CELLs.
 */
unsigned
cellwidth_ptr_to_ptr(CELL *pstart, CELL *pend)
{
    CELL *p;
    unsigned width = 0;
    int ww;

    if(pstart)
      for(p = pstart; p < pend; p++){
	  ww = wcellwidth((UCS) p->c);
	  width += (ww >= 0 ? ww : 1);
      }

    return(width);
}


/*
 * This returns the virtual screen width in row from index a to b (exclusive).
 */
unsigned
vcellwidth_a_to_b(int row, int a, int b)
{
    CELL *pstart, *pend;
    VIDEO *vp;
  
    if(row < 0 || row > term.t_nrow)
      return 0;

    if(a >= b)
      return 0;

    a = MIN(MAX(0, a), term.t_ncol-1);
    b = MIN(MAX(0, a), term.t_ncol);	/* b is past where we stop */

    vp = vscreen[row];
    pstart = &vp->v_text[a];
    pend   = &vp->v_text[b];

    return(cellwidth_ptr_to_ptr(pstart, pend));
}


/*
 * This returns the physical screen width in row from index a to b (exclusive).
 */
unsigned
pcellwidth_a_to_b(int row, int a, int b)
{
    CELL *pstart, *pend;
    VIDEO *vp;
  
    if(row < 0 || row > term.t_nrow)
      return 0;

    if(a >= b)
      return 0;

    a = MIN(MAX(0, a), term.t_ncol-1);
    b = MIN(MAX(0, a), term.t_ncol);	/* b is past where we stop */

    vp = pscreen[row];
    pstart = &vp->v_text[a];
    pend   = &vp->v_text[b];

    return(cellwidth_ptr_to_ptr(pstart, pend));
}


int
index_from_col(int row, int col)
{
    CELL *p_start, *p_end, *p_limit;
    int   w_consumed = 0, w, done = 0;

    if(row < 0 || row > term.t_nrow)
      return 0;

    p_end = p_start = pscreen[row]->v_text;
    p_limit = p_start + term.t_ncol;

    if(p_start)
      while(!done && p_end < p_limit && p_end->c && w_consumed <= col){
	w = wcellwidth((UCS) p_end->c);
	w = (w >= 0 ? w : 1);
	if(w_consumed + w <= col){
	    w_consumed += w;
	    ++p_end;
	}
	else
	  ++done;
      }

    /* MIN and MAX just to be sure */
    return(MIN(MAX(0, p_end - p_start), term.t_ncol-1));
}

#ifdef _WINDOWS

void
pico_config_menu_items (KEYMENU *keymenu)
{
    int		i;
    KEYMENU	*k;
    UCS		key;

    mswin_menuitemclear ();

    /* keymenu's seem to be hardcoded at 12 entries. */
    for (i = 0, k = keymenu; i < 12; ++i, ++k) {
	if (k->name != NULL && k->label != NULL && 
		k->menuitem != KS_NONE) {

	    if (k->name[0] == '^')
		key = CTRL | k->name[1];
	    else if (strcmp(k->name, "Ret") == 0) 
		key = '\r';
	    else
		key = k->name[0];

	    mswin_menuitemadd (key, k->label, k->menuitem, 0);
	}
    }
}

/*
 * Update the scroll range and position. (exported)
 *
 * This is where curbp->b_linecnt is really managed.  With out this function
 * to count the number of lines when needed curbp->b_linecnt will never
 * really be correct.  BUT, this function is only compiled into the 
 * windows version, so b_linecnt will only ever be right in the windows
 * version.  OK for now because that is the only version that
 * looks at b_linecnt.
 */
int
update_scroll (void)
{
    long	scr_pos;
    long	scr_range;
    LINE	*lp;
    static LINE *last_top_line = NULL;
    static long last_scroll_pos = -1;
    
    
    if (ComposerEditing) {
	/* Editing header - don't allow scroll bars. */
	mswin_setscrollrange (0, 0);
	return(0);
    }
	   
	
    /*
     * Count the number of lines in the current buffer.  Done when:
     *
     *      when told to recount:           curbp->b_linecnt == -1
     *      when the top line changed:      curwp->w_linep != last_top_line
     *  when we don't know the scroll pos:  last_scroll_pos == -1
     *
     * The first line in the list is a "place holder" line and is not
     * counted.  The list is circular, when we return the to place
     * holder we have reached the end.
     */
    if(curbp->b_linecnt == -1 || curwp->w_linep != last_top_line
       || last_scroll_pos == -1) {
	scr_range = 0;
	scr_pos = 0;
	for (lp = lforw (curbp->b_linep); lp != curbp->b_linep; 
	     lp = lforw (lp)) {
	    if (lp == curwp->w_linep)
              scr_pos = scr_range;

	    ++scr_range;
	}

	curbp->b_linecnt = scr_range;
	last_scroll_pos = scr_pos;
	last_top_line = curwp->w_linep;
    }

    /*
     * Set new scroll range and position.
     */
    mswin_setscrollrange (curwp->w_ntrows - 2, curbp->b_linecnt - 1);
    mswin_setscrollpos (last_scroll_pos);
    return (0);
}
#endif /* _WINDOWS */