summaryrefslogtreecommitdiff
path: root/src/hardcopy.c
blob: 95a367d496909de57373735fcc7c6ef2bb1e7311 (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
/* vi:set ts=8 sts=4 sw=4:
 *
 * VIM - Vi IMproved	by Bram Moolenaar
 *
 * Do ":help uganda"  in Vim to read copying and usage conditions.
 * Do ":help credits" in Vim to see a list of people who contributed.
 * See README.txt for an overview of the Vim source code.
 */

/*
 * hardcopy.c: printing to paper
 */

#include "vim.h"
#include "version.h"

#if defined(FEAT_PRINTER) || defined(PROTO)
/*
 * To implement printing on a platform, the following functions must be
 * defined:
 *
 * int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
 * Called once.  Code should display printer dialogue (if appropriate) and
 * determine printer font and margin settings.  Reset has_color if the printer
 * doesn't support colors at all.
 * Returns FAIL to abort.
 *
 * int mch_print_begin(prt_settings_T *settings)
 * Called to start the print job.
 * Return FALSE to abort.
 *
 * int mch_print_begin_page(char_u *msg)
 * Called at the start of each page.
 * "msg" indicates the progress of the print job, can be NULL.
 * Return FALSE to abort.
 *
 * int mch_print_end_page()
 * Called at the end of each page.
 * Return FALSE to abort.
 *
 * int mch_print_blank_page()
 * Called to generate a blank page for collated, duplex, multiple copy
 * document.  Return FALSE to abort.
 *
 * void mch_print_end(prt_settings_T *psettings)
 * Called at normal end of print job.
 *
 * void mch_print_cleanup()
 * Called if print job ends normally or is abandoned. Free any memory, close
 * devices and handles.  Also called when mch_print_begin() fails, but not
 * when mch_print_init() fails.
 *
 * void mch_print_set_font(int Bold, int Italic, int Underline);
 * Called whenever the font style changes.
 *
 * void mch_print_set_bg(long_u bgcol);
 * Called to set the background color for the following text. Parameter is an
 * RGB value.
 *
 * void mch_print_set_fg(long_u fgcol);
 * Called to set the foreground color for the following text. Parameter is an
 * RGB value.
 *
 * mch_print_start_line(int margin, int page_line)
 * Sets the current position at the start of line "page_line".
 * If margin is TRUE start in the left margin (for header and line number).
 *
 * int mch_print_text_out(char_u *p, int len);
 * Output one character of text p[len] at the current position.
 * Return TRUE if there is no room for another character in the same line.
 *
 * Note that the generic code has no idea of margins. The machine code should
 * simply make the page look smaller!  The header and the line numbers are
 * printed in the margin.
 */

#ifdef FEAT_SYN_HL
static const long_u  cterm_color_8[8] =
{
    (long_u)0x000000L, (long_u)0xff0000L, (long_u)0x00ff00L, (long_u)0xffff00L,
    (long_u)0x0000ffL, (long_u)0xff00ffL, (long_u)0x00ffffL, (long_u)0xffffffL
};

static const long_u  cterm_color_16[16] =
{
    (long_u)0x000000L, (long_u)0x0000c0L, (long_u)0x008000L, (long_u)0x004080L,
    (long_u)0xc00000L, (long_u)0xc000c0L, (long_u)0x808000L, (long_u)0xc0c0c0L,
    (long_u)0x808080L, (long_u)0x6060ffL, (long_u)0x00ff00L, (long_u)0x00ffffL,
    (long_u)0xff8080L, (long_u)0xff40ffL, (long_u)0xffff00L, (long_u)0xffffffL
};

static int		current_syn_id;
#endif

#define PRCOLOR_BLACK	(long_u)0
#define PRCOLOR_WHITE	(long_u)0xFFFFFFL

static int	curr_italic;
static int	curr_bold;
static int	curr_underline;
static long_u	curr_bg;
static long_u	curr_fg;
static int	page_count;

#if defined(FEAT_MBYTE) && defined(FEAT_POSTSCRIPT)
# define OPT_MBFONT_USECOURIER  0
# define OPT_MBFONT_ASCII       1
# define OPT_MBFONT_REGULAR     2
# define OPT_MBFONT_BOLD	3
# define OPT_MBFONT_OBLIQUE     4
# define OPT_MBFONT_BOLDOBLIQUE 5
# define OPT_MBFONT_NUM_OPTIONS 6

static option_table_T mbfont_opts[OPT_MBFONT_NUM_OPTIONS] =
{
    {"c",	FALSE, 0, NULL, 0, FALSE},
    {"a",	FALSE, 0, NULL, 0, FALSE},
    {"r",	FALSE, 0, NULL, 0, FALSE},
    {"b",	FALSE, 0, NULL, 0, FALSE},
    {"i",	FALSE, 0, NULL, 0, FALSE},
    {"o",	FALSE, 0, NULL, 0, FALSE},
};
#endif

/*
 * These values determine the print position on a page.
 */
typedef struct
{
    int		lead_spaces;	    /* remaining spaces for a TAB */
    int		print_pos;	    /* virtual column for computing TABs */
    colnr_T	column;		    /* byte column */
    linenr_T	file_line;	    /* line nr in the buffer */
    long_u	bytes_printed;	    /* bytes printed so far */
    int		ff;		    /* seen form feed character */
} prt_pos_T;

static char_u *parse_list_options __ARGS((char_u *option_str, option_table_T *table, int table_size));

#ifdef FEAT_SYN_HL
static long_u darken_rgb __ARGS((long_u rgb));
static long_u prt_get_term_color __ARGS((int colorindex));
#endif
static void prt_set_fg __ARGS((long_u fg));
static void prt_set_bg __ARGS((long_u bg));
static void prt_set_font __ARGS((int bold, int italic, int underline));
static void prt_line_number __ARGS((prt_settings_T *psettings, int page_line, linenr_T lnum));
static void prt_header __ARGS((prt_settings_T *psettings, int pagenum, linenr_T lnum));
static void prt_message __ARGS((char_u *s));
static colnr_T hardcopy_line __ARGS((prt_settings_T *psettings, int page_line, prt_pos_T *ppos));
#ifdef FEAT_SYN_HL
static void prt_get_attr __ARGS((int hl_id, prt_text_attr_T* pattr, int modec));
#endif

/*
 * Parse 'printoptions' and set the flags in "printer_opts".
 * Returns an error message or NULL;
 */
    char_u *
parse_printoptions()
{
    return parse_list_options(p_popt, printer_opts, OPT_PRINT_NUM_OPTIONS);
}

#if (defined(FEAT_MBYTE) && defined(FEAT_POSTSCRIPT)) || defined(PROTO)
/*
 * Parse 'printoptions' and set the flags in "printer_opts".
 * Returns an error message or NULL;
 */
    char_u *
parse_printmbfont()
{
    return parse_list_options(p_pmfn, mbfont_opts, OPT_MBFONT_NUM_OPTIONS);
}
#endif

/*
 * Parse a list of options in the form
 * option:value,option:value,option:value
 *
 * "value" can start with a number which is parsed out, e.g.  margin:12mm
 *
 * Returns an error message for an illegal option, NULL otherwise.
 * Only used for the printer at the moment...
 */
    static char_u *
parse_list_options(option_str, table, table_size)
    char_u		*option_str;
    option_table_T	*table;
    int			table_size;
{
    char_u	*stringp;
    char_u	*colonp;
    char_u	*commap;
    char_u	*p;
    int		idx = 0;		/* init for GCC */
    int		len;

    for (idx = 0; idx < table_size; ++idx)
	table[idx].present = FALSE;

    /*
     * Repeat for all comma separated parts.
     */
    stringp = option_str;
    while (*stringp)
    {
	colonp = vim_strchr(stringp, ':');
	if (colonp == NULL)
	    return (char_u *)N_("E550: Missing colon");
	commap = vim_strchr(stringp, ',');
	if (commap == NULL)
	    commap = option_str + STRLEN(option_str);

	len = (int)(colonp - stringp);

	for (idx = 0; idx < table_size; ++idx)
	    if (STRNICMP(stringp, table[idx].name, len) == 0)
		break;

	if (idx == table_size)
	    return (char_u *)N_("E551: Illegal component");

	p = colonp + 1;
	table[idx].present = TRUE;

	if (table[idx].hasnum)
	{
	    if (!VIM_ISDIGIT(*p))
		return (char_u *)N_("E552: digit expected");

	    table[idx].number = getdigits(&p); /*advances p*/
	}

	table[idx].string = p;
	table[idx].strlen = (int)(commap - p);

	stringp = commap;
	if (*stringp == ',')
	    ++stringp;
    }

    return NULL;
}


#ifdef FEAT_SYN_HL
/*
 * If using a dark background, the colors will probably be too bright to show
 * up well on white paper, so reduce their brightness.
 */
    static long_u
darken_rgb(rgb)
    long_u	rgb;
{
    return	((rgb >> 17) << 16)
	    +	(((rgb & 0xff00) >> 9) << 8)
	    +	((rgb & 0xff) >> 1);
}

    static long_u
prt_get_term_color(colorindex)
    int	    colorindex;
{
    /* TODO: Should check for xterm with 88 or 256 colors. */
    if (t_colors > 8)
	return cterm_color_16[colorindex % 16];
    return cterm_color_8[colorindex % 8];
}

    static void
prt_get_attr(hl_id, pattr, modec)
    int			hl_id;
    prt_text_attr_T	*pattr;
    int			modec;
{
    int     colorindex;
    long_u  fg_color;
    long_u  bg_color;
    char    *color;

    pattr->bold = (highlight_has_attr(hl_id, HL_BOLD, modec) != NULL);
    pattr->italic = (highlight_has_attr(hl_id, HL_ITALIC, modec) != NULL);
    pattr->underline = (highlight_has_attr(hl_id, HL_UNDERLINE, modec) != NULL);
    pattr->undercurl = (highlight_has_attr(hl_id, HL_UNDERCURL, modec) != NULL);

# ifdef FEAT_GUI
    if (gui.in_use)
    {
	bg_color = highlight_gui_color_rgb(hl_id, FALSE);
	if (bg_color == PRCOLOR_BLACK)
	    bg_color = PRCOLOR_WHITE;

	fg_color = highlight_gui_color_rgb(hl_id, TRUE);
    }
    else
# endif
    {
	bg_color = PRCOLOR_WHITE;

	color = (char *)highlight_color(hl_id, (char_u *)"fg", modec);
	if (color == NULL)
	    colorindex = 0;
	else
	    colorindex = atoi(color);

	if (colorindex >= 0 && colorindex < t_colors)
	    fg_color = prt_get_term_color(colorindex);
	else
	    fg_color = PRCOLOR_BLACK;
    }

    if (fg_color == PRCOLOR_WHITE)
	fg_color = PRCOLOR_BLACK;
    else if (*p_bg == 'd')
	fg_color = darken_rgb(fg_color);

    pattr->fg_color = fg_color;
    pattr->bg_color = bg_color;
}
#endif /* FEAT_SYN_HL */

    static void
prt_set_fg(fg)
    long_u fg;
{
    if (fg != curr_fg)
    {
	curr_fg = fg;
	mch_print_set_fg(fg);
    }
}

    static void
prt_set_bg(bg)
    long_u bg;
{
    if (bg != curr_bg)
    {
	curr_bg = bg;
	mch_print_set_bg(bg);
    }
}

    static void
prt_set_font(bold, italic, underline)
    int		bold;
    int		italic;
    int		underline;
{
    if (curr_bold != bold
	    || curr_italic != italic
	    || curr_underline != underline)
    {
	curr_underline = underline;
	curr_italic = italic;
	curr_bold = bold;
	mch_print_set_font(bold, italic, underline);
    }
}

/*
 * Print the line number in the left margin.
 */
    static void
prt_line_number(psettings, page_line, lnum)
    prt_settings_T *psettings;
    int		page_line;
    linenr_T	lnum;
{
    int		i;
    char_u	tbuf[20];

    prt_set_fg(psettings->number.fg_color);
    prt_set_bg(psettings->number.bg_color);
    prt_set_font(psettings->number.bold, psettings->number.italic, psettings->number.underline);
    mch_print_start_line(TRUE, page_line);

    /* Leave two spaces between the number and the text; depends on
     * PRINT_NUMBER_WIDTH. */
    sprintf((char *)tbuf, "%6ld", (long)lnum);
    for (i = 0; i < 6; i++)
	(void)mch_print_text_out(&tbuf[i], 1);

#ifdef FEAT_SYN_HL
    if (psettings->do_syntax)
	/* Set colors for next character. */
	current_syn_id = -1;
    else
#endif
    {
	/* Set colors and font back to normal. */
	prt_set_fg(PRCOLOR_BLACK);
	prt_set_bg(PRCOLOR_WHITE);
	prt_set_font(FALSE, FALSE, FALSE);
    }
}

/*
 * Get the currently effective header height.
 */
    int
prt_header_height()
{
    if (printer_opts[OPT_PRINT_HEADERHEIGHT].present)
	return printer_opts[OPT_PRINT_HEADERHEIGHT].number;
    return 2;
}

/*
 * Return TRUE if using a line number for printing.
 */
    int
prt_use_number()
{
    return (printer_opts[OPT_PRINT_NUMBER].present
	    && TOLOWER_ASC(printer_opts[OPT_PRINT_NUMBER].string[0]) == 'y');
}

/*
 * Return the unit used in a margin item in 'printoptions'.
 * Returns PRT_UNIT_NONE if not recognized.
 */
    int
prt_get_unit(idx)
    int		idx;
{
    int		u = PRT_UNIT_NONE;
    int		i;
    static char *(units[4]) = PRT_UNIT_NAMES;

    if (printer_opts[idx].present)
	for (i = 0; i < 4; ++i)
	    if (STRNICMP(printer_opts[idx].string, units[i], 2) == 0)
	    {
		u = i;
		break;
	    }
    return u;
}

/*
 * Print the page header.
 */
    static void
prt_header(psettings, pagenum, lnum)
    prt_settings_T  *psettings;
    int		pagenum;
    linenr_T	lnum UNUSED;
{
    int		width = psettings->chars_per_line;
    int		page_line;
    char_u	*tbuf;
    char_u	*p;
#ifdef FEAT_MBYTE
    int		l;
#endif

    /* Also use the space for the line number. */
    if (prt_use_number())
	width += PRINT_NUMBER_WIDTH;

    tbuf = alloc(width + IOSIZE);
    if (tbuf == NULL)
	return;

#ifdef FEAT_STL_OPT
    if (*p_header != NUL)
    {
	linenr_T	tmp_lnum, tmp_topline, tmp_botline;
	int		use_sandbox = FALSE;

	/*
	 * Need to (temporarily) set current line number and first/last line
	 * number on the 'window'.  Since we don't know how long the page is,
	 * set the first and current line number to the top line, and guess
	 * that the page length is 64.
	 */
	tmp_lnum = curwin->w_cursor.lnum;
	tmp_topline = curwin->w_topline;
	tmp_botline = curwin->w_botline;
	curwin->w_cursor.lnum = lnum;
	curwin->w_topline = lnum;
	curwin->w_botline = lnum + 63;
	printer_page_num = pagenum;

# ifdef FEAT_EVAL
	use_sandbox = was_set_insecurely((char_u *)"printheader", 0);
# endif
	build_stl_str_hl(curwin, tbuf, (size_t)(width + IOSIZE),
						  p_header, use_sandbox,
						  ' ', width, NULL, NULL);

	/* Reset line numbers */
	curwin->w_cursor.lnum = tmp_lnum;
	curwin->w_topline = tmp_topline;
	curwin->w_botline = tmp_botline;
    }
    else
#endif
	sprintf((char *)tbuf, _("Page %d"), pagenum);

    prt_set_fg(PRCOLOR_BLACK);
    prt_set_bg(PRCOLOR_WHITE);
    prt_set_font(TRUE, FALSE, FALSE);

    /* Use a negative line number to indicate printing in the top margin. */
    page_line = 0 - prt_header_height();
    mch_print_start_line(TRUE, page_line);
    for (p = tbuf; *p != NUL; )
    {
	if (mch_print_text_out(p,
#ifdef FEAT_MBYTE
		(l = (*mb_ptr2len)(p))
#else
		1
#endif
		    ))
	{
	    ++page_line;
	    if (page_line >= 0) /* out of room in header */
		break;
	    mch_print_start_line(TRUE, page_line);
	}
#ifdef FEAT_MBYTE
	p += l;
#else
	p++;
#endif
    }

    vim_free(tbuf);

#ifdef FEAT_SYN_HL
    if (psettings->do_syntax)
	/* Set colors for next character. */
	current_syn_id = -1;
    else
#endif
    {
	/* Set colors and font back to normal. */
	prt_set_fg(PRCOLOR_BLACK);
	prt_set_bg(PRCOLOR_WHITE);
	prt_set_font(FALSE, FALSE, FALSE);
    }
}

/*
 * Display a print status message.
 */
    static void
prt_message(s)
    char_u	*s;
{
    screen_fill((int)Rows - 1, (int)Rows, 0, (int)Columns, ' ', ' ', 0);
    screen_puts(s, (int)Rows - 1, 0, hl_attr(HLF_R));
    out_flush();
}

    void
ex_hardcopy(eap)
    exarg_T	*eap;
{
    linenr_T		lnum;
    int			collated_copies, uncollated_copies;
    prt_settings_T	settings;
    long_u		bytes_to_print = 0;
    int			page_line;
    int			jobsplit;

    vim_memset(&settings, 0, sizeof(prt_settings_T));
    settings.has_color = TRUE;

# ifdef FEAT_POSTSCRIPT
    if (*eap->arg == '>')
    {
	char_u	*errormsg = NULL;

	/* Expand things like "%.ps". */
	if (expand_filename(eap, eap->cmdlinep, &errormsg) == FAIL)
	{
	    if (errormsg != NULL)
		EMSG(errormsg);
	    return;
	}
	settings.outfile = skipwhite(eap->arg + 1);
    }
    else if (*eap->arg != NUL)
	settings.arguments = eap->arg;
# endif

    /*
     * Initialise for printing.  Ask the user for settings, unless forceit is
     * set.
     * The mch_print_init() code should set up margins if applicable. (It may
     * not be a real printer - for example the engine might generate HTML or
     * PS.)
     */
    if (mch_print_init(&settings,
			curbuf->b_fname == NULL
			    ? (char_u *)buf_spname(curbuf)
			    : curbuf->b_sfname == NULL
				? curbuf->b_fname
				: curbuf->b_sfname,
			eap->forceit) == FAIL)
	return;

#ifdef FEAT_SYN_HL
# ifdef  FEAT_GUI
    if (gui.in_use)
	settings.modec = 'g';
    else
# endif
	if (t_colors > 1)
	    settings.modec = 'c';
	else
	    settings.modec = 't';

    if (!syntax_present(curwin))
	settings.do_syntax = FALSE;
    else if (printer_opts[OPT_PRINT_SYNTAX].present
	    && TOLOWER_ASC(printer_opts[OPT_PRINT_SYNTAX].string[0]) != 'a')
	settings.do_syntax =
	       (TOLOWER_ASC(printer_opts[OPT_PRINT_SYNTAX].string[0]) == 'y');
    else
	settings.do_syntax = settings.has_color;
#endif

    /* Set up printing attributes for line numbers */
    settings.number.fg_color = PRCOLOR_BLACK;
    settings.number.bg_color = PRCOLOR_WHITE;
    settings.number.bold = FALSE;
    settings.number.italic = TRUE;
    settings.number.underline = FALSE;
#ifdef FEAT_SYN_HL
    /*
     * Syntax highlighting of line numbers.
     */
    if (prt_use_number() && settings.do_syntax)
    {
	int		id;

	id = syn_name2id((char_u *)"LineNr");
	if (id > 0)
	    id = syn_get_final_id(id);

	prt_get_attr(id, &settings.number, settings.modec);
    }
#endif

    /*
     * Estimate the total lines to be printed
     */
    for (lnum = eap->line1; lnum <= eap->line2; lnum++)
	bytes_to_print += (long_u)STRLEN(skipwhite(ml_get(lnum)));
    if (bytes_to_print == 0)
    {
	MSG(_("No text to be printed"));
	goto print_fail_no_begin;
    }

    /* Set colors and font to normal. */
    curr_bg = (long_u)0xffffffffL;
    curr_fg = (long_u)0xffffffffL;
    curr_italic = MAYBE;
    curr_bold = MAYBE;
    curr_underline = MAYBE;

    prt_set_fg(PRCOLOR_BLACK);
    prt_set_bg(PRCOLOR_WHITE);
    prt_set_font(FALSE, FALSE, FALSE);
#ifdef FEAT_SYN_HL
    current_syn_id = -1;
#endif

    jobsplit = (printer_opts[OPT_PRINT_JOBSPLIT].present
	   && TOLOWER_ASC(printer_opts[OPT_PRINT_JOBSPLIT].string[0]) == 'y');

    if (!mch_print_begin(&settings))
	goto print_fail_no_begin;

    /*
     * Loop over collated copies: 1 2 3, 1 2 3, ...
     */
    page_count = 0;
    for (collated_copies = 0;
	    collated_copies < settings.n_collated_copies;
	    collated_copies++)
    {
	prt_pos_T	prtpos;		/* current print position */
	prt_pos_T	page_prtpos;	/* print position at page start */
	int		side;

	vim_memset(&page_prtpos, 0, sizeof(prt_pos_T));
	page_prtpos.file_line = eap->line1;
	prtpos = page_prtpos;

	if (jobsplit && collated_copies > 0)
	{
	    /* Splitting jobs: Stop a previous job and start a new one. */
	    mch_print_end(&settings);
	    if (!mch_print_begin(&settings))
		goto print_fail_no_begin;
	}

	/*
	 * Loop over all pages in the print job: 1 2 3 ...
	 */
	for (page_count = 0; prtpos.file_line <= eap->line2; ++page_count)
	{
	    /*
	     * Loop over uncollated copies: 1 1 1, 2 2 2, 3 3 3, ...
	     * For duplex: 12 12 12 34 34 34, ...
	     */
	    for (uncollated_copies = 0;
		    uncollated_copies < settings.n_uncollated_copies;
		    uncollated_copies++)
	    {
		/* Set the print position to the start of this page. */
		prtpos = page_prtpos;

		/*
		 * Do front and rear side of a page.
		 */
		for (side = 0; side <= settings.duplex; ++side)
		{
		    /*
		     * Print one page.
		     */

		    /* Check for interrupt character every page. */
		    ui_breakcheck();
		    if (got_int || settings.user_abort)
			goto print_fail;

		    sprintf((char *)IObuff, _("Printing page %d (%d%%)"),
			    page_count + 1 + side,
			    prtpos.bytes_printed > 1000000
				? (int)(prtpos.bytes_printed /
						       (bytes_to_print / 100))
				: (int)((prtpos.bytes_printed * 100)
							   / bytes_to_print));
		    if (!mch_print_begin_page(IObuff))
			goto print_fail;

		    if (settings.n_collated_copies > 1)
			sprintf((char *)IObuff + STRLEN(IObuff),
				_(" Copy %d of %d"),
				collated_copies + 1,
				settings.n_collated_copies);
		    prt_message(IObuff);

		    /*
		     * Output header if required
		     */
		    if (prt_header_height() > 0)
			prt_header(&settings, page_count + 1 + side,
							prtpos.file_line);

		    for (page_line = 0; page_line < settings.lines_per_page;
								  ++page_line)
		    {
			prtpos.column = hardcopy_line(&settings,
							   page_line, &prtpos);
			if (prtpos.column == 0)
			{
			    /* finished a file line */
			    prtpos.bytes_printed +=
				  STRLEN(skipwhite(ml_get(prtpos.file_line)));
			    if (++prtpos.file_line > eap->line2)
				break; /* reached the end */
			}
			else if (prtpos.ff)
			{
			    /* Line had a formfeed in it - start new page but
			     * stay on the current line */
			    break;
			}
		    }

		    if (!mch_print_end_page())
			goto print_fail;
		    if (prtpos.file_line > eap->line2)
			break; /* reached the end */
		}

		/*
		 * Extra blank page for duplexing with odd number of pages and
		 * more copies to come.
		 */
		if (prtpos.file_line > eap->line2 && settings.duplex
								 && side == 0
		    && uncollated_copies + 1 < settings.n_uncollated_copies)
		{
		    if (!mch_print_blank_page())
			goto print_fail;
		}
	    }
	    if (settings.duplex && prtpos.file_line <= eap->line2)
		++page_count;

	    /* Remember the position where the next page starts. */
	    page_prtpos = prtpos;
	}

	vim_snprintf((char *)IObuff, IOSIZE, _("Printed: %s"),
							    settings.jobname);
	prt_message(IObuff);
    }

print_fail:
    if (got_int || settings.user_abort)
    {
	sprintf((char *)IObuff, "%s", _("Printing aborted"));
	prt_message(IObuff);
    }
    mch_print_end(&settings);

print_fail_no_begin:
    mch_print_cleanup();
}

/*
 * Print one page line.
 * Return the next column to print, or zero if the line is finished.
 */
    static colnr_T
hardcopy_line(psettings, page_line, ppos)
    prt_settings_T	*psettings;
    int			page_line;
    prt_pos_T		*ppos;
{
    colnr_T	col;
    char_u	*line;
    int		need_break = FALSE;
    int		outputlen;
    int		tab_spaces;
    long_u	print_pos;
#ifdef FEAT_SYN_HL
    prt_text_attr_T attr;
    int		id;
#endif

    if (ppos->column == 0 || ppos->ff)
    {
	print_pos = 0;
	tab_spaces = 0;
	if (!ppos->ff && prt_use_number())
	    prt_line_number(psettings, page_line, ppos->file_line);
	ppos->ff = FALSE;
    }
    else
    {
	/* left over from wrap halfway a tab */
	print_pos = ppos->print_pos;
	tab_spaces = ppos->lead_spaces;
    }

    mch_print_start_line(0, page_line);
    line = ml_get(ppos->file_line);

    /*
     * Loop over the columns until the end of the file line or right margin.
     */
    for (col = ppos->column; line[col] != NUL && !need_break; col += outputlen)
    {
	outputlen = 1;
#ifdef FEAT_MBYTE
	if (has_mbyte && (outputlen = (*mb_ptr2len)(line + col)) < 1)
	    outputlen = 1;
#endif
#ifdef FEAT_SYN_HL
	/*
	 * syntax highlighting stuff.
	 */
	if (psettings->do_syntax)
	{
	    id = syn_get_id(curwin, ppos->file_line, col, 1, NULL, FALSE);
	    if (id > 0)
		id = syn_get_final_id(id);
	    else
		id = 0;
	    /* Get the line again, a multi-line regexp may invalidate it. */
	    line = ml_get(ppos->file_line);

	    if (id != current_syn_id)
	    {
		current_syn_id = id;
		prt_get_attr(id, &attr, psettings->modec);
		prt_set_font(attr.bold, attr.italic, attr.underline);
		prt_set_fg(attr.fg_color);
		prt_set_bg(attr.bg_color);
	    }
	}
#endif

	/*
	 * Appropriately expand any tabs to spaces.
	 */
	if (line[col] == TAB || tab_spaces != 0)
	{
	    if (tab_spaces == 0)
		tab_spaces = (int)(curbuf->b_p_ts - (print_pos % curbuf->b_p_ts));

	    while (tab_spaces > 0)
	    {
		need_break = mch_print_text_out((char_u *)" ", 1);
		print_pos++;
		tab_spaces--;
		if (need_break)
		    break;
	    }
	    /* Keep the TAB if we didn't finish it. */
	    if (need_break && tab_spaces > 0)
		break;
	}
	else if (line[col] == FF
		&& printer_opts[OPT_PRINT_FORMFEED].present
		&& TOLOWER_ASC(printer_opts[OPT_PRINT_FORMFEED].string[0])
								       == 'y')
	{
	    ppos->ff = TRUE;
	    need_break = 1;
	}
	else
	{
	    need_break = mch_print_text_out(line + col, outputlen);
#ifdef FEAT_MBYTE
	    if (has_mbyte)
		print_pos += (*mb_ptr2cells)(line + col);
	    else
#endif
		print_pos++;
	}
    }

    ppos->lead_spaces = tab_spaces;
    ppos->print_pos = (int)print_pos;

    /*
     * Start next line of file if we clip lines, or have reached end of the
     * line, unless we are doing a formfeed.
     */
    if (!ppos->ff
	    && (line[col] == NUL
		|| (printer_opts[OPT_PRINT_WRAP].present
		    && TOLOWER_ASC(printer_opts[OPT_PRINT_WRAP].string[0])
								     == 'n')))
	return 0;
    return col;
}

# if defined(FEAT_POSTSCRIPT) || defined(PROTO)

/*
 * PS printer stuff.
 *
 * Sources of information to help maintain the PS printing code:
 *
 * 1. PostScript Language Reference, 3rd Edition,
 *      Addison-Wesley, 1999, ISBN 0-201-37922-8
 * 2. PostScript Language Program Design,
 *      Addison-Wesley, 1988, ISBN 0-201-14396-8
 * 3. PostScript Tutorial and Cookbook,
 *      Addison Wesley, 1985, ISBN 0-201-10179-3
 * 4. PostScript Language Document Structuring Conventions Specification,
 *    version 3.0,
 *      Adobe Technote 5001, 25th September 1992
 * 5. PostScript Printer Description File Format Specification, Version 4.3,
 *      Adobe technote 5003, 9th February 1996
 * 6. Adobe Font Metrics File Format Specification, Version 4.1,
 *      Adobe Technote 5007, 7th October 1998
 * 7. Adobe CMap and CIDFont Files Specification, Version 1.0,
 *      Adobe Technote 5014, 8th October 1996
 * 8. Adobe CJKV Character Collections and CMaps for CID-Keyed Fonts,
 *      Adoboe Technote 5094, 8th September, 2001
 * 9. CJKV Information Processing, 2nd Edition,
 *      O'Reilly, 2002, ISBN 1-56592-224-7
 *
 * Some of these documents can be found in PDF form on Adobe's web site -
 * http://www.adobe.com
 */

#define NUM_ELEMENTS(arr)   (sizeof(arr)/sizeof((arr)[0]))

#define PRT_PS_DEFAULT_DPI	    (72)    /* Default user space resolution */
#define PRT_PS_DEFAULT_FONTSIZE     (10)
#define PRT_PS_DEFAULT_BUFFER_SIZE  (80)

struct prt_mediasize_S
{
    char	*name;
    float	width;		/* width and height in points for portrait */
    float	height;
};

#define PRT_MEDIASIZE_LEN  (sizeof(prt_mediasize) / sizeof(struct prt_mediasize_S))

static struct prt_mediasize_S prt_mediasize[] =
{
    {"A4",		595.0,  842.0},
    {"letter",		612.0,  792.0},
    {"10x14",		720.0, 1008.0},
    {"A3",		842.0, 1191.0},
    {"A5",		420.0,  595.0},
    {"B4",		729.0, 1032.0},
    {"B5",		516.0,  729.0},
    {"executive",	522.0,  756.0},
    {"folio",		595.0,  935.0},
    {"ledger",	       1224.0,  792.0},   /* Yes, it is wider than taller! */
    {"legal",		612.0, 1008.0},
    {"quarto",		610.0,  780.0},
    {"statement",	396.0,  612.0},
    {"tabloid",		792.0, 1224.0}
};

/* PS font names, must be in Roman, Bold, Italic, Bold-Italic order */
struct prt_ps_font_S
{
    int		wx;
    int		uline_offset;
    int		uline_width;
    int		bbox_min_y;
    int		bbox_max_y;
    char	*(ps_fontname[4]);
};

#define PRT_PS_FONT_ROMAN	(0)
#define PRT_PS_FONT_BOLD	(1)
#define PRT_PS_FONT_OBLIQUE	(2)
#define PRT_PS_FONT_BOLDOBLIQUE (3)

/* Standard font metrics for Courier family */
static struct prt_ps_font_S prt_ps_courier_font =
{
    600,
    -100, 50,
    -250, 805,
    {"Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique"}
};

#ifdef FEAT_MBYTE
/* Generic font metrics for multi-byte fonts */
static struct prt_ps_font_S prt_ps_mb_font =
{
    1000,
    -100, 50,
    -250, 805,
    {NULL, NULL, NULL, NULL}
};
#endif

/* Pointer to current font set being used */
static struct prt_ps_font_S* prt_ps_font;

/* Structures to map user named encoding and mapping to PS equivalents for
 * building CID font name */
struct prt_ps_encoding_S
{
    char	*encoding;
    char	*cmap_encoding;
    int		needs_charset;
};

struct prt_ps_charset_S
{
    char	*charset;
    char	*cmap_charset;
    int		has_charset;
};

#ifdef FEAT_MBYTE

#define CS_JIS_C_1978   (0x01)
#define CS_JIS_X_1983   (0x02)
#define CS_JIS_X_1990   (0x04)
#define CS_NEC		(0x08)
#define CS_MSWINDOWS	(0x10)
#define CS_CP932	(0x20)
#define CS_KANJITALK6	(0x40)
#define CS_KANJITALK7   (0x80)

/* Japanese encodings and charsets */
static struct prt_ps_encoding_S j_encodings[] =
{
    {"iso-2022-jp", NULL,       (CS_JIS_C_1978|CS_JIS_X_1983|CS_JIS_X_1990|
								    CS_NEC)},
    {"euc-jp",	    "EUC",	(CS_JIS_C_1978|CS_JIS_X_1983|CS_JIS_X_1990)},
    {"sjis",	    "RKSJ",	(CS_JIS_C_1978|CS_JIS_X_1983|CS_MSWINDOWS|
						CS_KANJITALK6|CS_KANJITALK7)},
    {"cp932",       "RKSJ",     CS_JIS_X_1983},
    {"ucs-2",       "UCS2",     CS_JIS_X_1990},
    {"utf-8",       "UTF8" ,    CS_JIS_X_1990}
};
static struct prt_ps_charset_S j_charsets[] =
{
    {"JIS_C_1978",  "78",       CS_JIS_C_1978},
    {"JIS_X_1983",  NULL,       CS_JIS_X_1983},
    {"JIS_X_1990",  "Hojo",     CS_JIS_X_1990},
    {"NEC",	    "Ext",	CS_NEC},
    {"MSWINDOWS",   "90ms",     CS_MSWINDOWS},
    {"CP932",       "90ms",     CS_JIS_X_1983},
    {"KANJITALK6",  "83pv",     CS_KANJITALK6},
    {"KANJITALK7",  "90pv",     CS_KANJITALK7}
};

#define CS_GB_2312_80       (0x01)
#define CS_GBT_12345_90     (0x02)
#define CS_GBK2K	    (0x04)
#define CS_SC_MAC	    (0x08)
#define CS_GBT_90_MAC	    (0x10)
#define CS_GBK		    (0x20)
#define CS_SC_ISO10646      (0x40)

/* Simplified Chinese encodings and charsets */
static struct prt_ps_encoding_S sc_encodings[] =
{
    {"iso-2022",    NULL,       (CS_GB_2312_80|CS_GBT_12345_90)},
    {"gb18030",     NULL,       CS_GBK2K},
    {"euc-cn",      "EUC",      (CS_GB_2312_80|CS_GBT_12345_90|CS_SC_MAC|
								CS_GBT_90_MAC)},
    {"gbk",	    "EUC",	CS_GBK},
    {"ucs-2",       "UCS2",     CS_SC_ISO10646},
    {"utf-8",       "UTF8",     CS_SC_ISO10646}
};
static struct prt_ps_charset_S sc_charsets[] =
{
    {"GB_2312-80",  "GB",       CS_GB_2312_80},
    {"GBT_12345-90","GBT",      CS_GBT_12345_90},
    {"MAC",	    "GBpc",	CS_SC_MAC},
    {"GBT-90_MAC",  "GBTpc",	CS_GBT_90_MAC},
    {"GBK",	    "GBK",	CS_GBK},
    {"GB18030",     "GBK2K",    CS_GBK2K},
    {"ISO10646",    "UniGB",    CS_SC_ISO10646}
};

#define CS_CNS_PLANE_1      (0x01)
#define CS_CNS_PLANE_2      (0x02)
#define CS_CNS_PLANE_1_2    (0x04)
#define CS_B5		    (0x08)
#define CS_ETEN		    (0x10)
#define CS_HK_GCCS	    (0x20)
#define CS_HK_SCS	    (0x40)
#define CS_HK_SCS_ETEN	    (0x80)
#define CS_MTHKL	    (0x100)
#define CS_MTHKS	    (0x200)
#define CS_DLHKL	    (0x400)
#define CS_DLHKS	    (0x800)
#define CS_TC_ISO10646	    (0x1000)

/* Traditional Chinese encodings and charsets */
static struct prt_ps_encoding_S tc_encodings[] =
{
    {"iso-2022",    NULL,       (CS_CNS_PLANE_1|CS_CNS_PLANE_2)},
    {"euc-tw",      "EUC",      CS_CNS_PLANE_1_2},
    {"big5",	    "B5",	(CS_B5|CS_ETEN|CS_HK_GCCS|CS_HK_SCS|
				    CS_HK_SCS_ETEN|CS_MTHKL|CS_MTHKS|CS_DLHKL|
								    CS_DLHKS)},
    {"cp950",       "B5",       CS_B5},
    {"ucs-2",       "UCS2",     CS_TC_ISO10646},
    {"utf-8",       "UTF8",     CS_TC_ISO10646},
    {"utf-16",      "UTF16",    CS_TC_ISO10646},
    {"utf-32",      "UTF32",    CS_TC_ISO10646}
};
static struct prt_ps_charset_S tc_charsets[] =
{
    {"CNS_1992_1",  "CNS1",     CS_CNS_PLANE_1},
    {"CNS_1992_2",  "CNS2",     CS_CNS_PLANE_2},
    {"CNS_1993",    "CNS",      CS_CNS_PLANE_1_2},
    {"BIG5",	    NULL,	CS_B5},
    {"CP950",	    NULL,	CS_B5},
    {"ETEN",	    "ETen",	CS_ETEN},
    {"HK_GCCS",     "HKgccs",	CS_HK_GCCS},
    {"SCS",	    "HKscs",	CS_HK_SCS},
    {"SCS_ETEN",    "ETHK",     CS_HK_SCS_ETEN},
    {"MTHKL",       "HKm471",   CS_MTHKL},
    {"MTHKS",       "HKm314",   CS_MTHKS},
    {"DLHKL",       "HKdla",    CS_DLHKL},
    {"DLHKS",       "HKdlb",    CS_DLHKS},
    {"ISO10646",    "UniCNS",   CS_TC_ISO10646}
};

#define CS_KR_X_1992	    (0x01)
#define CS_KR_MAC	    (0x02)
#define CS_KR_X_1992_MS     (0x04)
#define CS_KR_ISO10646      (0x08)

/* Korean encodings and charsets */
static struct prt_ps_encoding_S k_encodings[] =
{
    {"iso-2022-kr", NULL,       CS_KR_X_1992},
    {"euc-kr",      "EUC",      (CS_KR_X_1992|CS_KR_MAC)},
    {"johab",       "Johab",    CS_KR_X_1992},
    {"cp1361",      "Johab",    CS_KR_X_1992},
    {"uhc",	    "UHC",	CS_KR_X_1992_MS},
    {"cp949",       "UHC",      CS_KR_X_1992_MS},
    {"ucs-2",       "UCS2",     CS_KR_ISO10646},
    {"utf-8",       "UTF8",     CS_KR_ISO10646}
};
static struct prt_ps_charset_S k_charsets[] =
{
    {"KS_X_1992",   "KSC",      CS_KR_X_1992},
    {"CP1361",      "KSC",      CS_KR_X_1992},
    {"MAC",	    "KSCpc",	CS_KR_MAC},
    {"MSWINDOWS",   "KSCms",    CS_KR_X_1992_MS},
    {"CP949",       "KSCms",    CS_KR_X_1992_MS},
    {"WANSUNG",     "KSCms",    CS_KR_X_1992_MS},
    {"ISO10646",    "UniKS",    CS_KR_ISO10646}
};

/* Collections of encodings and charsets for multi-byte printing */
struct prt_ps_mbfont_S
{
    int				num_encodings;
    struct prt_ps_encoding_S	*encodings;
    int				num_charsets;
    struct prt_ps_charset_S	*charsets;
    char			*ascii_enc;
    char			*defcs;
};

static struct prt_ps_mbfont_S prt_ps_mbfonts[] =
{
    {
	NUM_ELEMENTS(j_encodings),
	j_encodings,
	NUM_ELEMENTS(j_charsets),
	j_charsets,
	"jis_roman",
	"JIS_X_1983"
    },
    {
	NUM_ELEMENTS(sc_encodings),
	sc_encodings,
	NUM_ELEMENTS(sc_charsets),
	sc_charsets,
	"gb_roman",
	"GB_2312-80"
    },
    {
	NUM_ELEMENTS(tc_encodings),
	tc_encodings,
	NUM_ELEMENTS(tc_charsets),
	tc_charsets,
	"cns_roman",
	"BIG5"
    },
    {
	NUM_ELEMENTS(k_encodings),
	k_encodings,
	NUM_ELEMENTS(k_charsets),
	k_charsets,
	"ks_roman",
	"KS_X_1992"
    }
};
#endif /* FEAT_MBYTE */

struct prt_ps_resource_S
{
    char_u  name[64];
    char_u  filename[MAXPATHL + 1];
    int     type;
    char_u  title[256];
    char_u  version[256];
};

/* Types of PS resource file currently used */
#define PRT_RESOURCE_TYPE_PROCSET   (0)
#define PRT_RESOURCE_TYPE_ENCODING  (1)
#define PRT_RESOURCE_TYPE_CMAP      (2)

/* The PS prolog file version number has to match - if the prolog file is
 * updated, increment the number in the file and here.  Version checking was
 * added as of VIM 6.2.
 * The CID prolog file version number behaves as per PS prolog.
 * Table of VIM and prolog versions:
 *
 * VIM      Prolog  CIDProlog
 * 6.2      1.3
 * 7.0      1.4	    1.0
 */
#define PRT_PROLOG_VERSION  ((char_u *)"1.4")
#define PRT_CID_PROLOG_VERSION  ((char_u *)"1.0")

/* String versions of PS resource types - indexed by constants above so don't
 * re-order!
 */
static char *prt_resource_types[] =
{
    "procset",
    "encoding",
    "cmap"
};

/* Strings to look for in a PS resource file */
#define PRT_RESOURCE_HEADER	    "%!PS-Adobe-"
#define PRT_RESOURCE_RESOURCE	    "Resource-"
#define PRT_RESOURCE_PROCSET	    "ProcSet"
#define PRT_RESOURCE_ENCODING	    "Encoding"
#define PRT_RESOURCE_CMAP	    "CMap"


/* Data for table based DSC comment recognition, easy to extend if VIM needs to
 * read more comments. */
#define PRT_DSC_MISC_TYPE	    (-1)
#define PRT_DSC_TITLE_TYPE	    (1)
#define PRT_DSC_VERSION_TYPE	    (2)
#define PRT_DSC_ENDCOMMENTS_TYPE    (3)

#define PRT_DSC_TITLE		    "%%Title:"
#define PRT_DSC_VERSION		    "%%Version:"
#define PRT_DSC_ENDCOMMENTS	    "%%EndComments:"

struct prt_dsc_comment_S
{
    char	*string;
    int		len;
    int		type;
};

struct prt_dsc_line_S
{
    int		type;
    char_u	*string;
    int		len;
};


#define SIZEOF_CSTR(s)      (sizeof(s) - 1)
static struct prt_dsc_comment_S prt_dsc_table[] =
{
    {PRT_DSC_TITLE,       SIZEOF_CSTR(PRT_DSC_TITLE),     PRT_DSC_TITLE_TYPE},
    {PRT_DSC_VERSION,     SIZEOF_CSTR(PRT_DSC_VERSION),
							PRT_DSC_VERSION_TYPE},
    {PRT_DSC_ENDCOMMENTS, SIZEOF_CSTR(PRT_DSC_ENDCOMMENTS),
						     PRT_DSC_ENDCOMMENTS_TYPE}
};

static void prt_write_file_raw_len __ARGS((char_u *buffer, int bytes));
static void prt_write_file __ARGS((char_u *buffer));
static void prt_write_file_len __ARGS((char_u *buffer, int bytes));
static void prt_write_string __ARGS((char *s));
static void prt_write_int __ARGS((int i));
static void prt_write_boolean __ARGS((int b));
static void prt_def_font __ARGS((char *new_name, char *encoding, int height, char *font));
static void prt_real_bits __ARGS((double real, int precision, int *pinteger, int *pfraction));
static void prt_write_real __ARGS((double val, int prec));
static void prt_def_var __ARGS((char *name, double value, int prec));
static void prt_flush_buffer __ARGS((void));
static void prt_resource_name __ARGS((char_u *filename, void *cookie));
static int prt_find_resource __ARGS((char *name, struct prt_ps_resource_S *resource));
static int prt_open_resource __ARGS((struct prt_ps_resource_S *resource));
static int prt_check_resource __ARGS((struct prt_ps_resource_S *resource, char_u *version));
static void prt_dsc_start __ARGS((void));
static void prt_dsc_noarg __ARGS((char *comment));
static void prt_dsc_textline __ARGS((char *comment, char *text));
static void prt_dsc_text __ARGS((char *comment, char *text));
static void prt_dsc_ints __ARGS((char *comment, int count, int *ints));
static void prt_dsc_requirements __ARGS((int duplex, int tumble, int collate, int color, int num_copies));
static void prt_dsc_docmedia __ARGS((char *paper_name, double width, double height, double weight, char *colour, char *type));
static void prt_dsc_resources __ARGS((char *comment, char *type, char *strings));
static void prt_dsc_font_resource __ARGS((char *resource, struct prt_ps_font_S *ps_font));
static float to_device_units __ARGS((int idx, double physsize, int def_number));
static void prt_page_margins __ARGS((double width, double height, double *left, double *right, double *top, double *bottom));
static void prt_font_metrics __ARGS((int font_scale));
static int prt_get_cpl __ARGS((void));
static int prt_get_lpp __ARGS((void));
static int prt_add_resource __ARGS((struct prt_ps_resource_S *resource));
static int prt_resfile_next_line __ARGS((void));
static int prt_resfile_strncmp __ARGS((int offset, char *string, int len));
static int prt_resfile_skip_nonws __ARGS((int offset));
static int prt_resfile_skip_ws __ARGS((int offset));
static int prt_next_dsc __ARGS((struct prt_dsc_line_S *p_dsc_line));
#ifdef FEAT_MBYTE
static int prt_build_cid_fontname __ARGS((int font, char_u *name, int name_len));
static void prt_def_cidfont __ARGS((char *new_name, int height, char *cidfont));
static void prt_dup_cidfont __ARGS((char *original_name, char *new_name));
static int prt_match_encoding __ARGS((char *p_encoding, struct prt_ps_mbfont_S *p_cmap, struct prt_ps_encoding_S **pp_mbenc));
static int prt_match_charset __ARGS((char *p_charset, struct prt_ps_mbfont_S *p_cmap, struct prt_ps_charset_S **pp_mbchar));
#endif

/*
 * Variables for the output PostScript file.
 */
static FILE *prt_ps_fd;
static int prt_file_error;
static char_u *prt_ps_file_name = NULL;

/*
 * Various offsets and dimensions in default PostScript user space (points).
 * Used for text positioning calculations
 */
static float prt_page_width;
static float prt_page_height;
static float prt_left_margin;
static float prt_right_margin;
static float prt_top_margin;
static float prt_bottom_margin;
static float prt_line_height;
static float prt_first_line_height;
static float prt_char_width;
static float prt_number_width;
static float prt_bgcol_offset;
static float prt_pos_x_moveto = 0.0;
static float prt_pos_y_moveto = 0.0;

/*
 * Various control variables used to decide when and how to change the
 * PostScript graphics state.
 */
static int prt_need_moveto;
static int prt_do_moveto;
static int prt_need_font;
static int prt_font;
static int prt_need_underline;
static int prt_underline;
static int prt_do_underline;
static int prt_need_fgcol;
static int prt_fgcol;
static int prt_need_bgcol;
static int prt_do_bgcol;
static int prt_bgcol;
static int prt_new_bgcol;
static int prt_attribute_change;
static float prt_text_run;
static int prt_page_num;
static int prt_bufsiz;

/*
 * Variables controlling physical printing.
 */
static int prt_media;
static int prt_portrait;
static int prt_num_copies;
static int prt_duplex;
static int prt_tumble;
static int prt_collate;

/*
 * Buffers used when generating PostScript output
 */
static char_u prt_line_buffer[257];
static garray_T prt_ps_buffer;

# ifdef FEAT_MBYTE
static int prt_do_conv;
static vimconv_T prt_conv;

static int prt_out_mbyte;
static int prt_custom_cmap;
static char prt_cmap[80];
static int prt_use_courier;
static int prt_in_ascii;
static int prt_half_width;
static char *prt_ascii_encoding;
static char_u prt_hexchar[] = "0123456789abcdef";
# endif

    static void
prt_write_file_raw_len(buffer, bytes)
    char_u	*buffer;
    int		bytes;
{
    if (!prt_file_error
	    && fwrite(buffer, sizeof(char_u), bytes, prt_ps_fd)
							     != (size_t)bytes)
    {
	EMSG(_("E455: Error writing to PostScript output file"));
	prt_file_error = TRUE;
    }
}

    static void
prt_write_file(buffer)
    char_u	*buffer;
{
    prt_write_file_len(buffer, (int)STRLEN(buffer));
}

    static void
prt_write_file_len(buffer, bytes)
    char_u	*buffer;
    int		bytes;
{
#ifdef EBCDIC
    ebcdic2ascii(buffer, bytes);
#endif
    prt_write_file_raw_len(buffer, bytes);
}

/*
 * Write a string.
 */
    static void
prt_write_string(s)
    char	*s;
{
    vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "%s", s);
    prt_write_file(prt_line_buffer);
}

/*
 * Write an int and a space.
 */
    static void
prt_write_int(i)
    int		i;
{
    sprintf((char *)prt_line_buffer, "%d ", i);
    prt_write_file(prt_line_buffer);
}

/*
 * Write a boolean and a space.
 */
    static void
prt_write_boolean(b)
    int		b;
{
    sprintf((char *)prt_line_buffer, "%s ", (b ? "T" : "F"));
    prt_write_file(prt_line_buffer);
}

/*
 * Write PostScript to re-encode and define the font.
 */
    static void
prt_def_font(new_name, encoding, height, font)
    char	*new_name;
    char	*encoding;
    int		height;
    char	*font;
{
    vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
			  "/_%s /VIM-%s /%s ref\n", new_name, encoding, font);
    prt_write_file(prt_line_buffer);
#ifdef FEAT_MBYTE
    if (prt_out_mbyte)
	sprintf((char *)prt_line_buffer, "/%s %d %f /_%s sffs\n",
		       new_name, height, 500./prt_ps_courier_font.wx, new_name);
    else
#endif
	vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
			     "/%s %d /_%s ffs\n", new_name, height, new_name);
    prt_write_file(prt_line_buffer);
}

#ifdef FEAT_MBYTE
/*
 * Write a line to define the CID font.
 */
    static void
prt_def_cidfont(new_name, height, cidfont)
    char	*new_name;
    int		height;
    char	*cidfont;
{
    vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
	      "/_%s /%s[/%s] vim_composefont\n", new_name, prt_cmap, cidfont);
    prt_write_file(prt_line_buffer);
    vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
			     "/%s %d /_%s ffs\n", new_name, height, new_name);
    prt_write_file(prt_line_buffer);
}

/*
 * Write a line to define a duplicate of a CID font
 */
    static void
prt_dup_cidfont(original_name, new_name)
    char	*original_name;
    char	*new_name;
{
    vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
				       "/%s %s d\n", new_name, original_name);
    prt_write_file(prt_line_buffer);
}
#endif

/*
 * Convert a real value into an integer and fractional part as integers, with
 * the fractional part being in the range [0,10^precision).  The fractional part
 * is also rounded based on the precision + 1'th fractional digit.
 */
    static void
prt_real_bits(real, precision, pinteger, pfraction)
    double      real;
    int		precision;
    int		*pinteger;
    int		*pfraction;
{
    int     i;
    int     integer;
    float   fraction;

    integer = (int)real;
    fraction = (float)(real - integer);
    if (real < (double)integer)
	fraction = -fraction;
    for (i = 0; i < precision; i++)
	fraction *= 10.0;

    *pinteger = integer;
    *pfraction = (int)(fraction + 0.5);
}

/*
 * Write a real and a space.  Save bytes if real value has no fractional part!
 * We use prt_real_bits() as %f in sprintf uses the locale setting to decide
 * what decimal point character to use, but PS always requires a '.'.
 */
    static void
prt_write_real(val, prec)
    double	val;
    int		prec;
{
    int     integer;
    int     fraction;

    prt_real_bits(val, prec, &integer, &fraction);
    /* Emit integer part */
    sprintf((char *)prt_line_buffer, "%d", integer);
    prt_write_file(prt_line_buffer);
    /* Only emit fraction if necessary */
    if (fraction != 0)
    {
	/* Remove any trailing zeros */
	while ((fraction % 10) == 0)
	{
	    prec--;
	    fraction /= 10;
	}
	/* Emit fraction left padded with zeros */
	sprintf((char *)prt_line_buffer, ".%0*d", prec, fraction);
	prt_write_file(prt_line_buffer);
    }
    sprintf((char *)prt_line_buffer, " ");
    prt_write_file(prt_line_buffer);
}

/*
 * Write a line to define a numeric variable.
 */
    static void
prt_def_var(name, value, prec)
    char	*name;
    double	value;
    int		prec;
{
    vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
								"/%s ", name);
    prt_write_file(prt_line_buffer);
    prt_write_real(value, prec);
    sprintf((char *)prt_line_buffer, "d\n");
    prt_write_file(prt_line_buffer);
}

/* Convert size from font space to user space at current font scale */
#define PRT_PS_FONT_TO_USER(scale, size)    ((size) * ((scale)/1000.0))

    static void
prt_flush_buffer()
{
    if (prt_ps_buffer.ga_len > 0)
    {
	/* Any background color must be drawn first */
	if (prt_do_bgcol && (prt_new_bgcol != PRCOLOR_WHITE))
	{
	    int     r, g, b;

	    if (prt_do_moveto)
	    {
		prt_write_real(prt_pos_x_moveto, 2);
		prt_write_real(prt_pos_y_moveto, 2);
		prt_write_string("m\n");
		prt_do_moveto = FALSE;
	    }

	    /* Size of rect of background color on which text is printed */
	    prt_write_real(prt_text_run, 2);
	    prt_write_real(prt_line_height, 2);

	    /* Lastly add the color of the background */
	    r = ((unsigned)prt_new_bgcol & 0xff0000) >> 16;
	    g = ((unsigned)prt_new_bgcol & 0xff00) >> 8;
	    b = prt_new_bgcol & 0xff;
	    prt_write_real(r / 255.0, 3);
	    prt_write_real(g / 255.0, 3);
	    prt_write_real(b / 255.0, 3);
	    prt_write_string("bg\n");
	}
	/* Draw underlines before the text as it makes it slightly easier to
	 * find the starting point.
	 */
	if (prt_do_underline)
	{
	    if (prt_do_moveto)
	    {
		prt_write_real(prt_pos_x_moveto, 2);
		prt_write_real(prt_pos_y_moveto, 2);
		prt_write_string("m\n");
		prt_do_moveto = FALSE;
	    }

	    /* Underline length of text run */
	    prt_write_real(prt_text_run, 2);
	    prt_write_string("ul\n");
	}
	/* Draw the text
	 * Note: we write text out raw - EBCDIC conversion is handled in the
	 * PostScript world via the font encoding vector. */
#ifdef FEAT_MBYTE
	if (prt_out_mbyte)
	    prt_write_string("<");
	else
#endif
	    prt_write_string("(");
	prt_write_file_raw_len(prt_ps_buffer.ga_data, prt_ps_buffer.ga_len);
#ifdef FEAT_MBYTE
	if (prt_out_mbyte)
	    prt_write_string(">");
	else
#endif
	    prt_write_string(")");
	/* Add a moveto if need be and use the appropriate show procedure */
	if (prt_do_moveto)
	{
	    prt_write_real(prt_pos_x_moveto, 2);
	    prt_write_real(prt_pos_y_moveto, 2);
	    /* moveto and a show */
	    prt_write_string("ms\n");
	    prt_do_moveto = FALSE;
	}
	else /* Simple show */
	    prt_write_string("s\n");

	ga_clear(&prt_ps_buffer);
	ga_init2(&prt_ps_buffer, (int)sizeof(char), prt_bufsiz);
    }
}


    static void
prt_resource_name(filename, cookie)
    char_u  *filename;
    void    *cookie;
{
    char_u *resource_filename = cookie;

    if (STRLEN(filename) >= MAXPATHL)
	*resource_filename = NUL;
    else
	STRCPY(resource_filename, filename);
}

    static int
prt_find_resource(name, resource)
    char	*name;
    struct prt_ps_resource_S *resource;
{
    char_u	*buffer;
    int		retval;

    buffer = alloc(MAXPATHL + 1);
    if (buffer == NULL)
	return FALSE;

    vim_strncpy(resource->name, (char_u *)name, 63);
    /* Look for named resource file in runtimepath */
    STRCPY(buffer, "print");
    add_pathsep(buffer);
    vim_strcat(buffer, (char_u *)name, MAXPATHL);
    vim_strcat(buffer, (char_u *)".ps", MAXPATHL);
    resource->filename[0] = NUL;
    retval = (do_in_runtimepath(buffer, FALSE, prt_resource_name,
							   resource->filename)
	    && resource->filename[0] != NUL);
    vim_free(buffer);
    return retval;
}

/* PS CR and LF characters have platform independent values */
#define PSLF  (0x0a)
#define PSCR  (0x0d)

/* Static buffer to read initial comments in a resource file, some can have a
 * couple of KB of comments! */
#define PRT_FILE_BUFFER_LEN (2048)
struct prt_resfile_buffer_S
{
    char_u  buffer[PRT_FILE_BUFFER_LEN];
    int     len;
    int     line_start;
    int     line_end;
};

static struct prt_resfile_buffer_S prt_resfile;

    static int
prt_resfile_next_line()
{
    int     idx;

    /* Move to start of next line and then find end of line */
    idx = prt_resfile.line_end + 1;
    while (idx < prt_resfile.len)
    {
	if (prt_resfile.buffer[idx] != PSLF && prt_resfile.buffer[idx] != PSCR)
	    break;
	idx++;
    }
    prt_resfile.line_start = idx;

    while (idx < prt_resfile.len)
    {
	if (prt_resfile.buffer[idx] == PSLF || prt_resfile.buffer[idx] == PSCR)
	    break;
	idx++;
    }
    prt_resfile.line_end = idx;

    return (idx < prt_resfile.len);
}

    static int
prt_resfile_strncmp(offset, string, len)
    int     offset;
    char    *string;
    int     len;
{
    /* Force not equal if string is longer than remainder of line */
    if (len > (prt_resfile.line_end - (prt_resfile.line_start + offset)))
	return 1;

    return STRNCMP(&prt_resfile.buffer[prt_resfile.line_start + offset],
								string, len);
}

    static int
prt_resfile_skip_nonws(offset)
    int     offset;
{
    int     idx;

    idx = prt_resfile.line_start + offset;
    while (idx < prt_resfile.line_end)
    {
	if (isspace(prt_resfile.buffer[idx]))
	    return idx - prt_resfile.line_start;
	idx++;
    }
    return -1;
}

    static int
prt_resfile_skip_ws(offset)
    int     offset;
{
    int     idx;

    idx = prt_resfile.line_start + offset;
    while (idx < prt_resfile.line_end)
    {
	if (!isspace(prt_resfile.buffer[idx]))
	    return idx - prt_resfile.line_start;
	idx++;
    }
    return -1;
}

/* prt_next_dsc() - returns detail on next DSC comment line found.  Returns true
 * if a DSC comment is found, else false */
    static int
prt_next_dsc(p_dsc_line)
    struct prt_dsc_line_S *p_dsc_line;
{
    int     comment;
    int     offset;

    /* Move to start of next line */
    if (!prt_resfile_next_line())
	return FALSE;

    /* DSC comments always start %% */
    if (prt_resfile_strncmp(0, "%%", 2) != 0)
	return FALSE;

    /* Find type of DSC comment */
    for (comment = 0; comment < (int)NUM_ELEMENTS(prt_dsc_table); comment++)
	if (prt_resfile_strncmp(0, prt_dsc_table[comment].string,
					    prt_dsc_table[comment].len) == 0)
	    break;

    if (comment != NUM_ELEMENTS(prt_dsc_table))
    {
	/* Return type of comment */
	p_dsc_line->type = prt_dsc_table[comment].type;
	offset = prt_dsc_table[comment].len;
    }
    else
    {
	/* Unrecognised DSC comment, skip to ws after comment leader */
	p_dsc_line->type = PRT_DSC_MISC_TYPE;
	offset = prt_resfile_skip_nonws(0);
	if (offset == -1)
	    return FALSE;
    }

    /* Skip ws to comment value */
    offset = prt_resfile_skip_ws(offset);
    if (offset == -1)
	return FALSE;

    p_dsc_line->string = &prt_resfile.buffer[prt_resfile.line_start + offset];
    p_dsc_line->len = prt_resfile.line_end - (prt_resfile.line_start + offset);

    return TRUE;
}

/* Improved hand crafted parser to get the type, title, and version number of a
 * PS resource file so the file details can be added to the DSC header comments.
 */
    static int
prt_open_resource(resource)
    struct prt_ps_resource_S *resource;
{
    int		offset;
    int		seen_all;
    int		seen_title;
    int		seen_version;
    FILE	*fd_resource;
    struct prt_dsc_line_S dsc_line;

    fd_resource = mch_fopen((char *)resource->filename, READBIN);
    if (fd_resource == NULL)
    {
	EMSG2(_("E624: Can't open file \"%s\""), resource->filename);
	return FALSE;
    }
    vim_memset(prt_resfile.buffer, NUL, PRT_FILE_BUFFER_LEN);

    /* Parse first line to ensure valid resource file */
    prt_resfile.len = (int)fread((char *)prt_resfile.buffer, sizeof(char_u),
					    PRT_FILE_BUFFER_LEN, fd_resource);
    if (ferror(fd_resource))
    {
	EMSG2(_("E457: Can't read PostScript resource file \"%s\""),
		resource->filename);
	fclose(fd_resource);
	return FALSE;
    }
    fclose(fd_resource);

    prt_resfile.line_end = -1;
    prt_resfile.line_start = 0;
    if (!prt_resfile_next_line())
	return FALSE;

    offset = 0;

    if (prt_resfile_strncmp(offset, PRT_RESOURCE_HEADER,
				       (int)STRLEN(PRT_RESOURCE_HEADER)) != 0)
    {
	EMSG2(_("E618: file \"%s\" is not a PostScript resource file"),
		resource->filename);
	return FALSE;
    }

    /* Skip over any version numbers and following ws */
    offset += (int)STRLEN(PRT_RESOURCE_HEADER);
    offset = prt_resfile_skip_nonws(offset);
    if (offset == -1)
	return FALSE;
    offset = prt_resfile_skip_ws(offset);
    if (offset == -1)
	return FALSE;

    if (prt_resfile_strncmp(offset, PRT_RESOURCE_RESOURCE,
				     (int)STRLEN(PRT_RESOURCE_RESOURCE)) != 0)
    {
	EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"),
		resource->filename);
	return FALSE;
    }
    offset += (int)STRLEN(PRT_RESOURCE_RESOURCE);

    /* Decide type of resource in the file */
    if (prt_resfile_strncmp(offset, PRT_RESOURCE_PROCSET,
				      (int)STRLEN(PRT_RESOURCE_PROCSET)) == 0)
	resource->type = PRT_RESOURCE_TYPE_PROCSET;
    else if (prt_resfile_strncmp(offset, PRT_RESOURCE_ENCODING,
				     (int)STRLEN(PRT_RESOURCE_ENCODING)) == 0)
	resource->type = PRT_RESOURCE_TYPE_ENCODING;
    else if (prt_resfile_strncmp(offset, PRT_RESOURCE_CMAP,
					 (int)STRLEN(PRT_RESOURCE_CMAP)) == 0)
	resource->type = PRT_RESOURCE_TYPE_CMAP;
    else
    {
	EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"),
		resource->filename);
	return FALSE;
    }

    /* Look for title and version of resource */
    resource->title[0] = '\0';
    resource->version[0] = '\0';
    seen_title = FALSE;
    seen_version = FALSE;
    seen_all = FALSE;
    while (!seen_all && prt_next_dsc(&dsc_line))
    {
	switch (dsc_line.type)
	{
	case PRT_DSC_TITLE_TYPE:
	    vim_strncpy(resource->title, dsc_line.string, dsc_line.len);
	    seen_title = TRUE;
	    if (seen_version)
		seen_all = TRUE;
	    break;

	case PRT_DSC_VERSION_TYPE:
	    vim_strncpy(resource->version, dsc_line.string, dsc_line.len);
	    seen_version = TRUE;
	    if (seen_title)
		seen_all = TRUE;
	    break;

	case PRT_DSC_ENDCOMMENTS_TYPE:
	    /* Wont find title or resource after this comment, stop searching */
	    seen_all = TRUE;
	    break;

	case PRT_DSC_MISC_TYPE:
	    /* Not interested in whatever comment this line had */
	    break;
	}
    }

    if (!seen_title || !seen_version)
    {
	EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"),
		resource->filename);
	return FALSE;
    }

    return TRUE;
}

    static int
prt_check_resource(resource, version)
    struct prt_ps_resource_S *resource;
    char_u  *version;
{
    /* Version number m.n should match, the revision number does not matter */
    if (STRNCMP(resource->version, version, STRLEN(version)))
    {
	EMSG2(_("E621: \"%s\" resource file has wrong version"),
		resource->name);
	return FALSE;
    }

    /* Other checks to be added as needed */
    return TRUE;
}

    static void
prt_dsc_start()
{
    prt_write_string("%!PS-Adobe-3.0\n");
}

    static void
prt_dsc_noarg(comment)
    char	*comment;
{
    vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
							 "%%%%%s\n", comment);
    prt_write_file(prt_line_buffer);
}

    static void
prt_dsc_textline(comment, text)
    char	*comment;
    char	*text;
{
    vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
					       "%%%%%s: %s\n", comment, text);
    prt_write_file(prt_line_buffer);
}

    static void
prt_dsc_text(comment, text)
    char	*comment;
    char	*text;
{
    /* TODO - should scan 'text' for any chars needing escaping! */
    vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
					     "%%%%%s: (%s)\n", comment, text);
    prt_write_file(prt_line_buffer);
}

#define prt_dsc_atend(c)	prt_dsc_text((c), "atend")

    static void
prt_dsc_ints(comment, count, ints)
    char	*comment;
    int		count;
    int		*ints;
{
    int		i;

    vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
							  "%%%%%s:", comment);
    prt_write_file(prt_line_buffer);

    for (i = 0; i < count; i++)
    {
	sprintf((char *)prt_line_buffer, " %d", ints[i]);
	prt_write_file(prt_line_buffer);
    }

    prt_write_string("\n");
}

    static void
prt_dsc_resources(comment, type, string)
    char	*comment;	/* if NULL add to previous */
    char	*type;
    char	*string;
{
    if (comment != NULL)
	vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
						 "%%%%%s: %s", comment, type);
    else
	vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
							    "%%%%+ %s", type);
    prt_write_file(prt_line_buffer);

    vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
							     " %s\n", string);
    prt_write_file(prt_line_buffer);
}

    static void
prt_dsc_font_resource(resource, ps_font)
    char	*resource;
    struct prt_ps_font_S *ps_font;
{
    int     i;

    prt_dsc_resources(resource, "font",
				    ps_font->ps_fontname[PRT_PS_FONT_ROMAN]);
    for (i = PRT_PS_FONT_BOLD ; i <= PRT_PS_FONT_BOLDOBLIQUE ; i++)
	if (ps_font->ps_fontname[i] != NULL)
	    prt_dsc_resources(NULL, "font", ps_font->ps_fontname[i]);
}

    static void
prt_dsc_requirements(duplex, tumble, collate, color, num_copies)
    int		duplex;
    int		tumble;
    int		collate;
    int		color;
    int		num_copies;
{
    /* Only output the comment if we need to.
     * Note: tumble is ignored if we are not duplexing
     */
    if (!(duplex || collate || color || (num_copies > 1)))
	return;

    sprintf((char *)prt_line_buffer, "%%%%Requirements:");
    prt_write_file(prt_line_buffer);

    if (duplex)
    {
	prt_write_string(" duplex");
	if (tumble)
	    prt_write_string("(tumble)");
    }
    if (collate)
	prt_write_string(" collate");
    if (color)
	prt_write_string(" color");
    if (num_copies > 1)
    {
	prt_write_string(" numcopies(");
	/* Note: no space wanted so don't use prt_write_int() */
	sprintf((char *)prt_line_buffer, "%d", num_copies);
	prt_write_file(prt_line_buffer);
	prt_write_string(")");
    }
    prt_write_string("\n");
}

    static void
prt_dsc_docmedia(paper_name, width, height, weight, colour, type)
    char	*paper_name;
    double	width;
    double	height;
    double	weight;
    char	*colour;
    char	*type;
{
    vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
					"%%%%DocumentMedia: %s ", paper_name);
    prt_write_file(prt_line_buffer);
    prt_write_real(width, 2);
    prt_write_real(height, 2);
    prt_write_real(weight, 2);
    if (colour == NULL)
	prt_write_string("()");
    else
	prt_write_string(colour);
    prt_write_string(" ");
    if (type == NULL)
	prt_write_string("()");
    else
	prt_write_string(type);
    prt_write_string("\n");
}

    void
mch_print_cleanup()
{
#ifdef FEAT_MBYTE
    if (prt_out_mbyte)
    {
	int     i;

	/* Free off all CID font names created, but first clear duplicate
	 * pointers to the same string (when the same font is used for more than
	 * one style).
	 */
	for (i = PRT_PS_FONT_ROMAN; i <= PRT_PS_FONT_BOLDOBLIQUE; i++)
	{
	    if (prt_ps_mb_font.ps_fontname[i] != NULL)
		vim_free(prt_ps_mb_font.ps_fontname[i]);
	    prt_ps_mb_font.ps_fontname[i] = NULL;
	}
    }

    if (prt_do_conv)
    {
	convert_setup(&prt_conv, NULL, NULL);
	prt_do_conv = FALSE;
    }
#endif
    if (prt_ps_fd != NULL)
    {
	fclose(prt_ps_fd);
	prt_ps_fd = NULL;
	prt_file_error = FALSE;
    }
    if (prt_ps_file_name != NULL)
    {
	vim_free(prt_ps_file_name);
	prt_ps_file_name = NULL;
    }
}

    static float
to_device_units(idx, physsize, def_number)
    int		idx;
    double	physsize;
    int		def_number;
{
    float	ret;
    int		u;
    int		nr;

    u = prt_get_unit(idx);
    if (u == PRT_UNIT_NONE)
    {
	u = PRT_UNIT_PERC;
	nr = def_number;
    }
    else
	nr = printer_opts[idx].number;

    switch (u)
    {
	case PRT_UNIT_INCH:
	    ret = (float)(nr * PRT_PS_DEFAULT_DPI);
	    break;
	case PRT_UNIT_MM:
	    ret = (float)(nr * PRT_PS_DEFAULT_DPI) / (float)25.4;
	    break;
	case PRT_UNIT_POINT:
	    ret = (float)nr;
	    break;
	case PRT_UNIT_PERC:
	default:
	    ret = (float)(physsize * nr) / 100;
	    break;
    }

    return ret;
}

/*
 * Calculate margins for given width and height from printoptions settings.
 */
    static void
prt_page_margins(width, height, left, right, top, bottom)
    double	width;
    double	height;
    double	*left;
    double	*right;
    double	*top;
    double	*bottom;
{
    *left   = to_device_units(OPT_PRINT_LEFT, width, 10);
    *right  = width - to_device_units(OPT_PRINT_RIGHT, width, 5);
    *top    = height - to_device_units(OPT_PRINT_TOP, height, 5);
    *bottom = to_device_units(OPT_PRINT_BOT, height, 5);
}

    static void
prt_font_metrics(font_scale)
    int		font_scale;
{
    prt_line_height = (float)font_scale;
    prt_char_width = (float)PRT_PS_FONT_TO_USER(font_scale, prt_ps_font->wx);
}


    static int
prt_get_cpl()
{
    if (prt_use_number())
    {
	prt_number_width = PRINT_NUMBER_WIDTH * prt_char_width;
#ifdef FEAT_MBYTE
	/* If we are outputting multi-byte characters then line numbers will be
	 * printed with half width characters
	 */
	if (prt_out_mbyte)
	    prt_number_width /= 2;
#endif
	prt_left_margin += prt_number_width;
    }
    else
	prt_number_width = 0.0;

    return (int)((prt_right_margin - prt_left_margin) / prt_char_width);
}

#ifdef FEAT_MBYTE
    static int
prt_build_cid_fontname(font, name, name_len)
    int     font;
    char_u  *name;
    int     name_len;
{
    char    *fontname;

    fontname = (char *)alloc(name_len + 1);
    if (fontname == NULL)
	return FALSE;
    vim_strncpy((char_u *)fontname, name, name_len);
    prt_ps_mb_font.ps_fontname[font] = fontname;

    return TRUE;
}
#endif

/*
 * Get number of lines of text that fit on a page (excluding the header).
 */
    static int
prt_get_lpp()
{
    int lpp;

    /*
     * Calculate offset to lower left corner of background rect based on actual
     * font height (based on its bounding box) and the line height, handling the
     * case where the font height can exceed the line height.
     */
    prt_bgcol_offset = (float)PRT_PS_FONT_TO_USER(prt_line_height,
					   prt_ps_font->bbox_min_y);
    if ((prt_ps_font->bbox_max_y - prt_ps_font->bbox_min_y) < 1000.0)
    {
	prt_bgcol_offset -= (float)PRT_PS_FONT_TO_USER(prt_line_height,
				(1000.0 - (prt_ps_font->bbox_max_y -
					    prt_ps_font->bbox_min_y)) / 2);
    }

    /* Get height for topmost line based on background rect offset. */
    prt_first_line_height = prt_line_height + prt_bgcol_offset;

    /* Calculate lpp */
    lpp = (int)((prt_top_margin - prt_bottom_margin) / prt_line_height);

    /* Adjust top margin if there is a header */
    prt_top_margin -= prt_line_height * prt_header_height();

    return lpp - prt_header_height();
}

#ifdef FEAT_MBYTE
    static int
prt_match_encoding(p_encoding, p_cmap, pp_mbenc)
    char			*p_encoding;
    struct prt_ps_mbfont_S	*p_cmap;
    struct prt_ps_encoding_S	**pp_mbenc;
{
    int				mbenc;
    int				enc_len;
    struct prt_ps_encoding_S	*p_mbenc;

    *pp_mbenc = NULL;
    /* Look for recognised encoding */
    enc_len = (int)STRLEN(p_encoding);
    p_mbenc = p_cmap->encodings;
    for (mbenc = 0; mbenc < p_cmap->num_encodings; mbenc++)
    {
	if (STRNICMP(p_mbenc->encoding, p_encoding, enc_len) == 0)
	{
	    *pp_mbenc = p_mbenc;
	    return TRUE;
	}
	p_mbenc++;
    }
    return FALSE;
}

    static int
prt_match_charset(p_charset, p_cmap, pp_mbchar)
    char		    *p_charset;
    struct prt_ps_mbfont_S  *p_cmap;
    struct prt_ps_charset_S **pp_mbchar;
{
    int			    mbchar;
    int			    char_len;
    struct prt_ps_charset_S *p_mbchar;

    /* Look for recognised character set, using default if one is not given */
    if (*p_charset == NUL)
	p_charset = p_cmap->defcs;
    char_len = (int)STRLEN(p_charset);
    p_mbchar = p_cmap->charsets;
    for (mbchar = 0; mbchar < p_cmap->num_charsets; mbchar++)
    {
	if (STRNICMP(p_mbchar->charset, p_charset, char_len) == 0)
	{
	    *pp_mbchar = p_mbchar;
	    return TRUE;
	}
	p_mbchar++;
    }
    return FALSE;
}
#endif

    int
mch_print_init(psettings, jobname, forceit)
    prt_settings_T *psettings;
    char_u	*jobname;
    int		forceit UNUSED;
{
    int		i;
    char	*paper_name;
    int		paper_strlen;
    int		fontsize;
    char_u	*p;
    double      left;
    double      right;
    double      top;
    double      bottom;
#ifdef FEAT_MBYTE
    int		props;
    int		cmap = 0;
    char_u	*p_encoding;
    struct prt_ps_encoding_S *p_mbenc;
    struct prt_ps_encoding_S *p_mbenc_first;
    struct prt_ps_charset_S  *p_mbchar = NULL;
#endif

#if 0
    /*
     * TODO:
     * If "forceit" is false: pop up a dialog to select:
     *	- printer name
     *	- copies
     *	- collated/uncollated
     *	- duplex off/long side/short side
     *	- paper size
     *	- portrait/landscape
     *	- font size
     *
     * If "forceit" is true: use the default printer and settings
     */
    if (forceit)
	s_pd.Flags |= PD_RETURNDEFAULT;
#endif

    /*
     * Set up font and encoding.
     */
#ifdef FEAT_MBYTE
    p_encoding = enc_skip(p_penc);
    if (*p_encoding == NUL)
	p_encoding = enc_skip(p_enc);

    /* Look for a multi-byte font that matches the encoding and character set.
     * Only look if multi-byte character set is defined, or using multi-byte
     * encoding other than Unicode.  This is because a Unicode encoding does not
     * uniquely identify a CJK character set to use. */
    p_mbenc = NULL;
    props = enc_canon_props(p_encoding);
    if (!(props & ENC_8BIT) && ((*p_pmcs != NUL) || !(props & ENC_UNICODE)))
    {
	p_mbenc_first = NULL;
	for (cmap = 0; cmap < (int)NUM_ELEMENTS(prt_ps_mbfonts); cmap++)
	    if (prt_match_encoding((char *)p_encoding, &prt_ps_mbfonts[cmap],
								    &p_mbenc))
	    {
		if (p_mbenc_first == NULL)
		    p_mbenc_first = p_mbenc;
		if (prt_match_charset((char *)p_pmcs, &prt_ps_mbfonts[cmap],
								   &p_mbchar))
		    break;
	    }

	/* Use first encoding matched if no charset matched */
	if (p_mbchar == NULL && p_mbenc_first != NULL)
	    p_mbenc = p_mbenc_first;
    }

    prt_out_mbyte = (p_mbenc != NULL);
    if (prt_out_mbyte)
    {
	/* Build CMap name - will be same for all multi-byte fonts used */
	prt_cmap[0] = NUL;

	prt_custom_cmap = (p_mbchar == NULL);
	if (!prt_custom_cmap)
	{
	    /* Check encoding and character set are compatible */
	    if ((p_mbenc->needs_charset & p_mbchar->has_charset) == 0)
	    {
		EMSG(_("E673: Incompatible multi-byte encoding and character set."));
		return FALSE;
	    }

	    /* Add charset name if not empty */
	    if (p_mbchar->cmap_charset != NULL)
	    {
		vim_strncpy((char_u *)prt_cmap,
		      (char_u *)p_mbchar->cmap_charset, sizeof(prt_cmap) - 3);
		STRCAT(prt_cmap, "-");
	    }
	}
	else
	{
	    /* Add custom CMap character set name */
	    if (*p_pmcs == NUL)
	    {
		EMSG(_("E674: printmbcharset cannot be empty with multi-byte encoding."));
		return FALSE;
	    }
	    vim_strncpy((char_u *)prt_cmap, p_pmcs, sizeof(prt_cmap) - 3);
	    STRCAT(prt_cmap, "-");
	}

	/* CMap name ends with (optional) encoding name and -H for horizontal */
	if (p_mbenc->cmap_encoding != NULL && STRLEN(prt_cmap)
		      + STRLEN(p_mbenc->cmap_encoding) + 3 < sizeof(prt_cmap))
	{
	    STRCAT(prt_cmap, p_mbenc->cmap_encoding);
	    STRCAT(prt_cmap, "-");
	}
	STRCAT(prt_cmap, "H");

	if (!mbfont_opts[OPT_MBFONT_REGULAR].present)
	{
	    EMSG(_("E675: No default font specified for multi-byte printing."));
	    return FALSE;
	}

	/* Derive CID font names with fallbacks if not defined */
	if (!prt_build_cid_fontname(PRT_PS_FONT_ROMAN,
				    mbfont_opts[OPT_MBFONT_REGULAR].string,
				    mbfont_opts[OPT_MBFONT_REGULAR].strlen))
	    return FALSE;
	if (mbfont_opts[OPT_MBFONT_BOLD].present)
	    if (!prt_build_cid_fontname(PRT_PS_FONT_BOLD,
					mbfont_opts[OPT_MBFONT_BOLD].string,
					mbfont_opts[OPT_MBFONT_BOLD].strlen))
		return FALSE;
	if (mbfont_opts[OPT_MBFONT_OBLIQUE].present)
	    if (!prt_build_cid_fontname(PRT_PS_FONT_OBLIQUE,
					mbfont_opts[OPT_MBFONT_OBLIQUE].string,
					mbfont_opts[OPT_MBFONT_OBLIQUE].strlen))
		return FALSE;
	if (mbfont_opts[OPT_MBFONT_BOLDOBLIQUE].present)
	    if (!prt_build_cid_fontname(PRT_PS_FONT_BOLDOBLIQUE,
				   mbfont_opts[OPT_MBFONT_BOLDOBLIQUE].string,
				  mbfont_opts[OPT_MBFONT_BOLDOBLIQUE].strlen))
		return FALSE;

	/* Check if need to use Courier for ASCII code range, and if so pick up
	 * the encoding to use */
	prt_use_courier = mbfont_opts[OPT_MBFONT_USECOURIER].present &&
	    (TOLOWER_ASC(mbfont_opts[OPT_MBFONT_USECOURIER].string[0]) == 'y');
	if (prt_use_courier)
	{
	    /* Use national ASCII variant unless ASCII wanted */
	    if (mbfont_opts[OPT_MBFONT_ASCII].present &&
		(TOLOWER_ASC(mbfont_opts[OPT_MBFONT_ASCII].string[0]) == 'y'))
		prt_ascii_encoding = "ascii";
	    else
		prt_ascii_encoding = prt_ps_mbfonts[cmap].ascii_enc;
	}

	prt_ps_font = &prt_ps_mb_font;
    }
    else
#endif
    {
#ifdef FEAT_MBYTE
	prt_use_courier = FALSE;
#endif
	prt_ps_font = &prt_ps_courier_font;
    }

    /*
     * Find the size of the paper and set the margins.
     */
    prt_portrait = (!printer_opts[OPT_PRINT_PORTRAIT].present
	   || TOLOWER_ASC(printer_opts[OPT_PRINT_PORTRAIT].string[0]) == 'y');
    if (printer_opts[OPT_PRINT_PAPER].present)
    {
	paper_name = (char *)printer_opts[OPT_PRINT_PAPER].string;
	paper_strlen = printer_opts[OPT_PRINT_PAPER].strlen;
    }
    else
    {
	paper_name = "A4";
	paper_strlen = 2;
    }
    for (i = 0; i < (int)PRT_MEDIASIZE_LEN; ++i)
	if (STRLEN(prt_mediasize[i].name) == (unsigned)paper_strlen
		&& STRNICMP(prt_mediasize[i].name, paper_name,
							   paper_strlen) == 0)
	    break;
    if (i == PRT_MEDIASIZE_LEN)
	i = 0;
    prt_media = i;

    /*
     * Set PS pagesize based on media dimensions and print orientation.
     * Note: Media and page sizes have defined meanings in PostScript and should
     * be kept distinct.  Media is the paper (or transparency, or ...) that is
     * printed on, whereas the page size is the area that the PostScript
     * interpreter renders into.
     */
    if (prt_portrait)
    {
	prt_page_width = prt_mediasize[i].width;
	prt_page_height = prt_mediasize[i].height;
    }
    else
    {
	prt_page_width = prt_mediasize[i].height;
	prt_page_height = prt_mediasize[i].width;
    }

    /*
     * Set PS page margins based on the PS pagesize, not the mediasize - this
     * needs to be done before the cpl and lpp are calculated.
     */
    prt_page_margins(prt_page_width, prt_page_height, &left, &right, &top,
								    &bottom);
    prt_left_margin = (float)left;
    prt_right_margin = (float)right;
    prt_top_margin = (float)top;
    prt_bottom_margin = (float)bottom;

    /*
     * Set up the font size.
     */
    fontsize = PRT_PS_DEFAULT_FONTSIZE;
    for (p = p_pfn; (p = vim_strchr(p, ':')) != NULL; ++p)
	if (p[1] == 'h' && VIM_ISDIGIT(p[2]))
	    fontsize = atoi((char *)p + 2);
    prt_font_metrics(fontsize);

    /*
     * Return the number of characters per line, and lines per page for the
     * generic print code.
     */
    psettings->chars_per_line = prt_get_cpl();
    psettings->lines_per_page = prt_get_lpp();

    /* Catch margin settings that leave no space for output! */
    if (psettings->chars_per_line <= 0 || psettings->lines_per_page <= 0)
	return FAIL;

    /*
     * Sort out the number of copies to be printed.  PS by default will do
     * uncollated copies for you, so once we know how many uncollated copies are
     * wanted cache it away and lie to the generic code that we only want one
     * uncollated copy.
     */
    psettings->n_collated_copies = 1;
    psettings->n_uncollated_copies = 1;
    prt_num_copies = 1;
    prt_collate = (!printer_opts[OPT_PRINT_COLLATE].present
	    || TOLOWER_ASC(printer_opts[OPT_PRINT_COLLATE].string[0]) == 'y');
    if (prt_collate)
    {
	/* TODO: Get number of collated copies wanted. */
	psettings->n_collated_copies = 1;
    }
    else
    {
	/* TODO: Get number of uncollated copies wanted and update the cached
	 * count.
	 */
	prt_num_copies = 1;
    }

    psettings->jobname = jobname;

    /*
     * Set up printer duplex and tumble based on Duplex option setting - default
     * is long sided duplex printing (i.e. no tumble).
     */
    prt_duplex = TRUE;
    prt_tumble = FALSE;
    psettings->duplex = 1;
    if (printer_opts[OPT_PRINT_DUPLEX].present)
    {
	if (STRNICMP(printer_opts[OPT_PRINT_DUPLEX].string, "off", 3) == 0)
	{
	    prt_duplex = FALSE;
	    psettings->duplex = 0;
	}
	else if (STRNICMP(printer_opts[OPT_PRINT_DUPLEX].string, "short", 5)
									 == 0)
	    prt_tumble = TRUE;
    }

    /* For now user abort not supported */
    psettings->user_abort = 0;

    /* If the user didn't specify a file name, use a temp file. */
    if (psettings->outfile == NULL)
    {
	prt_ps_file_name = vim_tempname('p', TRUE);
	if (prt_ps_file_name == NULL)
	{
	    EMSG(_(e_notmp));
	    return FAIL;
	}
	prt_ps_fd = mch_fopen((char *)prt_ps_file_name, WRITEBIN);
    }
    else
    {
	p = expand_env_save(psettings->outfile);
	if (p != NULL)
	{
	    prt_ps_fd = mch_fopen((char *)p, WRITEBIN);
	    vim_free(p);
	}
    }
    if (prt_ps_fd == NULL)
    {
	EMSG(_("E324: Can't open PostScript output file"));
	mch_print_cleanup();
	return FAIL;
    }

    prt_bufsiz = psettings->chars_per_line;
#ifdef FEAT_MBYTE
    if (prt_out_mbyte)
	prt_bufsiz *= 2;
#endif
    ga_init2(&prt_ps_buffer, (int)sizeof(char), prt_bufsiz);

    prt_page_num = 0;

    prt_attribute_change = FALSE;
    prt_need_moveto = FALSE;
    prt_need_font = FALSE;
    prt_need_fgcol = FALSE;
    prt_need_bgcol = FALSE;
    prt_need_underline = FALSE;

    prt_file_error = FALSE;

    return OK;
}

    static int
prt_add_resource(resource)
    struct prt_ps_resource_S *resource;
{
    FILE*	fd_resource;
    char_u	resource_buffer[512];
    size_t	bytes_read;

    fd_resource = mch_fopen((char *)resource->filename, READBIN);
    if (fd_resource == NULL)
    {
	EMSG2(_("E456: Can't open file \"%s\""), resource->filename);
	return FALSE;
    }
    prt_dsc_resources("BeginResource", prt_resource_types[resource->type],
						     (char *)resource->title);

    prt_dsc_textline("BeginDocument", (char *)resource->filename);

    for (;;)
    {
	bytes_read = fread((char *)resource_buffer, sizeof(char_u),
			   sizeof(resource_buffer), fd_resource);
	if (ferror(fd_resource))
	{
	    EMSG2(_("E457: Can't read PostScript resource file \"%s\""),
							    resource->filename);
	    fclose(fd_resource);
	    return FALSE;
	}
	if (bytes_read == 0)
	    break;
	prt_write_file_raw_len(resource_buffer, (int)bytes_read);
	if (prt_file_error)
	{
	    fclose(fd_resource);
	    return FALSE;
	}
    }
    fclose(fd_resource);

    prt_dsc_noarg("EndDocument");

    prt_dsc_noarg("EndResource");

    return TRUE;
}

    int
mch_print_begin(psettings)
    prt_settings_T *psettings;
{
    time_t	now;
    int		bbox[4];
    char	*p_time;
    double      left;
    double      right;
    double      top;
    double      bottom;
    struct prt_ps_resource_S *res_prolog;
    struct prt_ps_resource_S *res_encoding;
    char	buffer[256];
    char_u      *p_encoding;
    char_u	*p;
#ifdef FEAT_MBYTE
    struct prt_ps_resource_S *res_cidfont;
    struct prt_ps_resource_S *res_cmap;
#endif
    int		retval = FALSE;

    res_prolog = (struct prt_ps_resource_S *)
				      alloc(sizeof(struct prt_ps_resource_S));
    res_encoding = (struct prt_ps_resource_S *)
				      alloc(sizeof(struct prt_ps_resource_S));
#ifdef FEAT_MBYTE
    res_cidfont = (struct prt_ps_resource_S *)
				      alloc(sizeof(struct prt_ps_resource_S));
    res_cmap = (struct prt_ps_resource_S *)
				      alloc(sizeof(struct prt_ps_resource_S));
#endif
    if (res_prolog == NULL || res_encoding == NULL
#ifdef FEAT_MBYTE
	    || res_cidfont == NULL || res_cmap == NULL
#endif
       )
	goto theend;

    /*
     * PS DSC Header comments - no PS code!
     */
    prt_dsc_start();
    prt_dsc_textline("Title", (char *)psettings->jobname);
    if (!get_user_name((char_u *)buffer, 256))
	STRCPY(buffer, "Unknown");
    prt_dsc_textline("For", buffer);
    prt_dsc_textline("Creator", VIM_VERSION_LONG);
    /* Note: to ensure Clean8bit I don't think we can use LC_TIME */
    now = time(NULL);
    p_time = ctime(&now);
    /* Note: ctime() adds a \n so we have to remove it :-( */
    p = vim_strchr((char_u *)p_time, '\n');
    if (p != NULL)
	*p = NUL;
    prt_dsc_textline("CreationDate", p_time);
    prt_dsc_textline("DocumentData", "Clean8Bit");
    prt_dsc_textline("Orientation", "Portrait");
    prt_dsc_atend("Pages");
    prt_dsc_textline("PageOrder", "Ascend");
    /* The bbox does not change with orientation - it is always in the default
     * user coordinate system!  We have to recalculate right and bottom
     * coordinates based on the font metrics for the bbox to be accurate. */
    prt_page_margins(prt_mediasize[prt_media].width,
					    prt_mediasize[prt_media].height,
					    &left, &right, &top, &bottom);
    bbox[0] = (int)left;
    if (prt_portrait)
    {
	/* In portrait printing the fixed point is the top left corner so we
	 * derive the bbox from that point.  We have the expected cpl chars
	 * across the media and lpp lines down the media.
	 */
	bbox[1] = (int)(top - (psettings->lines_per_page + prt_header_height())
							    * prt_line_height);
	bbox[2] = (int)(left + psettings->chars_per_line * prt_char_width
									+ 0.5);
	bbox[3] = (int)(top + 0.5);
    }
    else
    {
	/* In landscape printing the fixed point is the bottom left corner so we
	 * derive the bbox from that point.  We have lpp chars across the media
	 * and cpl lines up the media.
	 */
	bbox[1] = (int)bottom;
	bbox[2] = (int)(left + ((psettings->lines_per_page
			      + prt_header_height()) * prt_line_height) + 0.5);
	bbox[3] = (int)(bottom + psettings->chars_per_line * prt_char_width
									+ 0.5);
    }
    prt_dsc_ints("BoundingBox", 4, bbox);
    /* The media width and height does not change with landscape printing! */
    prt_dsc_docmedia(prt_mediasize[prt_media].name,
				prt_mediasize[prt_media].width,
				prt_mediasize[prt_media].height,
				(double)0, NULL, NULL);
    /* Define fonts needed */
#ifdef FEAT_MBYTE
    if (!prt_out_mbyte || prt_use_courier)
#endif
	prt_dsc_font_resource("DocumentNeededResources", &prt_ps_courier_font);
#ifdef FEAT_MBYTE
    if (prt_out_mbyte)
    {
	prt_dsc_font_resource((prt_use_courier ? NULL
				 : "DocumentNeededResources"), &prt_ps_mb_font);
	if (!prt_custom_cmap)
	    prt_dsc_resources(NULL, "cmap", prt_cmap);
    }
#endif

    /* Search for external resources VIM supplies */
    if (!prt_find_resource("prolog", res_prolog))
    {
	EMSG(_("E456: Can't find PostScript resource file \"prolog.ps\""));
	goto theend;
    }
    if (!prt_open_resource(res_prolog))
	goto theend;
    if (!prt_check_resource(res_prolog, PRT_PROLOG_VERSION))
	goto theend;
#ifdef FEAT_MBYTE
    if (prt_out_mbyte)
    {
	/* Look for required version of multi-byte printing procset */
	if (!prt_find_resource("cidfont", res_cidfont))
	{
	    EMSG(_("E456: Can't find PostScript resource file \"cidfont.ps\""));
	    goto theend;
	}
	if (!prt_open_resource(res_cidfont))
	    goto theend;
	if (!prt_check_resource(res_cidfont, PRT_CID_PROLOG_VERSION))
	    goto theend;
    }
#endif

    /* Find an encoding to use for printing.
     * Check 'printencoding'. If not set or not found, then use 'encoding'. If
     * that cannot be found then default to "latin1".
     * Note: VIM specific encoding header is always skipped.
     */
#ifdef FEAT_MBYTE
    if (!prt_out_mbyte)
    {
#endif
	p_encoding = enc_skip(p_penc);
	if (*p_encoding == NUL
		|| !prt_find_resource((char *)p_encoding, res_encoding))
	{
	    /* 'printencoding' not set or not supported - find alternate */
#ifdef FEAT_MBYTE
	    int		props;

	    p_encoding = enc_skip(p_enc);
	    props = enc_canon_props(p_encoding);
	    if (!(props & ENC_8BIT)
		    || !prt_find_resource((char *)p_encoding, res_encoding))
		/* 8-bit 'encoding' is not supported */
#endif
		{
		/* Use latin1 as default printing encoding */
		p_encoding = (char_u *)"latin1";
		if (!prt_find_resource((char *)p_encoding, res_encoding))
		{
		    EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""),
			    p_encoding);
		    goto theend;
		}
	    }
	}
	if (!prt_open_resource(res_encoding))
	    goto theend;
	/* For the moment there are no checks on encoding resource files to
	 * perform */
#ifdef FEAT_MBYTE
    }
    else
    {
	p_encoding = enc_skip(p_penc);
	if (*p_encoding == NUL)
	    p_encoding = enc_skip(p_enc);
	if (prt_use_courier)
	{
	    /* Include ASCII range encoding vector */
	    if (!prt_find_resource(prt_ascii_encoding, res_encoding))
	    {
		EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""),
							  prt_ascii_encoding);
		goto theend;
	    }
	    if (!prt_open_resource(res_encoding))
		goto theend;
	    /* For the moment there are no checks on encoding resource files to
	     * perform */
	}
    }

    prt_conv.vc_type = CONV_NONE;
    if (!(enc_canon_props(p_enc) & enc_canon_props(p_encoding) & ENC_8BIT)) {
	/* Set up encoding conversion if required */
	if (FAIL == convert_setup(&prt_conv, p_enc, p_encoding))
	{
	    EMSG2(_("E620: Unable to convert to print encoding \"%s\""),
		    p_encoding);
	    goto theend;
	}
	prt_do_conv = TRUE;
    }
    prt_do_conv = prt_conv.vc_type != CONV_NONE;

    if (prt_out_mbyte && prt_custom_cmap)
    {
	/* Find user supplied CMap */
	if (!prt_find_resource(prt_cmap, res_cmap))
	{
	    EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""),
								    prt_cmap);
	    goto theend;
	}
	if (!prt_open_resource(res_cmap))
	    goto theend;
    }
#endif

    /* List resources supplied */
    STRCPY(buffer, res_prolog->title);
    STRCAT(buffer, " ");
    STRCAT(buffer, res_prolog->version);
    prt_dsc_resources("DocumentSuppliedResources", "procset", buffer);
#ifdef FEAT_MBYTE
    if (prt_out_mbyte)
    {
	STRCPY(buffer, res_cidfont->title);
	STRCAT(buffer, " ");
	STRCAT(buffer, res_cidfont->version);
	prt_dsc_resources(NULL, "procset", buffer);

	if (prt_custom_cmap)
	{
	    STRCPY(buffer, res_cmap->title);
	    STRCAT(buffer, " ");
	    STRCAT(buffer, res_cmap->version);
	    prt_dsc_resources(NULL, "cmap", buffer);
	}
    }
    if (!prt_out_mbyte || prt_use_courier)
#endif
    {
	STRCPY(buffer, res_encoding->title);
	STRCAT(buffer, " ");
	STRCAT(buffer, res_encoding->version);
	prt_dsc_resources(NULL, "encoding", buffer);
    }
    prt_dsc_requirements(prt_duplex, prt_tumble, prt_collate,
#ifdef FEAT_SYN_HL
					psettings->do_syntax
#else
					0
#endif
					, prt_num_copies);
    prt_dsc_noarg("EndComments");

    /*
     * PS Document page defaults
     */
    prt_dsc_noarg("BeginDefaults");

    /* List font resources most likely common to all pages */
#ifdef FEAT_MBYTE
    if (!prt_out_mbyte || prt_use_courier)
#endif
	prt_dsc_font_resource("PageResources", &prt_ps_courier_font);
#ifdef FEAT_MBYTE
    if (prt_out_mbyte)
    {
	prt_dsc_font_resource((prt_use_courier ? NULL : "PageResources"),
							    &prt_ps_mb_font);
	if (!prt_custom_cmap)
	    prt_dsc_resources(NULL, "cmap", prt_cmap);
    }
#endif

    /* Paper will be used for all pages */
    prt_dsc_textline("PageMedia", prt_mediasize[prt_media].name);

    prt_dsc_noarg("EndDefaults");

    /*
     * PS Document prolog inclusion - all required procsets.
     */
    prt_dsc_noarg("BeginProlog");

    /* Add required procsets - NOTE: order is important! */
    if (!prt_add_resource(res_prolog))
	goto theend;
#ifdef FEAT_MBYTE
    if (prt_out_mbyte)
    {
	/* Add CID font procset, and any user supplied CMap */
	if (!prt_add_resource(res_cidfont))
	    goto theend;
	if (prt_custom_cmap && !prt_add_resource(res_cmap))
	    goto theend;
    }
#endif

#ifdef FEAT_MBYTE
    if (!prt_out_mbyte || prt_use_courier)
#endif
	/* There will be only one Roman font encoding to be included in the PS
	 * file. */
	if (!prt_add_resource(res_encoding))
	    goto theend;

    prt_dsc_noarg("EndProlog");

    /*
     * PS Document setup - must appear after the prolog
     */
    prt_dsc_noarg("BeginSetup");

    /* Device setup - page size and number of uncollated copies */
    prt_write_int((int)prt_mediasize[prt_media].width);
    prt_write_int((int)prt_mediasize[prt_media].height);
    prt_write_int(0);
    prt_write_string("sps\n");
    prt_write_int(prt_num_copies);
    prt_write_string("nc\n");
    prt_write_boolean(prt_duplex);
    prt_write_boolean(prt_tumble);
    prt_write_string("dt\n");
    prt_write_boolean(prt_collate);
    prt_write_string("c\n");

    /* Font resource inclusion and definition */
#ifdef FEAT_MBYTE
    if (!prt_out_mbyte || prt_use_courier)
    {
	/* When using Courier for ASCII range when printing multi-byte, need to
	 * pick up ASCII encoding to use with it. */
	if (prt_use_courier)
	    p_encoding = (char_u *)prt_ascii_encoding;
#endif
	prt_dsc_resources("IncludeResource", "font",
			  prt_ps_courier_font.ps_fontname[PRT_PS_FONT_ROMAN]);
	prt_def_font("F0", (char *)p_encoding, (int)prt_line_height,
		     prt_ps_courier_font.ps_fontname[PRT_PS_FONT_ROMAN]);
	prt_dsc_resources("IncludeResource", "font",
			  prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLD]);
	prt_def_font("F1", (char *)p_encoding, (int)prt_line_height,
		     prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLD]);
	prt_dsc_resources("IncludeResource", "font",
			  prt_ps_courier_font.ps_fontname[PRT_PS_FONT_OBLIQUE]);
	prt_def_font("F2", (char *)p_encoding, (int)prt_line_height,
		     prt_ps_courier_font.ps_fontname[PRT_PS_FONT_OBLIQUE]);
	prt_dsc_resources("IncludeResource", "font",
			  prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]);
	prt_def_font("F3", (char *)p_encoding, (int)prt_line_height,
		     prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]);
#ifdef FEAT_MBYTE
    }
    if (prt_out_mbyte)
    {
	/* Define the CID fonts to be used in the job.	Typically CJKV fonts do
	 * not have an italic form being a western style, so where no font is
	 * defined for these faces VIM falls back to an existing face.
	 * Note: if using Courier for the ASCII range then the printout will
	 * have bold/italic/bolditalic regardless of the setting of printmbfont.
	 */
	prt_dsc_resources("IncludeResource", "font",
			  prt_ps_mb_font.ps_fontname[PRT_PS_FONT_ROMAN]);
	if (!prt_custom_cmap)
	    prt_dsc_resources("IncludeResource", "cmap", prt_cmap);
	prt_def_cidfont("CF0", (int)prt_line_height,
			prt_ps_mb_font.ps_fontname[PRT_PS_FONT_ROMAN]);

	if (prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLD] != NULL)
	{
	    prt_dsc_resources("IncludeResource", "font",
			      prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLD]);
	    if (!prt_custom_cmap)
		prt_dsc_resources("IncludeResource", "cmap", prt_cmap);
	    prt_def_cidfont("CF1", (int)prt_line_height,
			    prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLD]);
	}
	else
	    /* Use ROMAN for BOLD */
	    prt_dup_cidfont("CF0", "CF1");

	if (prt_ps_mb_font.ps_fontname[PRT_PS_FONT_OBLIQUE] != NULL)
	{
	    prt_dsc_resources("IncludeResource", "font",
			      prt_ps_mb_font.ps_fontname[PRT_PS_FONT_OBLIQUE]);
	    if (!prt_custom_cmap)
		prt_dsc_resources("IncludeResource", "cmap", prt_cmap);
	    prt_def_cidfont("CF2", (int)prt_line_height,
			    prt_ps_mb_font.ps_fontname[PRT_PS_FONT_OBLIQUE]);
	}
	else
	    /* Use ROMAN for OBLIQUE */
	    prt_dup_cidfont("CF0", "CF2");

	if (prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE] != NULL)
	{
	    prt_dsc_resources("IncludeResource", "font",
			      prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]);
	    if (!prt_custom_cmap)
		prt_dsc_resources("IncludeResource", "cmap", prt_cmap);
	    prt_def_cidfont("CF3", (int)prt_line_height,
			    prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]);
	}
	else
	    /* Use BOLD for BOLDOBLIQUE */
	    prt_dup_cidfont("CF1", "CF3");
    }
#endif

    /* Misc constant vars used for underlining and background rects */
    prt_def_var("UO", PRT_PS_FONT_TO_USER(prt_line_height,
						prt_ps_font->uline_offset), 2);
    prt_def_var("UW", PRT_PS_FONT_TO_USER(prt_line_height,
						 prt_ps_font->uline_width), 2);
    prt_def_var("BO", prt_bgcol_offset, 2);

    prt_dsc_noarg("EndSetup");

    /* Fail if any problems writing out to the PS file */
    retval = !prt_file_error;

theend:
    vim_free(res_prolog);
    vim_free(res_encoding);
#ifdef FEAT_MBYTE
    vim_free(res_cidfont);
    vim_free(res_cmap);
#endif

    return retval;
}

    void
mch_print_end(psettings)
    prt_settings_T *psettings;
{
    prt_dsc_noarg("Trailer");

    /*
     * Output any info we don't know in toto until we finish
     */
    prt_dsc_ints("Pages", 1, &prt_page_num);

    prt_dsc_noarg("EOF");

    /* Write CTRL-D to close serial communication link if used.
     * NOTHING MUST BE WRITTEN AFTER THIS! */
    prt_write_file((char_u *)IF_EB("\004", "\067"));

    if (!prt_file_error && psettings->outfile == NULL
					&& !got_int && !psettings->user_abort)
    {
	/* Close the file first. */
	if (prt_ps_fd != NULL)
	{
	    fclose(prt_ps_fd);
	    prt_ps_fd = NULL;
	}
	prt_message((char_u *)_("Sending to printer..."));

	/* Not printing to a file: use 'printexpr' to print the file. */
	if (eval_printexpr(prt_ps_file_name, psettings->arguments) == FAIL)
	    EMSG(_("E365: Failed to print PostScript file"));
	else
	    prt_message((char_u *)_("Print job sent."));
    }

    mch_print_cleanup();
}

    int
mch_print_end_page()
{
    prt_flush_buffer();

    prt_write_string("re sp\n");

    prt_dsc_noarg("PageTrailer");

    return !prt_file_error;
}

    int
mch_print_begin_page(str)
    char_u	*str UNUSED;
{
    int		page_num[2];

    prt_page_num++;

    page_num[0] = page_num[1] = prt_page_num;
    prt_dsc_ints("Page", 2, page_num);

    prt_dsc_noarg("BeginPageSetup");

    prt_write_string("sv\n0 g\n");
#ifdef FEAT_MBYTE
    prt_in_ascii = !prt_out_mbyte;
    if (prt_out_mbyte)
	prt_write_string("CF0 sf\n");
    else
#endif
	prt_write_string("F0 sf\n");
    prt_fgcol = PRCOLOR_BLACK;
    prt_bgcol = PRCOLOR_WHITE;
    prt_font = PRT_PS_FONT_ROMAN;

    /* Set up page transformation for landscape printing. */
    if (!prt_portrait)
    {
	prt_write_int(-((int)prt_mediasize[prt_media].width));
	prt_write_string("sl\n");
    }

    prt_dsc_noarg("EndPageSetup");

    /* We have reset the font attributes, force setting them again. */
    curr_bg = (long_u)0xffffffff;
    curr_fg = (long_u)0xffffffff;
    curr_bold = MAYBE;

    return !prt_file_error;
}

    int
mch_print_blank_page()
{
    return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE);
}

static float prt_pos_x = 0;
static float prt_pos_y = 0;

    void
mch_print_start_line(margin, page_line)
    int		margin;
    int		page_line;
{
    prt_pos_x = prt_left_margin;
    if (margin)
	prt_pos_x -= prt_number_width;

    prt_pos_y = prt_top_margin - prt_first_line_height -
					page_line * prt_line_height;

    prt_attribute_change = TRUE;
    prt_need_moveto = TRUE;
#ifdef FEAT_MBYTE
    prt_half_width = FALSE;
#endif
}

    int
mch_print_text_out(p, len)
    char_u	*p;
    int		len UNUSED;
{
    int		need_break;
    char_u	ch;
    char_u      ch_buff[8];
    float       char_width;
    float       next_pos;
#ifdef FEAT_MBYTE
    int		in_ascii;
    int		half_width;
#endif

    char_width = prt_char_width;

#ifdef FEAT_MBYTE
    /* Ideally VIM would create a rearranged CID font to combine a Roman and
     * CJKV font to do what VIM is doing here - use a Roman font for characters
     * in the ASCII range, and the original CID font for everything else.
     * The problem is that GhostScript still (as of 8.13) does not support
     * rearranged fonts even though they have been documented by Adobe for 7
     * years!  If they ever do, a lot of this code will disappear.
     */
    if (prt_use_courier)
    {
	in_ascii = (len == 1 && *p < 0x80);
	if (prt_in_ascii)
	{
	    if (!in_ascii)
	    {
		/* No longer in ASCII range - need to switch font */
		prt_in_ascii = FALSE;
		prt_need_font = TRUE;
		prt_attribute_change = TRUE;
	    }
	}
	else if (in_ascii)
	{
	    /* Now in ASCII range - need to switch font */
	    prt_in_ascii = TRUE;
	    prt_need_font = TRUE;
	    prt_attribute_change = TRUE;
	}
    }
    if (prt_out_mbyte)
    {
	half_width = ((*mb_ptr2cells)(p) == 1);
	if (half_width)
	    char_width /= 2;
	if (prt_half_width)
	{
	    if (!half_width)
	    {
		prt_half_width = FALSE;
		prt_pos_x += prt_char_width/4;
		prt_need_moveto = TRUE;
		prt_attribute_change = TRUE;
	    }
	}
	else if (half_width)
	{
	    prt_half_width = TRUE;
	    prt_pos_x += prt_char_width/4;
	    prt_need_moveto = TRUE;
	    prt_attribute_change = TRUE;
	}
    }
#endif

    /* Output any required changes to the graphics state, after flushing any
     * text buffered so far.
     */
    if (prt_attribute_change)
    {
	prt_flush_buffer();
	/* Reset count of number of chars that will be printed */
	prt_text_run = 0;

	if (prt_need_moveto)
	{
	    prt_pos_x_moveto = prt_pos_x;
	    prt_pos_y_moveto = prt_pos_y;
	    prt_do_moveto = TRUE;

	    prt_need_moveto = FALSE;
	}
	if (prt_need_font)
	{
#ifdef FEAT_MBYTE
	    if (!prt_in_ascii)
		prt_write_string("CF");
	    else
#endif
		prt_write_string("F");
	    prt_write_int(prt_font);
	    prt_write_string("sf\n");
	    prt_need_font = FALSE;
	}
	if (prt_need_fgcol)
	{
	    int     r, g, b;
	    r = ((unsigned)prt_fgcol & 0xff0000) >> 16;
	    g = ((unsigned)prt_fgcol & 0xff00) >> 8;
	    b = prt_fgcol & 0xff;

	    prt_write_real(r / 255.0, 3);
	    if (r == g && g == b)
		prt_write_string("g\n");
	    else
	    {
		prt_write_real(g / 255.0, 3);
		prt_write_real(b / 255.0, 3);
		prt_write_string("r\n");
	    }
	    prt_need_fgcol = FALSE;
	}

	if (prt_bgcol != PRCOLOR_WHITE)
	{
	    prt_new_bgcol = prt_bgcol;
	    if (prt_need_bgcol)
		prt_do_bgcol = TRUE;
	}
	else
	    prt_do_bgcol = FALSE;
	prt_need_bgcol = FALSE;

	if (prt_need_underline)
	    prt_do_underline = prt_underline;
	prt_need_underline = FALSE;

	prt_attribute_change = FALSE;
    }

#ifdef FEAT_MBYTE
    if (prt_do_conv)
    {
	/* Convert from multi-byte to 8-bit encoding */
	p = string_convert(&prt_conv, p, &len);
	if (p == NULL)
	    p = (char_u *)"";
    }

    if (prt_out_mbyte)
    {
	/* Multi-byte character strings are represented more efficiently as hex
	 * strings when outputting clean 8 bit PS.
	 */
	do
	{
	    ch = prt_hexchar[(unsigned)(*p) >> 4];
	    ga_append(&prt_ps_buffer, ch);
	    ch = prt_hexchar[(*p) & 0xf];
	    ga_append(&prt_ps_buffer, ch);
	    p++;
	}
	while (--len);
    }
    else
#endif
    {
	/* Add next character to buffer of characters to output.
	 * Note: One printed character may require several PS characters to
	 * represent it, but we only count them as one printed character.
	 */
	ch = *p;
	if (ch < 32 || ch == '(' || ch == ')' || ch == '\\')
	{
	    /* Convert non-printing characters to either their escape or octal
	     * sequence, ensures PS sent over a serial line does not interfere
	     * with the comms protocol.  Note: For EBCDIC we need to write out
	     * the escape sequences as ASCII codes!
	     * Note 2: Char codes < 32 are identical in EBCDIC and ASCII AFAIK!
	     */
	    ga_append(&prt_ps_buffer, IF_EB('\\', 0134));
	    switch (ch)
	    {
		case BS:   ga_append(&prt_ps_buffer, IF_EB('b', 0142)); break;
		case TAB:  ga_append(&prt_ps_buffer, IF_EB('t', 0164)); break;
		case NL:   ga_append(&prt_ps_buffer, IF_EB('n', 0156)); break;
		case FF:   ga_append(&prt_ps_buffer, IF_EB('f', 0146)); break;
		case CAR:  ga_append(&prt_ps_buffer, IF_EB('r', 0162)); break;
		case '(':  ga_append(&prt_ps_buffer, IF_EB('(', 0050)); break;
		case ')':  ga_append(&prt_ps_buffer, IF_EB(')', 0051)); break;
		case '\\': ga_append(&prt_ps_buffer, IF_EB('\\', 0134)); break;

		default:
			   sprintf((char *)ch_buff, "%03o", (unsigned int)ch);
#ifdef EBCDIC
			   ebcdic2ascii(ch_buff, 3);
#endif
			   ga_append(&prt_ps_buffer, ch_buff[0]);
			   ga_append(&prt_ps_buffer, ch_buff[1]);
			   ga_append(&prt_ps_buffer, ch_buff[2]);
			   break;
	    }
	}
	else
	    ga_append(&prt_ps_buffer, ch);
    }

#ifdef FEAT_MBYTE
    /* Need to free any translated characters */
    if (prt_do_conv && (*p != NUL))
	vim_free(p);
#endif

    prt_text_run += char_width;
    prt_pos_x += char_width;

    /* The downside of fp - use relative error on right margin check */
    next_pos = prt_pos_x + prt_char_width;
    need_break = (next_pos > prt_right_margin) &&
		    ((next_pos - prt_right_margin) > (prt_right_margin*1e-5));

    if (need_break)
	prt_flush_buffer();

    return need_break;
}

    void
mch_print_set_font(iBold, iItalic, iUnderline)
    int		iBold;
    int		iItalic;
    int		iUnderline;
{
    int		font = 0;

    if (iBold)
	font |= 0x01;
    if (iItalic)
	font |= 0x02;

    if (font != prt_font)
    {
	prt_font = font;
	prt_attribute_change = TRUE;
	prt_need_font = TRUE;
    }
    if (prt_underline != iUnderline)
    {
	prt_underline = iUnderline;
	prt_attribute_change = TRUE;
	prt_need_underline = TRUE;
    }
}

    void
mch_print_set_bg(bgcol)
    long_u	bgcol;
{
    prt_bgcol = (int)bgcol;
    prt_attribute_change = TRUE;
    prt_need_bgcol = TRUE;
}

    void
mch_print_set_fg(fgcol)
    long_u	fgcol;
{
    if (fgcol != (long_u)prt_fgcol)
    {
	prt_fgcol = (int)fgcol;
	prt_attribute_change = TRUE;
	prt_need_fgcol = TRUE;
    }
}

# endif /*FEAT_POSTSCRIPT*/
#endif /*FEAT_PRINTER*/