1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
|
-- merged file : luatex-fonts-merged.lua
-- parent file : luatex-fonts.lua
-- merge date : 04/14/13 16:51:15
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['l-lua']={
version=1.001,
comment="companion to luat-lib.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local major,minor=string.match(_VERSION,"^[^%d]+(%d+)%.(%d+).*$")
_MAJORVERSION=tonumber(major) or 5
_MINORVERSION=tonumber(minor) or 1
_LUAVERSION=_MAJORVERSION+_MINORVERSION/10
if not lpeg then
lpeg=require("lpeg")
end
if loadstring then
local loadnormal=load
function load(first,...)
if type(first)=="string" then
return loadstring(first,...)
else
return loadnormal(first,...)
end
end
else
loadstring=load
end
if not ipairs then
local function iterate(a,i)
i=i+1
local v=a[i]
if v~=nil then
return i,v
end
end
function ipairs(a)
return iterate,a,0
end
end
if not pairs then
function pairs(t)
return next,t
end
end
if not table.unpack then
table.unpack=_G.unpack
elseif not unpack then
_G.unpack=table.unpack
end
if not package.loaders then
package.loaders=package.searchers
end
local print,select,tostring=print,select,tostring
local inspectors={}
function setinspector(inspector)
inspectors[#inspectors+1]=inspector
end
function inspect(...)
for s=1,select("#",...) do
local value=select(s,...)
local done=false
for i=1,#inspectors do
done=inspectors[i](value)
if done then
break
end
end
if not done then
print(tostring(value))
end
end
end
local dummy=function() end
function optionalrequire(...)
local ok,result=xpcall(require,dummy,...)
if ok then
return result
end
end
local type=type
local gsub,format=string.gsub,string.format
local package=package
local searchers=package.searchers or package.loaders
local libpaths=nil
local clibpaths=nil
local libhash={}
local clibhash={}
local libextras={}
local clibextras={}
local filejoin=file and file.join or function(path,name) return path.."/"..name end
local isreadable=file and file.is_readable or function(name) local f=io.open(name) if f then f:close() return true end end
local addsuffix=file and file.addsuffix or function(name,suffix) return name.."."..suffix end
local function cleanpath(path)
return path
end
local helpers=package.helpers or {
libpaths=function() return {} end,
clibpaths=function() return {} end,
cleanpath=cleanpath,
trace=false,
report=function(...) print(format(...)) end,
}
package.helpers=helpers
local function getlibpaths()
return libpaths or helpers.libpaths(libhash)
end
local function getclibpaths()
return clibpaths or helpers.clibpaths(clibhash)
end
package.libpaths=getlibpaths
package.clibpaths=getclibpaths
local function addpath(what,paths,extras,hash,...)
local pathlist={... }
local cleanpath=helpers.cleanpath
local trace=helpers.trace
local report=helpers.report
local function add(path)
local path=cleanpath(path)
if not hash[path] then
if trace then
report("extra %s path: %s",what,path)
end
paths [#paths+1]=path
extras[#extras+1]=path
end
end
for p=1,#pathlist do
local path=pathlist[p]
if type(path)=="table" then
for i=1,#path do
add(path[i])
end
else
add(path)
end
end
return paths,extras
end
function package.extralibpath(...)
libpaths,libextras=addpath("lua",getlibpaths(),libextras,libhash,...)
end
function package.extraclibpath(...)
clibpaths,clibextras=addpath("lib",getclibpaths(),clibextras,clibhash,...)
end
if not searchers[-2] then
searchers[-2]=searchers[2]
end
searchers[2]=function(name)
return helpers.loaded(name)
end
searchers[3]=nil
local function loadedaslib(resolved,rawname)
local init="luaopen_"..gsub(rawname,"%.","_")
if helpers.trace then
helpers.report("calling loadlib with '%s' with init '%s'",resolved,init)
end
return package.loadlib(resolved,init)
end
local function loadedbylua(name)
if helpers.trace then
helpers.report("locating '%s' using normal loader",name)
end
return true,searchers[-2](name)
end
local function loadedbypath(name,rawname,paths,islib,what)
local trace=helpers.trace
local report=helpers.report
if trace then
report("locating '%s' as '%s' on '%s' paths",rawname,name,what)
end
for p=1,#paths do
local path=paths[p]
local resolved=filejoin(path,name)
if trace then
report("checking for '%s' using '%s' path '%s'",name,what,path)
end
if isreadable(resolved) then
if trace then
report("lib '%s' located on '%s'",name,resolved)
end
if islib then
return true,loadedaslib(resolved,rawname)
else
return true,loadfile(resolved)
end
end
end
end
local function notloaded(name)
if helpers.trace then
helpers.report("unable to locate library '%s'",name)
end
end
helpers.loadedaslib=loadedaslib
helpers.loadedbylua=loadedbylua
helpers.loadedbypath=loadedbypath
helpers.notloaded=notloaded
function helpers.loaded(name)
local thename=gsub(name,"%.","/")
local luaname=addsuffix(thename,"lua")
local libname=addsuffix(thename,os.libsuffix or "so")
local libpaths=getlibpaths()
local clibpaths=getclibpaths()
local done,result=loadedbypath(luaname,name,libpaths,false,"lua")
if done then
return result
end
local done,result=loadedbypath(luaname,name,clibpaths,false,"lua")
if done then
return result
end
local done,result=loadedbypath(libname,name,clibpaths,true,"lib")
if done then
return result
end
local done,result=loadedbylua(name)
if done then
return result
end
return notloaded(name)
end
function helpers.unload(name)
if helpers.trace then
if package.loaded[name] then
helpers.report("unloading library '%s', %s",name,"done")
else
helpers.report("unloading library '%s', %s",name,"not loaded")
end
end
package.loaded[name]=nil
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['l-lpeg']={
version=1.001,
comment="companion to luat-lib.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
lpeg=require("lpeg")
local type,next,tostring=type,next,tostring
local byte,char,gmatch,format=string.byte,string.char,string.gmatch,string.format
local floor=math.floor
local P,R,S,V,Ct,C,Cs,Cc,Cp,Cmt=lpeg.P,lpeg.R,lpeg.S,lpeg.V,lpeg.Ct,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.Cp,lpeg.Cmt
local lpegtype,lpegmatch,lpegprint=lpeg.type,lpeg.match,lpeg.print
setinspector(function(v) if lpegtype(v) then lpegprint(v) return true end end)
lpeg.patterns=lpeg.patterns or {}
local patterns=lpeg.patterns
local anything=P(1)
local endofstring=P(-1)
local alwaysmatched=P(true)
patterns.anything=anything
patterns.endofstring=endofstring
patterns.beginofstring=alwaysmatched
patterns.alwaysmatched=alwaysmatched
local digit,sign=R('09'),S('+-')
local cr,lf,crlf=P("\r"),P("\n"),P("\r\n")
local newline=crlf+S("\r\n")
local escaped=P("\\")*anything
local squote=P("'")
local dquote=P('"')
local space=P(" ")
local utfbom_32_be=P('\000\000\254\255')
local utfbom_32_le=P('\255\254\000\000')
local utfbom_16_be=P('\255\254')
local utfbom_16_le=P('\254\255')
local utfbom_8=P('\239\187\191')
local utfbom=utfbom_32_be+utfbom_32_le+utfbom_16_be+utfbom_16_le+utfbom_8
local utftype=utfbom_32_be*Cc("utf-32-be")+utfbom_32_le*Cc("utf-32-le")+utfbom_16_be*Cc("utf-16-be")+utfbom_16_le*Cc("utf-16-le")+utfbom_8*Cc("utf-8")+alwaysmatched*Cc("utf-8")
local utfoffset=utfbom_32_be*Cc(4)+utfbom_32_le*Cc(4)+utfbom_16_be*Cc(2)+utfbom_16_le*Cc(2)+utfbom_8*Cc(3)+Cc(0)
local utf8next=R("\128\191")
patterns.utf8one=R("\000\127")
patterns.utf8two=R("\194\223")*utf8next
patterns.utf8three=R("\224\239")*utf8next*utf8next
patterns.utf8four=R("\240\244")*utf8next*utf8next*utf8next
patterns.utfbom=utfbom
patterns.utftype=utftype
patterns.utfoffset=utfoffset
local utf8char=patterns.utf8one+patterns.utf8two+patterns.utf8three+patterns.utf8four
local validutf8char=utf8char^0*endofstring*Cc(true)+Cc(false)
local utf8character=P(1)*R("\128\191")^0
patterns.utf8=utf8char
patterns.utf8char=utf8char
patterns.utf8character=utf8character
patterns.validutf8=validutf8char
patterns.validutf8char=validutf8char
local eol=S("\n\r")
local spacer=S(" \t\f\v")
local whitespace=eol+spacer
local nonspacer=1-spacer
local nonwhitespace=1-whitespace
patterns.eol=eol
patterns.spacer=spacer
patterns.whitespace=whitespace
patterns.nonspacer=nonspacer
patterns.nonwhitespace=nonwhitespace
local stripper=spacer^0*C((spacer^0*nonspacer^1)^0)
local collapser=Cs(spacer^0/""*nonspacer^0*((spacer^0/" "*nonspacer^1)^0))
patterns.stripper=stripper
patterns.collapser=collapser
patterns.digit=digit
patterns.sign=sign
patterns.cardinal=sign^0*digit^1
patterns.integer=sign^0*digit^1
patterns.unsigned=digit^0*P('.')*digit^1
patterns.float=sign^0*patterns.unsigned
patterns.cunsigned=digit^0*P(',')*digit^1
patterns.cfloat=sign^0*patterns.cunsigned
patterns.number=patterns.float+patterns.integer
patterns.cnumber=patterns.cfloat+patterns.integer
patterns.oct=P("0")*R("07")^1
patterns.octal=patterns.oct
patterns.HEX=P("0x")*R("09","AF")^1
patterns.hex=P("0x")*R("09","af")^1
patterns.hexadecimal=P("0x")*R("09","AF","af")^1
patterns.lowercase=R("az")
patterns.uppercase=R("AZ")
patterns.letter=patterns.lowercase+patterns.uppercase
patterns.space=space
patterns.tab=P("\t")
patterns.spaceortab=patterns.space+patterns.tab
patterns.newline=newline
patterns.emptyline=newline^1
patterns.equal=P("=")
patterns.comma=P(",")
patterns.commaspacer=P(",")*spacer^0
patterns.period=P(".")
patterns.colon=P(":")
patterns.semicolon=P(";")
patterns.underscore=P("_")
patterns.escaped=escaped
patterns.squote=squote
patterns.dquote=dquote
patterns.nosquote=(escaped+(1-squote))^0
patterns.nodquote=(escaped+(1-dquote))^0
patterns.unsingle=(squote/"")*patterns.nosquote*(squote/"")
patterns.undouble=(dquote/"")*patterns.nodquote*(dquote/"")
patterns.unquoted=patterns.undouble+patterns.unsingle
patterns.unspacer=((patterns.spacer^1)/"")^0
patterns.singlequoted=squote*patterns.nosquote*squote
patterns.doublequoted=dquote*patterns.nodquote*dquote
patterns.quoted=patterns.doublequoted+patterns.singlequoted
patterns.propername=R("AZ","az","__")*R("09","AZ","az","__")^0*P(-1)
patterns.somecontent=(anything-newline-space)^1
patterns.beginline=#(1-newline)
patterns.longtostring=Cs(whitespace^0/""*nonwhitespace^0*((whitespace^0/" "*(patterns.quoted+nonwhitespace)^1)^0))
local function anywhere(pattern)
return P { P(pattern)+1*V(1) }
end
lpeg.anywhere=anywhere
function lpeg.instringchecker(p)
p=anywhere(p)
return function(str)
return lpegmatch(p,str) and true or false
end
end
function lpeg.splitter(pattern,action)
return (((1-P(pattern))^1)/action+1)^0
end
function lpeg.tsplitter(pattern,action)
return Ct((((1-P(pattern))^1)/action+1)^0)
end
local splitters_s,splitters_m,splitters_t={},{},{}
local function splitat(separator,single)
local splitter=(single and splitters_s[separator]) or splitters_m[separator]
if not splitter then
separator=P(separator)
local other=C((1-separator)^0)
if single then
local any=anything
splitter=other*(separator*C(any^0)+"")
splitters_s[separator]=splitter
else
splitter=other*(separator*other)^0
splitters_m[separator]=splitter
end
end
return splitter
end
local function tsplitat(separator)
local splitter=splitters_t[separator]
if not splitter then
splitter=Ct(splitat(separator))
splitters_t[separator]=splitter
end
return splitter
end
lpeg.splitat=splitat
lpeg.tsplitat=tsplitat
function string.splitup(str,separator)
if not separator then
separator=","
end
return lpegmatch(splitters_m[separator] or splitat(separator),str)
end
local cache={}
function lpeg.split(separator,str)
local c=cache[separator]
if not c then
c=tsplitat(separator)
cache[separator]=c
end
return lpegmatch(c,str)
end
function string.split(str,separator)
if separator then
local c=cache[separator]
if not c then
c=tsplitat(separator)
cache[separator]=c
end
return lpegmatch(c,str)
else
return { str }
end
end
local spacing=patterns.spacer^0*newline
local empty=spacing*Cc("")
local nonempty=Cs((1-spacing)^1)*spacing^-1
local content=(empty+nonempty)^1
patterns.textline=content
local linesplitter=tsplitat(newline)
patterns.linesplitter=linesplitter
function string.splitlines(str)
return lpegmatch(linesplitter,str)
end
local cache={}
function lpeg.checkedsplit(separator,str)
local c=cache[separator]
if not c then
separator=P(separator)
local other=C((1-separator)^1)
c=Ct(separator^0*other*(separator^1*other)^0)
cache[separator]=c
end
return lpegmatch(c,str)
end
function string.checkedsplit(str,separator)
local c=cache[separator]
if not c then
separator=P(separator)
local other=C((1-separator)^1)
c=Ct(separator^0*other*(separator^1*other)^0)
cache[separator]=c
end
return lpegmatch(c,str)
end
local function f2(s) local c1,c2=byte(s,1,2) return c1*64+c2-12416 end
local function f3(s) local c1,c2,c3=byte(s,1,3) return (c1*64+c2)*64+c3-925824 end
local function f4(s) local c1,c2,c3,c4=byte(s,1,4) return ((c1*64+c2)*64+c3)*64+c4-63447168 end
local utf8byte=patterns.utf8one/byte+patterns.utf8two/f2+patterns.utf8three/f3+patterns.utf8four/f4
patterns.utf8byte=utf8byte
local cache={}
function lpeg.stripper(str)
if type(str)=="string" then
local s=cache[str]
if not s then
s=Cs(((S(str)^1)/""+1)^0)
cache[str]=s
end
return s
else
return Cs(((str^1)/""+1)^0)
end
end
local cache={}
function lpeg.keeper(str)
if type(str)=="string" then
local s=cache[str]
if not s then
s=Cs((((1-S(str))^1)/""+1)^0)
cache[str]=s
end
return s
else
return Cs((((1-str)^1)/""+1)^0)
end
end
function lpeg.frontstripper(str)
return (P(str)+P(true))*Cs(anything^0)
end
function lpeg.endstripper(str)
return Cs((1-P(str)*endofstring)^0)
end
function lpeg.replacer(one,two,makefunction,isutf)
local pattern
local u=isutf and utf8char or 1
if type(one)=="table" then
local no=#one
local p=P(false)
if no==0 then
for k,v in next,one do
p=p+P(k)/v
end
pattern=Cs((p+u)^0)
elseif no==1 then
local o=one[1]
one,two=P(o[1]),o[2]
pattern=Cs((one/two+u)^0)
else
for i=1,no do
local o=one[i]
p=p+P(o[1])/o[2]
end
pattern=Cs((p+u)^0)
end
else
pattern=Cs((P(one)/(two or "")+u)^0)
end
if makefunction then
return function(str)
return lpegmatch(pattern,str)
end
else
return pattern
end
end
function lpeg.finder(lst,makefunction)
local pattern
if type(lst)=="table" then
pattern=P(false)
if #lst==0 then
for k,v in next,lst do
pattern=pattern+P(k)
end
else
for i=1,#lst do
pattern=pattern+P(lst[i])
end
end
else
pattern=P(lst)
end
pattern=(1-pattern)^0*pattern
if makefunction then
return function(str)
return lpegmatch(pattern,str)
end
else
return pattern
end
end
local splitters_f,splitters_s={},{}
function lpeg.firstofsplit(separator)
local splitter=splitters_f[separator]
if not splitter then
separator=P(separator)
splitter=C((1-separator)^0)
splitters_f[separator]=splitter
end
return splitter
end
function lpeg.secondofsplit(separator)
local splitter=splitters_s[separator]
if not splitter then
separator=P(separator)
splitter=(1-separator)^0*separator*C(anything^0)
splitters_s[separator]=splitter
end
return splitter
end
function lpeg.balancer(left,right)
left,right=P(left),P(right)
return P { left*((1-left-right)+V(1))^0*right }
end
local nany=utf8char/""
function lpeg.counter(pattern)
pattern=Cs((P(pattern)/" "+nany)^0)
return function(str)
return #lpegmatch(pattern,str)
end
end
utf=utf or (unicode and unicode.utf8) or {}
local utfcharacters=utf and utf.characters or string.utfcharacters
local utfgmatch=utf and utf.gmatch
local utfchar=utf and utf.char
lpeg.UP=lpeg.P
if utfcharacters then
function lpeg.US(str)
local p=P(false)
for uc in utfcharacters(str) do
p=p+P(uc)
end
return p
end
elseif utfgmatch then
function lpeg.US(str)
local p=P(false)
for uc in utfgmatch(str,".") do
p=p+P(uc)
end
return p
end
else
function lpeg.US(str)
local p=P(false)
local f=function(uc)
p=p+P(uc)
end
lpegmatch((utf8char/f)^0,str)
return p
end
end
local range=utf8byte*utf8byte+Cc(false)
function lpeg.UR(str,more)
local first,last
if type(str)=="number" then
first=str
last=more or first
else
first,last=lpegmatch(range,str)
if not last then
return P(str)
end
end
if first==last then
return P(str)
elseif utfchar and (last-first<8) then
local p=P(false)
for i=first,last do
p=p+P(utfchar(i))
end
return p
else
local f=function(b)
return b>=first and b<=last
end
return utf8byte/f
end
end
function lpeg.is_lpeg(p)
return p and lpegtype(p)=="pattern"
end
function lpeg.oneof(list,...)
if type(list)~="table" then
list={ list,... }
end
local p=P(list[1])
for l=2,#list do
p=p+P(list[l])
end
return p
end
local sort=table.sort
local function copyindexed(old)
local new={}
for i=1,#old do
new[i]=old
end
return new
end
local function sortedkeys(tab)
local keys,s={},0
for key,_ in next,tab do
s=s+1
keys[s]=key
end
sort(keys)
return keys
end
function lpeg.append(list,pp,delayed,checked)
local p=pp
if #list>0 then
local keys=copyindexed(list)
sort(keys)
for i=#keys,1,-1 do
local k=keys[i]
if p then
p=P(k)+p
else
p=P(k)
end
end
elseif delayed then
local keys=sortedkeys(list)
if p then
for i=1,#keys,1 do
local k=keys[i]
local v=list[k]
p=P(k)/list+p
end
else
for i=1,#keys do
local k=keys[i]
local v=list[k]
if p then
p=P(k)+p
else
p=P(k)
end
end
if p then
p=p/list
end
end
elseif checked then
local keys=sortedkeys(list)
for i=1,#keys do
local k=keys[i]
local v=list[k]
if p then
if k==v then
p=P(k)+p
else
p=P(k)/v+p
end
else
if k==v then
p=P(k)
else
p=P(k)/v
end
end
end
else
local keys=sortedkeys(list)
for i=1,#keys do
local k=keys[i]
local v=list[k]
if p then
p=P(k)/v+p
else
p=P(k)/v
end
end
end
return p
end
local function make(t)
local p
local keys=sortedkeys(t)
for i=1,#keys do
local k=keys[i]
local v=t[k]
if not p then
if next(v) then
p=P(k)*make(v)
else
p=P(k)
end
else
if next(v) then
p=p+P(k)*make(v)
else
p=p+P(k)
end
end
end
return p
end
function lpeg.utfchartabletopattern(list)
local tree={}
for i=1,#list do
local t=tree
for c in gmatch(list[i],".") do
if not t[c] then
t[c]={}
end
t=t[c]
end
end
return make(tree)
end
patterns.containseol=lpeg.finder(eol)
local function nextstep(n,step,result)
local m=n%step
local d=floor(n/step)
if d>0 then
local v=V(tostring(step))
local s=result.start
for i=1,d do
if s then
s=v*s
else
s=v
end
end
result.start=s
end
if step>1 and result.start then
local v=V(tostring(step/2))
result[tostring(step)]=v*v
end
if step>0 then
return nextstep(m,step/2,result)
else
return result
end
end
function lpeg.times(pattern,n)
return P(nextstep(n,2^16,{ "start",["1"]=pattern }))
end
local digit=R("09")
local period=P(".")
local zero=P("0")
local trailingzeros=zero^0*-digit
local case_1=period*trailingzeros/""
local case_2=period*(digit-trailingzeros)^1*(trailingzeros/"")
local number=digit^1*(case_1+case_2)
local stripper=Cs((number+1)^0)
lpeg.patterns.stripzeros=stripper
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['l-functions']={
version=1.001,
comment="companion to luat-lib.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
functions=functions or {}
function functions.dummy() end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['l-string']={
version=1.001,
comment="companion to luat-lib.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local string=string
local sub,gmatch,format,char,byte,rep,lower=string.sub,string.gmatch,string.format,string.char,string.byte,string.rep,string.lower
local lpegmatch,patterns=lpeg.match,lpeg.patterns
local P,S,C,Ct,Cc,Cs=lpeg.P,lpeg.S,lpeg.C,lpeg.Ct,lpeg.Cc,lpeg.Cs
local unquoted=patterns.squote*C(patterns.nosquote)*patterns.squote+patterns.dquote*C(patterns.nodquote)*patterns.dquote
function string.unquoted(str)
return lpegmatch(unquoted,str) or str
end
function string.quoted(str)
return format("%q",str)
end
function string.count(str,pattern)
local n=0
for _ in gmatch(str,pattern) do
n=n+1
end
return n
end
function string.limit(str,n,sentinel)
if #str>n then
sentinel=sentinel or "..."
return sub(str,1,(n-#sentinel))..sentinel
else
return str
end
end
local stripper=patterns.stripper
local collapser=patterns.collapser
local longtostring=patterns.longtostring
function string.strip(str)
return lpegmatch(stripper,str) or ""
end
function string.collapsespaces(str)
return lpegmatch(collapser,str) or ""
end
function string.longtostring(str)
return lpegmatch(longtostring,str) or ""
end
local pattern=P(" ")^0*P(-1)
function string.is_empty(str)
if str=="" then
return true
else
return lpegmatch(pattern,str) and true or false
end
end
local anything=patterns.anything
local allescapes=Cc("%")*S(".-+%?()[]*")
local someescapes=Cc("%")*S(".-+%()[]")
local matchescapes=Cc(".")*S("*?")
local pattern_a=Cs ((allescapes+anything )^0 )
local pattern_b=Cs ((someescapes+matchescapes+anything )^0 )
local pattern_c=Cs (Cc("^")*(someescapes+matchescapes+anything )^0*Cc("$") )
function string.escapedpattern(str,simple)
return lpegmatch(simple and pattern_b or pattern_a,str)
end
function string.topattern(str,lowercase,strict)
if str=="" or type(str)~="string" then
return ".*"
elseif strict then
str=lpegmatch(pattern_c,str)
else
str=lpegmatch(pattern_b,str)
end
if lowercase then
return lower(str)
else
return str
end
end
function string.valid(str,default)
return (type(str)=="string" and str~="" and str) or default or nil
end
string.itself=function(s) return s end
local pattern=Ct(C(1)^0)
function string.totable(str)
return lpegmatch(pattern,str)
end
local replacer=lpeg.replacer("@","%%")
function string.tformat(fmt,...)
return format(lpegmatch(replacer,fmt),...)
end
string.quote=string.quoted
string.unquote=string.unquoted
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['l-table']={
version=1.001,
comment="companion to luat-lib.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local type,next,tostring,tonumber,ipairs,select=type,next,tostring,tonumber,ipairs,select
local table,string=table,string
local concat,sort,insert,remove=table.concat,table.sort,table.insert,table.remove
local format,lower,dump=string.format,string.lower,string.dump
local getmetatable,setmetatable=getmetatable,setmetatable
local getinfo=debug.getinfo
local lpegmatch,patterns=lpeg.match,lpeg.patterns
local floor=math.floor
local stripper=patterns.stripper
function table.strip(tab)
local lst,l={},0
for i=1,#tab do
local s=lpegmatch(stripper,tab[i]) or ""
if s=="" then
else
l=l+1
lst[l]=s
end
end
return lst
end
function table.keys(t)
if t then
local keys,k={},0
for key,_ in next,t do
k=k+1
keys[k]=key
end
return keys
else
return {}
end
end
local function compare(a,b)
local ta,tb=type(a),type(b)
if ta==tb then
return a<b
else
return tostring(a)<tostring(b)
end
end
local function sortedkeys(tab)
if tab then
local srt,category,s={},0,0
for key,_ in next,tab do
s=s+1
srt[s]=key
if category==3 then
else
local tkey=type(key)
if tkey=="string" then
category=(category==2 and 3) or 1
elseif tkey=="number" then
category=(category==1 and 3) or 2
else
category=3
end
end
end
if category==0 or category==3 then
sort(srt,compare)
else
sort(srt)
end
return srt
else
return {}
end
end
local function sortedhashkeys(tab,cmp)
if tab then
local srt,s={},0
for key,_ in next,tab do
if key then
s=s+1
srt[s]=key
end
end
sort(srt,cmp)
return srt
else
return {}
end
end
function table.allkeys(t)
local keys={}
for k,v in next,t do
for k,v in next,v do
keys[k]=true
end
end
return sortedkeys(keys)
end
table.sortedkeys=sortedkeys
table.sortedhashkeys=sortedhashkeys
local function nothing() end
local function sortedhash(t,cmp)
if t then
local s
if cmp then
s=sortedhashkeys(t,function(a,b) return cmp(t,a,b) end)
else
s=sortedkeys(t)
end
local n=0
local function kv(s)
n=n+1
local k=s[n]
return k,t[k]
end
return kv,s
else
return nothing
end
end
table.sortedhash=sortedhash
table.sortedpairs=sortedhash
function table.append(t,list)
local n=#t
for i=1,#list do
n=n+1
t[n]=list[i]
end
return t
end
function table.prepend(t,list)
local nl=#list
local nt=nl+#t
for i=#t,1,-1 do
t[nt]=t[i]
nt=nt-1
end
for i=1,#list do
t[i]=list[i]
end
return t
end
function table.merge(t,...)
t=t or {}
for i=1,select("#",...) do
for k,v in next,(select(i,...)) do
t[k]=v
end
end
return t
end
function table.merged(...)
local t={}
for i=1,select("#",...) do
for k,v in next,(select(i,...)) do
t[k]=v
end
end
return t
end
function table.imerge(t,...)
local nt=#t
for i=1,select("#",...) do
local nst=select(i,...)
for j=1,#nst do
nt=nt+1
t[nt]=nst[j]
end
end
return t
end
function table.imerged(...)
local tmp,ntmp={},0
for i=1,select("#",...) do
local nst=select(i,...)
for j=1,#nst do
ntmp=ntmp+1
tmp[ntmp]=nst[j]
end
end
return tmp
end
local function fastcopy(old,metatabletoo)
if old then
local new={}
for k,v in next,old do
if type(v)=="table" then
new[k]=fastcopy(v,metatabletoo)
else
new[k]=v
end
end
if metatabletoo then
local mt=getmetatable(old)
if mt then
setmetatable(new,mt)
end
end
return new
else
return {}
end
end
local function copy(t,tables)
tables=tables or {}
local tcopy={}
if not tables[t] then
tables[t]=tcopy
end
for i,v in next,t do
if type(i)=="table" then
if tables[i] then
i=tables[i]
else
i=copy(i,tables)
end
end
if type(v)~="table" then
tcopy[i]=v
elseif tables[v] then
tcopy[i]=tables[v]
else
tcopy[i]=copy(v,tables)
end
end
local mt=getmetatable(t)
if mt then
setmetatable(tcopy,mt)
end
return tcopy
end
table.fastcopy=fastcopy
table.copy=copy
function table.derive(parent)
local child={}
if parent then
setmetatable(child,{ __index=parent })
end
return child
end
function table.tohash(t,value)
local h={}
if t then
if value==nil then value=true end
for _,v in next,t do
h[v]=value
end
end
return h
end
function table.fromhash(t)
local hsh,h={},0
for k,v in next,t do
if v then
h=h+1
hsh[h]=k
end
end
return hsh
end
local noquotes,hexify,handle,reduce,compact,inline,functions
local reserved=table.tohash {
'and','break','do','else','elseif','end','false','for','function','if',
'in','local','nil','not','or','repeat','return','then','true','until','while',
}
local function simple_table(t)
if #t>0 then
local n=0
for _,v in next,t do
n=n+1
end
if n==#t then
local tt,nt={},0
for i=1,#t do
local v=t[i]
local tv=type(v)
if tv=="number" then
nt=nt+1
if hexify then
tt[nt]=format("0x%04X",v)
else
tt[nt]=tostring(v)
end
elseif tv=="boolean" then
nt=nt+1
tt[nt]=tostring(v)
elseif tv=="string" then
nt=nt+1
tt[nt]=format("%q",v)
else
tt=nil
break
end
end
return tt
end
end
return nil
end
local propername=patterns.propername
local function dummy() end
local function do_serialize(root,name,depth,level,indexed)
if level>0 then
depth=depth.." "
if indexed then
handle(format("%s{",depth))
else
local tn=type(name)
if tn=="number" then
if hexify then
handle(format("%s[0x%04X]={",depth,name))
else
handle(format("%s[%s]={",depth,name))
end
elseif tn=="string" then
if noquotes and not reserved[name] and lpegmatch(propername,name) then
handle(format("%s%s={",depth,name))
else
handle(format("%s[%q]={",depth,name))
end
elseif tn=="boolean" then
handle(format("%s[%s]={",depth,tostring(name)))
else
handle(format("%s{",depth))
end
end
end
if root and next(root) then
local first,last=nil,0
if compact then
last=#root
for k=1,last do
if root[k]==nil then
last=k-1
break
end
end
if last>0 then
first=1
end
end
local sk=sortedkeys(root)
for i=1,#sk do
local k=sk[i]
local v=root[k]
local t,tk=type(v),type(k)
if compact and first and tk=="number" and k>=first and k<=last then
if t=="number" then
if hexify then
handle(format("%s 0x%04X,",depth,v))
else
handle(format("%s %s,",depth,v))
end
elseif t=="string" then
if reduce and tonumber(v) then
handle(format("%s %s,",depth,v))
else
handle(format("%s %q,",depth,v))
end
elseif t=="table" then
if not next(v) then
handle(format("%s {},",depth))
elseif inline then
local st=simple_table(v)
if st then
handle(format("%s { %s },",depth,concat(st,", ")))
else
do_serialize(v,k,depth,level+1,true)
end
else
do_serialize(v,k,depth,level+1,true)
end
elseif t=="boolean" then
handle(format("%s %s,",depth,tostring(v)))
elseif t=="function" then
if functions then
handle(format('%s load(%q),',depth,dump(v)))
else
handle(format('%s "function",',depth))
end
else
handle(format("%s %q,",depth,tostring(v)))
end
elseif k=="__p__" then
if false then
handle(format("%s __p__=nil,",depth))
end
elseif t=="number" then
if tk=="number" then
if hexify then
handle(format("%s [0x%04X]=0x%04X,",depth,k,v))
else
handle(format("%s [%s]=%s,",depth,k,v))
end
elseif tk=="boolean" then
if hexify then
handle(format("%s [%s]=0x%04X,",depth,tostring(k),v))
else
handle(format("%s [%s]=%s,",depth,tostring(k),v))
end
elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
if hexify then
handle(format("%s %s=0x%04X,",depth,k,v))
else
handle(format("%s %s=%s,",depth,k,v))
end
else
if hexify then
handle(format("%s [%q]=0x%04X,",depth,k,v))
else
handle(format("%s [%q]=%s,",depth,k,v))
end
end
elseif t=="string" then
if reduce and tonumber(v) then
if tk=="number" then
if hexify then
handle(format("%s [0x%04X]=%s,",depth,k,v))
else
handle(format("%s [%s]=%s,",depth,k,v))
end
elseif tk=="boolean" then
handle(format("%s [%s]=%s,",depth,tostring(k),v))
elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
handle(format("%s %s=%s,",depth,k,v))
else
handle(format("%s [%q]=%s,",depth,k,v))
end
else
if tk=="number" then
if hexify then
handle(format("%s [0x%04X]=%q,",depth,k,v))
else
handle(format("%s [%s]=%q,",depth,k,v))
end
elseif tk=="boolean" then
handle(format("%s [%s]=%q,",depth,tostring(k),v))
elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
handle(format("%s %s=%q,",depth,k,v))
else
handle(format("%s [%q]=%q,",depth,k,v))
end
end
elseif t=="table" then
if not next(v) then
if tk=="number" then
if hexify then
handle(format("%s [0x%04X]={},",depth,k))
else
handle(format("%s [%s]={},",depth,k))
end
elseif tk=="boolean" then
handle(format("%s [%s]={},",depth,tostring(k)))
elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
handle(format("%s %s={},",depth,k))
else
handle(format("%s [%q]={},",depth,k))
end
elseif inline then
local st=simple_table(v)
if st then
if tk=="number" then
if hexify then
handle(format("%s [0x%04X]={ %s },",depth,k,concat(st,", ")))
else
handle(format("%s [%s]={ %s },",depth,k,concat(st,", ")))
end
elseif tk=="boolean" then
handle(format("%s [%s]={ %s },",depth,tostring(k),concat(st,", ")))
elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
handle(format("%s %s={ %s },",depth,k,concat(st,", ")))
else
handle(format("%s [%q]={ %s },",depth,k,concat(st,", ")))
end
else
do_serialize(v,k,depth,level+1)
end
else
do_serialize(v,k,depth,level+1)
end
elseif t=="boolean" then
if tk=="number" then
if hexify then
handle(format("%s [0x%04X]=%s,",depth,k,tostring(v)))
else
handle(format("%s [%s]=%s,",depth,k,tostring(v)))
end
elseif tk=="boolean" then
handle(format("%s [%s]=%s,",depth,tostring(k),tostring(v)))
elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
handle(format("%s %s=%s,",depth,k,tostring(v)))
else
handle(format("%s [%q]=%s,",depth,k,tostring(v)))
end
elseif t=="function" then
if functions then
local f=getinfo(v).what=="C" and dump(dummy) or dump(v)
if tk=="number" then
if hexify then
handle(format("%s [0x%04X]=load(%q),",depth,k,f))
else
handle(format("%s [%s]=load(%q),",depth,k,f))
end
elseif tk=="boolean" then
handle(format("%s [%s]=load(%q),",depth,tostring(k),f))
elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
handle(format("%s %s=load(%q),",depth,k,f))
else
handle(format("%s [%q]=load(%q),",depth,k,f))
end
end
else
if tk=="number" then
if hexify then
handle(format("%s [0x%04X]=%q,",depth,k,tostring(v)))
else
handle(format("%s [%s]=%q,",depth,k,tostring(v)))
end
elseif tk=="boolean" then
handle(format("%s [%s]=%q,",depth,tostring(k),tostring(v)))
elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
handle(format("%s %s=%q,",depth,k,tostring(v)))
else
handle(format("%s [%q]=%q,",depth,k,tostring(v)))
end
end
end
end
if level>0 then
handle(format("%s},",depth))
end
end
local function serialize(_handle,root,name,specification)
local tname=type(name)
if type(specification)=="table" then
noquotes=specification.noquotes
hexify=specification.hexify
handle=_handle or specification.handle or print
reduce=specification.reduce or false
functions=specification.functions
compact=specification.compact
inline=specification.inline and compact
if functions==nil then
functions=true
end
if compact==nil then
compact=true
end
if inline==nil then
inline=compact
end
else
noquotes=false
hexify=false
handle=_handle or print
reduce=false
compact=true
inline=true
functions=true
end
if tname=="string" then
if name=="return" then
handle("return {")
else
handle(name.."={")
end
elseif tname=="number" then
if hexify then
handle(format("[0x%04X]={",name))
else
handle("["..name.."]={")
end
elseif tname=="boolean" then
if name then
handle("return {")
else
handle("{")
end
else
handle("t={")
end
if root then
if getmetatable(root) then
local dummy=root._w_h_a_t_e_v_e_r_
root._w_h_a_t_e_v_e_r_=nil
end
if next(root) then
do_serialize(root,name,"",0)
end
end
handle("}")
end
function table.serialize(root,name,specification)
local t,n={},0
local function flush(s)
n=n+1
t[n]=s
end
serialize(flush,root,name,specification)
return concat(t,"\n")
end
table.tohandle=serialize
local maxtab=2*1024
function table.tofile(filename,root,name,specification)
local f=io.open(filename,'w')
if f then
if maxtab>1 then
local t,n={},0
local function flush(s)
n=n+1
t[n]=s
if n>maxtab then
f:write(concat(t,"\n"),"\n")
t,n={},0
end
end
serialize(flush,root,name,specification)
f:write(concat(t,"\n"),"\n")
else
local function flush(s)
f:write(s,"\n")
end
serialize(flush,root,name,specification)
end
f:close()
io.flush()
end
end
local function flattened(t,f,depth)
if f==nil then
f={}
depth=0xFFFF
elseif tonumber(f) then
depth=f
f={}
elseif not depth then
depth=0xFFFF
end
for k,v in next,t do
if type(k)~="number" then
if depth>0 and type(v)=="table" then
flattened(v,f,depth-1)
else
f[k]=v
end
end
end
local n=#f
for k=1,#t do
local v=t[k]
if depth>0 and type(v)=="table" then
flattened(v,f,depth-1)
n=#f
else
n=n+1
f[n]=v
end
end
return f
end
table.flattened=flattened
local function unnest(t,f)
if not f then
f={}
end
for i=1,#t do
local v=t[i]
if type(v)=="table" then
if type(v[1])=="table" then
unnest(v,f)
else
f[#f+1]=v
end
else
f[#f+1]=v
end
end
return f
end
function table.unnest(t)
return unnest(t)
end
local function are_equal(a,b,n,m)
if a and b and #a==#b then
n=n or 1
m=m or #a
for i=n,m do
local ai,bi=a[i],b[i]
if ai==bi then
elseif type(ai)=="table" and type(bi)=="table" then
if not are_equal(ai,bi) then
return false
end
else
return false
end
end
return true
else
return false
end
end
local function identical(a,b)
for ka,va in next,a do
local vb=b[ka]
if va==vb then
elseif type(va)=="table" and type(vb)=="table" then
if not identical(va,vb) then
return false
end
else
return false
end
end
return true
end
table.identical=identical
table.are_equal=are_equal
function table.compact(t)
if t then
for k,v in next,t do
if not next(v) then
t[k]=nil
end
end
end
end
function table.contains(t,v)
if t then
for i=1,#t do
if t[i]==v then
return i
end
end
end
return false
end
function table.count(t)
local n=0
for k,v in next,t do
n=n+1
end
return n
end
function table.swapped(t,s)
local n={}
if s then
for k,v in next,s do
n[k]=v
end
end
for k,v in next,t do
n[v]=k
end
return n
end
function table.mirrored(t)
local n={}
for k,v in next,t do
n[v]=k
n[k]=v
end
return n
end
function table.reversed(t)
if t then
local tt,tn={},#t
if tn>0 then
local ttn=0
for i=tn,1,-1 do
ttn=ttn+1
tt[ttn]=t[i]
end
end
return tt
end
end
function table.reverse(t)
if t then
local n=#t
for i=1,floor(n/2) do
local j=n-i+1
t[i],t[j]=t[j],t[i]
end
return t
end
end
function table.sequenced(t,sep,simple)
if not t then
return ""
end
local n=#t
local s={}
if n>0 then
for i=1,n do
s[i]=tostring(t[i])
end
else
n=0
for k,v in sortedhash(t) do
if simple then
if v==true then
n=n+1
s[n]=k
elseif v and v~="" then
n=n+1
s[n]=k.."="..tostring(v)
end
else
n=n+1
s[n]=k.."="..tostring(v)
end
end
end
return concat(s,sep or " | ")
end
function table.print(t,...)
if type(t)~="table" then
print(tostring(t))
else
serialize(print,t,...)
end
end
setinspector(function(v) if type(v)=="table" then serialize(print,v,"table") return true end end)
function table.sub(t,i,j)
return { unpack(t,i,j) }
end
function table.is_empty(t)
return not t or not next(t)
end
function table.has_one_entry(t)
return t and not next(t,next(t))
end
function table.loweredkeys(t)
local l={}
for k,v in next,t do
l[lower(k)]=v
end
return l
end
function table.unique(old)
local hash={}
local new={}
local n=0
for i=1,#old do
local oi=old[i]
if not hash[oi] then
n=n+1
new[n]=oi
hash[oi]=true
end
end
return new
end
function table.sorted(t,...)
sort(t,...)
return t
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['l-io']={
version=1.001,
comment="companion to luat-lib.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local io=io
local byte,find,gsub,format=string.byte,string.find,string.gsub,string.format
local concat=table.concat
local floor=math.floor
local type=type
if string.find(os.getenv("PATH"),";") then
io.fileseparator,io.pathseparator="\\",";"
else
io.fileseparator,io.pathseparator="/",":"
end
local function readall(f)
return f:read("*all")
end
local function readall(f)
local size=f:seek("end")
if size==0 then
return ""
elseif size<1024*1024 then
f:seek("set",0)
return f:read('*all')
else
local done=f:seek("set",0)
if size<1024*1024 then
step=1024*1024
elseif size>16*1024*1024 then
step=16*1024*1024
else
step=floor(size/(1024*1024))*1024*1024/8
end
local data={}
while true do
local r=f:read(step)
if not r then
return concat(data)
else
data[#data+1]=r
end
end
end
end
io.readall=readall
function io.loaddata(filename,textmode)
local f=io.open(filename,(textmode and 'r') or 'rb')
if f then
local data=readall(f)
f:close()
if #data>0 then
return data
end
end
end
function io.savedata(filename,data,joiner)
local f=io.open(filename,"wb")
if f then
if type(data)=="table" then
f:write(concat(data,joiner or ""))
elseif type(data)=="function" then
data(f)
else
f:write(data or "")
end
f:close()
io.flush()
return true
else
return false
end
end
function io.loadlines(filename,n)
local f=io.open(filename,'r')
if not f then
elseif n then
local lines={}
for i=1,n do
local line=f:read("*lines")
if line then
lines[#lines+1]=line
else
break
end
end
f:close()
lines=concat(lines,"\n")
if #lines>0 then
return lines
end
else
local line=f:read("*line") or ""
f:close()
if #line>0 then
return line
end
end
end
function io.loadchunk(filename,n)
local f=io.open(filename,'rb')
if f then
local data=f:read(n or 1024)
f:close()
if #data>0 then
return data
end
end
end
function io.exists(filename)
local f=io.open(filename)
if f==nil then
return false
else
f:close()
return true
end
end
function io.size(filename)
local f=io.open(filename)
if f==nil then
return 0
else
local s=f:seek("end")
f:close()
return s
end
end
function io.noflines(f)
if type(f)=="string" then
local f=io.open(filename)
if f then
local n=f and io.noflines(f) or 0
f:close()
return n
else
return 0
end
else
local n=0
for _ in f:lines() do
n=n+1
end
f:seek('set',0)
return n
end
end
local nextchar={
[ 4]=function(f)
return f:read(1,1,1,1)
end,
[ 2]=function(f)
return f:read(1,1)
end,
[ 1]=function(f)
return f:read(1)
end,
[-2]=function(f)
local a,b=f:read(1,1)
return b,a
end,
[-4]=function(f)
local a,b,c,d=f:read(1,1,1,1)
return d,c,b,a
end
}
function io.characters(f,n)
if f then
return nextchar[n or 1],f
end
end
local nextbyte={
[4]=function(f)
local a,b,c,d=f:read(1,1,1,1)
if d then
return byte(a),byte(b),byte(c),byte(d)
end
end,
[3]=function(f)
local a,b,c=f:read(1,1,1)
if b then
return byte(a),byte(b),byte(c)
end
end,
[2]=function(f)
local a,b=f:read(1,1)
if b then
return byte(a),byte(b)
end
end,
[1]=function (f)
local a=f:read(1)
if a then
return byte(a)
end
end,
[-2]=function (f)
local a,b=f:read(1,1)
if b then
return byte(b),byte(a)
end
end,
[-3]=function(f)
local a,b,c=f:read(1,1,1)
if b then
return byte(c),byte(b),byte(a)
end
end,
[-4]=function(f)
local a,b,c,d=f:read(1,1,1,1)
if d then
return byte(d),byte(c),byte(b),byte(a)
end
end
}
function io.bytes(f,n)
if f then
return nextbyte[n or 1],f
else
return nil,nil
end
end
function io.ask(question,default,options)
while true do
io.write(question)
if options then
io.write(format(" [%s]",concat(options,"|")))
end
if default then
io.write(format(" [%s]",default))
end
io.write(format(" "))
io.flush()
local answer=io.read()
answer=gsub(answer,"^%s*(.*)%s*$","%1")
if answer=="" and default then
return default
elseif not options then
return answer
else
for k=1,#options do
if options[k]==answer then
return answer
end
end
local pattern="^"..answer
for k=1,#options do
local v=options[k]
if find(v,pattern) then
return v
end
end
end
end
end
local function readnumber(f,n,m)
if m then
f:seek("set",n)
n=m
end
if n==1 then
return byte(f:read(1))
elseif n==2 then
local a,b=byte(f:read(2),1,2)
return 256*a+b
elseif n==3 then
local a,b,c=byte(f:read(3),1,3)
return 256*256*a+256*b+c
elseif n==4 then
local a,b,c,d=byte(f:read(4),1,4)
return 256*256*256*a+256*256*b+256*c+d
elseif n==8 then
local a,b=readnumber(f,4),readnumber(f,4)
return 256*a+b
elseif n==12 then
local a,b,c=readnumber(f,4),readnumber(f,4),readnumber(f,4)
return 256*256*a+256*b+c
elseif n==-2 then
local b,a=byte(f:read(2),1,2)
return 256*a+b
elseif n==-3 then
local c,b,a=byte(f:read(3),1,3)
return 256*256*a+256*b+c
elseif n==-4 then
local d,c,b,a=byte(f:read(4),1,4)
return 256*256*256*a+256*256*b+256*c+d
elseif n==-8 then
local h,g,f,e,d,c,b,a=byte(f:read(8),1,8)
return 256*256*256*256*256*256*256*a+256*256*256*256*256*256*b+256*256*256*256*256*c+256*256*256*256*d+256*256*256*e+256*256*f+256*g+h
else
return 0
end
end
io.readnumber=readnumber
function io.readstring(f,n,m)
if m then
f:seek("set",n)
n=m
end
local str=gsub(f:read(n),"\000","")
return str
end
if not io.i_limiter then function io.i_limiter() end end
if not io.o_limiter then function io.o_limiter() end end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['l-file']={
version=1.001,
comment="companion to luat-lib.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
file=file or {}
local file=file
if not lfs then
lfs=optionalrequire("lfs")
end
if not lfs then
lfs={
getcurrentdir=function()
return "."
end,
attributes=function()
return nil
end,
isfile=function(name)
local f=io.open(name,'rb')
if f then
f:close()
return true
end
end,
isdir=function(name)
print("you need to load lfs")
return false
end
}
elseif not lfs.isfile then
local attributes=lfs.attributes
function lfs.isdir(name)
return attributes(name,"mode")=="directory"
end
function lfs.isfile(name)
return attributes(name,"mode")=="file"
end
end
local insert,concat=table.insert,table.concat
local match=string.match
local lpegmatch=lpeg.match
local getcurrentdir,attributes=lfs.currentdir,lfs.attributes
local checkedsplit=string.checkedsplit
local P,R,S,C,Cs,Cp,Cc,Ct=lpeg.P,lpeg.R,lpeg.S,lpeg.C,lpeg.Cs,lpeg.Cp,lpeg.Cc,lpeg.Ct
local colon=P(":")
local period=P(".")
local periods=P("..")
local fwslash=P("/")
local bwslash=P("\\")
local slashes=S("\\/")
local noperiod=1-period
local noslashes=1-slashes
local name=noperiod^1
local suffix=period/""*(1-period-slashes)^1*-1
local pattern=C((1-(slashes^1*noslashes^1*-1))^1)*P(1)
local function pathpart(name,default)
return name and lpegmatch(pattern,name) or default or ""
end
local pattern=(noslashes^0*slashes)^1*C(noslashes^1)*-1
local function basename(name)
return name and lpegmatch(pattern,name) or name
end
local pattern=(noslashes^0*slashes^1)^0*Cs((1-suffix)^1)*suffix^0
local function nameonly(name)
return name and lpegmatch(pattern,name) or name
end
local pattern=(noslashes^0*slashes)^0*(noperiod^1*period)^1*C(noperiod^1)*-1
local function suffixonly(name)
return name and lpegmatch(pattern,name) or ""
end
file.pathpart=pathpart
file.basename=basename
file.nameonly=nameonly
file.suffixonly=suffixonly
file.suffix=suffixonly
file.dirname=pathpart
file.extname=suffixonly
local drive=C(R("az","AZ"))*colon
local path=C((noslashes^0*slashes)^0)
local suffix=period*C(P(1-period)^0*P(-1))
local base=C((1-suffix)^0)
local rest=C(P(1)^0)
drive=drive+Cc("")
path=path+Cc("")
base=base+Cc("")
suffix=suffix+Cc("")
local pattern_a=drive*path*base*suffix
local pattern_b=path*base*suffix
local pattern_c=C(drive*path)*C(base*suffix)
local pattern_d=path*rest
function file.splitname(str,splitdrive)
if not str then
elseif splitdrive then
return lpegmatch(pattern_a,str)
else
return lpegmatch(pattern_b,str)
end
end
function file.splitbase(str)
return str and lpegmatch(pattern_d,str)
end
function file.nametotable(str,splitdrive)
if str then
local path,drive,subpath,name,base,suffix=lpegmatch(pattern_c,str)
if splitdrive then
return {
path=path,
drive=drive,
subpath=subpath,
name=name,
base=base,
suffix=suffix,
}
else
return {
path=path,
name=name,
base=base,
suffix=suffix,
}
end
end
end
local pattern=Cs(((period*(1-period-slashes)^1*-1)/""+1)^1)
function file.removesuffix(name)
return name and lpegmatch(pattern,name)
end
local suffix=period/""*(1-period-slashes)^1*-1
local pattern=Cs((noslashes^0*slashes^1)^0*((1-suffix)^1))*Cs(suffix)
function file.addsuffix(filename,suffix,criterium)
if not filename or not suffix or suffix=="" then
return filename
elseif criterium==true then
return filename.."."..suffix
elseif not criterium then
local n,s=lpegmatch(pattern,filename)
if not s or s=="" then
return filename.."."..suffix
else
return filename
end
else
local n,s=lpegmatch(pattern,filename)
if s and s~="" then
local t=type(criterium)
if t=="table" then
for i=1,#criterium do
if s==criterium[i] then
return filename
end
end
elseif t=="string" then
if s==criterium then
return filename
end
end
end
return (n or filename).."."..suffix
end
end
local suffix=period*(1-period-slashes)^1*-1
local pattern=Cs((1-suffix)^0)
function file.replacesuffix(name,suffix)
if name and suffix and suffix~="" then
return lpegmatch(pattern,name).."."..suffix
else
return name
end
end
local reslasher=lpeg.replacer(P("\\"),"/")
function file.reslash(str)
return str and lpegmatch(reslasher,str)
end
function file.is_writable(name)
if not name then
elseif lfs.isdir(name) then
name=name.."/m_t_x_t_e_s_t.tmp"
local f=io.open(name,"wb")
if f then
f:close()
os.remove(name)
return true
end
elseif lfs.isfile(name) then
local f=io.open(name,"ab")
if f then
f:close()
return true
end
else
local f=io.open(name,"ab")
if f then
f:close()
os.remove(name)
return true
end
end
return false
end
local readable=P("r")*Cc(true)
function file.is_readable(name)
if name then
local a=attributes(name)
return a and lpegmatch(readable,a.permissions) or false
else
return false
end
end
file.isreadable=file.is_readable
file.iswritable=file.is_writable
function file.size(name)
if name then
local a=attributes(name)
return a and a.size or 0
else
return 0
end
end
function file.splitpath(str,separator)
return str and checkedsplit(lpegmatch(reslasher,str),separator or io.pathseparator)
end
function file.joinpath(tab,separator)
return tab and concat(tab,separator or io.pathseparator)
end
local stripper=Cs(P(fwslash)^0/""*reslasher)
local isnetwork=fwslash*fwslash*(1-fwslash)+(1-fwslash-colon)^1*colon
local isroot=fwslash^1*-1
local hasroot=fwslash^1
local deslasher=lpeg.replacer(S("\\/")^1,"/")
function file.join(...)
local lst={... }
local one=lst[1]
if lpegmatch(isnetwork,one) then
local two=lpegmatch(deslasher,concat(lst,"/",2))
return one.."/"..two
elseif lpegmatch(isroot,one) then
local two=lpegmatch(deslasher,concat(lst,"/",2))
if lpegmatch(hasroot,two) then
return two
else
return "/"..two
end
elseif one=="" then
return lpegmatch(stripper,concat(lst,"/",2))
else
return lpegmatch(deslasher,concat(lst,"/"))
end
end
local drivespec=R("az","AZ")^1*colon
local anchors=fwslash+drivespec
local untouched=periods+(1-period)^1*P(-1)
local splitstarter=(Cs(drivespec*(bwslash/"/"+fwslash)^0)+Cc(false))*Ct(lpeg.splitat(S("/\\")^1))
local absolute=fwslash
function file.collapsepath(str,anchor)
if not str then
return
end
if anchor and not lpegmatch(anchors,str) then
str=getcurrentdir().."/"..str
end
if str=="" or str=="." then
return "."
elseif lpegmatch(untouched,str) then
return lpegmatch(reslasher,str)
end
local starter,oldelements=lpegmatch(splitstarter,str)
local newelements={}
local i=#oldelements
while i>0 do
local element=oldelements[i]
if element=='.' then
elseif element=='..' then
local n=i-1
while n>0 do
local element=oldelements[n]
if element~='..' and element~='.' then
oldelements[n]='.'
break
else
n=n-1
end
end
if n<1 then
insert(newelements,1,'..')
end
elseif element~="" then
insert(newelements,1,element)
end
i=i-1
end
if #newelements==0 then
return starter or "."
elseif starter then
return starter..concat(newelements,'/')
elseif lpegmatch(absolute,str) then
return "/"..concat(newelements,'/')
else
return concat(newelements,'/')
end
end
local validchars=R("az","09","AZ","--","..")
local pattern_a=lpeg.replacer(1-validchars)
local pattern_a=Cs((validchars+P(1)/"-")^1)
local whatever=P("-")^0/""
local pattern_b=Cs(whatever*(1-whatever*-1)^1)
function file.robustname(str,strict)
if str then
str=lpegmatch(pattern_a,str) or str
if strict then
return lpegmatch(pattern_b,str) or str
else
return str
end
end
end
file.readdata=io.loaddata
file.savedata=io.savedata
function file.copy(oldname,newname)
if oldname and newname then
local data=io.loaddata(oldname)
if data and data~="" then
file.savedata(newname,data)
end
end
end
local letter=R("az","AZ")+S("_-+")
local separator=P("://")
local qualified=period^0*fwslash+letter*colon+letter^1*separator+letter^1*fwslash
local rootbased=fwslash+letter*colon
lpeg.patterns.qualified=qualified
lpeg.patterns.rootbased=rootbased
function file.is_qualified_path(filename)
return filename and lpegmatch(qualified,filename)~=nil
end
function file.is_rootbased_path(filename)
return filename and lpegmatch(rootbased,filename)~=nil
end
function file.strip(name,dir)
if name then
local b,a=match(name,"^(.-)"..dir.."(.*)$")
return a~="" and a or name
end
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['l-boolean']={
version=1.001,
comment="companion to luat-lib.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local type,tonumber=type,tonumber
boolean=boolean or {}
local boolean=boolean
function boolean.tonumber(b)
if b then return 1 else return 0 end
end
function toboolean(str,tolerant)
if str==nil then
return false
elseif str==false then
return false
elseif str==true then
return true
elseif str=="true" then
return true
elseif str=="false" then
return false
elseif not tolerant then
return false
elseif str==0 then
return false
elseif (tonumber(str) or 0)>0 then
return true
else
return str=="yes" or str=="on" or str=="t"
end
end
string.toboolean=toboolean
function string.booleanstring(str)
if str=="0" then
return false
elseif str=="1" then
return true
elseif str=="" then
return false
elseif str=="false" then
return false
elseif str=="true" then
return true
elseif (tonumber(str) or 0)>0 then
return true
else
return str=="yes" or str=="on" or str=="t"
end
end
function string.is_boolean(str,default)
if type(str)=="string" then
if str=="true" or str=="yes" or str=="on" or str=="t" then
return true
elseif str=="false" or str=="no" or str=="off" or str=="f" then
return false
end
end
return default
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['l-math']={
version=1.001,
comment="companion to luat-lib.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local floor,sin,cos,tan=math.floor,math.sin,math.cos,math.tan
if not math.round then
function math.round(x) return floor(x+0.5) end
end
if not math.div then
function math.div(n,m) return floor(n/m) end
end
if not math.mod then
function math.mod(n,m) return n%m end
end
local pipi=2*math.pi/360
if not math.sind then
function math.sind(d) return sin(d*pipi) end
function math.cosd(d) return cos(d*pipi) end
function math.tand(d) return tan(d*pipi) end
end
if not math.odd then
function math.odd (n) return n%2~=0 end
function math.even(n) return n%2==0 end
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['util-str']={
version=1.001,
comment="companion to luat-lib.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
utilities=utilities or {}
utilities.strings=utilities.strings or {}
local strings=utilities.strings
local format,gsub,rep,sub=string.format,string.gsub,string.rep,string.sub
local load,dump=load,string.dump
local tonumber,type,tostring=tonumber,type,tostring
local unpack,concat=table.unpack,table.concat
local P,V,C,S,R,Ct,Cs,Cp,Carg,Cc=lpeg.P,lpeg.V,lpeg.C,lpeg.S,lpeg.R,lpeg.Ct,lpeg.Cs,lpeg.Cp,lpeg.Carg,lpeg.Cc
local patterns,lpegmatch=lpeg.patterns,lpeg.match
local utfchar,utfbyte=utf.char,utf.byte
local loadstripped=_LUAVERSION<5.2 and load or function(str)
return load(dump(load(str),true))
end
if not number then number={} end
local stripper=patterns.stripzeros
local function points(n)
return (not n or n==0) and "0pt" or lpegmatch(stripper,format("%.5fpt",n/65536))
end
local function basepoints(n)
return (not n or n==0) and "0bp" or lpegmatch(stripper,format("%.5fbp",n*(7200/7227)/65536))
end
number.points=points
number.basepoints=basepoints
local rubish=patterns.spaceortab^0*patterns.newline
local anyrubish=patterns.spaceortab+patterns.newline
local anything=patterns.anything
local stripped=(patterns.spaceortab^1/"")*patterns.newline
local leading=rubish^0/""
local trailing=(anyrubish^1*patterns.endofstring)/""
local redundant=rubish^3/"\n"
local pattern=Cs(leading*(trailing+redundant+stripped+anything)^0)
function strings.collapsecrlf(str)
return lpegmatch(pattern,str)
end
local repeaters={}
function strings.newrepeater(str,offset)
offset=offset or 0
local s=repeaters[str]
if not s then
s={}
repeaters[str]=s
end
local t=s[offset]
if t then
return t
end
t={}
setmetatable(t,{ __index=function(t,k)
if not k then
return ""
end
local n=k+offset
local s=n>0 and rep(str,n) or ""
t[k]=s
return s
end })
s[offset]=t
return t
end
local extra,tab,start=0,0,4,0
local nspaces=strings.newrepeater(" ")
string.nspaces=nspaces
local pattern=Carg(1)/function(t)
extra,tab,start=0,t or 7,1
end*Cs((
Cp()*patterns.tab/function(position)
local current=(position-start+1)+extra
local spaces=tab-(current-1)%tab
if spaces>0 then
extra=extra+spaces-1
return nspaces[spaces]
else
return ""
end
end+patterns.newline*Cp()/function(position)
extra,start=0,position
end+patterns.anything
)^1)
function strings.tabtospace(str,tab)
return lpegmatch(pattern,str,1,tab or 7)
end
function strings.striplong(str)
str=gsub(str,"^%s*","")
str=gsub(str,"[\n\r]+ *","\n")
return str
end
function strings.nice(str)
str=gsub(str,"[:%-+_]+"," ")
return str
end
local n=0
local sequenced=table.sequenced
function string.autodouble(s,sep)
if s==nil then
return '""'
end
local t=type(s)
if t=="number" then
return tostring(s)
end
if t=="table" then
return ('"'..sequenced(s,sep or ",")..'"')
end
return ('"'..tostring(s)..'"')
end
function string.autosingle(s,sep)
if s==nil then
return "''"
end
local t=type(s)
if t=="number" then
return tostring(s)
end
if t=="table" then
return ("'"..sequenced(s,sep or ",").."'")
end
return ("'"..tostring(s).."'")
end
local tracedchars={}
string.tracedchars=tracedchars
strings.tracers=tracedchars
function string.tracedchar(b)
if type(b)=="number" then
return tracedchars[b] or (utfchar(b).." (U+"..format('%05X',b)..")")
else
local c=utfbyte(b)
return tracedchars[c] or (b.." (U+"..format('%05X',c)..")")
end
end
function number.signed(i)
if i>0 then
return "+",i
else
return "-",-i
end
end
local preamble=[[
local type = type
local tostring = tostring
local tonumber = tonumber
local format = string.format
local concat = table.concat
local signed = number.signed
local points = number.points
local basepoints = number.basepoints
local utfchar = utf.char
local utfbyte = utf.byte
local lpegmatch = lpeg.match
local nspaces = string.nspaces
local tracedchar = string.tracedchar
local autosingle = string.autosingle
local autodouble = string.autodouble
local sequenced = table.sequenced
]]
local template=[[
%s
%s
return function(%s) return %s end
]]
local arguments={ "a1" }
setmetatable(arguments,{ __index=function(t,k)
local v=t[k-1]..",a"..k
t[k]=v
return v
end
})
local prefix_any=C((S("+- .")+R("09"))^0)
local prefix_tab=C((1-R("az","AZ","09","%%"))^0)
local format_s=function(f)
n=n+1
if f and f~="" then
return format("format('%%%ss',a%s)",f,n)
else
return format("(a%s or '')",n)
end
end
local format_S=function(f)
n=n+1
if f and f~="" then
return format("format('%%%ss',tostring(a%s))",f,n)
else
return format("tostring(a%s)",n)
end
end
local format_q=function()
n=n+1
return format("(a%s and format('%%q',a%s) or '')",n,n)
end
local format_Q=function()
n=n+1
return format("format('%%q',tostring(a%s))",n)
end
local format_i=function(f)
n=n+1
if f and f~="" then
return format("format('%%%si',a%s)",f,n)
else
return format("a%s",n)
end
end
local format_d=format_i
local format_I=function(f)
n=n+1
return format("format('%%s%%%si',signed(a%s))",f,n)
end
local format_f=function(f)
n=n+1
return format("format('%%%sf',a%s)",f,n)
end
local format_g=function(f)
n=n+1
return format("format('%%%sg',a%s)",f,n)
end
local format_G=function(f)
n=n+1
return format("format('%%%sG',a%s)",f,n)
end
local format_e=function(f)
n=n+1
return format("format('%%%se',a%s)",f,n)
end
local format_E=function(f)
n=n+1
return format("format('%%%sE',a%s)",f,n)
end
local format_x=function(f)
n=n+1
return format("format('%%%sx',a%s)",f,n)
end
local format_X=function(f)
n=n+1
return format("format('%%%sX',a%s)",f,n)
end
local format_o=function(f)
n=n+1
return format("format('%%%so',a%s)",f,n)
end
local format_c=function()
n=n+1
return format("utfchar(a%s)",n)
end
local format_C=function()
n=n+1
return format("tracedchar(a%s)",n)
end
local format_r=function(f)
n=n+1
return format("format('%%%s.0f',a%s)",f,n)
end
local format_h=function(f)
n=n+1
if f=="-" then
f=sub(f,2)
return format("format('%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
else
return format("format('0x%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
end
end
local format_H=function(f)
n=n+1
if f=="-" then
f=sub(f,2)
return format("format('%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
else
return format("format('0x%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
end
end
local format_u=function(f)
n=n+1
if f=="-" then
f=sub(f,2)
return format("format('%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
else
return format("format('u+%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
end
end
local format_U=function(f)
n=n+1
if f=="-" then
f=sub(f,2)
return format("format('%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
else
return format("format('U+%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
end
end
local format_p=function()
n=n+1
return format("points(a%s)",n)
end
local format_b=function()
n=n+1
return format("basepoints(a%s)",n)
end
local format_t=function(f)
n=n+1
if f and f~="" then
return format("concat(a%s,%q)",n,f)
else
return format("concat(a%s)",n)
end
end
local format_T=function(f)
n=n+1
if f and f~="" then
return format("sequenced(a%s,%q)",n,f)
else
return format("sequenced(a%s)",n)
end
end
local format_l=function()
n=n+1
return format("(a%s and 'true' or 'false')",n)
end
local format_L=function()
n=n+1
return format("(a%s and 'TRUE' or 'FALSE')",n)
end
local format_N=function()
n=n+1
return format("tostring(tonumber(a%s) or a%s)",n,n)
end
local format_a=function(f)
n=n+1
if f and f~="" then
return format("autosingle(a%s,%q)",n,f)
else
return format("autosingle(a%s)",n)
end
end
local format_A=function(f)
n=n+1
if f and f~="" then
return format("autodouble(a%s,%q)",n,f)
else
return format("autodouble(a%s)",n)
end
end
local format_w=function(f)
n=n+1
f=tonumber(f)
if f then
return format("nspaces[%s+a%s]",f,n)
else
return format("nspaces[a%s]",n)
end
end
local format_W=function(f)
return format("nspaces[%s]",tonumber(f) or 0)
end
local format_rest=function(s)
return format("%q",s)
end
local format_extension=function(extensions,f,name)
local extension=extensions[name] or "tostring(%s)"
local f=tonumber(f) or 1
if f==0 then
return extension
elseif f==1 then
n=n+1
local a="a"..n
return format(extension,a,a)
elseif f<0 then
local a="a"..(n+f+1)
return format(extension,a,a)
else
local t={}
for i=1,f do
n=n+1
t[#t+1]="a"..n
end
return format(extension,unpack(t))
end
end
local builder=Cs { "start",
start=(
(
P("%")/""*(
V("!")
+V("s")+V("q")+V("i")+V("d")+V("f")+V("g")+V("G")+V("e")+V("E")+V("x")+V("X")+V("o")
+V("c")+V("C")+V("S")
+V("Q")
+V("N")
+V("r")+V("h")+V("H")+V("u")+V("U")+V("p")+V("b")+V("t")+V("T")+V("l")+V("L")+V("I")+V("h")
+V("w")
+V("W")
+V("a")
+V("A")
+V("*")
)+V("*")
)*(P(-1)+Carg(1))
)^0,
["s"]=(prefix_any*P("s"))/format_s,
["q"]=(prefix_any*P("q"))/format_q,
["i"]=(prefix_any*P("i"))/format_i,
["d"]=(prefix_any*P("d"))/format_d,
["f"]=(prefix_any*P("f"))/format_f,
["g"]=(prefix_any*P("g"))/format_g,
["G"]=(prefix_any*P("G"))/format_G,
["e"]=(prefix_any*P("e"))/format_e,
["E"]=(prefix_any*P("E"))/format_E,
["x"]=(prefix_any*P("x"))/format_x,
["X"]=(prefix_any*P("X"))/format_X,
["o"]=(prefix_any*P("o"))/format_o,
["S"]=(prefix_any*P("S"))/format_S,
["Q"]=(prefix_any*P("Q"))/format_S,
["N"]=(prefix_any*P("N"))/format_N,
["c"]=(prefix_any*P("c"))/format_c,
["C"]=(prefix_any*P("C"))/format_C,
["r"]=(prefix_any*P("r"))/format_r,
["h"]=(prefix_any*P("h"))/format_h,
["H"]=(prefix_any*P("H"))/format_H,
["u"]=(prefix_any*P("u"))/format_u,
["U"]=(prefix_any*P("U"))/format_U,
["p"]=(prefix_any*P("p"))/format_p,
["b"]=(prefix_any*P("b"))/format_b,
["t"]=(prefix_tab*P("t"))/format_t,
["T"]=(prefix_tab*P("T"))/format_T,
["l"]=(prefix_tab*P("l"))/format_l,
["L"]=(prefix_tab*P("L"))/format_L,
["I"]=(prefix_any*P("I"))/format_I,
["w"]=(prefix_any*P("w"))/format_w,
["W"]=(prefix_any*P("W"))/format_W,
["a"]=(prefix_any*P("a"))/format_a,
["A"]=(prefix_any*P("A"))/format_A,
["*"]=Cs(((1-P("%"))^1+P("%%")/"%%%%")^1)/format_rest,
["!"]=Carg(2)*prefix_any*P("!")*C((1-P("!"))^1)*P("!")/format_extension,
}
local direct=Cs (
P("%")/""*Cc([[local format = string.format return function(str) return format("%]])*(S("+- .")+R("09"))^0*S("sqidfgGeExXo")*Cc([[",str) end]])*P(-1)
)
local function make(t,str)
local f
local p
local p=lpegmatch(direct,str)
if p then
f=loadstripped(p)()
else
n=0
p=lpegmatch(builder,str,1,"..",t._extensions_)
if n>0 then
p=format(template,preamble,t._preamble_,arguments[n],p)
f=loadstripped(p)()
else
f=function() return str end
end
end
t[str]=f
return f
end
local function use(t,fmt,...)
return t[fmt](...)
end
strings.formatters={}
function strings.formatters.new()
local t={ _extensions_={},_preamble_="",_type_="formatter" }
setmetatable(t,{ __index=make,__call=use })
return t
end
local formatters=strings.formatters.new()
string.formatters=formatters
string.formatter=function(str,...) return formatters[str](...) end
local function add(t,name,template,preamble)
if type(t)=="table" and t._type_=="formatter" then
t._extensions_[name]=template or "%s"
if preamble then
t._preamble_=preamble.."\n"..t._preamble_
end
end
end
strings.formatters.add=add
lpeg.patterns.xmlescape=Cs((P("<")/"<"+P(">")/">"+P("&")/"&"+P('"')/"""+P(1))^0)
lpeg.patterns.texescape=Cs((C(S("#$%\\{}"))/"\\%1"+P(1))^0)
add(formatters,"xml",[[lpegmatch(xmlescape,%s)]],[[local xmlescape = lpeg.patterns.xmlescape]])
add(formatters,"tex",[[lpegmatch(texescape,%s)]],[[local texescape = lpeg.patterns.texescape]])
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['luat-basics-gen']={
version=1.100,
comment="companion to luatex-*.tex",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
if context then
texio.write_nl("fatal error: this module is not for context")
os.exit()
end
local dummyfunction=function() end
local dummyreporter=function(c) return function(...) texio.write_nl(c.." : "..string.formatters(...)) end end
statistics={
register=dummyfunction,
starttiming=dummyfunction,
stoptiming=dummyfunction,
elapsedtime=nil,
}
directives={
register=dummyfunction,
enable=dummyfunction,
disable=dummyfunction,
}
trackers={
register=dummyfunction,
enable=dummyfunction,
disable=dummyfunction,
}
experiments={
register=dummyfunction,
enable=dummyfunction,
disable=dummyfunction,
}
storage={
register=dummyfunction,
shared={},
}
logs={
new=dummyreporter,
reporter=dummyreporter,
messenger=dummyreporter,
report=dummyfunction,
}
callbacks={
register=function(n,f) return callback.register(n,f) end,
}
utilities={
storage={
allocate=function(t) return t or {} end,
mark=function(t) return t or {} end,
},
}
characters=characters or {
data={}
}
texconfig.kpse_init=true
resolvers=resolvers or {}
local remapper={
otf="opentype fonts",
ttf="truetype fonts",
ttc="truetype fonts",
dfont="truetype fonts",
cid="cid maps",
cidmap="cid maps",
fea="font feature files",
pfa="type1 fonts",
pfb="type1 fonts",
}
function resolvers.findfile(name,fileformat)
name=string.gsub(name,"\\","/")
if not fileformat or fileformat=="" then
fileformat=file.suffix(name)
if fileformat=="" then
fileformat="tex"
end
end
fileformat=string.lower(fileformat)
fileformat=remapper[fileformat] or fileformat
local found=kpse.find_file(name,fileformat)
if not found or found=="" then
found=kpse.find_file(name,"other text files")
end
return found
end
resolvers.findbinfile=resolvers.findfile
function resolvers.resolve(s)
return s
end
function resolvers.unresolve(s)
return s
end
caches={}
local writable,readables=nil,{}
if not caches.namespace or caches.namespace=="" or caches.namespace=="context" then
caches.namespace='generic'
end
do
local cachepaths=kpse.expand_path('$TEXMFCACHE') or ""
if cachepaths=="" then
cachepaths=kpse.expand_path('$TEXMFVAR')
end
if cachepaths=="" then
cachepaths=kpse.expand_path('$VARTEXMF')
end
if cachepaths=="" then
cachepaths="."
end
cachepaths=string.split(cachepaths,os.type=="windows" and ";" or ":")
for i=1,#cachepaths do
if file.is_writable(cachepaths[i]) then
writable=file.join(cachepaths[i],"luatex-cache")
lfs.mkdir(writable)
writable=file.join(writable,caches.namespace)
lfs.mkdir(writable)
break
end
end
for i=1,#cachepaths do
if file.is_readable(cachepaths[i]) then
readables[#readables+1]=file.join(cachepaths[i],"luatex-cache",caches.namespace)
end
end
if not writable then
texio.write_nl("quiting: fix your writable cache path")
os.exit()
elseif #readables==0 then
texio.write_nl("quiting: fix your readable cache path")
os.exit()
elseif #readables==1 and readables[1]==writable then
texio.write(string.format("(using cache: %s)",writable))
else
texio.write(string.format("(using write cache: %s)",writable))
texio.write(string.format("(using read cache: %s)",table.concat(readables," ")))
end
end
function caches.getwritablepath(category,subcategory)
local path=file.join(writable,category)
lfs.mkdir(path)
path=file.join(path,subcategory)
lfs.mkdir(path)
return path
end
function caches.getreadablepaths(category,subcategory)
local t={}
for i=1,#readables do
t[i]=file.join(readables[i],category,subcategory)
end
return t
end
local function makefullname(path,name)
if path and path~="" then
name="temp-"..name
return file.addsuffix(file.join(path,name),"lua"),file.addsuffix(file.join(path,name),"luc")
end
end
function caches.is_writable(path,name)
local fullname=makefullname(path,name)
return fullname and file.is_writable(fullname)
end
function caches.loaddata(paths,name)
for i=1,#paths do
local data=false
local luaname,lucname=makefullname(paths[i],name)
if lucname and lfs.isfile(lucname) then
texio.write(string.format("(load luc: %s)",lucname))
data=loadfile(lucname)
if data then
data=data()
end
if data then
return data
else
texio.write(string.format("(loading failed: %s)",lucname))
end
end
if luaname and lfs.isfile(luaname) then
texio.write(string.format("(load lua: %s)",luaname))
data=loadfile(luaname)
if data then
data=data()
end
if data then
return data
end
end
end
end
function caches.savedata(path,name,data)
local luaname,lucname=makefullname(path,name)
if luaname then
texio.write(string.format("(save: %s)",luaname))
table.tofile(luaname,data,true,{ reduce=true })
if lucname and type(caches.compile)=="function" then
os.remove(lucname)
texio.write(string.format("(save: %s)",lucname))
caches.compile(data,luaname,lucname)
end
end
end
caches.compilemethod="both"
function caches.compile(data,luaname,lucname)
local done=false
if caches.compilemethod=="luac" or caches.compilemethod=="both" then
done=os.spawn("texluac -o "..string.quoted(lucname).." -s "..string.quoted(luaname))==0
end
if not done and (caches.compilemethod=="dump" or caches.compilemethod=="both") then
local d=io.loaddata(luaname)
if not d or d=="" then
d=table.serialize(data,true)
end
if d and d~="" then
local f=io.open(lucname,'w')
if f then
local s=loadstring(d)
if s then
f:write(string.dump(s,true))
end
f:close()
end
end
end
end
function table.setmetatableindex(t,f)
setmetatable(t,{ __index=f })
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['data-con']={
version=1.100,
comment="companion to luat-lib.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local format,lower,gsub=string.format,string.lower,string.gsub
local trace_cache=false trackers.register("resolvers.cache",function(v) trace_cache=v end)
local trace_containers=false trackers.register("resolvers.containers",function(v) trace_containers=v end)
local trace_storage=false trackers.register("resolvers.storage",function(v) trace_storage=v end)
containers=containers or {}
local containers=containers
containers.usecache=true
local report_containers=logs.reporter("resolvers","containers")
local allocated={}
local mt={
__index=function(t,k)
if k=="writable" then
local writable=caches.getwritablepath(t.category,t.subcategory) or { "." }
t.writable=writable
return writable
elseif k=="readables" then
local readables=caches.getreadablepaths(t.category,t.subcategory) or { "." }
t.readables=readables
return readables
end
end,
__storage__=true
}
function containers.define(category,subcategory,version,enabled)
if category and subcategory then
local c=allocated[category]
if not c then
c={}
allocated[category]=c
end
local s=c[subcategory]
if not s then
s={
category=category,
subcategory=subcategory,
storage={},
enabled=enabled,
version=version or math.pi,
trace=false,
}
setmetatable(s,mt)
c[subcategory]=s
end
return s
end
end
function containers.is_usable(container,name)
return container.enabled and caches and caches.is_writable(container.writable,name)
end
function containers.is_valid(container,name)
if name and name~="" then
local storage=container.storage[name]
return storage and storage.cache_version==container.version
else
return false
end
end
function containers.read(container,name)
local storage=container.storage
local stored=storage[name]
if not stored and container.enabled and caches and containers.usecache then
stored=caches.loaddata(container.readables,name)
if stored and stored.cache_version==container.version then
if trace_cache or trace_containers then
report_containers("action %a, category %a, name %a","load",container.subcategory,name)
end
else
stored=nil
end
storage[name]=stored
elseif stored then
if trace_cache or trace_containers then
report_containers("action %a, category %a, name %a","reuse",container.subcategory,name)
end
end
return stored
end
function containers.write(container,name,data)
if data then
data.cache_version=container.version
if container.enabled and caches then
local unique,shared=data.unique,data.shared
data.unique,data.shared=nil,nil
caches.savedata(container.writable,name,data)
if trace_cache or trace_containers then
report_containers("action %a, category %a, name %a","save",container.subcategory,name)
end
data.unique,data.shared=unique,shared
end
if trace_cache or trace_containers then
report_containers("action %a, category %a, name %a","store",container.subcategory,name)
end
container.storage[name]=data
end
return data
end
function containers.content(container,name)
return container.storage[name]
end
function containers.cleanname(name)
return (gsub(lower(name),"[^%w%d]+","-"))
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['luatex-fonts-nod']={
version=1.001,
comment="companion to luatex-fonts.lua",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
if context then
texio.write_nl("fatal error: this module is not for context")
os.exit()
end
if tex.attribute[0]~=0 then
texio.write_nl("log","!")
texio.write_nl("log","! Attribute 0 is reserved for ConTeXt's font feature management and has to be")
texio.write_nl("log","! set to zero. Also, some attributes in the range 1-255 are used for special")
texio.write_nl("log","! purposes so setting them at the TeX end might break the font handler.")
texio.write_nl("log","!")
tex.attribute[0]=0
end
attributes={}
attributes.unsetvalue=-0x7FFFFFFF
local numbers,last={},127
function attributes.private(name)
local number=numbers[name]
if not number then
if last<255 then
last=last+1
end
number=last
numbers[name]=number
end
return number
end
nodes={}
nodes.pool={}
nodes.handlers={}
local nodecodes={} for k,v in next,node.types () do nodecodes[string.gsub(v,"_","")]=k end
local whatcodes={} for k,v in next,node.whatsits() do whatcodes[string.gsub(v,"_","")]=k end
local glyphcodes={ [0]="character","glyph","ligature","ghost","left","right" }
nodes.nodecodes=nodecodes
nodes.whatcodes=whatcodes
nodes.whatsitcodes=whatcodes
nodes.glyphcodes=glyphcodes
local free_node=node.free
local remove_node=node.remove
local new_node=node.new
local traverse_id=node.traverse_id
local math_code=nodecodes.math
nodes.handlers.protectglyphs=node.protect_glyphs
nodes.handlers.unprotectglyphs=node.unprotect_glyphs
function nodes.remove(head,current,free_too)
local t=current
head,current=remove_node(head,current)
if t then
if free_too then
free_node(t)
t=nil
else
t.next,t.prev=nil,nil
end
end
return head,current,t
end
function nodes.delete(head,current)
return nodes.remove(head,current,true)
end
nodes.before=node.insert_before
nodes.after=node.insert_after
function nodes.pool.kern(k)
local n=new_node("kern",1)
n.kern=k
return n
end
function nodes.endofmath(n)
for n in traverse_id(math_code,n.next) do
return n
end
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['font-ini']={
version=1.001,
comment="companion to font-ini.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local allocate=utilities.storage.allocate
local report_defining=logs.reporter("fonts","defining")
fonts=fonts or {}
local fonts=fonts
fonts.hashes={ identifiers=allocate() }
fonts.tables=fonts.tables or {}
fonts.helpers=fonts.helpers or {}
fonts.tracers=fonts.tracers or {}
fonts.specifiers=fonts.specifiers or {}
fonts.analyzers={}
fonts.readers={}
fonts.definers={ methods={} }
fonts.loggers={ register=function() end }
fontloader.totable=fontloader.to_table
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['font-con']={
version=1.001,
comment="companion to font-ini.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local next,tostring,rawget=next,tostring,rawget
local format,match,lower,gsub=string.format,string.match,string.lower,string.gsub
local utfbyte=utf.byte
local sort,insert,concat,sortedkeys,serialize,fastcopy=table.sort,table.insert,table.concat,table.sortedkeys,table.serialize,table.fastcopy
local derivetable=table.derive
local trace_defining=false trackers.register("fonts.defining",function(v) trace_defining=v end)
local trace_scaling=false trackers.register("fonts.scaling",function(v) trace_scaling=v end)
local report_defining=logs.reporter("fonts","defining")
local fonts=fonts
local constructors=fonts.constructors or {}
fonts.constructors=constructors
local handlers=fonts.handlers or {}
fonts.handlers=handlers
local allocate=utilities.storage.allocate
local setmetatableindex=table.setmetatableindex
constructors.dontembed=allocate()
constructors.autocleanup=true
constructors.namemode="fullpath"
constructors.version=1.01
constructors.cache=containers.define("fonts","constructors",constructors.version,false)
constructors.privateoffset=0xF0000
constructors.keys={
properties={
encodingbytes="number",
embedding="number",
cidinfo={},
format="string",
fontname="string",
fullname="string",
filename="filename",
psname="string",
name="string",
virtualized="boolean",
hasitalics="boolean",
autoitalicamount="basepoints",
nostackmath="boolean",
noglyphnames="boolean",
mode="string",
hasmath="boolean",
mathitalics="boolean",
textitalics="boolean",
finalized="boolean",
},
parameters={
mathsize="number",
scriptpercentage="float",
scriptscriptpercentage="float",
units="cardinal",
designsize="scaledpoints",
expansion={
stretch="integerscale",
shrink="integerscale",
step="integerscale",
auto="boolean",
},
protrusion={
auto="boolean",
},
slantfactor="float",
extendfactor="float",
factor="float",
hfactor="float",
vfactor="float",
size="scaledpoints",
units="scaledpoints",
scaledpoints="scaledpoints",
slantperpoint="scaledpoints",
spacing={
width="scaledpoints",
stretch="scaledpoints",
shrink="scaledpoints",
extra="scaledpoints",
},
xheight="scaledpoints",
quad="scaledpoints",
ascender="scaledpoints",
descender="scaledpoints",
synonyms={
space="spacing.width",
spacestretch="spacing.stretch",
spaceshrink="spacing.shrink",
extraspace="spacing.extra",
x_height="xheight",
space_stretch="spacing.stretch",
space_shrink="spacing.shrink",
extra_space="spacing.extra",
em="quad",
ex="xheight",
slant="slantperpoint",
},
},
description={
width="basepoints",
height="basepoints",
depth="basepoints",
boundingbox={},
},
character={
width="scaledpoints",
height="scaledpoints",
depth="scaledpoints",
italic="scaledpoints",
},
}
local designsizes=allocate()
constructors.designsizes=designsizes
local loadedfonts=allocate()
constructors.loadedfonts=loadedfonts
local factors={
pt=65536.0,
bp=65781.8,
}
function constructors.setfactor(f)
constructors.factor=factors[f or 'pt'] or factors.pt
end
constructors.setfactor()
function constructors.scaled(scaledpoints,designsize)
if scaledpoints<0 then
if designsize then
local factor=constructors.factor
if designsize>factor then
return (- scaledpoints/1000)*designsize
else
return (- scaledpoints/1000)*designsize*factor
end
else
return (- scaledpoints/1000)*10*factor
end
else
return scaledpoints
end
end
function constructors.cleanuptable(tfmdata)
if constructors.autocleanup and tfmdata.properties.virtualized then
for k,v in next,tfmdata.characters do
if v.commands then v.commands=nil end
end
end
end
function constructors.calculatescale(tfmdata,scaledpoints)
local parameters=tfmdata.parameters
if scaledpoints<0 then
scaledpoints=(- scaledpoints/1000)*(tfmdata.designsize or parameters.designsize)
end
return scaledpoints,scaledpoints/(parameters.units or 1000)
end
local unscaled={
ScriptPercentScaleDown=true,
ScriptScriptPercentScaleDown=true,
RadicalDegreeBottomRaisePercent=true
}
function constructors.assignmathparameters(target,original)
local mathparameters=original.mathparameters
if mathparameters and next(mathparameters) then
local targetparameters=target.parameters
local targetproperties=target.properties
local targetmathparameters={}
local factor=targetproperties.math_is_scaled and 1 or targetparameters.factor
for name,value in next,mathparameters do
if unscaled[name] then
targetmathparameters[name]=value
else
targetmathparameters[name]=value*factor
end
end
if not targetmathparameters.FractionDelimiterSize then
targetmathparameters.FractionDelimiterSize=1.01*targetparameters.size
end
if not mathparameters.FractionDelimiterDisplayStyleSize then
targetmathparameters.FractionDelimiterDisplayStyleSize=2.40*targetparameters.size
end
target.mathparameters=targetmathparameters
end
end
function constructors.beforecopyingcharacters(target,original)
end
function constructors.aftercopyingcharacters(target,original)
end
function constructors.enhanceparameters(parameters)
local xheight=parameters.x_height
local quad=parameters.quad
local space=parameters.space
local stretch=parameters.space_stretch
local shrink=parameters.space_shrink
local extra=parameters.extra_space
local slant=parameters.slant
parameters.xheight=xheight
parameters.spacestretch=stretch
parameters.spaceshrink=shrink
parameters.extraspace=extra
parameters.em=quad
parameters.ex=xheight
parameters.slantperpoint=slant
parameters.spacing={
width=space,
stretch=stretch,
shrink=shrink,
extra=extra,
}
end
function constructors.scale(tfmdata,specification)
local target={}
if tonumber(specification) then
specification={ size=specification }
end
local scaledpoints=specification.size
local relativeid=specification.relativeid
local properties=tfmdata.properties or {}
local goodies=tfmdata.goodies or {}
local resources=tfmdata.resources or {}
local descriptions=tfmdata.descriptions or {}
local characters=tfmdata.characters or {}
local changed=tfmdata.changed or {}
local shared=tfmdata.shared or {}
local parameters=tfmdata.parameters or {}
local mathparameters=tfmdata.mathparameters or {}
local targetcharacters={}
local targetdescriptions=derivetable(descriptions)
local targetparameters=derivetable(parameters)
local targetproperties=derivetable(properties)
local targetgoodies=goodies
target.characters=targetcharacters
target.descriptions=targetdescriptions
target.parameters=targetparameters
target.properties=targetproperties
target.goodies=targetgoodies
target.shared=shared
target.resources=resources
target.unscaled=tfmdata
local mathsize=tonumber(specification.mathsize) or 0
local textsize=tonumber(specification.textsize) or scaledpoints
local forcedsize=tonumber(parameters.mathsize ) or 0
local extrafactor=tonumber(specification.factor ) or 1
if (mathsize==2 or forcedsize==2) and parameters.scriptpercentage then
scaledpoints=parameters.scriptpercentage*textsize/100
elseif (mathsize==3 or forcedsize==3) and parameters.scriptscriptpercentage then
scaledpoints=parameters.scriptscriptpercentage*textsize/100
elseif forcedsize>1000 then
scaledpoints=forcedsize
end
targetparameters.mathsize=mathsize
targetparameters.textsize=textsize
targetparameters.forcedsize=forcedsize
targetparameters.extrafactor=extrafactor
local tounicode=resources.tounicode
local defaultwidth=resources.defaultwidth or 0
local defaultheight=resources.defaultheight or 0
local defaultdepth=resources.defaultdepth or 0
local units=parameters.units or 1000
if target.fonts then
target.fonts=fastcopy(target.fonts)
end
targetproperties.language=properties.language or "dflt"
targetproperties.script=properties.script or "dflt"
targetproperties.mode=properties.mode or "base"
local askedscaledpoints=scaledpoints
local scaledpoints,delta=constructors.calculatescale(tfmdata,scaledpoints)
local hdelta=delta
local vdelta=delta
target.designsize=parameters.designsize
target.units_per_em=units
local direction=properties.direction or tfmdata.direction or 0
target.direction=direction
properties.direction=direction
target.size=scaledpoints
target.encodingbytes=properties.encodingbytes or 1
target.embedding=properties.embedding or "subset"
target.tounicode=1
target.cidinfo=properties.cidinfo
target.format=properties.format
local fontname=properties.fontname or tfmdata.fontname
local fullname=properties.fullname or tfmdata.fullname
local filename=properties.filename or tfmdata.filename
local psname=properties.psname or tfmdata.psname
local name=properties.name or tfmdata.name
if not psname or psname=="" then
psname=fontname or (fullname and fonts.names.cleanname(fullname))
end
target.fontname=fontname
target.fullname=fullname
target.filename=filename
target.psname=psname
target.name=name
properties.fontname=fontname
properties.fullname=fullname
properties.filename=filename
properties.psname=psname
properties.name=name
local expansion=parameters.expansion
if expansion then
target.stretch=expansion.stretch
target.shrink=expansion.shrink
target.step=expansion.step
target.auto_expand=expansion.auto
end
local protrusion=parameters.protrusion
if protrusion then
target.auto_protrude=protrusion.auto
end
local extendfactor=parameters.extendfactor or 0
if extendfactor~=0 and extendfactor~=1 then
hdelta=hdelta*extendfactor
target.extend=extendfactor*1000
else
target.extend=1000
end
local slantfactor=parameters.slantfactor or 0
if slantfactor~=0 then
target.slant=slantfactor*1000
else
target.slant=0
end
targetparameters.factor=delta
targetparameters.hfactor=hdelta
targetparameters.vfactor=vdelta
targetparameters.size=scaledpoints
targetparameters.units=units
targetparameters.scaledpoints=askedscaledpoints
local isvirtual=properties.virtualized or tfmdata.type=="virtual"
local hasquality=target.auto_expand or target.auto_protrude
local hasitalics=properties.hasitalics
local autoitalicamount=properties.autoitalicamount
local stackmath=not properties.nostackmath
local nonames=properties.noglyphnames
local nodemode=properties.mode=="node"
if changed and not next(changed) then
changed=false
end
target.type=isvirtual and "virtual" or "real"
target.postprocessors=tfmdata.postprocessors
local targetslant=(parameters.slant or parameters[1] or 0)
local targetspace=(parameters.space or parameters[2] or 0)*hdelta
local targetspace_stretch=(parameters.space_stretch or parameters[3] or 0)*hdelta
local targetspace_shrink=(parameters.space_shrink or parameters[4] or 0)*hdelta
local targetx_height=(parameters.x_height or parameters[5] or 0)*vdelta
local targetquad=(parameters.quad or parameters[6] or 0)*hdelta
local targetextra_space=(parameters.extra_space or parameters[7] or 0)*hdelta
targetparameters.slant=targetslant
targetparameters.space=targetspace
targetparameters.space_stretch=targetspace_stretch
targetparameters.space_shrink=targetspace_shrink
targetparameters.x_height=targetx_height
targetparameters.quad=targetquad
targetparameters.extra_space=targetextra_space
local ascender=parameters.ascender
if ascender then
targetparameters.ascender=delta*ascender
end
local descender=parameters.descender
if descender then
targetparameters.descender=delta*descender
end
constructors.enhanceparameters(targetparameters)
local protrusionfactor=(targetquad~=0 and 1000/targetquad) or 0
local scaledwidth=defaultwidth*hdelta
local scaledheight=defaultheight*vdelta
local scaleddepth=defaultdepth*vdelta
local hasmath=(properties.hasmath or next(mathparameters)) and true
if hasmath then
constructors.assignmathparameters(target,tfmdata)
properties.hasmath=true
target.nomath=false
target.MathConstants=target.mathparameters
else
properties.hasmath=false
target.nomath=true
target.mathparameters=nil
end
local italickey="italic"
local useitalics=true
if hasmath then
autoitalicamount=false
elseif properties.textitalics then
italickey="italic_correction"
useitalics=false
if properties.delaytextitalics then
autoitalicamount=false
end
end
if trace_defining then
report_defining("defining tfm, name %a, fullname %a, filename %a, hscale %a, vscale %a, math %a, italics %a",
name,fullname,filename,hdelta,vdelta,
hasmath and "enabled" or "disabled",useitalics and "enabled" or "disabled")
end
constructors.beforecopyingcharacters(target,tfmdata)
local sharedkerns={}
for unicode,character in next,characters do
local chr,description,index,touni
if changed then
local c=changed[unicode]
if c then
description=descriptions[c] or descriptions[unicode] or character
character=characters[c] or character
index=description.index or c
if tounicode then
touni=tounicode[index]
if not touni then
local d=descriptions[unicode] or characters[unicode]
local i=d.index or unicode
touni=tounicode[i]
end
end
else
description=descriptions[unicode] or character
index=description.index or unicode
if tounicode then
touni=tounicode[index]
end
end
else
description=descriptions[unicode] or character
index=description.index or unicode
if tounicode then
touni=tounicode[index]
end
end
local width=description.width
local height=description.height
local depth=description.depth
if width then width=hdelta*width else width=scaledwidth end
if height then height=vdelta*height else height=scaledheight end
if depth and depth~=0 then
depth=delta*depth
if nonames then
chr={
index=index,
height=height,
depth=depth,
width=width,
}
else
chr={
name=description.name,
index=index,
height=height,
depth=depth,
width=width,
}
end
else
if nonames then
chr={
index=index,
height=height,
width=width,
}
else
chr={
name=description.name,
index=index,
height=height,
width=width,
}
end
end
if touni then
chr.tounicode=touni
end
if hasquality then
local ve=character.expansion_factor
if ve then
chr.expansion_factor=ve*1000
end
local vl=character.left_protruding
if vl then
chr.left_protruding=protrusionfactor*width*vl
end
local vr=character.right_protruding
if vr then
chr.right_protruding=protrusionfactor*width*vr
end
end
if autoitalicamount then
local vi=description.italic
if not vi then
local vi=description.boundingbox[3]-description.width+autoitalicamount
if vi>0 then
chr[italickey]=vi*hdelta
end
elseif vi~=0 then
chr[italickey]=vi*hdelta
end
elseif hasitalics then
local vi=description.italic
if vi and vi~=0 then
chr[italickey]=vi*hdelta
end
end
if hasmath then
local vn=character.next
if vn then
chr.next=vn
else
local vv=character.vert_variants
if vv then
local t={}
for i=1,#vv do
local vvi=vv[i]
t[i]={
["start"]=(vvi["start"] or 0)*vdelta,
["end"]=(vvi["end"] or 0)*vdelta,
["advance"]=(vvi["advance"] or 0)*vdelta,
["extender"]=vvi["extender"],
["glyph"]=vvi["glyph"],
}
end
chr.vert_variants=t
else
local hv=character.horiz_variants
if hv then
local t={}
for i=1,#hv do
local hvi=hv[i]
t[i]={
["start"]=(hvi["start"] or 0)*hdelta,
["end"]=(hvi["end"] or 0)*hdelta,
["advance"]=(hvi["advance"] or 0)*hdelta,
["extender"]=hvi["extender"],
["glyph"]=hvi["glyph"],
}
end
chr.horiz_variants=t
end
end
end
local va=character.top_accent
if va then
chr.top_accent=vdelta*va
end
if stackmath then
local mk=character.mathkerns
if mk then
local kerns={}
local v=mk.top_right if v then local k={} for i=1,#v do local vi=v[i]
k[i]={ height=vdelta*vi.height,kern=vdelta*vi.kern }
end kerns.top_right=k end
local v=mk.top_left if v then local k={} for i=1,#v do local vi=v[i]
k[i]={ height=vdelta*vi.height,kern=vdelta*vi.kern }
end kerns.top_left=k end
local v=mk.bottom_left if v then local k={} for i=1,#v do local vi=v[i]
k[i]={ height=vdelta*vi.height,kern=vdelta*vi.kern }
end kerns.bottom_left=k end
local v=mk.bottom_right if v then local k={} for i=1,#v do local vi=v[i]
k[i]={ height=vdelta*vi.height,kern=vdelta*vi.kern }
end kerns.bottom_right=k end
chr.mathkern=kerns
end
end
end
if not nodemode then
local vk=character.kerns
if vk then
local s=sharedkerns[vk]
if not s then
s={}
for k,v in next,vk do s[k]=v*hdelta end
sharedkerns[vk]=s
end
chr.kerns=s
end
local vl=character.ligatures
if vl then
if true then
chr.ligatures=vl
else
local tt={}
for i,l in next,vl do
tt[i]=l
end
chr.ligatures=tt
end
end
end
if isvirtual then
local vc=character.commands
if vc then
local ok=false
for i=1,#vc do
local key=vc[i][1]
if key=="right" or key=="down" then
ok=true
break
end
end
if ok then
local tt={}
for i=1,#vc do
local ivc=vc[i]
local key=ivc[1]
if key=="right" then
tt[i]={ key,ivc[2]*hdelta }
elseif key=="down" then
tt[i]={ key,ivc[2]*vdelta }
elseif key=="rule" then
tt[i]={ key,ivc[2]*vdelta,ivc[3]*hdelta }
else
tt[i]=ivc
end
end
chr.commands=tt
else
chr.commands=vc
end
chr.index=nil
end
end
targetcharacters[unicode]=chr
end
constructors.aftercopyingcharacters(target,tfmdata)
return target
end
function constructors.finalize(tfmdata)
if tfmdata.properties and tfmdata.properties.finalized then
return
end
if not tfmdata.characters then
return nil
end
if not tfmdata.goodies then
tfmdata.goodies={}
end
local parameters=tfmdata.parameters
if not parameters then
return nil
end
if not parameters.expansion then
parameters.expansion={
stretch=tfmdata.stretch or 0,
shrink=tfmdata.shrink or 0,
step=tfmdata.step or 0,
auto=tfmdata.auto_expand or false,
}
end
if not parameters.protrusion then
parameters.protrusion={
auto=auto_protrude
}
end
if not parameters.size then
parameters.size=tfmdata.size
end
if not parameters.extendfactor then
parameters.extendfactor=tfmdata.extend or 0
end
if not parameters.slantfactor then
parameters.slantfactor=tfmdata.slant or 0
end
if not parameters.designsize then
parameters.designsize=tfmdata.designsize or 655360
end
if not parameters.units then
parameters.units=tfmdata.units_per_em or 1000
end
if not tfmdata.descriptions then
local descriptions={}
setmetatableindex(descriptions,function(t,k) local v={} t[k]=v return v end)
tfmdata.descriptions=descriptions
end
local properties=tfmdata.properties
if not properties then
properties={}
tfmdata.properties=properties
end
if not properties.virtualized then
properties.virtualized=tfmdata.type=="virtual"
end
if not tfmdata.properties then
tfmdata.properties={
fontname=tfmdata.fontname,
filename=tfmdata.filename,
fullname=tfmdata.fullname,
name=tfmdata.name,
psname=tfmdata.psname,
encodingbytes=tfmdata.encodingbytes or 1,
embedding=tfmdata.embedding or "subset",
tounicode=tfmdata.tounicode or 1,
cidinfo=tfmdata.cidinfo or nil,
format=tfmdata.format or "type1",
direction=tfmdata.direction or 0,
}
end
if not tfmdata.resources then
tfmdata.resources={}
end
if not tfmdata.shared then
tfmdata.shared={}
end
if not properties.hasmath then
properties.hasmath=not tfmdata.nomath
end
tfmdata.MathConstants=nil
tfmdata.postprocessors=nil
tfmdata.fontname=nil
tfmdata.filename=nil
tfmdata.fullname=nil
tfmdata.name=nil
tfmdata.psname=nil
tfmdata.encodingbytes=nil
tfmdata.embedding=nil
tfmdata.tounicode=nil
tfmdata.cidinfo=nil
tfmdata.format=nil
tfmdata.direction=nil
tfmdata.type=nil
tfmdata.nomath=nil
tfmdata.designsize=nil
tfmdata.size=nil
tfmdata.stretch=nil
tfmdata.shrink=nil
tfmdata.step=nil
tfmdata.auto_expand=nil
tfmdata.auto_protrude=nil
tfmdata.extend=nil
tfmdata.slant=nil
tfmdata.units_per_em=nil
properties.finalized=true
return tfmdata
end
local hashmethods={}
constructors.hashmethods=hashmethods
function constructors.hashfeatures(specification)
local features=specification.features
if features then
local t,tn={},0
for category,list in next,features do
if next(list) then
local hasher=hashmethods[category]
if hasher then
local hash=hasher(list)
if hash then
tn=tn+1
t[tn]=category..":"..hash
end
end
end
end
if tn>0 then
return concat(t," & ")
end
end
return "unknown"
end
hashmethods.normal=function(list)
local s={}
local n=0
for k,v in next,list do
if not k then
elseif k=="number" or k=="features" then
else
n=n+1
s[n]=k
end
end
if n>0 then
sort(s)
for i=1,n do
local k=s[i]
s[i]=k..'='..tostring(list[k])
end
return concat(s,"+")
end
end
function constructors.hashinstance(specification,force)
local hash,size,fallbacks=specification.hash,specification.size,specification.fallbacks
if force or not hash then
hash=constructors.hashfeatures(specification)
specification.hash=hash
end
if size<1000 and designsizes[hash] then
size=math.round(constructors.scaled(size,designsizes[hash]))
specification.size=size
end
if fallbacks then
return hash..' @ '..tostring(size)..' @ '..fallbacks
else
return hash..' @ '..tostring(size)
end
end
function constructors.setname(tfmdata,specification)
if constructors.namemode=="specification" then
local specname=specification.specification
if specname then
tfmdata.properties.name=specname
if trace_defining then
report_otf("overloaded fontname %a",specname)
end
end
end
end
function constructors.checkedfilename(data)
local foundfilename=data.foundfilename
if not foundfilename then
local askedfilename=data.filename or ""
if askedfilename~="" then
askedfilename=resolvers.resolve(askedfilename)
foundfilename=resolvers.findbinfile(askedfilename,"") or ""
if foundfilename=="" then
report_defining("source file %a is not found",askedfilename)
foundfilename=resolvers.findbinfile(file.basename(askedfilename),"") or ""
if foundfilename~="" then
report_defining("using source file %a due to cache mismatch",foundfilename)
end
end
end
data.foundfilename=foundfilename
end
return foundfilename
end
local formats=allocate()
fonts.formats=formats
setmetatableindex(formats,function(t,k)
local l=lower(k)
if rawget(t,k) then
t[k]=l
return l
end
return rawget(t,file.suffix(l))
end)
local locations={}
local function setindeed(mode,target,group,name,action,position)
local t=target[mode]
if not t then
report_defining("fatal error in setting feature %a, group %a, mode %a",name,group,mode)
os.exit()
elseif position then
insert(t,position,{ name=name,action=action })
else
for i=1,#t do
local ti=t[i]
if ti.name==name then
ti.action=action
return
end
end
insert(t,{ name=name,action=action })
end
end
local function set(group,name,target,source)
target=target[group]
if not target then
report_defining("fatal target error in setting feature %a, group %a",name,group)
os.exit()
end
local source=source[group]
if not source then
report_defining("fatal source error in setting feature %a, group %a",name,group)
os.exit()
end
local node=source.node
local base=source.base
local position=source.position
if node then
setindeed("node",target,group,name,node,position)
end
if base then
setindeed("base",target,group,name,base,position)
end
end
local function register(where,specification)
local name=specification.name
if name and name~="" then
local default=specification.default
local description=specification.description
local initializers=specification.initializers
local processors=specification.processors
local manipulators=specification.manipulators
local modechecker=specification.modechecker
if default then
where.defaults[name]=default
end
if description and description~="" then
where.descriptions[name]=description
end
if initializers then
set('initializers',name,where,specification)
end
if processors then
set('processors',name,where,specification)
end
if manipulators then
set('manipulators',name,where,specification)
end
if modechecker then
where.modechecker=modechecker
end
end
end
constructors.registerfeature=register
function constructors.getfeatureaction(what,where,mode,name)
what=handlers[what].features
if what then
where=what[where]
if where then
mode=where[mode]
if mode then
for i=1,#mode do
local m=mode[i]
if m.name==name then
return m.action
end
end
end
end
end
end
function constructors.newhandler(what)
local handler=handlers[what]
if not handler then
handler={}
handlers[what]=handler
end
return handler
end
function constructors.newfeatures(what)
local handler=handlers[what]
local features=handler.features
if not features then
local tables=handler.tables
local statistics=handler.statistics
features=allocate {
defaults={},
descriptions=tables and tables.features or {},
used=statistics and statistics.usedfeatures or {},
initializers={ base={},node={} },
processors={ base={},node={} },
manipulators={ base={},node={} },
}
features.register=function(specification) return register(features,specification) end
handler.features=features
end
return features
end
function constructors.checkedfeatures(what,features)
local defaults=handlers[what].features.defaults
if features and next(features) then
features=fastcopy(features)
for key,value in next,defaults do
if features[key]==nil then
features[key]=value
end
end
return features
else
return fastcopy(defaults)
end
end
function constructors.initializefeatures(what,tfmdata,features,trace,report)
if features and next(features) then
local properties=tfmdata.properties or {}
local whathandler=handlers[what]
local whatfeatures=whathandler.features
local whatinitializers=whatfeatures.initializers
local whatmodechecker=whatfeatures.modechecker
local mode=properties.mode or (whatmodechecker and whatmodechecker(tfmdata,features,features.mode)) or features.mode or "base"
properties.mode=mode
features.mode=mode
local done={}
while true do
local redo=false
local initializers=whatfeatures.initializers[mode]
if initializers then
for i=1,#initializers do
local step=initializers[i]
local feature=step.name
local value=features[feature]
if not value then
elseif done[feature] then
else
local action=step.action
if trace then
report("initializing feature %a to %a for mode %a for font %a",feature,
value,mode,tfmdata.properties.fullname)
end
action(tfmdata,value,features)
if mode~=properties.mode or mode~=features.mode then
if whatmodechecker then
properties.mode=whatmodechecker(tfmdata,features,properties.mode)
features.mode=properties.mode
end
if mode~=properties.mode then
mode=properties.mode
redo=true
end
end
done[feature]=true
end
if redo then
break
end
end
if not redo then
break
end
else
break
end
end
properties.mode=mode
return true
else
return false
end
end
function constructors.collectprocessors(what,tfmdata,features,trace,report)
local processes,nofprocesses={},0
if features and next(features) then
local properties=tfmdata.properties
local whathandler=handlers[what]
local whatfeatures=whathandler.features
local whatprocessors=whatfeatures.processors
local processors=whatprocessors[properties.mode]
if processors then
for i=1,#processors do
local step=processors[i]
local feature=step.name
if features[feature] then
local action=step.action
if trace then
report("installing feature processor %a for mode %a for font %a",feature,mode,tfmdata.properties.fullname)
end
if action then
nofprocesses=nofprocesses+1
processes[nofprocesses]=action
end
end
end
elseif trace then
report("no feature processors for mode %a for font %a",mode,tfmdata.properties.fullname)
end
end
return processes
end
function constructors.applymanipulators(what,tfmdata,features,trace,report)
if features and next(features) then
local properties=tfmdata.properties
local whathandler=handlers[what]
local whatfeatures=whathandler.features
local whatmanipulators=whatfeatures.manipulators
local manipulators=whatmanipulators[properties.mode]
if manipulators then
for i=1,#manipulators do
local step=manipulators[i]
local feature=step.name
local value=features[feature]
if value then
local action=step.action
if trace then
report("applying feature manipulator %a for mode %a for font %a",feature,mode,tfmdata.properties.fullname)
end
if action then
action(tfmdata,feature,value)
end
end
end
end
end
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['luatex-font-enc']={
version=1.001,
comment="companion to luatex-*.tex",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
if context then
texio.write_nl("fatal error: this module is not for context")
os.exit()
end
local fonts=fonts
fonts.encodings={}
fonts.encodings.agl={}
setmetatable(fonts.encodings.agl,{ __index=function(t,k)
if k=="unicodes" then
texio.write(" <loading (extended) adobe glyph list>")
local unicodes=dofile(resolvers.findfile("font-age.lua"))
fonts.encodings.agl={ unicodes=unicodes }
return unicodes
else
return nil
end
end })
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['font-cid']={
version=1.001,
comment="companion to font-otf.lua (cidmaps)",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local format,match,lower=string.format,string.match,string.lower
local tonumber=tonumber
local P,S,R,C,V,lpegmatch=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.V,lpeg.match
local fonts,logs,trackers=fonts,logs,trackers
local trace_loading=false trackers.register("otf.loading",function(v) trace_loading=v end)
local report_otf=logs.reporter("fonts","otf loading")
local cid={}
fonts.cid=cid
local cidmap={}
local cidmax=10
local number=C(R("09","af","AF")^1)
local space=S(" \n\r\t")
local spaces=space^0
local period=P(".")
local periods=period*period
local name=P("/")*C((1-space)^1)
local unicodes,names={},{}
local function do_one(a,b)
unicodes[tonumber(a)]=tonumber(b,16)
end
local function do_range(a,b,c)
c=tonumber(c,16)
for i=tonumber(a),tonumber(b) do
unicodes[i]=c
c=c+1
end
end
local function do_name(a,b)
names[tonumber(a)]=b
end
local grammar=P { "start",
start=number*spaces*number*V("series"),
series=(spaces*(V("one")+V("range")+V("named")))^1,
one=(number*spaces*number)/do_one,
range=(number*periods*number*spaces*number)/do_range,
named=(number*spaces*name)/do_name
}
local function loadcidfile(filename)
local data=io.loaddata(filename)
if data then
unicodes,names={},{}
lpegmatch(grammar,data)
local supplement,registry,ordering=match(filename,"^(.-)%-(.-)%-()%.(.-)$")
return {
supplement=supplement,
registry=registry,
ordering=ordering,
filename=filename,
unicodes=unicodes,
names=names
}
end
end
cid.loadfile=loadcidfile
local template="%s-%s-%s.cidmap"
local function locate(registry,ordering,supplement)
local filename=format(template,registry,ordering,supplement)
local hashname=lower(filename)
local found=cidmap[hashname]
if not found then
if trace_loading then
report_otf("checking cidmap, registry %a, ordering %a, supplement %a, filename %a",registry,ordering,supplement,filename)
end
local fullname=resolvers.findfile(filename,'cid') or ""
if fullname~="" then
found=loadcidfile(fullname)
if found then
if trace_loading then
report_otf("using cidmap file %a",filename)
end
cidmap[hashname]=found
found.usedname=file.basename(filename)
end
end
end
return found
end
function cid.getmap(specification)
if not specification then
report_otf("invalid cidinfo specification, table expected")
return
end
local registry=specification.registry
local ordering=specification.ordering
local supplement=specification.supplement
local filename=format(registry,ordering,supplement)
local found=cidmap[lower(filename)]
if found then
return found
end
if trace_loading then
report_otf("cidmap needed, registry %a, ordering %a, supplement %a",registry,ordering,supplement)
end
found=locate(registry,ordering,supplement)
if not found then
local supnum=tonumber(supplement)
local cidnum=nil
if supnum<cidmax then
for s=supnum+1,cidmax do
local c=locate(registry,ordering,s)
if c then
found,cidnum=c,s
break
end
end
end
if not found and supnum>0 then
for s=supnum-1,0,-1 do
local c=locate(registry,ordering,s)
if c then
found,cidnum=c,s
break
end
end
end
registry=lower(registry)
ordering=lower(ordering)
if found and cidnum>0 then
for s=0,cidnum-1 do
local filename=format(template,registry,ordering,s)
if not cidmap[filename] then
cidmap[filename]=found
end
end
end
end
return found
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['font-map']={
version=1.001,
comment="companion to font-ini.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local tonumber=tonumber
local match,format,find,concat,gsub,lower=string.match,string.format,string.find,table.concat,string.gsub,string.lower
local P,R,S,C,Ct,Cc,lpegmatch=lpeg.P,lpeg.R,lpeg.S,lpeg.C,lpeg.Ct,lpeg.Cc,lpeg.match
local utfbyte=utf.byte
local floor=math.floor
local trace_loading=false trackers.register("fonts.loading",function(v) trace_loading=v end)
local trace_mapping=false trackers.register("fonts.mapping",function(v) trace_unimapping=v end)
local report_fonts=logs.reporter("fonts","loading")
local fonts=fonts
local mappings=fonts.mappings or {}
fonts.mappings=mappings
local function loadlumtable(filename)
local lumname=file.replacesuffix(file.basename(filename),"lum")
local lumfile=resolvers.findfile(lumname,"map") or ""
if lumfile~="" and lfs.isfile(lumfile) then
if trace_loading or trace_mapping then
report_fonts("loading map table %a",lumfile)
end
lumunic=dofile(lumfile)
return lumunic,lumfile
end
end
local hex=R("AF","09")
local hexfour=(hex*hex*hex*hex)/function(s) return tonumber(s,16) end
local hexsix=(hex^1)/function(s) return tonumber(s,16) end
local dec=(R("09")^1)/tonumber
local period=P(".")
local unicode=P("uni")*(hexfour*(period+P(-1))*Cc(false)+Ct(hexfour^1)*Cc(true))
local ucode=P("u")*(hexsix*(period+P(-1))*Cc(false)+Ct(hexsix^1)*Cc(true))
local index=P("index")*dec*Cc(false)
local parser=unicode+ucode+index
local parsers={}
local function makenameparser(str)
if not str or str=="" then
return parser
else
local p=parsers[str]
if not p then
p=P(str)*period*dec*Cc(false)
parsers[str]=p
end
return p
end
end
local function tounicode16(unicode)
if unicode<0x10000 then
return format("%04X",unicode)
elseif unicode<0x1FFFFFFFFF then
return format("%04X%04X",floor(unicode/1024),unicode%1024+0xDC00)
else
report_fonts("can't convert %a into tounicode",unicode)
end
end
local function tounicode16sequence(unicodes)
local t={}
for l=1,#unicodes do
local unicode=unicodes[l]
if unicode<0x10000 then
t[l]=format("%04X",unicode)
elseif unicode<0x1FFFFFFFFF then
t[l]=format("%04X%04X",floor(unicode/1024),unicode%1024+0xDC00)
else
report_fonts ("can't convert %a into tounicode",unicode)
end
end
return concat(t)
end
local function fromunicode16(str)
if #str==4 then
return tonumber(str,16)
else
local l,r=match(str,"(....)(....)")
return (tonumber(l,16)- 0xD800)*0x400+tonumber(r,16)-0xDC00
end
end
mappings.loadlumtable=loadlumtable
mappings.makenameparser=makenameparser
mappings.tounicode16=tounicode16
mappings.tounicode16sequence=tounicode16sequence
mappings.fromunicode16=fromunicode16
local separator=S("_.")
local other=C((1-separator)^1)
local ligsplitter=Ct(other*(separator*other)^0)
function mappings.addtounicode(data,filename)
local resources=data.resources
local properties=data.properties
local descriptions=data.descriptions
local unicodes=resources.unicodes
if not unicodes then
return
end
unicodes['space']=unicodes['space'] or 32
unicodes['hyphen']=unicodes['hyphen'] or 45
unicodes['zwj']=unicodes['zwj'] or 0x200D
unicodes['zwnj']=unicodes['zwnj'] or 0x200C
local private=fonts.constructors.privateoffset
local unknown=format("%04X",utfbyte("?"))
local unicodevector=fonts.encodings.agl.unicodes
local tounicode={}
local originals={}
resources.tounicode=tounicode
resources.originals=originals
local lumunic,uparser,oparser
local cidinfo,cidnames,cidcodes,usedmap
if false then
lumunic=loadlumtable(filename)
lumunic=lumunic and lumunic.tounicode
end
cidinfo=properties.cidinfo
usedmap=cidinfo and fonts.cid.getmap(cidinfo)
if usedmap then
oparser=usedmap and makenameparser(cidinfo.ordering)
cidnames=usedmap.names
cidcodes=usedmap.unicodes
end
uparser=makenameparser()
local ns,nl=0,0
for unic,glyph in next,descriptions do
local index=glyph.index
local name=glyph.name
if unic==-1 or unic>=private or (unic>=0xE000 and unic<=0xF8FF) or unic==0xFFFE or unic==0xFFFF then
local unicode=lumunic and lumunic[name] or unicodevector[name]
if unicode then
originals[index]=unicode
tounicode[index]=tounicode16(unicode)
ns=ns+1
end
if (not unicode) and usedmap then
local foundindex=lpegmatch(oparser,name)
if foundindex then
unicode=cidcodes[foundindex]
if unicode then
originals[index]=unicode
tounicode[index]=tounicode16(unicode)
ns=ns+1
else
local reference=cidnames[foundindex]
if reference then
local foundindex=lpegmatch(oparser,reference)
if foundindex then
unicode=cidcodes[foundindex]
if unicode then
originals[index]=unicode
tounicode[index]=tounicode16(unicode)
ns=ns+1
end
end
if not unicode then
local foundcodes,multiple=lpegmatch(uparser,reference)
if foundcodes then
originals[index]=foundcodes
if multiple then
tounicode[index]=tounicode16sequence(foundcodes)
nl=nl+1
unicode=true
else
tounicode[index]=tounicode16(foundcodes)
ns=ns+1
unicode=foundcodes
end
end
end
end
end
end
end
if not unicode then
local split=lpegmatch(ligsplitter,name)
local nplit=split and #split or 0
if nplit>=2 then
local t,n={},0
for l=1,nplit do
local base=split[l]
local u=unicodes[base] or unicodevector[base]
if not u then
break
elseif type(u)=="table" then
n=n+1
t[n]=u[1]
else
n=n+1
t[n]=u
end
end
if n==0 then
elseif n==1 then
originals[index]=t[1]
tounicode[index]=tounicode16(t[1])
else
originals[index]=t
tounicode[index]=tounicode16sequence(t)
end
nl=nl+1
unicode=true
else
end
end
if not unicode then
local foundcodes,multiple=lpegmatch(uparser,name)
if foundcodes then
if multiple then
originals[index]=foundcodes
tounicode[index]=tounicode16sequence(foundcodes)
nl=nl+1
unicode=true
else
originals[index]=foundcodes
tounicode[index]=tounicode16(foundcodes)
ns=ns+1
unicode=foundcodes
end
end
end
end
end
if trace_mapping then
for unic,glyph in table.sortedhash(descriptions) do
local name=glyph.name
local index=glyph.index
local toun=tounicode[index]
if toun then
report_fonts("internal slot %U, name %a, unicode %U, tounicode %a",index,name,unic,toun)
else
report_fonts("internal slot %U, name %a, unicode %U",index,name,unic)
end
end
end
if trace_loading and (ns>0 or nl>0) then
report_fonts("%s tounicode entries added, ligatures %s",nl+ns,ns)
end
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['luatex-fonts-syn']={
version=1.001,
comment="companion to luatex-*.tex",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
if context then
texio.write_nl("fatal error: this module is not for context")
os.exit()
end
local fonts=fonts
fonts.names=fonts.names or {}
fonts.names.version=1.001
fonts.names.basename="luatex-fonts-names.lua"
fonts.names.new_to_old={}
fonts.names.old_to_new={}
local data,loaded=nil,false
local fileformats={ "lua","tex","other text files" }
function fonts.names.resolve(name,sub)
if not loaded then
local basename=fonts.names.basename
if basename and basename~="" then
for i=1,#fileformats do
local format=fileformats[i]
local foundname=resolvers.findfile(basename,format) or ""
if foundname~="" then
data=dofile(foundname)
texio.write("<font database loaded: ",foundname,">")
break
end
end
end
loaded=true
end
if type(data)=="table" and data.version==fonts.names.version then
local condensed=string.gsub(string.lower(name),"[^%a%d]","")
local found=data.mappings and data.mappings[condensed]
if found then
local fontname,filename,subfont=found[1],found[2],found[3]
if subfont then
return filename,fontname
else
return filename,false
end
else
return name,false
end
end
end
fonts.names.resolvespec=fonts.names.resolve
function fonts.names.getfilename(askedname,suffix)
return ""
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['luatex-fonts-tfm']={
version=1.001,
comment="companion to luatex-*.tex",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
if context then
texio.write_nl("fatal error: this module is not for context")
os.exit()
end
local fonts=fonts
local tfm={}
fonts.handlers.tfm=tfm
fonts.formats.tfm="type1"
function fonts.readers.tfm(specification)
local fullname=specification.filename or ""
if fullname=="" then
local forced=specification.forced or ""
if forced~="" then
fullname=specification.name.."."..forced
else
fullname=specification.name
end
end
local foundname=resolvers.findbinfile(fullname,'tfm') or ""
if foundname=="" then
foundname=resolvers.findbinfile(fullname,'ofm') or ""
end
if foundname~="" then
specification.filename=foundname
specification.format="ofm"
return font.read_tfm(specification.filename,specification.size)
end
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['font-oti']={
version=1.001,
comment="companion to font-ini.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local lower=string.lower
local fonts=fonts
local constructors=fonts.constructors
local otf=constructors.newhandler("otf")
local otffeatures=constructors.newfeatures("otf")
local otftables=otf.tables
local registerotffeature=otffeatures.register
local allocate=utilities.storage.allocate
registerotffeature {
name="features",
description="initialization of feature handler",
default=true,
}
local function setmode(tfmdata,value)
if value then
tfmdata.properties.mode=lower(value)
end
end
local function setlanguage(tfmdata,value)
if value then
local cleanvalue=lower(value)
local languages=otftables and otftables.languages
local properties=tfmdata.properties
if not languages then
properties.language=cleanvalue
elseif languages[value] then
properties.language=cleanvalue
else
properties.language="dflt"
end
end
end
local function setscript(tfmdata,value)
if value then
local cleanvalue=lower(value)
local scripts=otftables and otftables.scripts
local properties=tfmdata.properties
if not scripts then
properties.script=cleanvalue
elseif scripts[value] then
properties.script=cleanvalue
else
properties.script="dflt"
end
end
end
registerotffeature {
name="mode",
description="mode",
initializers={
base=setmode,
node=setmode,
}
}
registerotffeature {
name="language",
description="language",
initializers={
base=setlanguage,
node=setlanguage,
}
}
registerotffeature {
name="script",
description="script",
initializers={
base=setscript,
node=setscript,
}
}
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['font-otf']={
version=1.001,
comment="companion to font-ini.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local utfbyte=utf.byte
local format,gmatch,gsub,find,match,lower,strip=string.format,string.gmatch,string.gsub,string.find,string.match,string.lower,string.strip
local type,next,tonumber,tostring=type,next,tonumber,tostring
local abs=math.abs
local getn=table.getn
local lpegmatch=lpeg.match
local reversed,concat,remove=table.reversed,table.concat,table.remove
local ioflush=io.flush
local fastcopy,tohash,derivetable=table.fastcopy,table.tohash,table.derive
local allocate=utilities.storage.allocate
local registertracker=trackers.register
local registerdirective=directives.register
local starttiming=statistics.starttiming
local stoptiming=statistics.stoptiming
local elapsedtime=statistics.elapsedtime
local findbinfile=resolvers.findbinfile
local trace_private=false registertracker("otf.private",function(v) trace_private=v end)
local trace_loading=false registertracker("otf.loading",function(v) trace_loading=v end)
local trace_features=false registertracker("otf.features",function(v) trace_features=v end)
local trace_dynamics=false registertracker("otf.dynamics",function(v) trace_dynamics=v end)
local trace_sequences=false registertracker("otf.sequences",function(v) trace_sequences=v end)
local trace_markwidth=false registertracker("otf.markwidth",function(v) trace_markwidth=v end)
local trace_defining=false registertracker("fonts.defining",function(v) trace_defining=v end)
local report_otf=logs.reporter("fonts","otf loading")
local fonts=fonts
local otf=fonts.handlers.otf
otf.glists={ "gsub","gpos" }
otf.version=2.741
otf.cache=containers.define("fonts","otf",otf.version,true)
local fontdata=fonts.hashes.identifiers
local chardata=characters and characters.data
local otffeatures=fonts.constructors.newfeatures("otf")
local registerotffeature=otffeatures.register
local enhancers=allocate()
otf.enhancers=enhancers
local patches={}
enhancers.patches=patches
local definers=fonts.definers
local readers=fonts.readers
local constructors=fonts.constructors
local forceload=false
local cleanup=0
local usemetatables=false
local packdata=true
local syncspace=true
local forcenotdef=false
local wildcard="*"
local default="dflt"
local fontloaderfields=fontloader.fields
local mainfields=nil
local glyphfields=nil
registerdirective("fonts.otf.loader.cleanup",function(v) cleanup=tonumber(v) or (v and 1) or 0 end)
registerdirective("fonts.otf.loader.force",function(v) forceload=v end)
registerdirective("fonts.otf.loader.usemetatables",function(v) usemetatables=v end)
registerdirective("fonts.otf.loader.pack",function(v) packdata=v end)
registerdirective("fonts.otf.loader.syncspace",function(v) syncspace=v end)
registerdirective("fonts.otf.loader.forcenotdef",function(v) forcenotdef=v end)
local function load_featurefile(raw,featurefile)
if featurefile and featurefile~="" then
if trace_loading then
report_otf("using featurefile %a",featurefile)
end
fontloader.apply_featurefile(raw,featurefile)
end
end
local function showfeatureorder(rawdata,filename)
local sequences=rawdata.resources.sequences
if sequences and #sequences>0 then
if trace_loading then
report_otf("font %a has %s sequences",filename,#sequences)
report_otf(" ")
end
for nos=1,#sequences do
local sequence=sequences[nos]
local typ=sequence.type or "no-type"
local name=sequence.name or "no-name"
local subtables=sequence.subtables or { "no-subtables" }
local features=sequence.features
if trace_loading then
report_otf("%3i %-15s %-20s [% t]",nos,name,typ,subtables)
end
if features then
for feature,scripts in next,features do
local tt={}
if type(scripts)=="table" then
for script,languages in next,scripts do
local ttt={}
for language,_ in next,languages do
ttt[#ttt+1]=language
end
tt[#tt+1]=formatters["[%s: % t]"](script,ttt)
end
if trace_loading then
report_otf(" %s: % t",feature,tt)
end
else
if trace_loading then
report_otf(" %s: %S",feature,scripts)
end
end
end
end
end
if trace_loading then
report_otf("\n")
end
elseif trace_loading then
report_otf("font %a has no sequences",filename)
end
end
local valid_fields=table.tohash {
"ascent",
"cidinfo",
"copyright",
"descent",
"design_range_bottom",
"design_range_top",
"design_size",
"encodingchanged",
"extrema_bound",
"familyname",
"fontname",
"fontname",
"fontstyle_id",
"fontstyle_name",
"fullname",
"hasvmetrics",
"horiz_base",
"issans",
"isserif",
"italicangle",
"macstyle",
"onlybitmaps",
"origname",
"os2_version",
"pfminfo",
"serifcheck",
"sfd_version",
"strokedfont",
"strokewidth",
"table_version",
"ttf_tables",
"uni_interp",
"uniqueid",
"units_per_em",
"upos",
"use_typo_metrics",
"uwidth",
"version",
"vert_base",
"weight",
"weight_width_slope_only",
}
local ordered_enhancers={
"prepare tables",
"prepare glyphs",
"prepare lookups",
"analyze glyphs",
"analyze math",
"prepare tounicode",
"reorganize lookups",
"reorganize mark classes",
"reorganize anchor classes",
"reorganize glyph kerns",
"reorganize glyph lookups",
"reorganize glyph anchors",
"merge kern classes",
"reorganize features",
"reorganize subtables",
"check glyphs",
"check metadata",
"check extra features",
"add duplicates",
"check encoding",
"cleanup tables",
}
local actions=allocate()
local before=allocate()
local after=allocate()
patches.before=before
patches.after=after
local function enhance(name,data,filename,raw)
local enhancer=actions[name]
if enhancer then
if trace_loading then
report_otf("apply enhancement %a to file %a",name,filename)
ioflush()
end
enhancer(data,filename,raw)
else
end
end
function enhancers.apply(data,filename,raw)
local basename=file.basename(lower(filename))
if trace_loading then
report_otf("%s enhancing file %a","start",filename)
end
ioflush()
for e=1,#ordered_enhancers do
local enhancer=ordered_enhancers[e]
local b=before[enhancer]
if b then
for pattern,action in next,b do
if find(basename,pattern) then
action(data,filename,raw)
end
end
end
enhance(enhancer,data,filename,raw)
local a=after[enhancer]
if a then
for pattern,action in next,a do
if find(basename,pattern) then
action(data,filename,raw)
end
end
end
ioflush()
end
if trace_loading then
report_otf("%s enhancing file %a","stop",filename)
end
ioflush()
end
function patches.register(what,where,pattern,action)
local pw=patches[what]
if pw then
local ww=pw[where]
if ww then
ww[pattern]=action
else
pw[where]={ [pattern]=action}
end
end
end
function patches.report(fmt,...)
if trace_loading then
report_otf("patching: %s",formatters[fmt](...))
end
end
function enhancers.register(what,action)
actions[what]=action
end
function otf.load(filename,format,sub,featurefile)
local base=file.basename(file.removesuffix(filename))
local name=file.removesuffix(base)
local attr=lfs.attributes(filename)
local size=attr and attr.size or 0
local time=attr and attr.modification or 0
if featurefile then
name=name.."@"..file.removesuffix(file.basename(featurefile))
end
if sub=="" then
sub=false
end
local hash=name
if sub then
hash=hash.."-"..sub
end
hash=containers.cleanname(hash)
local featurefiles
if featurefile then
featurefiles={}
for s in gmatch(featurefile,"[^,]+") do
local name=resolvers.findfile(file.addsuffix(s,'fea'),'fea') or ""
if name=="" then
report_otf("loading error, no featurefile %a",s)
else
local attr=lfs.attributes(name)
featurefiles[#featurefiles+1]={
name=name,
size=attr and attr.size or 0,
time=attr and attr.modification or 0,
}
end
end
if #featurefiles==0 then
featurefiles=nil
end
end
local data=containers.read(otf.cache,hash)
local reload=not data or data.size~=size or data.time~=time
if forceload then
report_otf("forced reload of %a due to hard coded flag",filename)
reload=true
end
if not reload then
local featuredata=data.featuredata
if featurefiles then
if not featuredata or #featuredata~=#featurefiles then
reload=true
else
for i=1,#featurefiles do
local fi,fd=featurefiles[i],featuredata[i]
if fi.name~=fd.name or fi.size~=fd.size or fi.time~=fd.time then
reload=true
break
end
end
end
elseif featuredata then
reload=true
end
if reload then
report_otf("loading: forced reload due to changed featurefile specification %a",featurefile)
end
end
if reload then
report_otf("loading %a, hash %a",filename,hash)
local fontdata,messages
if sub then
fontdata,messages=fontloader.open(filename,sub)
else
fontdata,messages=fontloader.open(filename)
end
if fontdata then
mainfields=mainfields or (fontloaderfields and fontloaderfields(fontdata))
end
if trace_loading and messages and #messages>0 then
if type(messages)=="string" then
report_otf("warning: %s",messages)
else
for m=1,#messages do
report_otf("warning: %S",messages[m])
end
end
else
report_otf("loading done")
end
if fontdata then
if featurefiles then
for i=1,#featurefiles do
load_featurefile(fontdata,featurefiles[i].name)
end
end
local unicodes={
}
local splitter=lpeg.splitter(" ",unicodes)
data={
size=size,
time=time,
format=format,
featuredata=featurefiles,
resources={
filename=resolvers.unresolve(filename),
version=otf.version,
creator="context mkiv",
unicodes=unicodes,
indices={
},
duplicates={
},
variants={
},
lookuptypes={},
},
metadata={
},
properties={
},
descriptions={},
goodies={},
helpers={
tounicodelist=splitter,
tounicodetable=lpeg.Ct(splitter),
},
}
starttiming(data)
report_otf("file size: %s",size)
enhancers.apply(data,filename,fontdata)
local packtime={}
if packdata then
if cleanup>0 then
collectgarbage("collect")
end
starttiming(packtime)
enhance("pack",data,filename,nil)
stoptiming(packtime)
end
report_otf("saving %a in cache",filename)
data=containers.write(otf.cache,hash,data)
if cleanup>1 then
collectgarbage("collect")
end
stoptiming(data)
if elapsedtime then
report_otf("preprocessing and caching time %s, packtime %s",
elapsedtime(data),packdata and elapsedtime(packtime) or 0)
end
fontloader.close(fontdata)
if cleanup>3 then
collectgarbage("collect")
end
data=containers.read(otf.cache,hash)
if cleanup>2 then
collectgarbage("collect")
end
else
data=nil
report_otf("loading failed due to read error")
end
end
if data then
if trace_defining then
report_otf("loading from cache using hash %a",hash)
end
enhance("unpack",data,filename,nil,false)
enhance("add dimensions",data,filename,nil,false)
if trace_sequences then
showfeatureorder(data,filename)
end
end
return data
end
local mt={
__index=function(t,k)
if k=="height" then
local ht=t.boundingbox[4]
return ht<0 and 0 or ht
elseif k=="depth" then
local dp=-t.boundingbox[2]
return dp<0 and 0 or dp
elseif k=="width" then
return 0
elseif k=="name" then
return forcenotdef and ".notdef"
end
end
}
actions["prepare tables"]=function(data,filename,raw)
data.properties.hasitalics=false
end
actions["add dimensions"]=function(data,filename)
if data then
local descriptions=data.descriptions
local resources=data.resources
local defaultwidth=resources.defaultwidth or 0
local defaultheight=resources.defaultheight or 0
local defaultdepth=resources.defaultdepth or 0
local basename=trace_markwidth and file.basename(filename)
if usemetatables then
for _,d in next,descriptions do
local wd=d.width
if not wd then
d.width=defaultwidth
elseif trace_markwidth and wd~=0 and d.class=="mark" then
report_otf("mark %a with width %b found in %a",d.name or "<noname>",wd,basename)
end
setmetatable(d,mt)
end
else
for _,d in next,descriptions do
local bb,wd=d.boundingbox,d.width
if not wd then
d.width=defaultwidth
elseif trace_markwidth and wd~=0 and d.class=="mark" then
report_otf("mark %a with width %b found in %a",d.name or "<noname>",wd,basename)
end
if bb then
local ht,dp=bb[4],-bb[2]
if ht==0 or ht<0 then
else
d.height=ht
end
if dp==0 or dp<0 then
else
d.depth=dp
end
end
end
end
end
end
local function somecopy(old)
if old then
local new={}
if type(old)=="table" then
for k,v in next,old do
if k=="glyphs" then
elseif type(v)=="table" then
new[k]=somecopy(v)
else
new[k]=v
end
end
else
for i=1,#mainfields do
local k=mainfields[i]
local v=old[k]
if k=="glyphs" then
elseif type(v)=="table" then
new[k]=somecopy(v)
else
new[k]=v
end
end
end
return new
else
return {}
end
end
actions["prepare glyphs"]=function(data,filename,raw)
local rawglyphs=raw.glyphs
local rawsubfonts=raw.subfonts
local rawcidinfo=raw.cidinfo
local criterium=constructors.privateoffset
local private=criterium
local resources=data.resources
local metadata=data.metadata
local properties=data.properties
local descriptions=data.descriptions
local unicodes=resources.unicodes
local indices=resources.indices
local duplicates=resources.duplicates
local variants=resources.variants
if rawsubfonts then
metadata.subfonts={}
properties.cidinfo=rawcidinfo
if rawcidinfo.registry then
local cidmap=fonts.cid.getmap(rawcidinfo)
if cidmap then
rawcidinfo.usedname=cidmap.usedname
local nofnames,nofunicodes=0,0
local cidunicodes,cidnames=cidmap.unicodes,cidmap.names
for cidindex=1,#rawsubfonts do
local subfont=rawsubfonts[cidindex]
local cidglyphs=subfont.glyphs
metadata.subfonts[cidindex]=somecopy(subfont)
for index=0,subfont.glyphcnt-1 do
local glyph=cidglyphs[index]
if glyph then
local unicode=glyph.unicode
local name=glyph.name or cidnames[index]
if not unicode or unicode==-1 or unicode>=criterium then
unicode=cidunicodes[index]
end
if not unicode or unicode==-1 or unicode>=criterium then
if not name then
name=format("u%06X",private)
end
unicode=private
unicodes[name]=private
if trace_private then
report_otf("glyph %a at index %H is moved to private unicode slot %U",name,index,private)
end
private=private+1
nofnames=nofnames+1
else
if not name then
name=format("u%06X",unicode)
end
unicodes[name]=unicode
nofunicodes=nofunicodes+1
end
indices[index]=unicode
local description={
boundingbox=glyph.boundingbox,
name=glyph.name or name or "unknown",
cidindex=cidindex,
index=index,
glyph=glyph,
}
descriptions[unicode]=description
else
end
end
end
if trace_loading then
report_otf("cid font remapped, %s unicode points, %s symbolic names, %s glyphs",nofunicodes,nofnames,nofunicodes+nofnames)
end
elseif trace_loading then
report_otf("unable to remap cid font, missing cid file for %a",filename)
end
elseif trace_loading then
report_otf("font %a has no glyphs",filename)
end
else
for index=0,raw.glyphcnt-1 do
local glyph=rawglyphs[index]
if glyph then
local unicode=glyph.unicode
local name=glyph.name
if not unicode or unicode==-1 or unicode>=criterium then
unicode=private
unicodes[name]=private
if trace_private then
report_otf("glyph %a at index %H is moved to private unicode slot %U",name,index,private)
end
private=private+1
else
unicodes[name]=unicode
end
indices[index]=unicode
if not name then
name=format("u%06X",unicode)
end
descriptions[unicode]={
boundingbox=glyph.boundingbox,
name=name,
index=index,
glyph=glyph,
}
local altuni=glyph.altuni
if altuni then
local d
for i=1,#altuni do
local a=altuni[i]
local u=a.unicode
local v=a.variant
if v then
local vv=variants[v]
if vv then
vv[u]=unicode
else
vv={ [u]=unicode }
variants[v]=vv
end
elseif d then
d[#d+1]=u
else
d={ u }
end
end
if d then
duplicates[unicode]=d
end
end
else
report_otf("potential problem: glyph %U is used but empty",index)
end
end
end
resources.private=private
end
actions["check encoding"]=function(data,filename,raw)
local descriptions=data.descriptions
local resources=data.resources
local properties=data.properties
local unicodes=resources.unicodes
local indices=resources.indices
local mapdata=raw.map or {}
local unicodetoindex=mapdata and mapdata.map or {}
local encname=lower(data.enc_name or mapdata.enc_name or "")
local criterium=0xFFFF
if find(encname,"unicode") then
if trace_loading then
report_otf("checking embedded unicode map %a",encname)
end
for unicode,index in next,unicodetoindex do
if unicode<=criterium and not descriptions[unicode] then
local parent=indices[index]
if parent then
report_otf("weird, unicode %U points to %U with index %H",unicode,parent,index)
else
report_otf("weird, unicode %U points to nowhere with index %H",unicode,index)
end
end
end
elseif properties.cidinfo then
report_otf("warning: no unicode map, used cidmap %a",properties.cidinfo.usedname)
else
report_otf("warning: non unicode map %a, only using glyph unicode data",encname or "whatever")
end
if mapdata then
mapdata.map={}
end
end
actions["add duplicates"]=function(data,filename,raw)
local descriptions=data.descriptions
local resources=data.resources
local properties=data.properties
local unicodes=resources.unicodes
local indices=resources.indices
local duplicates=resources.duplicates
for unicode,d in next,duplicates do
for i=1,#d do
local u=d[i]
if not descriptions[u] then
local description=descriptions[unicode]
local duplicate=table.copy(description)
duplicate.comment=format("copy of U+%05X",unicode)
descriptions[u]=duplicate
local n=0
for _,description in next,descriptions do
if kerns then
local kerns=description.kerns
for _,k in next,kerns do
local ku=k[unicode]
if ku then
k[u]=ku
n=n+1
end
end
end
end
if trace_loading then
report_otf("duplicating %U to %U with index %H (%s kerns)",unicode,u,description.index,n)
end
end
end
end
end
actions["analyze glyphs"]=function(data,filename,raw)
local descriptions=data.descriptions
local resources=data.resources
local metadata=data.metadata
local properties=data.properties
local hasitalics=false
local widths={}
local marks={}
for unicode,description in next,descriptions do
local glyph=description.glyph
local italic=glyph.italic_correction
if not italic then
elseif italic==0 then
else
description.italic=italic
hasitalics=true
end
local width=glyph.width
widths[width]=(widths[width] or 0)+1
local class=glyph.class
if class then
if class=="mark" then
marks[unicode]=true
end
description.class=class
end
end
properties.hasitalics=hasitalics
resources.marks=marks
local wd,most=0,1
for k,v in next,widths do
if v>most then
wd,most=k,v
end
end
if most>1000 then
if trace_loading then
report_otf("most common width: %s (%s times), sharing (cjk font)",wd,most)
end
for unicode,description in next,descriptions do
if description.width==wd then
else
description.width=description.glyph.width
end
end
resources.defaultwidth=wd
else
for unicode,description in next,descriptions do
description.width=description.glyph.width
end
end
end
actions["reorganize mark classes"]=function(data,filename,raw)
local mark_classes=raw.mark_classes
if mark_classes then
local resources=data.resources
local unicodes=resources.unicodes
local markclasses={}
resources.markclasses=markclasses
for name,class in next,mark_classes do
local t={}
for s in gmatch(class,"[^ ]+") do
t[unicodes[s]]=true
end
markclasses[name]=t
end
end
end
actions["reorganize features"]=function(data,filename,raw)
local features={}
data.resources.features=features
for k,what in next,otf.glists do
local dw=raw[what]
if dw then
local f={}
features[what]=f
for i=1,#dw do
local d=dw[i]
local dfeatures=d.features
if dfeatures then
for i=1,#dfeatures do
local df=dfeatures[i]
local tag=strip(lower(df.tag))
local ft=f[tag]
if not ft then
ft={}
f[tag]=ft
end
local dscripts=df.scripts
for i=1,#dscripts do
local d=dscripts[i]
local languages=d.langs
local script=strip(lower(d.script))
local fts=ft[script] if not fts then fts={} ft[script]=fts end
for i=1,#languages do
fts[strip(lower(languages[i]))]=true
end
end
end
end
end
end
end
end
actions["reorganize anchor classes"]=function(data,filename,raw)
local resources=data.resources
local anchor_to_lookup={}
local lookup_to_anchor={}
resources.anchor_to_lookup=anchor_to_lookup
resources.lookup_to_anchor=lookup_to_anchor
local classes=raw.anchor_classes
if classes then
for c=1,#classes do
local class=classes[c]
local anchor=class.name
local lookups=class.lookup
if type(lookups)~="table" then
lookups={ lookups }
end
local a=anchor_to_lookup[anchor]
if not a then
a={}
anchor_to_lookup[anchor]=a
end
for l=1,#lookups do
local lookup=lookups[l]
local l=lookup_to_anchor[lookup]
if l then
l[anchor]=true
else
l={ [anchor]=true }
lookup_to_anchor[lookup]=l
end
a[lookup]=true
end
end
end
end
actions["prepare tounicode"]=function(data,filename,raw)
fonts.mappings.addtounicode(data,filename)
end
local g_directions={
gsub_contextchain=1,
gpos_contextchain=1,
gsub_reversecontextchain=-1,
gpos_reversecontextchain=-1,
}
local function supported(features)
for i=1,#features do
if features[i].ismac then
return false
end
end
return true
end
actions["reorganize subtables"]=function(data,filename,raw)
local resources=data.resources
local sequences={}
local lookups={}
local chainedfeatures={}
resources.sequences=sequences
resources.lookups=lookups
for _,what in next,otf.glists do
local dw=raw[what]
if dw then
for k=1,#dw do
local gk=dw[k]
local features=gk.features
if not features or supported(features) then
local typ=gk.type
local chain=g_directions[typ] or 0
local subtables=gk.subtables
if subtables then
local t={}
for s=1,#subtables do
t[s]=subtables[s].name
end
subtables=t
end
local flags,markclass=gk.flags,nil
if flags then
local t={
(flags.ignorecombiningmarks and "mark") or false,
(flags.ignoreligatures and "ligature") or false,
(flags.ignorebaseglyphs and "base") or false,
flags.r2l or false,
}
markclass=flags.mark_class
if markclass then
markclass=resources.markclasses[markclass]
end
flags=t
end
local name=gk.name
if not name then
report_otf("skipping weird lookup number %s",k)
elseif features then
local f={}
for i=1,#features do
local df=features[i]
local tag=strip(lower(df.tag))
local ft=f[tag] if not ft then ft={} f[tag]=ft end
local dscripts=df.scripts
for i=1,#dscripts do
local d=dscripts[i]
local languages=d.langs
local script=strip(lower(d.script))
local fts=ft[script] if not fts then fts={} ft[script]=fts end
for i=1,#languages do
fts[strip(lower(languages[i]))]=true
end
end
end
sequences[#sequences+1]={
type=typ,
chain=chain,
flags=flags,
name=name,
subtables=subtables,
markclass=markclass,
features=f,
}
else
lookups[name]={
type=typ,
chain=chain,
flags=flags,
subtables=subtables,
markclass=markclass,
}
end
end
end
end
end
end
actions["prepare lookups"]=function(data,filename,raw)
local lookups=raw.lookups
if lookups then
data.lookups=lookups
end
end
local function t_uncover(splitter,cache,covers)
local result={}
for n=1,#covers do
local cover=covers[n]
local uncovered=cache[cover]
if not uncovered then
uncovered=lpegmatch(splitter,cover)
cache[cover]=uncovered
end
result[n]=uncovered
end
return result
end
local function s_uncover(splitter,cache,cover)
if cover=="" then
return nil
else
local uncovered=cache[cover]
if not uncovered then
uncovered=lpegmatch(splitter,cover)
cache[cover]=uncovered
end
return { uncovered }
end
end
local function t_hashed(t,cache)
if t then
local ht={}
for i=1,#t do
local ti=t[i]
local tih=cache[ti]
if not tih then
tih={}
for i=1,#ti do
tih[ti[i]]=true
end
cache[ti]=tih
end
ht[i]=tih
end
return ht
else
return nil
end
end
local s_hashed=t_hashed
local function r_uncover(splitter,cache,cover,replacements)
if cover=="" then
return nil
else
local uncovered=cover[1]
local replaced=cache[replacements]
if not replaced then
replaced=lpegmatch(splitter,replacements)
cache[replacements]=replaced
end
local nu,nr=#uncovered,#replaced
local r={}
if nu==nr then
for i=1,nu do
r[uncovered[i]]=replaced[i]
end
end
return r
end
end
actions["reorganize lookups"]=function(data,filename,raw)
if data.lookups then
local splitter=data.helpers.tounicodetable
local t_u_cache={}
local s_u_cache=t_u_cache
local t_h_cache={}
local s_h_cache=t_h_cache
local r_u_cache={}
for _,lookup in next,data.lookups do
local rules=lookup.rules
if rules then
local format=lookup.format
if format=="class" then
local before_class=lookup.before_class
if before_class then
before_class=t_uncover(splitter,t_u_cache,reversed(before_class))
end
local current_class=lookup.current_class
if current_class then
current_class=t_uncover(splitter,t_u_cache,current_class)
end
local after_class=lookup.after_class
if after_class then
after_class=t_uncover(splitter,t_u_cache,after_class)
end
for i=1,#rules do
local rule=rules[i]
local class=rule.class
local before=class.before
if before then
for i=1,#before do
before[i]=before_class[before[i]] or {}
end
rule.before=t_hashed(before,t_h_cache)
end
local current=class.current
local lookups=rule.lookups
if current then
for i=1,#current do
current[i]=current_class[current[i]] or {}
if lookups and not lookups[i] then
lookups[i]=""
end
end
rule.current=t_hashed(current,t_h_cache)
end
local after=class.after
if after then
for i=1,#after do
after[i]=after_class[after[i]] or {}
end
rule.after=t_hashed(after,t_h_cache)
end
rule.class=nil
end
lookup.before_class=nil
lookup.current_class=nil
lookup.after_class=nil
lookup.format="coverage"
elseif format=="coverage" then
for i=1,#rules do
local rule=rules[i]
local coverage=rule.coverage
if coverage then
local before=coverage.before
if before then
before=t_uncover(splitter,t_u_cache,reversed(before))
rule.before=t_hashed(before,t_h_cache)
end
local current=coverage.current
if current then
current=t_uncover(splitter,t_u_cache,current)
rule.current=t_hashed(current,t_h_cache)
end
local after=coverage.after
if after then
after=t_uncover(splitter,t_u_cache,after)
rule.after=t_hashed(after,t_h_cache)
end
rule.coverage=nil
end
end
elseif format=="reversecoverage" then
for i=1,#rules do
local rule=rules[i]
local reversecoverage=rule.reversecoverage
if reversecoverage then
local before=reversecoverage.before
if before then
before=t_uncover(splitter,t_u_cache,reversed(before))
rule.before=t_hashed(before,t_h_cache)
end
local current=reversecoverage.current
if current then
current=t_uncover(splitter,t_u_cache,current)
rule.current=t_hashed(current,t_h_cache)
end
local after=reversecoverage.after
if after then
after=t_uncover(splitter,t_u_cache,after)
rule.after=t_hashed(after,t_h_cache)
end
local replacements=reversecoverage.replacements
if replacements then
rule.replacements=r_uncover(splitter,r_u_cache,current,replacements)
end
rule.reversecoverage=nil
end
end
elseif format=="glyphs" then
for i=1,#rules do
local rule=rules[i]
local glyphs=rule.glyphs
if glyphs then
local fore=glyphs.fore
if fore and fore~="" then
fore=s_uncover(splitter,s_u_cache,fore)
rule.before=s_hashed(fore,s_h_cache)
end
local back=glyphs.back
if back then
back=s_uncover(splitter,s_u_cache,back)
rule.after=s_hashed(back,s_h_cache)
end
local names=glyphs.names
if names then
names=s_uncover(splitter,s_u_cache,names)
rule.current=s_hashed(names,s_h_cache)
end
rule.glyphs=nil
end
end
end
end
end
end
end
local function check_variants(unicode,the_variants,splitter,unicodes)
local variants=the_variants.variants
if variants then
local glyphs=lpegmatch(splitter,variants)
local done={ [unicode]=true }
local n=0
for i=1,#glyphs do
local g=glyphs[i]
if done[g] then
report_otf("skipping cyclic reference %U in math variant %U",g,unicode)
else
if n==0 then
n=1
variants={ g }
else
n=n+1
variants[n]=g
end
done[g]=true
end
end
if n==0 then
variants=nil
end
end
local parts=the_variants.parts
if parts then
local p=#parts
if p>0 then
for i=1,p do
local pi=parts[i]
pi.glyph=unicodes[pi.component] or 0
pi.component=nil
end
else
parts=nil
end
end
local italic_correction=the_variants.italic_correction
if italic_correction and italic_correction==0 then
italic_correction=nil
end
return variants,parts,italic_correction
end
actions["analyze math"]=function(data,filename,raw)
if raw.math then
data.metadata.math=raw.math
local unicodes=data.resources.unicodes
local splitter=data.helpers.tounicodetable
for unicode,description in next,data.descriptions do
local glyph=description.glyph
local mathkerns=glyph.mathkern
local horiz_variants=glyph.horiz_variants
local vert_variants=glyph.vert_variants
local top_accent=glyph.top_accent
if mathkerns or horiz_variants or vert_variants or top_accent then
local math={}
if top_accent then
math.top_accent=top_accent
end
if mathkerns then
for k,v in next,mathkerns do
if not next(v) then
mathkerns[k]=nil
else
for k,v in next,v do
if v==0 then
k[v]=nil
end
end
end
end
math.kerns=mathkerns
end
if horiz_variants then
math.horiz_variants,math.horiz_parts,math.horiz_italic_correction=check_variants(unicode,horiz_variants,splitter,unicodes)
end
if vert_variants then
math.vert_variants,math.vert_parts,math.vert_italic_correction=check_variants(unicode,vert_variants,splitter,unicodes)
end
local italic_correction=description.italic
if italic_correction and italic_correction~=0 then
math.italic_correction=italic_correction
end
description.math=math
end
end
end
end
actions["reorganize glyph kerns"]=function(data,filename,raw)
local descriptions=data.descriptions
local resources=data.resources
local unicodes=resources.unicodes
for unicode,description in next,descriptions do
local kerns=description.glyph.kerns
if kerns then
local newkerns={}
for k,kern in next,kerns do
local name=kern.char
local offset=kern.off
local lookup=kern.lookup
if name and offset and lookup then
local unicode=unicodes[name]
if unicode then
if type(lookup)=="table" then
for l=1,#lookup do
local lookup=lookup[l]
local lookupkerns=newkerns[lookup]
if lookupkerns then
lookupkerns[unicode]=offset
else
newkerns[lookup]={ [unicode]=offset }
end
end
else
local lookupkerns=newkerns[lookup]
if lookupkerns then
lookupkerns[unicode]=offset
else
newkerns[lookup]={ [unicode]=offset }
end
end
elseif trace_loading then
report_otf("problems with unicode %a of kern %a of glyph %U",name,k,unicode)
end
end
end
description.kerns=newkerns
end
end
end
actions["merge kern classes"]=function(data,filename,raw)
local gposlist=raw.gpos
if gposlist then
local descriptions=data.descriptions
local resources=data.resources
local unicodes=resources.unicodes
local splitter=data.helpers.tounicodetable
for gp=1,#gposlist do
local gpos=gposlist[gp]
local subtables=gpos.subtables
if subtables then
for s=1,#subtables do
local subtable=subtables[s]
local kernclass=subtable.kernclass
if kernclass then
local split={}
for k=1,#kernclass do
local kcl=kernclass[k]
local firsts=kcl.firsts
local seconds=kcl.seconds
local offsets=kcl.offsets
local lookups=kcl.lookup
if type(lookups)~="table" then
lookups={ lookups }
end
for n,s in next,firsts do
split[s]=split[s] or lpegmatch(splitter,s)
end
local maxseconds=0
for n,s in next,seconds do
if n>maxseconds then
maxseconds=n
end
split[s]=split[s] or lpegmatch(splitter,s)
end
for l=1,#lookups do
local lookup=lookups[l]
for fk=1,#firsts do
local fv=firsts[fk]
local splt=split[fv]
if splt then
local extrakerns={}
local baseoffset=(fk-1)*maxseconds
for sk=2,maxseconds do
local sv=seconds[sk]
local splt=split[sv]
if splt then
local offset=offsets[baseoffset+sk]
if offset then
for i=1,#splt do
extrakerns[splt[i]]=offset
end
end
end
end
for i=1,#splt do
local first_unicode=splt[i]
local description=descriptions[first_unicode]
if description then
local kerns=description.kerns
if not kerns then
kerns={}
description.kerns=kerns
end
local lookupkerns=kerns[lookup]
if not lookupkerns then
lookupkerns={}
kerns[lookup]=lookupkerns
end
for second_unicode,kern in next,extrakerns do
lookupkerns[second_unicode]=kern
end
elseif trace_loading then
report_otf("no glyph data for %U",first_unicode)
end
end
end
end
end
end
subtable.kernclass={}
end
end
end
end
end
end
actions["check glyphs"]=function(data,filename,raw)
for unicode,description in next,data.descriptions do
description.glyph=nil
end
end
actions["check metadata"]=function(data,filename,raw)
local metadata=data.metadata
for _,k in next,mainfields do
if valid_fields[k] then
local v=raw[k]
if not metadata[k] then
metadata[k]=v
end
end
end
local ttftables=metadata.ttf_tables
if ttftables then
for i=1,#ttftables do
ttftables[i].data="deleted"
end
end
end
actions["cleanup tables"]=function(data,filename,raw)
data.resources.indices=nil
data.helpers=nil
end
actions["reorganize glyph lookups"]=function(data,filename,raw)
local resources=data.resources
local unicodes=resources.unicodes
local descriptions=data.descriptions
local splitter=data.helpers.tounicodelist
local lookuptypes=resources.lookuptypes
for unicode,description in next,descriptions do
local lookups=description.glyph.lookups
if lookups then
for tag,lookuplist in next,lookups do
for l=1,#lookuplist do
local lookup=lookuplist[l]
local specification=lookup.specification
local lookuptype=lookup.type
local lt=lookuptypes[tag]
if not lt then
lookuptypes[tag]=lookuptype
elseif lt~=lookuptype then
report_otf("conflicting lookuptypes, %a points to %a and %a",tag,lt,lookuptype)
end
if lookuptype=="ligature" then
lookuplist[l]={ lpegmatch(splitter,specification.components) }
elseif lookuptype=="alternate" then
lookuplist[l]={ lpegmatch(splitter,specification.components) }
elseif lookuptype=="substitution" then
lookuplist[l]=unicodes[specification.variant]
elseif lookuptype=="multiple" then
lookuplist[l]={ lpegmatch(splitter,specification.components) }
elseif lookuptype=="position" then
lookuplist[l]={
specification.x or 0,
specification.y or 0,
specification.h or 0,
specification.v or 0
}
elseif lookuptype=="pair" then
local one=specification.offsets[1]
local two=specification.offsets[2]
local paired=unicodes[specification.paired]
if one then
if two then
lookuplist[l]={ paired,{ one.x or 0,one.y or 0,one.h or 0,one.v or 0 },{ two.x or 0,two.y or 0,two.h or 0,two.v or 0 } }
else
lookuplist[l]={ paired,{ one.x or 0,one.y or 0,one.h or 0,one.v or 0 } }
end
else
if two then
lookuplist[l]={ paired,{},{ two.x or 0,two.y or 0,two.h or 0,two.v or 0} }
else
lookuplist[l]={ paired }
end
end
end
end
end
local slookups,mlookups
for tag,lookuplist in next,lookups do
if #lookuplist==1 then
if slookups then
slookups[tag]=lookuplist[1]
else
slookups={ [tag]=lookuplist[1] }
end
else
if mlookups then
mlookups[tag]=lookuplist
else
mlookups={ [tag]=lookuplist }
end
end
end
if slookups then
description.slookups=slookups
end
if mlookups then
description.mlookups=mlookups
end
end
end
end
actions["reorganize glyph anchors"]=function(data,filename,raw)
local descriptions=data.descriptions
for unicode,description in next,descriptions do
local anchors=description.glyph.anchors
if anchors then
for class,data in next,anchors do
if class=="baselig" then
for tag,specification in next,data do
for i=1,#specification do
local si=specification[i]
specification[i]={ si.x or 0,si.y or 0 }
end
end
else
for tag,specification in next,data do
data[tag]={ specification.x or 0,specification.y or 0 }
end
end
end
description.anchors=anchors
end
end
end
function otf.setfeatures(tfmdata,features)
local okay=constructors.initializefeatures("otf",tfmdata,features,trace_features,report_otf)
if okay then
return constructors.collectprocessors("otf",tfmdata,features,trace_features,report_otf)
else
return {}
end
end
local function copytotfm(data,cache_id)
if data then
local metadata=data.metadata
local resources=data.resources
local properties=derivetable(data.properties)
local descriptions=derivetable(data.descriptions)
local goodies=derivetable(data.goodies)
local characters={}
local parameters={}
local mathparameters={}
local pfminfo=metadata.pfminfo or {}
local resources=data.resources
local unicodes=resources.unicodes
local spaceunits=500
local spacer="space"
local designsize=metadata.designsize or metadata.design_size or 100
local mathspecs=metadata.math
if designsize==0 then
designsize=100
end
if mathspecs then
for name,value in next,mathspecs do
mathparameters[name]=value
end
end
for unicode,_ in next,data.descriptions do
characters[unicode]={}
end
if mathspecs then
for unicode,character in next,characters do
local d=descriptions[unicode]
local m=d.math
if m then
local variants=m.horiz_variants
local parts=m.horiz_parts
if variants then
local c=character
for i=1,#variants do
local un=variants[i]
c.next=un
c=characters[un]
end
c.horiz_variants=parts
elseif parts then
character.horiz_variants=parts
end
local variants=m.vert_variants
local parts=m.vert_parts
if variants then
local c=character
for i=1,#variants do
local un=variants[i]
c.next=un
c=characters[un]
end
c.vert_variants=parts
elseif parts then
character.vert_variants=parts
end
local italic_correction=m.vert_italic_correction
if italic_correction then
character.vert_italic_correction=italic_correction
end
local top_accent=m.top_accent
if top_accent then
character.top_accent=top_accent
end
local kerns=m.kerns
if kerns then
character.mathkerns=kerns
end
end
end
end
local monospaced=metadata.isfixedpitch or (pfminfo.panose and pfminfo.panose.proportion=="Monospaced")
local charwidth=pfminfo.avgwidth
local italicangle=metadata.italicangle
local charxheight=pfminfo.os2_xheight and pfminfo.os2_xheight>0 and pfminfo.os2_xheight
properties.monospaced=monospaced
parameters.italicangle=italicangle
parameters.charwidth=charwidth
parameters.charxheight=charxheight
local space=0x0020
local emdash=0x2014
if monospaced then
if descriptions[space] then
spaceunits,spacer=descriptions[space].width,"space"
end
if not spaceunits and descriptions[emdash] then
spaceunits,spacer=descriptions[emdash].width,"emdash"
end
if not spaceunits and charwidth then
spaceunits,spacer=charwidth,"charwidth"
end
else
if descriptions[space] then
spaceunits,spacer=descriptions[space].width,"space"
end
if not spaceunits and descriptions[emdash] then
spaceunits,spacer=descriptions[emdash].width/2,"emdash/2"
end
if not spaceunits and charwidth then
spaceunits,spacer=charwidth,"charwidth"
end
end
spaceunits=tonumber(spaceunits) or 500
local filename=constructors.checkedfilename(resources)
local fontname=metadata.fontname
local fullname=metadata.fullname or fontname
local units=metadata.units_per_em or 1000
if units==0 then
units=1000
metadata.units_per_em=1000
end
parameters.slant=0
parameters.space=spaceunits
parameters.space_stretch=units/2
parameters.space_shrink=1*units/3
parameters.x_height=2*units/5
parameters.quad=units
if spaceunits<2*units/5 then
end
if italicangle then
parameters.italicangle=italicangle
parameters.italicfactor=math.cos(math.rad(90+italicangle))
parameters.slant=- math.round(math.tan(italicangle*math.pi/180))
end
if monospaced then
parameters.space_stretch=0
parameters.space_shrink=0
elseif syncspace then
parameters.space_stretch=spaceunits/2
parameters.space_shrink=spaceunits/3
end
parameters.extra_space=parameters.space_shrink
if charxheight then
parameters.x_height=charxheight
else
local x=0x78
if x then
local x=descriptions[x]
if x then
parameters.x_height=x.height
end
end
end
parameters.designsize=(designsize/10)*65536
parameters.ascender=abs(metadata.ascent or 0)
parameters.descender=abs(metadata.descent or 0)
parameters.units=units
properties.space=spacer
properties.encodingbytes=2
properties.format=data.format or fonts.formats[filename] or "opentype"
properties.noglyphnames=true
properties.filename=filename
properties.fontname=fontname
properties.fullname=fullname
properties.psname=fontname or fullname
properties.name=filename or fullname
return {
characters=characters,
descriptions=descriptions,
parameters=parameters,
mathparameters=mathparameters,
resources=resources,
properties=properties,
goodies=goodies,
}
end
end
local function otftotfm(specification)
local cache_id=specification.hash
local tfmdata=containers.read(constructors.cache,cache_id)
if not tfmdata then
local name=specification.name
local sub=specification.sub
local filename=specification.filename
local format=specification.format
local features=specification.features.normal
local rawdata=otf.load(filename,format,sub,features and features.featurefile)
if rawdata and next(rawdata) then
rawdata.lookuphash={}
tfmdata=copytotfm(rawdata,cache_id)
if tfmdata and next(tfmdata) then
local features=constructors.checkedfeatures("otf",features)
local shared=tfmdata.shared
if not shared then
shared={}
tfmdata.shared=shared
end
shared.rawdata=rawdata
shared.dynamics={}
tfmdata.changed={}
shared.features=features
shared.processes=otf.setfeatures(tfmdata,features)
end
end
containers.write(constructors.cache,cache_id,tfmdata)
end
return tfmdata
end
local function read_from_otf(specification)
local tfmdata=otftotfm(specification)
if tfmdata then
tfmdata.properties.name=specification.name
tfmdata.properties.sub=specification.sub
tfmdata=constructors.scale(tfmdata,specification)
local allfeatures=tfmdata.shared.features or specification.features.normal
constructors.applymanipulators("otf",tfmdata,allfeatures,trace_features,report_otf)
constructors.setname(tfmdata,specification)
fonts.loggers.register(tfmdata,file.suffix(specification.filename),specification)
end
return tfmdata
end
local function checkmathsize(tfmdata,mathsize)
local mathdata=tfmdata.shared.rawdata.metadata.math
local mathsize=tonumber(mathsize)
if mathdata then
local parameters=tfmdata.parameters
parameters.scriptpercentage=mathdata.ScriptPercentScaleDown
parameters.scriptscriptpercentage=mathdata.ScriptScriptPercentScaleDown
parameters.mathsize=mathsize
end
end
registerotffeature {
name="mathsize",
description="apply mathsize as specified in the font",
initializers={
base=checkmathsize,
node=checkmathsize,
}
}
function otf.collectlookups(rawdata,kind,script,language)
local sequences=rawdata.resources.sequences
if sequences then
local featuremap,featurelist={},{}
for s=1,#sequences do
local sequence=sequences[s]
local features=sequence.features
features=features and features[kind]
features=features and (features[script] or features[default] or features[wildcard])
features=features and (features[language] or features[default] or features[wildcard])
if features then
local subtables=sequence.subtables
if subtables then
for s=1,#subtables do
local ss=subtables[s]
if not featuremap[s] then
featuremap[ss]=true
featurelist[#featurelist+1]=ss
end
end
end
end
end
if #featurelist>0 then
return featuremap,featurelist
end
end
return nil,nil
end
local function check_otf(forced,specification,suffix,what)
local name=specification.name
if forced then
name=file.addsuffix(name,suffix,true)
end
local fullname=findbinfile(name,suffix) or ""
if fullname=="" then
fullname=fonts.names.getfilename(name,suffix) or ""
end
if fullname~="" then
specification.filename=fullname
specification.format=what
return read_from_otf(specification)
end
end
local function opentypereader(specification,suffix,what)
local forced=specification.forced or ""
if forced=="otf" then
return check_otf(true,specification,forced,"opentype")
elseif forced=="ttf" or forced=="ttc" or forced=="dfont" then
return check_otf(true,specification,forced,"truetype")
else
return check_otf(false,specification,suffix,what)
end
end
readers.opentype=opentypereader
local formats=fonts.formats
formats.otf="opentype"
formats.ttf="truetype"
formats.ttc="truetype"
formats.dfont="truetype"
function readers.otf (specification) return opentypereader(specification,"otf",formats.otf ) end
function readers.ttf (specification) return opentypereader(specification,"ttf",formats.ttf ) end
function readers.ttc (specification) return opentypereader(specification,"ttf",formats.ttc ) end
function readers.dfont(specification) return opentypereader(specification,"ttf",formats.dfont) end
function otf.scriptandlanguage(tfmdata,attr)
local properties=tfmdata.properties
return properties.script or "dflt",properties.language or "dflt"
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['font-otb']={
version=1.001,
comment="companion to font-ini.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local concat=table.concat
local format,gmatch,gsub,find,match,lower,strip=string.format,string.gmatch,string.gsub,string.find,string.match,string.lower,string.strip
local type,next,tonumber,tostring=type,next,tonumber,tostring
local lpegmatch=lpeg.match
local utfchar=utf.char
local trace_baseinit=false trackers.register("otf.baseinit",function(v) trace_baseinit=v end)
local trace_singles=false trackers.register("otf.singles",function(v) trace_singles=v end)
local trace_multiples=false trackers.register("otf.multiples",function(v) trace_multiples=v end)
local trace_alternatives=false trackers.register("otf.alternatives",function(v) trace_alternatives=v end)
local trace_ligatures=false trackers.register("otf.ligatures",function(v) trace_ligatures=v end)
local trace_ligatures_detail=false trackers.register("otf.ligatures.detail",function(v) trace_ligatures_detail=v end)
local trace_kerns=false trackers.register("otf.kerns",function(v) trace_kerns=v end)
local trace_preparing=false trackers.register("otf.preparing",function(v) trace_preparing=v end)
local report_prepare=logs.reporter("fonts","otf prepare")
local fonts=fonts
local otf=fonts.handlers.otf
local otffeatures=otf.features
local registerotffeature=otffeatures.register
otf.defaultbasealternate="none"
local wildcard="*"
local default="dflt"
local formatters=string.formatters
local f_unicode=formatters["%U"]
local f_uniname=formatters["%U (%s)"]
local f_unilist=formatters["% t (% t)"]
local function gref(descriptions,n)
if type(n)=="number" then
local name=descriptions[n].name
if name then
return f_uniname(n,name)
else
return f_unicode(n)
end
elseif n then
local num,nam={},{}
for i=2,#n do
local ni=n[i]
if tonumber(ni) then
local di=descriptions[ni]
num[i]=f_unicode(ni)
nam[i]=di and di.name or "-"
end
end
return f_unilist(num,nam)
else
return "<error in base mode tracing>"
end
end
local function cref(feature,lookupname)
if lookupname then
return formatters["feature %a, lookup %a"](feature,lookupname)
else
return formatters["feature %a"](feature)
end
end
local function report_alternate(feature,lookupname,descriptions,unicode,replacement,value,comment)
report_prepare("%s: base alternate %s => %s (%S => %S)",
cref(feature,lookupname),
gref(descriptions,unicode),
replacement and gref(descriptions,replacement),
value,
comment)
end
local function report_substitution(feature,lookupname,descriptions,unicode,substitution)
report_prepare("%s: base substitution %s => %S",
cref(feature,lookupname),
gref(descriptions,unicode),
gref(descriptions,substitution))
end
local function report_ligature(feature,lookupname,descriptions,unicode,ligature)
report_prepare("%s: base ligature %s => %S",
cref(feature,lookupname),
gref(descriptions,ligature),
gref(descriptions,unicode))
end
local function report_kern(feature,lookupname,descriptions,unicode,otherunicode,value)
report_prepare("%s: base kern %s + %s => %S",
cref(feature,lookupname),
gref(descriptions,unicode),
gref(descriptions,otherunicode),
value)
end
local basemethods={}
local basemethod="<unset>"
local function applybasemethod(what,...)
local m=basemethods[basemethod][what]
if m then
return m(...)
end
end
local basehash,basehashes,applied={},1,{}
local function registerbasehash(tfmdata)
local properties=tfmdata.properties
local hash=concat(applied," ")
local base=basehash[hash]
if not base then
basehashes=basehashes+1
base=basehashes
basehash[hash]=base
end
properties.basehash=base
properties.fullname=properties.fullname.."-"..base
applied={}
end
local function registerbasefeature(feature,value)
applied[#applied+1]=feature.."="..tostring(value)
end
local trace=false
local function finalize_ligatures(tfmdata,ligatures)
local nofligatures=#ligatures
if nofligatures>0 then
local characters=tfmdata.characters
local descriptions=tfmdata.descriptions
local resources=tfmdata.resources
local unicodes=resources.unicodes
local private=resources.private
local alldone=false
while not alldone do
local done=0
for i=1,nofligatures do
local ligature=ligatures[i]
if ligature then
local unicode,lookupdata=ligature[1],ligature[2]
if trace then
trace_ligatures_detail("building % a into %a",lookupdata,unicode)
end
local size=#lookupdata
local firstcode=lookupdata[1]
local firstdata=characters[firstcode]
local okay=false
if firstdata then
local firstname="ctx_"..firstcode
for i=1,size-1 do
local firstdata=characters[firstcode]
if not firstdata then
firstcode=private
if trace then
trace_ligatures_detail("defining %a as %a",firstname,firstcode)
end
unicodes[firstname]=firstcode
firstdata={ intermediate=true,ligatures={} }
characters[firstcode]=firstdata
descriptions[firstcode]={ name=firstname }
private=private+1
end
local target
local secondcode=lookupdata[i+1]
local secondname=firstname.."_"..secondcode
if i==size-1 then
target=unicode
if not unicodes[secondname] then
unicodes[secondname]=unicode
end
okay=true
else
target=unicodes[secondname]
if not target then
break
end
end
if trace then
trace_ligatures_detail("codes (%a,%a) + (%a,%a) -> %a",firstname,firstcode,secondname,secondcode,target)
end
local firstligs=firstdata.ligatures
if firstligs then
firstligs[secondcode]={ char=target }
else
firstdata.ligatures={ [secondcode]={ char=target } }
end
firstcode=target
firstname=secondname
end
end
if okay then
ligatures[i]=false
done=done+1
end
end
end
alldone=done==0
end
if trace then
for k,v in next,characters do
if v.ligatures then table.print(v,k) end
end
end
tfmdata.resources.private=private
end
end
local function preparesubstitutions(tfmdata,feature,value,validlookups,lookuplist)
local characters=tfmdata.characters
local descriptions=tfmdata.descriptions
local resources=tfmdata.resources
local changed=tfmdata.changed
local unicodes=resources.unicodes
local lookuphash=resources.lookuphash
local lookuptypes=resources.lookuptypes
local ligatures={}
local alternate=tonumber(value)
local defaultalt=otf.defaultbasealternate
local trace_singles=trace_baseinit and trace_singles
local trace_alternatives=trace_baseinit and trace_alternatives
local trace_ligatures=trace_baseinit and trace_ligatures
local actions={
substitution=function(lookupdata,lookupname,description,unicode)
if trace_singles then
report_substitution(feature,lookupname,descriptions,unicode,lookupdata)
end
changed[unicode]=lookupdata
end,
alternate=function(lookupdata,lookupname,description,unicode)
local replacement=lookupdata[alternate]
if replacement then
changed[unicode]=replacement
if trace_alternatives then
report_alternate(feature,lookupname,descriptions,unicode,replacement,value,"normal")
end
elseif defaultalt=="first" then
replacement=lookupdata[1]
changed[unicode]=replacement
if trace_alternatives then
report_alternate(feature,lookupname,descriptions,unicode,replacement,value,defaultalt)
end
elseif defaultalt=="last" then
replacement=lookupdata[#data]
if trace_alternatives then
report_alternate(feature,lookupname,descriptions,unicode,replacement,value,defaultalt)
end
else
if trace_alternatives then
report_alternate(feature,lookupname,descriptions,unicode,replacement,value,"unknown")
end
end
end,
ligature=function(lookupdata,lookupname,description,unicode)
if trace_ligatures then
report_ligature(feature,lookupname,descriptions,unicode,lookupdata)
end
ligatures[#ligatures+1]={ unicode,lookupdata }
end,
}
for unicode,character in next,characters do
local description=descriptions[unicode]
local lookups=description.slookups
if lookups then
for l=1,#lookuplist do
local lookupname=lookuplist[l]
local lookupdata=lookups[lookupname]
if lookupdata then
local lookuptype=lookuptypes[lookupname]
local action=actions[lookuptype]
if action then
action(lookupdata,lookupname,description,unicode)
end
end
end
end
local lookups=description.mlookups
if lookups then
for l=1,#lookuplist do
local lookupname=lookuplist[l]
local lookuplist=lookups[lookupname]
if lookuplist then
local lookuptype=lookuptypes[lookupname]
local action=actions[lookuptype]
if action then
for i=1,#lookuplist do
action(lookuplist[i],lookupname,description,unicode)
end
end
end
end
end
end
finalize_ligatures(tfmdata,ligatures)
end
local function preparepositionings(tfmdata,feature,value,validlookups,lookuplist)
local characters=tfmdata.characters
local descriptions=tfmdata.descriptions
local resources=tfmdata.resources
local unicodes=resources.unicodes
local sharedkerns={}
local traceindeed=trace_baseinit and trace_kerns
for unicode,character in next,characters do
local description=descriptions[unicode]
local rawkerns=description.kerns
if rawkerns then
local s=sharedkerns[rawkerns]
if s==false then
elseif s then
character.kerns=s
else
local newkerns=character.kerns
local done=false
for l=1,#lookuplist do
local lookup=lookuplist[l]
local kerns=rawkerns[lookup]
if kerns then
for otherunicode,value in next,kerns do
if value==0 then
elseif not newkerns then
newkerns={ [otherunicode]=value }
done=true
if traceindeed then
report_kern(feature,lookup,descriptions,unicode,otherunicode,value)
end
elseif not newkerns[otherunicode] then
newkerns[otherunicode]=value
done=true
if traceindeed then
report_kern(feature,lookup,descriptions,unicode,otherunicode,value)
end
end
end
end
end
if done then
sharedkerns[rawkerns]=newkerns
character.kerns=newkerns
else
sharedkerns[rawkerns]=false
end
end
end
end
end
basemethods.independent={
preparesubstitutions=preparesubstitutions,
preparepositionings=preparepositionings,
}
local function makefake(tfmdata,name,present)
local resources=tfmdata.resources
local private=resources.private
local character={ intermediate=true,ligatures={} }
resources.unicodes[name]=private
tfmdata.characters[private]=character
tfmdata.descriptions[private]={ name=name }
resources.private=private+1
present[name]=private
return character
end
local function make_1(present,tree,name)
for k,v in next,tree do
if k=="ligature" then
present[name]=v
else
make_1(present,v,name.."_"..k)
end
end
end
local function make_2(present,tfmdata,characters,tree,name,preceding,unicode,done,lookupname)
for k,v in next,tree do
if k=="ligature" then
local character=characters[preceding]
if not character then
if trace_baseinit then
report_prepare("weird ligature in lookup %a, current %C, preceding %C",lookupname,v,preceding)
end
character=makefake(tfmdata,name,present)
end
local ligatures=character.ligatures
if ligatures then
ligatures[unicode]={ char=v }
else
character.ligatures={ [unicode]={ char=v } }
end
if done then
local d=done[lookupname]
if not d then
done[lookupname]={ "dummy",v }
else
d[#d+1]=v
end
end
else
local code=present[name] or unicode
local name=name.."_"..k
make_2(present,tfmdata,characters,v,name,code,k,done,lookupname)
end
end
end
local function preparesubstitutions(tfmdata,feature,value,validlookups,lookuplist)
local characters=tfmdata.characters
local descriptions=tfmdata.descriptions
local resources=tfmdata.resources
local changed=tfmdata.changed
local lookuphash=resources.lookuphash
local lookuptypes=resources.lookuptypes
local ligatures={}
local alternate=tonumber(value)
local defaultalt=otf.defaultbasealternate
local trace_singles=trace_baseinit and trace_singles
local trace_alternatives=trace_baseinit and trace_alternatives
local trace_ligatures=trace_baseinit and trace_ligatures
for l=1,#lookuplist do
local lookupname=lookuplist[l]
local lookupdata=lookuphash[lookupname]
local lookuptype=lookuptypes[lookupname]
for unicode,data in next,lookupdata do
if lookuptype=="substitution" then
if trace_singles then
report_substitution(feature,lookupname,descriptions,unicode,data)
end
changed[unicode]=data
elseif lookuptype=="alternate" then
local replacement=data[alternate]
if replacement then
changed[unicode]=replacement
if trace_alternatives then
report_alternate(feature,lookupname,descriptions,unicode,replacement,value,"normal")
end
elseif defaultalt=="first" then
replacement=data[1]
changed[unicode]=replacement
if trace_alternatives then
report_alternate(feature,lookupname,descriptions,unicode,replacement,value,defaultalt)
end
elseif defaultalt=="last" then
replacement=data[#data]
if trace_alternatives then
report_alternate(feature,lookupname,descriptions,unicode,replacement,value,defaultalt)
end
else
if trace_alternatives then
report_alternate(feature,lookupname,descriptions,unicode,replacement,value,"unknown")
end
end
elseif lookuptype=="ligature" then
ligatures[#ligatures+1]={ unicode,data,lookupname }
if trace_ligatures then
report_ligature(feature,lookupname,descriptions,unicode,data)
end
end
end
end
local nofligatures=#ligatures
if nofligatures>0 then
local characters=tfmdata.characters
local present={}
local done=trace_baseinit and trace_ligatures and {}
for i=1,nofligatures do
local ligature=ligatures[i]
local unicode,tree=ligature[1],ligature[2]
make_1(present,tree,"ctx_"..unicode)
end
for i=1,nofligatures do
local ligature=ligatures[i]
local unicode,tree,lookupname=ligature[1],ligature[2],ligature[3]
make_2(present,tfmdata,characters,tree,"ctx_"..unicode,unicode,unicode,done,lookupname)
end
end
end
local function preparepositionings(tfmdata,feature,value,validlookups,lookuplist)
local characters=tfmdata.characters
local descriptions=tfmdata.descriptions
local resources=tfmdata.resources
local lookuphash=resources.lookuphash
local traceindeed=trace_baseinit and trace_kerns
for l=1,#lookuplist do
local lookupname=lookuplist[l]
local lookupdata=lookuphash[lookupname]
for unicode,data in next,lookupdata do
local character=characters[unicode]
local kerns=character.kerns
if not kerns then
kerns={}
character.kerns=kerns
end
if traceindeed then
for otherunicode,kern in next,data do
if not kerns[otherunicode] and kern~=0 then
kerns[otherunicode]=kern
report_kern(feature,lookup,descriptions,unicode,otherunicode,kern)
end
end
else
for otherunicode,kern in next,data do
if not kerns[otherunicode] and kern~=0 then
kerns[otherunicode]=kern
end
end
end
end
end
end
local function initializehashes(tfmdata)
nodeinitializers.features(tfmdata)
end
basemethods.shared={
initializehashes=initializehashes,
preparesubstitutions=preparesubstitutions,
preparepositionings=preparepositionings,
}
basemethod="independent"
local function featuresinitializer(tfmdata,value)
if true then
local t=trace_preparing and os.clock()
local features=tfmdata.shared.features
if features then
applybasemethod("initializehashes",tfmdata)
local collectlookups=otf.collectlookups
local rawdata=tfmdata.shared.rawdata
local properties=tfmdata.properties
local script=properties.script
local language=properties.language
local basesubstitutions=rawdata.resources.features.gsub
local basepositionings=rawdata.resources.features.gpos
if basesubstitutions then
for feature,data in next,basesubstitutions do
local value=features[feature]
if value then
local validlookups,lookuplist=collectlookups(rawdata,feature,script,language)
if validlookups then
applybasemethod("preparesubstitutions",tfmdata,feature,value,validlookups,lookuplist)
registerbasefeature(feature,value)
end
end
end
end
if basepositions then
for feature,data in next,basepositions do
local value=features[feature]
if value then
local validlookups,lookuplist=collectlookups(rawdata,feature,script,language)
if validlookups then
applybasemethod("preparepositionings",tfmdata,feature,features[feature],validlookups,lookuplist)
registerbasefeature(feature,value)
end
end
end
end
registerbasehash(tfmdata)
end
if trace_preparing then
report_prepare("preparation time is %0.3f seconds for %a",os.clock()-t,tfmdata.properties.fullname)
end
end
end
registerotffeature {
name="features",
description="features",
default=true,
initializers={
base=featuresinitializer,
}
}
directives.register("fonts.otf.loader.basemethod",function(v)
if basemethods[v] then
basemethod=v
end
end)
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['node-inj']={
version=1.001,
comment="companion to node-ini.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files",
}
local next=next
local utfchar=utf.char
local trace_injections=false trackers.register("nodes.injections",function(v) trace_injections=v end)
local report_injections=logs.reporter("nodes","injections")
local attributes,nodes,node=attributes,nodes,node
fonts=fonts
local fontdata=fonts.hashes.identifiers
nodes.injections=nodes.injections or {}
local injections=nodes.injections
local nodecodes=nodes.nodecodes
local glyph_code=nodecodes.glyph
local nodepool=nodes.pool
local newkern=nodepool.kern
local traverse_id=node.traverse_id
local insert_node_before=node.insert_before
local insert_node_after=node.insert_after
local a_kernpair=attributes.private('kernpair')
local a_ligacomp=attributes.private('ligacomp')
local a_markbase=attributes.private('markbase')
local a_markmark=attributes.private('markmark')
local a_markdone=attributes.private('markdone')
local a_cursbase=attributes.private('cursbase')
local a_curscurs=attributes.private('curscurs')
local a_cursdone=attributes.private('cursdone')
function injections.installnewkern(nk)
newkern=nk or newkern
end
local cursives={}
local marks={}
local kerns={}
function injections.setcursive(start,nxt,factor,rlmode,exit,entry,tfmstart,tfmnext)
local dx,dy=factor*(exit[1]-entry[1]),factor*(exit[2]-entry[2])
local ws,wn=tfmstart.width,tfmnext.width
local bound=#cursives+1
start[a_cursbase]=bound
nxt[a_curscurs]=bound
cursives[bound]={ rlmode,dx,dy,ws,wn }
return dx,dy,bound
end
function injections.setpair(current,factor,rlmode,r2lflag,spec,tfmchr)
local x,y,w,h=factor*spec[1],factor*spec[2],factor*spec[3],factor*spec[4]
if x~=0 or w~=0 or y~=0 or h~=0 then
local bound=current[a_kernpair]
if bound then
local kb=kerns[bound]
kb[2],kb[3],kb[4],kb[5]=(kb[2] or 0)+x,(kb[3] or 0)+y,(kb[4] or 0)+w,(kb[5] or 0)+h
else
bound=#kerns+1
current[a_kernpair]=bound
kerns[bound]={ rlmode,x,y,w,h,r2lflag,tfmchr.width }
end
return x,y,w,h,bound
end
return x,y,w,h
end
function injections.setkern(current,factor,rlmode,x,tfmchr)
local dx=factor*x
if dx~=0 then
local bound=#kerns+1
current[a_kernpair]=bound
kerns[bound]={ rlmode,dx }
return dx,bound
else
return 0,0
end
end
function injections.setmark(start,base,factor,rlmode,ba,ma,index)
local dx,dy=factor*(ba[1]-ma[1]),factor*(ba[2]-ma[2])
local bound=base[a_markbase]
local index=1
if bound then
local mb=marks[bound]
if mb then
index=#mb+1
mb[index]={ dx,dy,rlmode }
start[a_markmark]=bound
start[a_markdone]=index
return dx,dy,bound
else
report_injections("possible problem, %U is base mark without data (id %a)",base.char,bound)
end
end
index=index or 1
bound=#marks+1
base[a_markbase]=bound
start[a_markmark]=bound
start[a_markdone]=index
marks[bound]={ [index]={ dx,dy,rlmode } }
return dx,dy,bound
end
local function dir(n)
return (n and n<0 and "r-to-l") or (n and n>0 and "l-to-r") or "unset"
end
local function trace(head)
report_injections("begin run")
for n in traverse_id(glyph_code,head) do
if n.subtype<256 then
local kp=n[a_kernpair]
local mb=n[a_markbase]
local mm=n[a_markmark]
local md=n[a_markdone]
local cb=n[a_cursbase]
local cc=n[a_curscurs]
local char=n.char
report_injections("font %s, char %U, glyph %c",char,n.font,char)
if kp then
local k=kerns[kp]
if k[3] then
report_injections(" pairkern: dir %a, x %p, y %p, w %p, h %p",dir(k[1]),k[2],k[3],k[4],k[5])
else
report_injections(" kern: dir %a, dx %p",dir(k[1]),k[2])
end
end
if mb then
report_injections(" markbase: bound %a",mb)
end
if mm then
local m=marks[mm]
if mb then
local m=m[mb]
if m then
report_injections(" markmark: bound %a, index %a, dx %p, dy %p",mm,md,m[1],m[2])
else
report_injections(" markmark: bound %a, missing index",mm)
end
else
m=m[1]
report_injections(" markmark: bound %a, dx %p, dy %p",mm,m and m[1],m and m[2])
end
end
if cb then
report_injections(" cursbase: bound %a",cb)
end
if cc then
local c=cursives[cc]
report_injections(" curscurs: bound %a, dir %a, dx %p, dy %p",cc,dir(c[1]),c[2],c[3])
end
end
end
report_injections("end run")
end
function injections.handler(head,where,keep)
local has_marks,has_cursives,has_kerns=next(marks),next(cursives),next(kerns)
if has_marks or has_cursives then
if trace_injections then
trace(head)
end
local done,ky,rl,valid,cx,wx,mk,nofvalid=false,{},{},{},{},{},{},0
if has_kerns then
local nf,tm=nil,nil
for n in traverse_id(glyph_code,head) do
if n.subtype<256 then
nofvalid=nofvalid+1
valid[nofvalid]=n
if n.font~=nf then
nf=n.font
tm=fontdata[nf].resources.marks
end
if tm then
mk[n]=tm[n.char]
end
local k=n[a_kernpair]
if k then
local kk=kerns[k]
if kk then
local x,y,w,h=kk[2] or 0,kk[3] or 0,kk[4] or 0,kk[5] or 0
local dy=y-h
if dy~=0 then
ky[n]=dy
end
if w~=0 or x~=0 then
wx[n]=kk
end
rl[n]=kk[1]
end
end
end
end
else
local nf,tm=nil,nil
for n in traverse_id(glyph_code,head) do
if n.subtype<256 then
nofvalid=nofvalid+1
valid[nofvalid]=n
if n.font~=nf then
nf=n.font
tm=fontdata[nf].resources.marks
end
if tm then
mk[n]=tm[n.char]
end
end
end
end
if nofvalid>0 then
local cx={}
if has_kerns and next(ky) then
for n,k in next,ky do
n.yoffset=k
end
end
if has_cursives then
local p_cursbase,p=nil,nil
local t,d,maxt={},{},0
for i=1,nofvalid do
local n=valid[i]
if not mk[n] then
local n_cursbase=n[a_cursbase]
if p_cursbase then
local n_curscurs=n[a_curscurs]
if p_cursbase==n_curscurs then
local c=cursives[n_curscurs]
if c then
local rlmode,dx,dy,ws,wn=c[1],c[2],c[3],c[4],c[5]
if rlmode>=0 then
dx=dx-ws
else
dx=dx+wn
end
if dx~=0 then
cx[n]=dx
rl[n]=rlmode
end
dy=-dy
maxt=maxt+1
t[maxt]=p
d[maxt]=dy
else
maxt=0
end
end
elseif maxt>0 then
local ny=n.yoffset
for i=maxt,1,-1 do
ny=ny+d[i]
local ti=t[i]
ti.yoffset=ti.yoffset+ny
end
maxt=0
end
if not n_cursbase and maxt>0 then
local ny=n.yoffset
for i=maxt,1,-1 do
ny=ny+d[i]
local ti=t[i]
ti.yoffset=ny
end
maxt=0
end
p_cursbase,p=n_cursbase,n
end
end
if maxt>0 then
local ny=n.yoffset
for i=maxt,1,-1 do
ny=ny+d[i]
local ti=t[i]
ti.yoffset=ny
end
maxt=0
end
if not keep then
cursives={}
end
end
if has_marks then
for i=1,nofvalid do
local p=valid[i]
local p_markbase=p[a_markbase]
if p_markbase then
local mrks=marks[p_markbase]
local nofmarks=#mrks
for n in traverse_id(glyph_code,p.next) do
local n_markmark=n[a_markmark]
if p_markbase==n_markmark then
local index=n[a_markdone] or 1
local d=mrks[index]
if d then
local rlmode=d[3]
if rlmode and rlmode>=0 then
local k=wx[p]
if k then
n.xoffset=p.xoffset-p.width+d[1]-k[2]
else
n.xoffset=p.xoffset-p.width+d[1]
end
else
local k=wx[p]
if k then
n.xoffset=p.xoffset-d[1]-k[2]
else
n.xoffset=p.xoffset-d[1]
end
end
if mk[p] then
n.yoffset=p.yoffset+d[2]
else
n.yoffset=n.yoffset+p.yoffset+d[2]
end
if nofmarks==1 then
break
else
nofmarks=nofmarks-1
end
end
else
end
end
end
end
if not keep then
marks={}
end
end
if next(wx) then
for n,k in next,wx do
local x,w=k[2] or 0,k[4]
if w then
local rl=k[1]
local wx=w-x
if rl<0 then
if wx~=0 then
insert_node_before(head,n,newkern(wx))
end
if x~=0 then
insert_node_after (head,n,newkern(x))
end
else
if x~=0 then
insert_node_before(head,n,newkern(x))
end
if wx~=0 then
insert_node_after(head,n,newkern(wx))
end
end
elseif x~=0 then
insert_node_before(head,n,newkern(x))
end
end
end
if next(cx) then
for n,k in next,cx do
if k~=0 then
local rln=rl[n]
if rln and rln<0 then
insert_node_before(head,n,newkern(-k))
else
insert_node_before(head,n,newkern(k))
end
end
end
end
if not keep then
kerns={}
end
return head,true
elseif not keep then
kerns,cursives,marks={},{},{}
end
elseif has_kerns then
if trace_injections then
trace(head)
end
for n in traverse_id(glyph_code,head) do
if n.subtype<256 then
local k=n[a_kernpair]
if k then
local kk=kerns[k]
if kk then
local rl,x,y,w=kk[1],kk[2] or 0,kk[3],kk[4]
if y and y~=0 then
n.yoffset=y
end
if w then
local wx=w-x
if rl<0 then
if wx~=0 then
insert_node_before(head,n,newkern(wx))
end
if x~=0 then
insert_node_after (head,n,newkern(x))
end
else
if x~=0 then
insert_node_before(head,n,newkern(x))
end
if wx~=0 then
insert_node_after(head,n,newkern(wx))
end
end
else
if x~=0 then
insert_node_before(head,n,newkern(x))
end
end
end
end
end
end
if not keep then
kerns={}
end
return head,true
else
end
return head,false
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['font-ota']={
version=1.001,
comment="companion to font-otf.lua (analysing)",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local type=type
if not trackers then trackers={ register=function() end } end
local fonts,nodes,node=fonts,nodes,node
local allocate=utilities.storage.allocate
local otf=fonts.handlers.otf
local analyzers=fonts.analyzers
local initializers=allocate()
local methods=allocate()
analyzers.initializers=initializers
analyzers.methods=methods
analyzers.useunicodemarks=false
local a_state=attributes.private('state')
local nodecodes=nodes.nodecodes
local glyph_code=nodecodes.glyph
local math_code=nodecodes.math
local traverse_id=node.traverse_id
local traverse_node_list=node.traverse
local end_of_math=node.end_of_math
local fontdata=fonts.hashes.identifiers
local categories=characters and characters.categories or {}
local otffeatures=fonts.constructors.newfeatures("otf")
local registerotffeature=otffeatures.register
local s_init=1 local s_rphf=7
local s_medi=2 local s_half=8
local s_fina=3 local s_pref=9
local s_isol=4 local s_blwf=10
local s_mark=5 local s_pstf=11
local s_rest=6
local states={
init=s_init,
medi=s_medi,
fina=s_fina,
isol=s_isol,
mark=s_mark,
rest=s_rest,
rphf=s_rphf,
half=s_half,
pref=s_pref,
blwf=s_blwf,
pstf=s_pstf,
}
local features={
init=s_init,
medi=s_medi,
fina=s_fina,
isol=s_isol,
}
analyzers.states=states
analyzers.features=features
function analyzers.setstate(head,font)
local useunicodemarks=analyzers.useunicodemarks
local tfmdata=fontdata[font]
local descriptions=tfmdata.descriptions
local first,last,current,n,done=nil,nil,head,0,false
while current do
local id=current.id
if id==glyph_code and current.font==font then
done=true
local char=current.char
local d=descriptions[char]
if d then
if d.class=="mark" or (useunicodemarks and categories[char]=="mn") then
done=true
current[a_state]=s_mark
elseif n==0 then
first,last,n=current,current,1
current[a_state]=s_init
else
last,n=current,n+1
current[a_state]=s_medi
end
else
if first and first==last then
last[a_state]=s_isol
elseif last then
last[a_state]=s_fina
end
first,last,n=nil,nil,0
end
elseif id==disc_code then
current[a_state]=s_midi
last=current
else
if first and first==last then
last[a_state]=s_isol
elseif last then
last[a_state]=s_fina
end
first,last,n=nil,nil,0
if id==math_code then
current=end_of_math(current)
end
end
current=current.next
end
if first and first==last then
last[a_state]=s_isol
elseif last then
last[a_state]=s_fina
end
return head,done
end
local function analyzeinitializer(tfmdata,value)
local script,language=otf.scriptandlanguage(tfmdata)
local action=initializers[script]
if not action then
elseif type(action)=="function" then
return action(tfmdata,value)
else
local action=action[language]
if action then
return action(tfmdata,value)
end
end
end
local function analyzeprocessor(head,font,attr)
local tfmdata=fontdata[font]
local script,language=otf.scriptandlanguage(tfmdata,attr)
local action=methods[script]
if not action then
elseif type(action)=="function" then
return action(head,font,attr)
else
action=action[language]
if action then
return action(head,font,attr)
end
end
return head,false
end
registerotffeature {
name="analyze",
description="analysis of (for instance) character classes",
default=true,
initializers={
node=analyzeinitializer,
},
processors={
position=1,
node=analyzeprocessor,
}
}
methods.latn=analyzers.setstate
local tatweel=0x0640
local zwnj=0x200C
local zwj=0x200D
local isolated={
[0x0600]=true,[0x0601]=true,[0x0602]=true,[0x0603]=true,
[0x0604]=true,
[0x0608]=true,[0x060B]=true,[0x0621]=true,[0x0674]=true,
[0x06DD]=true,
[0x0856]=true,[0x0858]=true,[0x0857]=true,
[0x07FA]=true,
[zwnj]=true,
}
local final={
[0x0622]=true,[0x0623]=true,[0x0624]=true,[0x0625]=true,
[0x0627]=true,[0x0629]=true,[0x062F]=true,[0x0630]=true,
[0x0631]=true,[0x0632]=true,[0x0648]=true,[0x0671]=true,
[0x0672]=true,[0x0673]=true,[0x0675]=true,[0x0676]=true,
[0x0677]=true,[0x0688]=true,[0x0689]=true,[0x068A]=true,
[0x068B]=true,[0x068C]=true,[0x068D]=true,[0x068E]=true,
[0x068F]=true,[0x0690]=true,[0x0691]=true,[0x0692]=true,
[0x0693]=true,[0x0694]=true,[0x0695]=true,[0x0696]=true,
[0x0697]=true,[0x0698]=true,[0x0699]=true,[0x06C0]=true,
[0x06C3]=true,[0x06C4]=true,[0x06C5]=true,[0x06C6]=true,
[0x06C7]=true,[0x06C8]=true,[0x06C9]=true,[0x06CA]=true,
[0x06CB]=true,[0x06CD]=true,[0x06CF]=true,[0x06D2]=true,
[0x06D3]=true,[0x06D5]=true,[0x06EE]=true,[0x06EF]=true,
[0x0759]=true,[0x075A]=true,[0x075B]=true,[0x076B]=true,
[0x076C]=true,[0x0771]=true,[0x0773]=true,[0x0774]=true,
[0x0778]=true,[0x0779]=true,
[0x08AA]=true,[0x08AB]=true,[0x08AC]=true,
[0xFEF5]=true,[0xFEF7]=true,[0xFEF9]=true,[0xFEFB]=true,
[0x0710]=true,[0x0715]=true,[0x0716]=true,[0x0717]=true,
[0x0718]=true,[0x0719]=true,[0x0728]=true,[0x072A]=true,
[0x072C]=true,[0x071E]=true,
[0x072F]=true,[0x074D]=true,
[0x0840]=true,[0x0849]=true,[0x0854]=true,[0x0846]=true,
[0x084F]=true
}
local medial={
[0x0626]=true,[0x0628]=true,[0x062A]=true,[0x062B]=true,
[0x062C]=true,[0x062D]=true,[0x062E]=true,[0x0633]=true,
[0x0634]=true,[0x0635]=true,[0x0636]=true,[0x0637]=true,
[0x0638]=true,[0x0639]=true,[0x063A]=true,[0x063B]=true,
[0x063C]=true,[0x063D]=true,[0x063E]=true,[0x063F]=true,
[0x0641]=true,[0x0642]=true,[0x0643]=true,
[0x0644]=true,[0x0645]=true,[0x0646]=true,[0x0647]=true,
[0x0649]=true,[0x064A]=true,[0x066E]=true,[0x066F]=true,
[0x0678]=true,[0x0679]=true,[0x067A]=true,[0x067B]=true,
[0x067C]=true,[0x067D]=true,[0x067E]=true,[0x067F]=true,
[0x0680]=true,[0x0681]=true,[0x0682]=true,[0x0683]=true,
[0x0684]=true,[0x0685]=true,[0x0686]=true,[0x0687]=true,
[0x069A]=true,[0x069B]=true,[0x069C]=true,[0x069D]=true,
[0x069E]=true,[0x069F]=true,[0x06A0]=true,[0x06A1]=true,
[0x06A2]=true,[0x06A3]=true,[0x06A4]=true,[0x06A5]=true,
[0x06A6]=true,[0x06A7]=true,[0x06A8]=true,[0x06A9]=true,
[0x06AA]=true,[0x06AB]=true,[0x06AC]=true,[0x06AD]=true,
[0x06AE]=true,[0x06AF]=true,[0x06B0]=true,[0x06B1]=true,
[0x06B2]=true,[0x06B3]=true,[0x06B4]=true,[0x06B5]=true,
[0x06B6]=true,[0x06B7]=true,[0x06B8]=true,[0x06B9]=true,
[0x06BA]=true,[0x06BB]=true,[0x06BC]=true,[0x06BD]=true,
[0x06BE]=true,[0x06BF]=true,[0x06C1]=true,[0x06C2]=true,
[0x06CC]=true,[0x06CE]=true,[0x06D0]=true,[0x06D1]=true,
[0x06FA]=true,[0x06FB]=true,[0x06FC]=true,[0x06FF]=true,
[0x0750]=true,[0x0751]=true,[0x0752]=true,[0x0753]=true,
[0x0754]=true,[0x0755]=true,[0x0756]=true,[0x0757]=true,
[0x0758]=true,[0x075C]=true,[0x075D]=true,[0x075E]=true,
[0x075F]=true,[0x0760]=true,[0x0761]=true,[0x0762]=true,
[0x0763]=true,[0x0764]=true,[0x0765]=true,[0x0766]=true,
[0x0767]=true,[0x0768]=true,[0x0769]=true,[0x076A]=true,
[0x076D]=true,[0x076E]=true,[0x076F]=true,[0x0770]=true,
[0x0772]=true,[0x0775]=true,[0x0776]=true,[0x0777]=true,
[0x077A]=true,[0x077B]=true,[0x077C]=true,[0x077D]=true,
[0x077E]=true,[0x077F]=true,
[0x08A0]=true,[0x08A2]=true,[0x08A4]=true,[0x08A5]=true,
[0x08A6]=true,[0x0620]=true,[0x08A8]=true,[0x08A9]=true,
[0x08A7]=true,[0x08A3]=true,
[0x0712]=true,[0x0713]=true,[0x0714]=true,[0x071A]=true,
[0x071B]=true,[0x071C]=true,[0x071D]=true,[0x071F]=true,
[0x0720]=true,[0x0721]=true,[0x0722]=true,[0x0723]=true,
[0x0724]=true,[0x0725]=true,[0x0726]=true,[0x0727]=true,
[0x0729]=true,[0x072B]=true,[0x072D]=true,[0x072E]=true,
[0x074E]=true,[0x074F]=true,
[0x0841]=true,[0x0842]=true,[0x0843]=true,[0x0844]=true,
[0x0845]=true,[0x0847]=true,[0x0848]=true,[0x0855]=true,
[0x0851]=true,[0x084E]=true,[0x084D]=true,[0x084A]=true,
[0x084B]=true,[0x084C]=true,[0x0850]=true,[0x0852]=true,
[0x0853]=true,
[0x07D7]=true,[0x07E8]=true,[0x07D9]=true,[0x07EA]=true,
[0x07CA]=true,[0x07DB]=true,[0x07CC]=true,[0x07DD]=true,
[0x07CE]=true,[0x07DF]=true,[0x07D4]=true,[0x07E5]=true,
[0x07E9]=true,[0x07E7]=true,[0x07E3]=true,[0x07E2]=true,
[0x07E0]=true,[0x07E1]=true,[0x07DE]=true,[0x07DC]=true,
[0x07D1]=true,[0x07DA]=true,[0x07D8]=true,[0x07D6]=true,
[0x07D2]=true,[0x07D0]=true,[0x07CF]=true,[0x07CD]=true,
[0x07CB]=true,[0x07D3]=true,[0x07E4]=true,[0x07D5]=true,
[0x07E6]=true,
[tatweel]=true,
[zwj]=true,
}
local arab_warned={}
local function warning(current,what)
local char=current.char
if not arab_warned[char] then
log.report("analyze","arab: character %C has no %a class",char,what)
arab_warned[char]=true
end
end
local function finish(first,last)
if last then
if first==last then
local fc=first.char
if medial[fc] or final[fc] then
first[a_state]=s_isol
else
warning(first,"isol")
first[a_state]=s_error
end
else
local lc=last.char
if medial[lc] or final[lc] then
last[a_state]=s_fina
else
warning(last,"fina")
last[a_state]=s_error
end
end
first,last=nil,nil
elseif first then
local fc=first.char
if medial[fc] or final[fc] then
first[a_state]=s_isol
else
warning(first,"isol")
first[a_state]=s_error
end
first=nil
end
return first,last
end
function methods.arab(head,font,attr)
local useunicodemarks=analyzers.useunicodemarks
local tfmdata=fontdata[font]
local marks=tfmdata.resources.marks
local first,last,current,done=nil,nil,head,false
while current do
local id=current.id
if id==glyph_code and current.font==font and current.subtype<256 and not current[a_state] then
done=true
local char=current.char
if marks[char] or (useunicodemarks and categories[char]=="mn") then
current[a_state]=s_mark
elseif isolated[char] then
first,last=finish(first,last)
current[a_state]=s_isol
first,last=nil,nil
elseif not first then
if medial[char] then
current[a_state]=s_init
first,last=first or current,current
elseif final[char] then
current[a_state]=s_isol
first,last=nil,nil
else
first,last=finish(first,last)
end
elseif medial[char] then
first,last=first or current,current
current[a_state]=s_medi
elseif final[char] then
if not last[a_state]==s_init then
last[a_state]=s_medi
end
current[a_state]=s_fina
first,last=nil,nil
elseif char>=0x0600 and char<=0x06FF then
current[a_state]=s_rest
first,last=finish(first,last)
else
first,last=finish(first,last)
end
else
if first or last then
first,last=finish(first,last)
end
if id==math_code then
current=end_of_math(current)
end
end
current=current.next
end
if first or last then
finish(first,last)
end
return head,done
end
methods.syrc=methods.arab
methods.mand=methods.arab
methods.nko=methods.arab
directives.register("otf.analyze.useunicodemarks",function(v)
analyzers.useunicodemarks=v
end)
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['font-otn']={
version=1.001,
comment="companion to font-ini.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files",
}
local concat,insert,remove=table.concat,table.insert,table.remove
local gmatch,gsub,find,match,lower,strip=string.gmatch,string.gsub,string.find,string.match,string.lower,string.strip
local type,next,tonumber,tostring=type,next,tonumber,tostring
local lpegmatch=lpeg.match
local random=math.random
local formatters=string.formatters
local logs,trackers,nodes,attributes=logs,trackers,nodes,attributes
local registertracker=trackers.register
local fonts=fonts
local otf=fonts.handlers.otf
local trace_lookups=false registertracker("otf.lookups",function(v) trace_lookups=v end)
local trace_singles=false registertracker("otf.singles",function(v) trace_singles=v end)
local trace_multiples=false registertracker("otf.multiples",function(v) trace_multiples=v end)
local trace_alternatives=false registertracker("otf.alternatives",function(v) trace_alternatives=v end)
local trace_ligatures=false registertracker("otf.ligatures",function(v) trace_ligatures=v end)
local trace_contexts=false registertracker("otf.contexts",function(v) trace_contexts=v end)
local trace_marks=false registertracker("otf.marks",function(v) trace_marks=v end)
local trace_kerns=false registertracker("otf.kerns",function(v) trace_kerns=v end)
local trace_cursive=false registertracker("otf.cursive",function(v) trace_cursive=v end)
local trace_preparing=false registertracker("otf.preparing",function(v) trace_preparing=v end)
local trace_bugs=false registertracker("otf.bugs",function(v) trace_bugs=v end)
local trace_details=false registertracker("otf.details",function(v) trace_details=v end)
local trace_applied=false registertracker("otf.applied",function(v) trace_applied=v end)
local trace_steps=false registertracker("otf.steps",function(v) trace_steps=v end)
local trace_skips=false registertracker("otf.skips",function(v) trace_skips=v end)
local trace_directions=false registertracker("otf.directions",function(v) trace_directions=v end)
local report_direct=logs.reporter("fonts","otf direct")
local report_subchain=logs.reporter("fonts","otf subchain")
local report_chain=logs.reporter("fonts","otf chain")
local report_process=logs.reporter("fonts","otf process")
local report_prepare=logs.reporter("fonts","otf prepare")
local report_warning=logs.reporter("fonts","otf warning")
registertracker("otf.verbose_chain",function(v) otf.setcontextchain(v and "verbose") end)
registertracker("otf.normal_chain",function(v) otf.setcontextchain(v and "normal") end)
registertracker("otf.replacements","otf.singles,otf.multiples,otf.alternatives,otf.ligatures")
registertracker("otf.positions","otf.marks,otf.kerns,otf.cursive")
registertracker("otf.actions","otf.replacements,otf.positions")
registertracker("otf.injections","nodes.injections")
registertracker("*otf.sample","otf.steps,otf.actions,otf.analyzing")
local insert_node_after=node.insert_after
local delete_node=nodes.delete
local copy_node=node.copy
local find_node_tail=node.tail or node.slide
local flush_node_list=node.flush_list
local end_of_math=node.end_of_math
local setmetatableindex=table.setmetatableindex
local zwnj=0x200C
local zwj=0x200D
local wildcard="*"
local default="dflt"
local nodecodes=nodes.nodecodes
local whatcodes=nodes.whatcodes
local glyphcodes=nodes.glyphcodes
local glyph_code=nodecodes.glyph
local glue_code=nodecodes.glue
local disc_code=nodecodes.disc
local whatsit_code=nodecodes.whatsit
local math_code=nodecodes.math
local dir_code=whatcodes.dir
local localpar_code=whatcodes.localpar
local ligature_code=glyphcodes.ligature
local privateattribute=attributes.private
local a_state=privateattribute('state')
local a_markbase=privateattribute('markbase')
local a_markmark=privateattribute('markmark')
local a_markdone=privateattribute('markdone')
local a_cursbase=privateattribute('cursbase')
local a_curscurs=privateattribute('curscurs')
local a_cursdone=privateattribute('cursdone')
local a_kernpair=privateattribute('kernpair')
local a_ligacomp=privateattribute('ligacomp')
local injections=nodes.injections
local setmark=injections.setmark
local setcursive=injections.setcursive
local setkern=injections.setkern
local setpair=injections.setpair
local markonce=true
local cursonce=true
local kernonce=true
local fonthashes=fonts.hashes
local fontdata=fonthashes.identifiers
local otffeatures=fonts.constructors.newfeatures("otf")
local registerotffeature=otffeatures.register
local onetimemessage=fonts.loggers.onetimemessage
otf.defaultnodealternate="none"
local tfmdata=false
local characters=false
local descriptions=false
local resources=false
local marks=false
local currentfont=false
local lookuptable=false
local anchorlookups=false
local lookuptypes=false
local handlers={}
local rlmode=0
local featurevalue=false
local checkstep=(nodes and nodes.tracers and nodes.tracers.steppers.check) or function() end
local registerstep=(nodes and nodes.tracers and nodes.tracers.steppers.register) or function() end
local registermessage=(nodes and nodes.tracers and nodes.tracers.steppers.message) or function() end
local function logprocess(...)
if trace_steps then
registermessage(...)
end
report_direct(...)
end
local function logwarning(...)
report_direct(...)
end
local f_unicode=formatters["%U"]
local f_uniname=formatters["%U (%s)"]
local f_unilist=formatters["% t (% t)"]
local function gref(n)
if type(n)=="number" then
local description=descriptions[n]
local name=description and description.name
if name then
return f_uniname(n,name)
else
return f_unicode(n)
end
elseif n then
local num,nam={},{}
for i=1,#n do
local ni=n[i]
if tonumber(ni) then
local di=descriptions[ni]
num[i]=f_unicode(ni)
nam[i]=di and di.name or "-"
end
end
return f_unilist(num,nam)
else
return "<error in node mode tracing>"
end
end
local function cref(kind,chainname,chainlookupname,lookupname,index)
if index then
return formatters["feature %a, chain %a, sub %a, lookup %a, index %a"](kind,chainname,chainlookupname,lookupname,index)
elseif lookupname then
return formatters["feature %a, chain %a, sub %a, lookup %a"](kind,chainname,chainlookupname,lookupname)
elseif chainlookupname then
return formatters["feature %a, chain %a, sub %a"](kind,chainname,chainlookupname)
elseif chainname then
return formatters["feature %a, chain %a"](kind,chainname)
else
return formatters["feature %a"](kind)
end
end
local function pref(kind,lookupname)
return formatters["feature %a, lookup %a"](kind,lookupname)
end
local function copy_glyph(g)
local components=g.components
if components then
g.components=nil
local n=copy_node(g)
g.components=components
return n
else
return copy_node(g)
end
end
local function markstoligature(kind,lookupname,head,start,stop,char)
if start==stop and start.char==char then
return head,start
else
local prev=start.prev
local next=stop.next
start.prev=nil
stop.next=nil
local base=copy_glyph(start)
if head==start then
head=base
end
base.char=char
base.subtype=ligature_code
base.components=start
if prev then
prev.next=base
end
if next then
next.prev=base
end
base.next=next
base.prev=prev
return head,base
end
end
local function getcomponentindex(start)
if start.id~=glyph_code then
return 0
elseif start.subtype==ligature_code then
local i=0
local components=start.components
while components do
i=i+getcomponentindex(components)
components=components.next
end
return i
elseif not marks[start.char] then
return 1
else
return 0
end
end
local function toligature(kind,lookupname,head,start,stop,char,markflag,discfound)
if start==stop and start.char==char then
start.char=char
return head,start
end
local prev=start.prev
local next=stop.next
start.prev=nil
stop.next=nil
local base=copy_glyph(start)
if start==head then
head=base
end
base.char=char
base.subtype=ligature_code
base.components=start
if prev then
prev.next=base
end
if next then
next.prev=base
end
base.next=next
base.prev=prev
if not discfound then
local deletemarks=markflag~="mark"
local components=start
local baseindex=0
local componentindex=0
local head=base
local current=base
while start do
local char=start.char
if not marks[char] then
baseindex=baseindex+componentindex
componentindex=getcomponentindex(start)
elseif not deletemarks then
start[a_ligacomp]=baseindex+(start[a_ligacomp] or componentindex)
if trace_marks then
logwarning("%s: keep mark %s, gets index %s",pref(kind,lookupname),gref(char),start[a_ligacomp])
end
head,current=insert_node_after(head,current,copy_node(start))
end
start=start.next
end
local start=components
while start and start.id==glyph_code do
local char=start.char
if marks[char] then
start[a_ligacomp]=baseindex+(start[a_ligacomp] or componentindex)
if trace_marks then
logwarning("%s: keep mark %s, gets index %s",pref(kind,lookupname),gref(char),start[a_ligacomp])
end
else
break
end
start=start.next
end
end
return head,base
end
function handlers.gsub_single(head,start,kind,lookupname,replacement)
if trace_singles then
logprocess("%s: replacing %s by single %s",pref(kind,lookupname),gref(start.char),gref(replacement))
end
start.char=replacement
return head,start,true
end
local function get_alternative_glyph(start,alternatives,value,trace_alternatives)
local n=#alternatives
if value=="random" then
local r=random(1,n)
return alternatives[r],trace_alternatives and formatters["value %a, taking %a"](value,r)
elseif value=="first" then
return alternatives[1],trace_alternatives and formatters["value %a, taking %a"](value,1)
elseif value=="last" then
return alternatives[n],trace_alternatives and formatters["value %a, taking %a"](value,n)
else
value=tonumber(value)
if type(value)~="number" then
return alternatives[1],trace_alternatives and formatters["invalid value %s, taking %a"](value,1)
elseif value>n then
local defaultalt=otf.defaultnodealternate
if defaultalt=="first" then
return alternatives[n],trace_alternatives and formatters["invalid value %s, taking %a"](value,1)
elseif defaultalt=="last" then
return alternatives[1],trace_alternatives and formatters["invalid value %s, taking %a"](value,n)
else
return false,trace_alternatives and formatters["invalid value %a, %s"](value,"out of range")
end
elseif value==0 then
return start.char,trace_alternatives and formatters["invalid value %a, %s"](value,"no change")
elseif value<1 then
return alternatives[1],trace_alternatives and formatters["invalid value %a, taking %a"](value,1)
else
return alternatives[value],trace_alternatives and formatters["value %a, taking %a"](value,value)
end
end
end
local function multiple_glyphs(head,start,multiple)
local nofmultiples=#multiple
if nofmultiples>0 then
start.char=multiple[1]
if nofmultiples>1 then
local sn=start.next
for k=2,nofmultiples do
local n=copy_node(start)
n.char=multiple[k]
n.next=sn
n.prev=start
if sn then
sn.prev=n
end
start.next=n
start=n
end
end
return head,start,true
else
if trace_multiples then
logprocess("no multiple for %s",gref(start.char))
end
return head,start,false
end
end
function handlers.gsub_alternate(head,start,kind,lookupname,alternative,sequence)
local value=featurevalue==true and tfmdata.shared.features[kind] or featurevalue
local choice,comment=get_alternative_glyph(start,alternative,value,trace_alternatives)
if choice then
if trace_alternatives then
logprocess("%s: replacing %s by alternative %a to %s, %s",pref(kind,lookupname),gref(start.char),choice,gref(choice),comment)
end
start.char=choice
else
if trace_alternatives then
logwarning("%s: no variant %a for %s, %s",pref(kind,lookupname),value,gref(start.char),comment)
end
end
return head,start,true
end
function handlers.gsub_multiple(head,start,kind,lookupname,multiple)
if trace_multiples then
logprocess("%s: replacing %s by multiple %s",pref(kind,lookupname),gref(start.char),gref(multiple))
end
return multiple_glyphs(head,start,multiple)
end
function handlers.gsub_ligature(head,start,kind,lookupname,ligature,sequence)
local s,stop,discfound=start.next,nil,false
local startchar=start.char
if marks[startchar] then
while s do
local id=s.id
if id==glyph_code and s.font==currentfont and s.subtype<256 then
local lg=ligature[s.char]
if lg then
stop=s
ligature=lg
s=s.next
else
break
end
else
break
end
end
if stop then
local lig=ligature.ligature
if lig then
if trace_ligatures then
local stopchar=stop.char
head,start=markstoligature(kind,lookupname,head,start,stop,lig)
logprocess("%s: replacing %s upto %s by ligature %s case 1",pref(kind,lookupname),gref(startchar),gref(stopchar),gref(start.char))
else
head,start=markstoligature(kind,lookupname,head,start,stop,lig)
end
return head,start,true
else
end
end
else
local skipmark=sequence.flags[1]
while s do
local id=s.id
if id==glyph_code and s.subtype<256 then
if s.font==currentfont then
local char=s.char
if skipmark and marks[char] then
s=s.next
else
local lg=ligature[char]
if lg then
stop=s
ligature=lg
s=s.next
else
break
end
end
else
break
end
elseif id==disc_code then
discfound=true
s=s.next
else
break
end
end
if stop then
local lig=ligature.ligature
if lig then
if trace_ligatures then
local stopchar=stop.char
head,start=toligature(kind,lookupname,head,start,stop,lig,skipmark,discfound)
logprocess("%s: replacing %s upto %s by ligature %s case 2",pref(kind,lookupname),gref(startchar),gref(stopchar),gref(start.char))
else
head,start=toligature(kind,lookupname,head,start,stop,lig,skipmark,discfound)
end
return head,start,true
else
end
end
end
return head,start,false
end
function handlers.gpos_mark2base(head,start,kind,lookupname,markanchors,sequence)
local markchar=start.char
if marks[markchar] then
local base=start.prev
if base and base.id==glyph_code and base.font==currentfont and base.subtype<256 then
local basechar=base.char
if marks[basechar] then
while true do
base=base.prev
if base and base.id==glyph_code and base.font==currentfont and base.subtype<256 then
basechar=base.char
if not marks[basechar] then
break
end
else
if trace_bugs then
logwarning("%s: no base for mark %s",pref(kind,lookupname),gref(markchar))
end
return head,start,false
end
end
end
local baseanchors=descriptions[basechar]
if baseanchors then
baseanchors=baseanchors.anchors
end
if baseanchors then
local baseanchors=baseanchors['basechar']
if baseanchors then
local al=anchorlookups[lookupname]
for anchor,ba in next,baseanchors do
if al[anchor] then
local ma=markanchors[anchor]
if ma then
local dx,dy,bound=setmark(start,base,tfmdata.parameters.factor,rlmode,ba,ma)
if trace_marks then
logprocess("%s, anchor %s, bound %s: anchoring mark %s to basechar %s => (%p,%p)",
pref(kind,lookupname),anchor,bound,gref(markchar),gref(basechar),dx,dy)
end
return head,start,true
end
end
end
if trace_bugs then
logwarning("%s, no matching anchors for mark %s and base %s",pref(kind,lookupname),gref(markchar),gref(basechar))
end
end
else
onetimemessage(currentfont,basechar,"no base anchors",report_fonts)
end
elseif trace_bugs then
logwarning("%s: prev node is no char",pref(kind,lookupname))
end
elseif trace_bugs then
logwarning("%s: mark %s is no mark",pref(kind,lookupname),gref(markchar))
end
return head,start,false
end
function handlers.gpos_mark2ligature(head,start,kind,lookupname,markanchors,sequence)
local markchar=start.char
if marks[markchar] then
local base=start.prev
if base and base.id==glyph_code and base.font==currentfont and base.subtype<256 then
local basechar=base.char
if marks[basechar] then
while true do
base=base.prev
if base and base.id==glyph_code and base.font==currentfont and base.subtype<256 then
basechar=base.char
if not marks[basechar] then
break
end
else
if trace_bugs then
logwarning("%s: no base for mark %s",pref(kind,lookupname),gref(markchar))
end
return head,start,false
end
end
end
local index=start[a_ligacomp]
local baseanchors=descriptions[basechar]
if baseanchors then
baseanchors=baseanchors.anchors
if baseanchors then
local baseanchors=baseanchors['baselig']
if baseanchors then
local al=anchorlookups[lookupname]
for anchor,ba in next,baseanchors do
if al[anchor] then
local ma=markanchors[anchor]
if ma then
ba=ba[index]
if ba then
local dx,dy,bound=setmark(start,base,tfmdata.parameters.factor,rlmode,ba,ma)
if trace_marks then
logprocess("%s, anchor %s, index %s, bound %s: anchoring mark %s to baselig %s at index %s => (%p,%p)",
pref(kind,lookupname),anchor,index,bound,gref(markchar),gref(basechar),index,dx,dy)
end
return head,start,true
end
end
end
end
if trace_bugs then
logwarning("%s: no matching anchors for mark %s and baselig %s",pref(kind,lookupname),gref(markchar),gref(basechar))
end
end
end
else
onetimemessage(currentfont,basechar,"no base anchors",report_fonts)
end
elseif trace_bugs then
logwarning("%s: prev node is no char",pref(kind,lookupname))
end
elseif trace_bugs then
logwarning("%s: mark %s is no mark",pref(kind,lookupname),gref(markchar))
end
return head,start,false
end
function handlers.gpos_mark2mark(head,start,kind,lookupname,markanchors,sequence)
local markchar=start.char
if marks[markchar] then
local base=start.prev
local slc=start[a_ligacomp]
if slc then
while base do
local blc=base[a_ligacomp]
if blc and blc~=slc then
base=base.prev
else
break
end
end
end
if base and base.id==glyph_code and base.font==currentfont and base.subtype<256 then
local basechar=base.char
local baseanchors=descriptions[basechar]
if baseanchors then
baseanchors=baseanchors.anchors
if baseanchors then
baseanchors=baseanchors['basemark']
if baseanchors then
local al=anchorlookups[lookupname]
for anchor,ba in next,baseanchors do
if al[anchor] then
local ma=markanchors[anchor]
if ma then
local dx,dy,bound=setmark(start,base,tfmdata.parameters.factor,rlmode,ba,ma)
if trace_marks then
logprocess("%s, anchor %s, bound %s: anchoring mark %s to basemark %s => (%p,%p)",
pref(kind,lookupname),anchor,bound,gref(markchar),gref(basechar),dx,dy)
end
return head,start,true
end
end
end
if trace_bugs then
logwarning("%s: no matching anchors for mark %s and basemark %s",pref(kind,lookupname),gref(markchar),gref(basechar))
end
end
end
else
onetimemessage(currentfont,basechar,"no base anchors",report_fonts)
end
elseif trace_bugs then
logwarning("%s: prev node is no mark",pref(kind,lookupname))
end
elseif trace_bugs then
logwarning("%s: mark %s is no mark",pref(kind,lookupname),gref(markchar))
end
return head,start,false
end
function handlers.gpos_cursive(head,start,kind,lookupname,exitanchors,sequence)
local alreadydone=cursonce and start[a_cursbase]
if not alreadydone then
local done=false
local startchar=start.char
if marks[startchar] then
if trace_cursive then
logprocess("%s: ignoring cursive for mark %s",pref(kind,lookupname),gref(startchar))
end
else
local nxt=start.next
while not done and nxt and nxt.id==glyph_code and nxt.font==currentfont and nxt.subtype<256 do
local nextchar=nxt.char
if marks[nextchar] then
nxt=nxt.next
else
local entryanchors=descriptions[nextchar]
if entryanchors then
entryanchors=entryanchors.anchors
if entryanchors then
entryanchors=entryanchors['centry']
if entryanchors then
local al=anchorlookups[lookupname]
for anchor,entry in next,entryanchors do
if al[anchor] then
local exit=exitanchors[anchor]
if exit then
local dx,dy,bound=setcursive(start,nxt,tfmdata.parameters.factor,rlmode,exit,entry,characters[startchar],characters[nextchar])
if trace_cursive then
logprocess("%s: moving %s to %s cursive (%p,%p) using anchor %s and bound %s in rlmode %s",pref(kind,lookupname),gref(startchar),gref(nextchar),dx,dy,anchor,bound,rlmode)
end
done=true
break
end
end
end
end
end
else
onetimemessage(currentfont,startchar,"no entry anchors",report_fonts)
end
break
end
end
end
return head,start,done
else
if trace_cursive and trace_details then
logprocess("%s, cursive %s is already done",pref(kind,lookupname),gref(start.char),alreadydone)
end
return head,start,false
end
end
function handlers.gpos_single(head,start,kind,lookupname,kerns,sequence)
local startchar=start.char
local dx,dy,w,h=setpair(start,tfmdata.parameters.factor,rlmode,sequence.flags[4],kerns,characters[startchar])
if trace_kerns then
logprocess("%s: shifting single %s by (%p,%p) and correction (%p,%p)",pref(kind,lookupname),gref(startchar),dx,dy,w,h)
end
return head,start,false
end
function handlers.gpos_pair(head,start,kind,lookupname,kerns,sequence)
local snext=start.next
if not snext then
return head,start,false
else
local prev,done=start,false
local factor=tfmdata.parameters.factor
local lookuptype=lookuptypes[lookupname]
while snext and snext.id==glyph_code and snext.font==currentfont and snext.subtype<256 do
local nextchar=snext.char
local krn=kerns[nextchar]
if not krn and marks[nextchar] then
prev=snext
snext=snext.next
else
local krn=kerns[nextchar]
if not krn then
elseif type(krn)=="table" then
if lookuptype=="pair" then
local a,b=krn[2],krn[3]
if a and #a>0 then
local startchar=start.char
local x,y,w,h=setpair(start,factor,rlmode,sequence.flags[4],a,characters[startchar])
if trace_kerns then
logprocess("%s: shifting first of pair %s and %s by (%p,%p) and correction (%p,%p)",pref(kind,lookupname),gref(startchar),gref(nextchar),x,y,w,h)
end
end
if b and #b>0 then
local startchar=start.char
local x,y,w,h=setpair(snext,factor,rlmode,sequence.flags[4],b,characters[nextchar])
if trace_kerns then
logprocess("%s: shifting second of pair %s and %s by (%p,%p) and correction (%p,%p)",pref(kind,lookupname),gref(startchar),gref(nextchar),x,y,w,h)
end
end
else
report_process("%s: check this out (old kern stuff)",pref(kind,lookupname))
end
done=true
elseif krn~=0 then
local k=setkern(snext,factor,rlmode,krn)
if trace_kerns then
logprocess("%s: inserting kern %s between %s and %s",pref(kind,lookupname),k,gref(prev.char),gref(nextchar))
end
done=true
end
break
end
end
return head,start,done
end
end
local chainmores={}
local chainprocs={}
local function logprocess(...)
if trace_steps then
registermessage(...)
end
report_subchain(...)
end
local logwarning=report_subchain
local function logprocess(...)
if trace_steps then
registermessage(...)
end
report_chain(...)
end
local logwarning=report_chain
function chainprocs.chainsub(head,start,stop,kind,chainname,currentcontext,lookuphash,lookuplist,chainlookupname)
logwarning("%s: a direct call to chainsub cannot happen",cref(kind,chainname,chainlookupname))
return head,start,false
end
function chainmores.chainsub(head,start,stop,kind,chainname,currentcontext,lookuphash,lookuplist,chainlookupname,n)
logprocess("%s: a direct call to chainsub cannot happen",cref(kind,chainname,chainlookupname))
return head,start,false
end
function chainprocs.reversesub(head,start,stop,kind,chainname,currentcontext,lookuphash,replacements)
local char=start.char
local replacement=replacements[char]
if replacement then
if trace_singles then
logprocess("%s: single reverse replacement of %s by %s",cref(kind,chainname),gref(char),gref(replacement))
end
start.char=replacement
return head,start,true
else
return head,start,false
end
end
local function delete_till_stop(start,stop,ignoremarks)
local n=1
if start==stop then
elseif ignoremarks then
repeat
local next=start.next
if not marks[next.char] then
local components=next.components
if components then
flush_node_list(components)
end
delete_node(start,next)
end
n=n+1
until next==stop
else
repeat
local next=start.next
local components=next.components
if components then
flush_node_list(components)
end
delete_node(start,next)
n=n+1
until next==stop
end
return n
end
function chainprocs.gsub_single(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname,chainindex)
local current=start
local subtables=currentlookup.subtables
if #subtables>1 then
logwarning("todo: check if we need to loop over the replacements: %s",concat(subtables," "))
end
while current do
if current.id==glyph_code then
local currentchar=current.char
local lookupname=subtables[1]
local replacement=lookuphash[lookupname]
if not replacement then
if trace_bugs then
logwarning("%s: no single hits",cref(kind,chainname,chainlookupname,lookupname,chainindex))
end
else
replacement=replacement[currentchar]
if not replacement or replacement=="" then
if trace_bugs then
logwarning("%s: no single for %s",cref(kind,chainname,chainlookupname,lookupname,chainindex),gref(currentchar))
end
else
if trace_singles then
logprocess("%s: replacing single %s by %s",cref(kind,chainname,chainlookupname,lookupname,chainindex),gref(currentchar),gref(replacement))
end
current.char=replacement
end
end
return head,start,true
elseif current==stop then
break
else
current=current.next
end
end
return head,start,false
end
chainmores.gsub_single=chainprocs.gsub_single
function chainprocs.gsub_multiple(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname)
delete_till_stop(start,stop)
local startchar=start.char
local subtables=currentlookup.subtables
local lookupname=subtables[1]
local replacements=lookuphash[lookupname]
if not replacements then
if trace_bugs then
logwarning("%s: no multiple hits",cref(kind,chainname,chainlookupname,lookupname))
end
else
replacements=replacements[startchar]
if not replacements or replacement=="" then
if trace_bugs then
logwarning("%s: no multiple for %s",cref(kind,chainname,chainlookupname,lookupname),gref(startchar))
end
else
if trace_multiples then
logprocess("%s: replacing %s by multiple characters %s",cref(kind,chainname,chainlookupname,lookupname),gref(startchar),gref(replacements))
end
return multiple_glyphs(head,start,replacements)
end
end
return head,start,false
end
chainmores.gsub_multiple=chainprocs.gsub_multiple
function chainprocs.gsub_alternate(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname)
local current=start
local subtables=currentlookup.subtables
local value=featurevalue==true and tfmdata.shared.features[kind] or featurevalue
while current do
if current.id==glyph_code then
local currentchar=current.char
local lookupname=subtables[1]
local alternatives=lookuphash[lookupname]
if not alternatives then
if trace_bugs then
logwarning("%s: no alternative hit",cref(kind,chainname,chainlookupname,lookupname))
end
else
alternatives=alternatives[currentchar]
if alternatives then
local choice,comment=get_alternative_glyph(current,alternatives,value,trace_alternatives)
if choice then
if trace_alternatives then
logprocess("%s: replacing %s by alternative %a to %s, %s",cref(kind,chainname,chainlookupname,lookupname),gref(char),choice,gref(choice),comment)
end
start.char=choice
else
if trace_alternatives then
logwarning("%s: no variant %a for %s, %s",cref(kind,chainname,chainlookupname,lookupname),value,gref(char),comment)
end
end
elseif trace_bugs then
logwarning("%s: no alternative for %s, %s",cref(kind,chainname,chainlookupname,lookupname),gref(currentchar),comment)
end
end
return head,start,true
elseif current==stop then
break
else
current=current.next
end
end
return head,start,false
end
chainmores.gsub_alternate=chainprocs.gsub_alternate
function chainprocs.gsub_ligature(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname,chainindex)
local startchar=start.char
local subtables=currentlookup.subtables
local lookupname=subtables[1]
local ligatures=lookuphash[lookupname]
if not ligatures then
if trace_bugs then
logwarning("%s: no ligature hits",cref(kind,chainname,chainlookupname,lookupname,chainindex))
end
else
ligatures=ligatures[startchar]
if not ligatures then
if trace_bugs then
logwarning("%s: no ligatures starting with %s",cref(kind,chainname,chainlookupname,lookupname,chainindex),gref(startchar))
end
else
local s=start.next
local discfound=false
local last=stop
local nofreplacements=0
local skipmark=currentlookup.flags[1]
while s do
local id=s.id
if id==disc_code then
s=s.next
discfound=true
else
local schar=s.char
if skipmark and marks[schar] then
s=s.next
else
local lg=ligatures[schar]
if lg then
ligatures,last,nofreplacements=lg,s,nofreplacements+1
if s==stop then
break
else
s=s.next
end
else
break
end
end
end
end
local l2=ligatures.ligature
if l2 then
if chainindex then
stop=last
end
if trace_ligatures then
if start==stop then
logprocess("%s: replacing character %s by ligature %s case 3",cref(kind,chainname,chainlookupname,lookupname,chainindex),gref(startchar),gref(l2))
else
logprocess("%s: replacing character %s upto %s by ligature %s case 4",cref(kind,chainname,chainlookupname,lookupname,chainindex),gref(startchar),gref(stop.char),gref(l2))
end
end
head,start=toligature(kind,lookupname,head,start,stop,l2,currentlookup.flags[1],discfound)
return head,start,true,nofreplacements
elseif trace_bugs then
if start==stop then
logwarning("%s: replacing character %s by ligature fails",cref(kind,chainname,chainlookupname,lookupname,chainindex),gref(startchar))
else
logwarning("%s: replacing character %s upto %s by ligature fails",cref(kind,chainname,chainlookupname,lookupname,chainindex),gref(startchar),gref(stop.char))
end
end
end
end
return head,start,false,0
end
chainmores.gsub_ligature=chainprocs.gsub_ligature
function chainprocs.gpos_mark2base(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname)
local markchar=start.char
if marks[markchar] then
local subtables=currentlookup.subtables
local lookupname=subtables[1]
local markanchors=lookuphash[lookupname]
if markanchors then
markanchors=markanchors[markchar]
end
if markanchors then
local base=start.prev
if base and base.id==glyph_code and base.font==currentfont and base.subtype<256 then
local basechar=base.char
if marks[basechar] then
while true do
base=base.prev
if base and base.id==glyph_code and base.font==currentfont and base.subtype<256 then
basechar=base.char
if not marks[basechar] then
break
end
else
if trace_bugs then
logwarning("%s: no base for mark %s",pref(kind,lookupname),gref(markchar))
end
return head,start,false
end
end
end
local baseanchors=descriptions[basechar].anchors
if baseanchors then
local baseanchors=baseanchors['basechar']
if baseanchors then
local al=anchorlookups[lookupname]
for anchor,ba in next,baseanchors do
if al[anchor] then
local ma=markanchors[anchor]
if ma then
local dx,dy,bound=setmark(start,base,tfmdata.parameters.factor,rlmode,ba,ma)
if trace_marks then
logprocess("%s, anchor %s, bound %s: anchoring mark %s to basechar %s => (%p,%p)",
cref(kind,chainname,chainlookupname,lookupname),anchor,bound,gref(markchar),gref(basechar),dx,dy)
end
return head,start,true
end
end
end
if trace_bugs then
logwarning("%s, no matching anchors for mark %s and base %s",cref(kind,chainname,chainlookupname,lookupname),gref(markchar),gref(basechar))
end
end
end
elseif trace_bugs then
logwarning("%s: prev node is no char",cref(kind,chainname,chainlookupname,lookupname))
end
elseif trace_bugs then
logwarning("%s: mark %s has no anchors",cref(kind,chainname,chainlookupname,lookupname),gref(markchar))
end
elseif trace_bugs then
logwarning("%s: mark %s is no mark",cref(kind,chainname,chainlookupname),gref(markchar))
end
return head,start,false
end
function chainprocs.gpos_mark2ligature(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname)
local markchar=start.char
if marks[markchar] then
local subtables=currentlookup.subtables
local lookupname=subtables[1]
local markanchors=lookuphash[lookupname]
if markanchors then
markanchors=markanchors[markchar]
end
if markanchors then
local base=start.prev
if base and base.id==glyph_code and base.font==currentfont and base.subtype<256 then
local basechar=base.char
if marks[basechar] then
while true do
base=base.prev
if base and base.id==glyph_code and base.font==currentfont and base.subtype<256 then
basechar=base.char
if not marks[basechar] then
break
end
else
if trace_bugs then
logwarning("%s: no base for mark %s",cref(kind,chainname,chainlookupname,lookupname),markchar)
end
return head,start,false
end
end
end
local index=start[a_ligacomp]
local baseanchors=descriptions[basechar].anchors
if baseanchors then
local baseanchors=baseanchors['baselig']
if baseanchors then
local al=anchorlookups[lookupname]
for anchor,ba in next,baseanchors do
if al[anchor] then
local ma=markanchors[anchor]
if ma then
ba=ba[index]
if ba then
local dx,dy,bound=setmark(start,base,tfmdata.parameters.factor,rlmode,ba,ma)
if trace_marks then
logprocess("%s, anchor %s, bound %s: anchoring mark %s to baselig %s at index %s => (%p,%p)",
cref(kind,chainname,chainlookupname,lookupname),anchor,a or bound,gref(markchar),gref(basechar),index,dx,dy)
end
return head,start,true
end
end
end
end
if trace_bugs then
logwarning("%s: no matching anchors for mark %s and baselig %s",cref(kind,chainname,chainlookupname,lookupname),gref(markchar),gref(basechar))
end
end
end
elseif trace_bugs then
logwarning("feature %s, lookup %s: prev node is no char",kind,lookupname)
end
elseif trace_bugs then
logwarning("%s: mark %s has no anchors",cref(kind,chainname,chainlookupname,lookupname),gref(markchar))
end
elseif trace_bugs then
logwarning("%s: mark %s is no mark",cref(kind,chainname,chainlookupname),gref(markchar))
end
return head,start,false
end
function chainprocs.gpos_mark2mark(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname)
local markchar=start.char
if marks[markchar] then
local subtables=currentlookup.subtables
local lookupname=subtables[1]
local markanchors=lookuphash[lookupname]
if markanchors then
markanchors=markanchors[markchar]
end
if markanchors then
local base=start.prev
local slc=start[a_ligacomp]
if slc then
while base do
local blc=base[a_ligacomp]
if blc and blc~=slc then
base=base.prev
else
break
end
end
end
if base and base.id==glyph_code and base.font==currentfont and base.subtype<256 then
local basechar=base.char
local baseanchors=descriptions[basechar].anchors
if baseanchors then
baseanchors=baseanchors['basemark']
if baseanchors then
local al=anchorlookups[lookupname]
for anchor,ba in next,baseanchors do
if al[anchor] then
local ma=markanchors[anchor]
if ma then
local dx,dy,bound=setmark(start,base,tfmdata.parameters.factor,rlmode,ba,ma)
if trace_marks then
logprocess("%s, anchor %s, bound %s: anchoring mark %s to basemark %s => (%p,%p)",
cref(kind,chainname,chainlookupname,lookupname),anchor,bound,gref(markchar),gref(basechar),dx,dy)
end
return head,start,true
end
end
end
if trace_bugs then
logwarning("%s: no matching anchors for mark %s and basemark %s",gref(kind,chainname,chainlookupname,lookupname),gref(markchar),gref(basechar))
end
end
end
elseif trace_bugs then
logwarning("%s: prev node is no mark",cref(kind,chainname,chainlookupname,lookupname))
end
elseif trace_bugs then
logwarning("%s: mark %s has no anchors",cref(kind,chainname,chainlookupname,lookupname),gref(markchar))
end
elseif trace_bugs then
logwarning("%s: mark %s is no mark",cref(kind,chainname,chainlookupname),gref(markchar))
end
return head,start,false
end
function chainprocs.gpos_cursive(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname)
local alreadydone=cursonce and start[a_cursbase]
if not alreadydone then
local startchar=start.char
local subtables=currentlookup.subtables
local lookupname=subtables[1]
local exitanchors=lookuphash[lookupname]
if exitanchors then
exitanchors=exitanchors[startchar]
end
if exitanchors then
local done=false
if marks[startchar] then
if trace_cursive then
logprocess("%s: ignoring cursive for mark %s",pref(kind,lookupname),gref(startchar))
end
else
local nxt=start.next
while not done and nxt and nxt.id==glyph_code and nxt.font==currentfont and nxt.subtype<256 do
local nextchar=nxt.char
if marks[nextchar] then
nxt=nxt.next
else
local entryanchors=descriptions[nextchar]
if entryanchors then
entryanchors=entryanchors.anchors
if entryanchors then
entryanchors=entryanchors['centry']
if entryanchors then
local al=anchorlookups[lookupname]
for anchor,entry in next,entryanchors do
if al[anchor] then
local exit=exitanchors[anchor]
if exit then
local dx,dy,bound=setcursive(start,nxt,tfmdata.parameters.factor,rlmode,exit,entry,characters[startchar],characters[nextchar])
if trace_cursive then
logprocess("%s: moving %s to %s cursive (%p,%p) using anchor %s and bound %s in rlmode %s",pref(kind,lookupname),gref(startchar),gref(nextchar),dx,dy,anchor,bound,rlmode)
end
done=true
break
end
end
end
end
end
else
onetimemessage(currentfont,startchar,"no entry anchors",report_fonts)
end
break
end
end
end
return head,start,done
else
if trace_cursive and trace_details then
logprocess("%s, cursive %s is already done",pref(kind,lookupname),gref(start.char),alreadydone)
end
return head,start,false
end
end
return head,start,false
end
function chainprocs.gpos_single(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname,chainindex,sequence)
local startchar=start.char
local subtables=currentlookup.subtables
local lookupname=subtables[1]
local kerns=lookuphash[lookupname]
if kerns then
kerns=kerns[startchar]
if kerns then
local dx,dy,w,h=setpair(start,tfmdata.parameters.factor,rlmode,sequence.flags[4],kerns,characters[startchar])
if trace_kerns then
logprocess("%s: shifting single %s by (%p,%p) and correction (%p,%p)",cref(kind,chainname,chainlookupname),gref(startchar),dx,dy,w,h)
end
end
end
return head,start,false
end
function chainprocs.gpos_pair(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname,chainindex,sequence)
local snext=start.next
if snext then
local startchar=start.char
local subtables=currentlookup.subtables
local lookupname=subtables[1]
local kerns=lookuphash[lookupname]
if kerns then
kerns=kerns[startchar]
if kerns then
local lookuptype=lookuptypes[lookupname]
local prev,done=start,false
local factor=tfmdata.parameters.factor
while snext and snext.id==glyph_code and snext.font==currentfont and snext.subtype<256 do
local nextchar=snext.char
local krn=kerns[nextchar]
if not krn and marks[nextchar] then
prev=snext
snext=snext.next
else
if not krn then
elseif type(krn)=="table" then
if lookuptype=="pair" then
local a,b=krn[2],krn[3]
if a and #a>0 then
local startchar=start.char
local x,y,w,h=setpair(start,factor,rlmode,sequence.flags[4],a,characters[startchar])
if trace_kerns then
logprocess("%s: shifting first of pair %s and %s by (%p,%p) and correction (%p,%p)",cref(kind,chainname,chainlookupname),gref(startchar),gref(nextchar),x,y,w,h)
end
end
if b and #b>0 then
local startchar=start.char
local x,y,w,h=setpair(snext,factor,rlmode,sequence.flags[4],b,characters[nextchar])
if trace_kerns then
logprocess("%s: shifting second of pair %s and %s by (%p,%p) and correction (%p,%p)",cref(kind,chainname,chainlookupname),gref(startchar),gref(nextchar),x,y,w,h)
end
end
else
report_process("%s: check this out (old kern stuff)",cref(kind,chainname,chainlookupname))
local a,b=krn[2],krn[6]
if a and a~=0 then
local k=setkern(snext,factor,rlmode,a)
if trace_kerns then
logprocess("%s: inserting first kern %s between %s and %s",cref(kind,chainname,chainlookupname),k,gref(prev.char),gref(nextchar))
end
end
if b and b~=0 then
logwarning("%s: ignoring second kern xoff %s",cref(kind,chainname,chainlookupname),b*factor)
end
end
done=true
elseif krn~=0 then
local k=setkern(snext,factor,rlmode,krn)
if trace_kerns then
logprocess("%s: inserting kern %s between %s and %s",cref(kind,chainname,chainlookupname),k,gref(prev.char),gref(nextchar))
end
done=true
end
break
end
end
return head,start,done
end
end
end
return head,start,false
end
local function show_skip(kind,chainname,char,ck,class)
if ck[9] then
logwarning("%s: skipping char %s, class %a, rule %a, lookuptype %a, %a => %a",cref(kind,chainname),gref(char),class,ck[1],ck[2],ck[9],ck[10])
else
logwarning("%s: skipping char %s, class %a, rule %a, lookuptype %a",cref(kind,chainname),gref(char),class,ck[1],ck[2])
end
end
local function normal_handle_contextchain(head,start,kind,chainname,contexts,sequence,lookuphash)
local flags=sequence.flags
local done=false
local skipmark=flags[1]
local skipligature=flags[2]
local skipbase=flags[3]
local someskip=skipmark or skipligature or skipbase
local markclass=sequence.markclass
local skipped=false
for k=1,#contexts do
local match=true
local current=start
local last=start
local ck=contexts[k]
local seq=ck[3]
local s=#seq
if s==1 then
match=current.id==glyph_code and current.font==currentfont and current.subtype<256 and seq[1][current.char]
else
local f,l=ck[4],ck[5]
if f==1 and f==l then
else
if f==l then
else
local n=f+1
last=last.next
while n<=l do
if last then
local id=last.id
if id==glyph_code then
if last.font==currentfont and last.subtype<256 then
local char=last.char
local ccd=descriptions[char]
if ccd then
local class=ccd.class
if class==skipmark or class==skipligature or class==skipbase or (markclass and class=="mark" and not markclass[char]) then
skipped=true
if trace_skips then
show_skip(kind,chainname,char,ck,class)
end
last=last.next
elseif seq[n][char] then
if n<l then
last=last.next
end
n=n+1
else
match=false
break
end
else
match=false
break
end
else
match=false
break
end
elseif id==disc_code then
last=last.next
else
match=false
break
end
else
match=false
break
end
end
end
end
if match and f>1 then
local prev=start.prev
if prev then
local n=f-1
while n>=1 do
if prev then
local id=prev.id
if id==glyph_code then
if prev.font==currentfont and prev.subtype<256 then
local char=prev.char
local ccd=descriptions[char]
if ccd then
local class=ccd.class
if class==skipmark or class==skipligature or class==skipbase or (markclass and class=="mark" and not markclass[char]) then
skipped=true
if trace_skips then
show_skip(kind,chainname,char,ck,class)
end
elseif seq[n][char] then
n=n -1
else
match=false
break
end
else
match=false
break
end
else
match=false
break
end
elseif id==disc_code then
elseif seq[n][32] then
n=n -1
else
match=false
break
end
prev=prev.prev
elseif seq[n][32] then
n=n -1
else
match=false
break
end
end
elseif f==2 then
match=seq[1][32]
else
for n=f-1,1 do
if not seq[n][32] then
match=false
break
end
end
end
end
if match and s>l then
local current=last and last.next
if current then
local n=l+1
while n<=s do
if current then
local id=current.id
if id==glyph_code then
if current.font==currentfont and current.subtype<256 then
local char=current.char
local ccd=descriptions[char]
if ccd then
local class=ccd.class
if class==skipmark or class==skipligature or class==skipbase or (markclass and class=="mark" and not markclass[char]) then
skipped=true
if trace_skips then
show_skip(kind,chainname,char,ck,class)
end
elseif seq[n][char] then
n=n+1
else
match=false
break
end
else
match=false
break
end
else
match=false
break
end
elseif id==disc_code then
elseif seq[n][32] then
n=n+1
else
match=false
break
end
current=current.next
elseif seq[n][32] then
n=n+1
else
match=false
break
end
end
elseif s-l==1 then
match=seq[s][32]
else
for n=l+1,s do
if not seq[n][32] then
match=false
break
end
end
end
end
end
if match then
if trace_contexts then
local rule,lookuptype,f,l=ck[1],ck[2],ck[4],ck[5]
local char=start.char
if ck[9] then
logwarning("%s: rule %s matches at char %s for (%s,%s,%s) chars, lookuptype %a, %a => %a",
cref(kind,chainname),rule,gref(char),f-1,l-f+1,s-l,lookuptype,ck[9],ck[10])
else
logwarning("%s: rule %s matches at char %s for (%s,%s,%s) chars, lookuptype %a",
cref(kind,chainname),rule,gref(char),f-1,l-f+1,s-l,lookuptype)
end
end
local chainlookups=ck[6]
if chainlookups then
local nofchainlookups=#chainlookups
if nofchainlookups==1 then
local chainlookupname=chainlookups[1]
local chainlookup=lookuptable[chainlookupname]
if chainlookup then
local cp=chainprocs[chainlookup.type]
if cp then
head,start,done=cp(head,start,last,kind,chainname,ck,lookuphash,chainlookup,chainlookupname,nil,sequence)
else
logprocess("%s: %s is not yet supported",cref(kind,chainname,chainlookupname),chainlookup.type)
end
else
logprocess("%s is not yet supported",cref(kind,chainname,chainlookupname))
end
else
local i=1
repeat
if skipped then
while true do
local char=start.char
local ccd=descriptions[char]
if ccd then
local class=ccd.class
if class==skipmark or class==skipligature or class==skipbase or (markclass and class=="mark" and not markclass[char]) then
start=start.next
else
break
end
else
break
end
end
end
local chainlookupname=chainlookups[i]
local chainlookup=lookuptable[chainlookupname]
local cp=chainlookup and chainmores[chainlookup.type]
if cp then
local ok,n
head,start,ok,n=cp(head,start,last,kind,chainname,ck,lookuphash,chainlookup,chainlookupname,i,sequence)
if ok then
done=true
i=i+(n or 1)
else
i=i+1
end
else
i=i+1
end
if start then
start=start.next
else
end
until i>nofchainlookups
end
else
local replacements=ck[7]
if replacements then
head,start,done=chainprocs.reversesub(head,start,last,kind,chainname,ck,lookuphash,replacements)
else
done=true
if trace_contexts then
logprocess("%s: skipping match",cref(kind,chainname))
end
end
end
end
end
return head,start,done
end
local verbose_handle_contextchain=function(font,...)
logwarning("no verbose handler installed, reverting to 'normal'")
otf.setcontextchain()
return normal_handle_contextchain(...)
end
otf.chainhandlers={
normal=normal_handle_contextchain,
verbose=verbose_handle_contextchain,
}
function otf.setcontextchain(method)
if not method or method=="normal" or not otf.chainhandlers[method] then
if handlers.contextchain then
logwarning("installing normal contextchain handler")
end
handlers.contextchain=normal_handle_contextchain
else
logwarning("installing contextchain handler %a",method)
local handler=otf.chainhandlers[method]
handlers.contextchain=function(...)
return handler(currentfont,...)
end
end
handlers.gsub_context=handlers.contextchain
handlers.gsub_contextchain=handlers.contextchain
handlers.gsub_reversecontextchain=handlers.contextchain
handlers.gpos_contextchain=handlers.contextchain
handlers.gpos_context=handlers.contextchain
end
otf.setcontextchain()
local missing={}
local function logprocess(...)
if trace_steps then
registermessage(...)
end
report_process(...)
end
local logwarning=report_process
local function report_missing_cache(typ,lookup)
local f=missing[currentfont] if not f then f={} missing[currentfont]=f end
local t=f[typ] if not t then t={} f[typ]=t end
if not t[lookup] then
t[lookup]=true
logwarning("missing cache for lookup %a, type %a, font %a, name %a",lookup,typ,currentfont,tfmdata.properties.fullname)
end
end
local resolved={}
local lookuphashes={}
setmetatableindex(lookuphashes,function(t,font)
local lookuphash=fontdata[font].resources.lookuphash
if not lookuphash or not next(lookuphash) then
lookuphash=false
end
t[font]=lookuphash
return lookuphash
end)
local autofeatures=fonts.analyzers.features
local function initialize(sequence,script,language,enabled)
local features=sequence.features
if features then
for kind,scripts in next,features do
local valid=enabled[kind]
if valid then
local languages=scripts[script] or scripts[wildcard]
if languages and (languages[language] or languages[wildcard]) then
return { valid,autofeatures[kind] or false,sequence.chain or 0,kind,sequence }
end
end
end
end
return false
end
function otf.dataset(tfmdata,font)
local shared=tfmdata.shared
local properties=tfmdata.properties
local language=properties.language or "dflt"
local script=properties.script or "dflt"
local enabled=shared.features
local res=resolved[font]
if not res then
res={}
resolved[font]=res
end
local rs=res[script]
if not rs then
rs={}
res[script]=rs
end
local rl=rs[language]
if not rl then
rl={
}
rs[language]=rl
local sequences=tfmdata.resources.sequences
for s=1,#sequences do
local v=enabled and initialize(sequences[s],script,language,enabled)
if v then
rl[#rl+1]=v
end
end
end
return rl
end
local function featuresprocessor(head,font,attr)
local lookuphash=lookuphashes[font]
if not lookuphash then
return head,false
end
if trace_steps then
checkstep(head)
end
tfmdata=fontdata[font]
descriptions=tfmdata.descriptions
characters=tfmdata.characters
resources=tfmdata.resources
marks=resources.marks
anchorlookups=resources.lookup_to_anchor
lookuptable=resources.lookups
lookuptypes=resources.lookuptypes
currentfont=font
rlmode=0
local sequences=resources.sequences
local done=false
local datasets=otf.dataset(tfmdata,font,attr)
local dirstack={}
for s=1,#datasets do
local dataset=datasets[s]
featurevalue=dataset[1]
local sequence=dataset[5]
local rlparmode=0
local topstack=0
local success=false
local attribute=dataset[2]
local chain=dataset[3]
local typ=sequence.type
local subtables=sequence.subtables
if chain<0 then
local handler=handlers[typ]
local start=find_node_tail(head)
while start do
local id=start.id
if id==glyph_code then
if start.font==font and start.subtype<256 then
local a=start[0]
if a then
a=a==attr
else
a=true
end
if a then
for i=1,#subtables do
local lookupname=subtables[i]
local lookupcache=lookuphash[lookupname]
if lookupcache then
local lookupmatch=lookupcache[start.char]
if lookupmatch then
head,start,success=handler(head,start,dataset[4],lookupname,lookupmatch,sequence,lookuphash,i)
if success then
break
end
end
else
report_missing_cache(typ,lookupname)
end
end
if start then start=start.prev end
else
start=start.prev
end
else
start=start.prev
end
else
start=start.prev
end
end
else
local handler=handlers[typ]
local ns=#subtables
local start=head
rlmode=0
if ns==1 then
local lookupname=subtables[1]
local lookupcache=lookuphash[lookupname]
if not lookupcache then
report_missing_cache(typ,lookupname)
else
while start do
local id=start.id
if id==glyph_code then
if start.font==font and start.subtype<256 then
local a=start[0]
if a then
a=(a==attr) and (not attribute or start[a_state]==attribute)
else
a=not attribute or start[a_state]==attribute
end
if a then
local lookupmatch=lookupcache[start.char]
if lookupmatch then
local ok
head,start,ok=handler(head,start,dataset[4],lookupname,lookupmatch,sequence,lookuphash,1)
if ok then
success=true
end
end
if start then start=start.next end
else
start=start.next
end
elseif id==math_code then
start=end_of_math(start).next
else
start=start.next
end
elseif id==whatsit_code then
local subtype=start.subtype
if subtype==dir_code then
local dir=start.dir
if dir=="+TRT" or dir=="+TLT" then
topstack=topstack+1
dirstack[topstack]=dir
elseif dir=="-TRT" or dir=="-TLT" then
topstack=topstack-1
end
local newdir=dirstack[topstack]
if newdir=="+TRT" then
rlmode=-1
elseif newdir=="+TLT" then
rlmode=1
else
rlmode=rlparmode
end
if trace_directions then
report_process("directions after txtdir %a: parmode %a, txtmode %a, # stack %a, new dir %a",dir,rlparmode,rlmode,topstack,newdir)
end
elseif subtype==localpar_code then
local dir=start.dir
if dir=="TRT" then
rlparmode=-1
elseif dir=="TLT" then
rlparmode=1
else
rlparmode=0
end
rlmode=rlparmode
if trace_directions then
report_process("directions after pardir %a: parmode %a, txtmode %a",dir,rlparmode,rlmode)
end
end
start=start.next
elseif id==math_code then
start=end_of_math(start).next
else
start=start.next
end
end
end
else
while start do
local id=start.id
if id==glyph_code then
if start.font==font and start.subtype<256 then
local a=start[0]
if a then
a=(a==attr) and (not attribute or start[a_state]==attribute)
else
a=not attribute or start[a_state]==attribute
end
if a then
for i=1,ns do
local lookupname=subtables[i]
local lookupcache=lookuphash[lookupname]
if lookupcache then
local lookupmatch=lookupcache[start.char]
if lookupmatch then
local ok
head,start,ok=handler(head,start,dataset[4],lookupname,lookupmatch,sequence,lookuphash,i)
if ok then
success=true
break
end
end
else
report_missing_cache(typ,lookupname)
end
end
if start then start=start.next end
else
start=start.next
end
else
start=start.next
end
elseif id==whatsit_code then
local subtype=start.subtype
if subtype==dir_code then
local dir=start.dir
if dir=="+TRT" or dir=="+TLT" then
topstack=topstack+1
dirstack[topstack]=dir
elseif dir=="-TRT" or dir=="-TLT" then
topstack=topstack-1
end
local newdir=dirstack[topstack]
if newdir=="+TRT" then
rlmode=-1
elseif newdir=="+TLT" then
rlmode=1
else
rlmode=rlparmode
end
if trace_directions then
report_process("directions after txtdir %a: parmode %a, txtmode %a, # stack %a, new dir %a",dir,rlparmode,rlmode,topstack,newdir)
end
elseif subtype==localpar_code then
local dir=start.dir
if dir=="TRT" then
rlparmode=-1
elseif dir=="TLT" then
rlparmode=1
else
rlparmode=0
end
rlmode=rlparmode
if trace_directions then
report_process("directions after pardir %a: parmode %a, txtmode %a",dir,rlparmode,rlmode)
end
end
start=start.next
elseif id==math_code then
start=end_of_math(start).next
else
start=start.next
end
end
end
end
if success then
done=true
end
if trace_steps then
registerstep(head)
end
end
return head,done
end
local function generic(lookupdata,lookupname,unicode,lookuphash)
local target=lookuphash[lookupname]
if target then
target[unicode]=lookupdata
else
lookuphash[lookupname]={ [unicode]=lookupdata }
end
end
local action={
substitution=generic,
multiple=generic,
alternate=generic,
position=generic,
ligature=function(lookupdata,lookupname,unicode,lookuphash)
local target=lookuphash[lookupname]
if not target then
target={}
lookuphash[lookupname]=target
end
for i=1,#lookupdata do
local li=lookupdata[i]
local tu=target[li]
if not tu then
tu={}
target[li]=tu
end
target=tu
end
target.ligature=unicode
end,
pair=function(lookupdata,lookupname,unicode,lookuphash)
local target=lookuphash[lookupname]
if not target then
target={}
lookuphash[lookupname]=target
end
local others=target[unicode]
local paired=lookupdata[1]
if others then
others[paired]=lookupdata
else
others={ [paired]=lookupdata }
target[unicode]=others
end
end,
}
local function prepare_lookups(tfmdata)
local rawdata=tfmdata.shared.rawdata
local resources=rawdata.resources
local lookuphash=resources.lookuphash
local anchor_to_lookup=resources.anchor_to_lookup
local lookup_to_anchor=resources.lookup_to_anchor
local lookuptypes=resources.lookuptypes
local characters=tfmdata.characters
local descriptions=tfmdata.descriptions
for unicode,character in next,characters do
local description=descriptions[unicode]
if description then
local lookups=description.slookups
if lookups then
for lookupname,lookupdata in next,lookups do
action[lookuptypes[lookupname]](lookupdata,lookupname,unicode,lookuphash)
end
end
local lookups=description.mlookups
if lookups then
for lookupname,lookuplist in next,lookups do
local lookuptype=lookuptypes[lookupname]
for l=1,#lookuplist do
local lookupdata=lookuplist[l]
action[lookuptype](lookupdata,lookupname,unicode,lookuphash)
end
end
end
local list=description.kerns
if list then
for lookup,krn in next,list do
local target=lookuphash[lookup]
if target then
target[unicode]=krn
else
lookuphash[lookup]={ [unicode]=krn }
end
end
end
local list=description.anchors
if list then
for typ,anchors in next,list do
if typ=="mark" or typ=="cexit" then
for name,anchor in next,anchors do
local lookups=anchor_to_lookup[name]
if lookups then
for lookup,_ in next,lookups do
local target=lookuphash[lookup]
if target then
target[unicode]=anchors
else
lookuphash[lookup]={ [unicode]=anchors }
end
end
end
end
end
end
end
end
end
end
local function split(replacement,original)
local result={}
for i=1,#replacement do
result[original[i]]=replacement[i]
end
return result
end
local valid={
coverage={ chainsub=true,chainpos=true,contextsub=true },
reversecoverage={ reversesub=true },
glyphs={ chainsub=true,chainpos=true },
}
local function prepare_contextchains(tfmdata)
local rawdata=tfmdata.shared.rawdata
local resources=rawdata.resources
local lookuphash=resources.lookuphash
local lookups=rawdata.lookups
if lookups then
for lookupname,lookupdata in next,rawdata.lookups do
local lookuptype=lookupdata.type
if lookuptype then
local rules=lookupdata.rules
if rules then
local format=lookupdata.format
local validformat=valid[format]
if not validformat then
report_prepare("unsupported format %a",format)
elseif not validformat[lookuptype] then
report_prepare("unsupported format %a, lookuptype %a, lookupname %a",format,lookuptype,lookupname)
else
local contexts=lookuphash[lookupname]
if not contexts then
contexts={}
lookuphash[lookupname]=contexts
end
local t,nt={},0
for nofrules=1,#rules do
local rule=rules[nofrules]
local current=rule.current
local before=rule.before
local after=rule.after
local replacements=rule.replacements
local sequence={}
local nofsequences=0
if before then
for n=1,#before do
nofsequences=nofsequences+1
sequence[nofsequences]=before[n]
end
end
local start=nofsequences+1
for n=1,#current do
nofsequences=nofsequences+1
sequence[nofsequences]=current[n]
end
local stop=nofsequences
if after then
for n=1,#after do
nofsequences=nofsequences+1
sequence[nofsequences]=after[n]
end
end
if sequence[1] then
nt=nt+1
t[nt]={ nofrules,lookuptype,sequence,start,stop,rule.lookups,replacements }
for unic,_ in next,sequence[start] do
local cu=contexts[unic]
if not cu then
contexts[unic]=t
end
end
end
end
end
else
end
else
report_prepare("missing lookuptype for lookupname %a",lookupname)
end
end
end
end
local function featuresinitializer(tfmdata,value)
if true then
local rawdata=tfmdata.shared.rawdata
local properties=rawdata.properties
if not properties.initialized then
local starttime=trace_preparing and os.clock()
local resources=rawdata.resources
resources.lookuphash=resources.lookuphash or {}
prepare_contextchains(tfmdata)
prepare_lookups(tfmdata)
properties.initialized=true
if trace_preparing then
report_prepare("preparation time is %0.3f seconds for %a",os.clock()-starttime,tfmdata.properties.fullname)
end
end
end
end
registerotffeature {
name="features",
description="features",
default=true,
initializers={
position=1,
node=featuresinitializer,
},
processors={
node=featuresprocessor,
}
}
otf.handlers=handlers
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['luatex-fonts-lua']={
version=1.001,
comment="companion to luatex-*.tex",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
if context then
texio.write_nl("fatal error: this module is not for context")
os.exit()
end
local fonts=fonts
fonts.formats.lua="lua"
function fonts.readers.lua(specification)
local fullname=specification.filename or ""
if fullname=="" then
local forced=specification.forced or ""
if forced~="" then
fullname=specification.name.."."..forced
else
fullname=specification.name
end
end
local fullname=resolvers.findfile(fullname) or ""
if fullname~="" then
local loader=loadfile(fullname)
loader=loader and loader()
return loader and loader(specification)
end
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['font-def']={
version=1.001,
comment="companion to font-ini.mkiv",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local format,gmatch,match,find,lower,gsub=string.format,string.gmatch,string.match,string.find,string.lower,string.gsub
local tostring,next=tostring,next
local lpegmatch=lpeg.match
local allocate=utilities.storage.allocate
local trace_defining=false trackers .register("fonts.defining",function(v) trace_defining=v end)
local directive_embedall=false directives.register("fonts.embedall",function(v) directive_embedall=v end)
trackers.register("fonts.loading","fonts.defining","otf.loading","afm.loading","tfm.loading")
trackers.register("fonts.all","fonts.*","otf.*","afm.*","tfm.*")
local report_defining=logs.reporter("fonts","defining")
local fonts=fonts
local fontdata=fonts.hashes.identifiers
local readers=fonts.readers
local definers=fonts.definers
local specifiers=fonts.specifiers
local constructors=fonts.constructors
local fontgoodies=fonts.goodies
readers.sequence=allocate { 'otf','ttf','afm','tfm','lua' }
local variants=allocate()
specifiers.variants=variants
definers.methods=definers.methods or {}
local internalized=allocate()
local loadedfonts=constructors.loadedfonts
local designsizes=constructors.designsizes
local resolvefile=fontgoodies and fontgoodies.filenames and fontgoodies.filenames.resolve or function(s) return s end
local splitter,splitspecifiers=nil,""
local P,C,S,Cc=lpeg.P,lpeg.C,lpeg.S,lpeg.Cc
local left=P("(")
local right=P(")")
local colon=P(":")
local space=P(" ")
definers.defaultlookup="file"
local prefixpattern=P(false)
local function addspecifier(symbol)
splitspecifiers=splitspecifiers..symbol
local method=S(splitspecifiers)
local lookup=C(prefixpattern)*colon
local sub=left*C(P(1-left-right-method)^1)*right
local specification=C(method)*C(P(1)^1)
local name=C((1-sub-specification)^1)
splitter=P((lookup+Cc(""))*name*(sub+Cc(""))*(specification+Cc("")))
end
local function addlookup(str,default)
prefixpattern=prefixpattern+P(str)
end
definers.addlookup=addlookup
addlookup("file")
addlookup("name")
addlookup("spec")
local function getspecification(str)
return lpegmatch(splitter,str)
end
definers.getspecification=getspecification
function definers.registersplit(symbol,action,verbosename)
addspecifier(symbol)
variants[symbol]=action
if verbosename then
variants[verbosename]=action
end
end
local function makespecification(specification,lookup,name,sub,method,detail,size)
size=size or 655360
if not lookup or lookup=="" then
lookup=definers.defaultlookup
end
if trace_defining then
report_defining("specification %a, lookup %a, name %a, sub %a, method %a, detail %a",
specification,lookup,name,sub,method,detail)
end
local t={
lookup=lookup,
specification=specification,
size=size,
name=name,
sub=sub,
method=method,
detail=detail,
resolved="",
forced="",
features={},
}
return t
end
definers.makespecification=makespecification
function definers.analyze(specification,size)
local lookup,name,sub,method,detail=getspecification(specification or "")
return makespecification(specification,lookup,name,sub,method,detail,size)
end
definers.resolvers=definers.resolvers or {}
local resolvers=definers.resolvers
function resolvers.file(specification)
local name=resolvefile(specification.name)
local suffix=file.suffix(name)
if fonts.formats[suffix] then
specification.forced=suffix
specification.name=file.removesuffix(name)
else
specification.name=name
end
end
function resolvers.name(specification)
local resolve=fonts.names.resolve
if resolve then
local resolved,sub=resolve(specification.name,specification.sub,specification)
if resolved then
specification.resolved=resolved
specification.sub=sub
local suffix=file.suffix(resolved)
if fonts.formats[suffix] then
specification.forced=suffix
specification.name=file.removesuffix(resolved)
else
specification.name=resolved
end
end
else
resolvers.file(specification)
end
end
function resolvers.spec(specification)
local resolvespec=fonts.names.resolvespec
if resolvespec then
local resolved,sub=resolvespec(specification.name,specification.sub,specification)
if resolved then
specification.resolved=resolved
specification.sub=sub
specification.forced=file.suffix(resolved)
specification.name=file.removesuffix(resolved)
end
else
resolvers.name(specification)
end
end
function definers.resolve(specification)
if not specification.resolved or specification.resolved=="" then
local r=resolvers[specification.lookup]
if r then
r(specification)
end
end
if specification.forced=="" then
specification.forced=nil
else
specification.forced=specification.forced
end
specification.hash=lower(specification.name..' @ '..constructors.hashfeatures(specification))
if specification.sub and specification.sub~="" then
specification.hash=specification.sub..' @ '..specification.hash
end
return specification
end
function definers.applypostprocessors(tfmdata)
local postprocessors=tfmdata.postprocessors
if postprocessors then
local properties=tfmdata.properties
for i=1,#postprocessors do
local extrahash=postprocessors[i](tfmdata)
if type(extrahash)=="string" and extrahash~="" then
extrahash=gsub(lower(extrahash),"[^a-z]","-")
properties.fullname=format("%s-%s",properties.fullname,extrahash)
end
end
end
return tfmdata
end
local function checkembedding(tfmdata)
local properties=tfmdata.properties
local embedding
if directive_embedall then
embedding="full"
elseif properties and properties.filename and constructors.dontembed[properties.filename] then
embedding="no"
else
embedding="subset"
end
if properties then
properties.embedding=embedding
else
tfmdata.properties={ embedding=embedding }
end
tfmdata.embedding=embedding
end
function definers.loadfont(specification)
local hash=constructors.hashinstance(specification)
local tfmdata=loadedfonts[hash]
if not tfmdata then
local forced=specification.forced or ""
if forced~="" then
local reader=readers[lower(forced)]
tfmdata=reader and reader(specification)
if not tfmdata then
report_defining("forced type %a of %a not found",forced,specification.name)
end
else
local sequence=readers.sequence
for s=1,#sequence do
local reader=sequence[s]
if readers[reader] then
if trace_defining then
report_defining("trying (reader sequence driven) type %a for %a with file %a",reader,specification.name,specification.filename)
end
tfmdata=readers[reader](specification)
if tfmdata then
break
else
specification.filename=nil
end
end
end
end
if tfmdata then
tfmdata=definers.applypostprocessors(tfmdata)
checkembedding(tfmdata)
loadedfonts[hash]=tfmdata
designsizes[specification.hash]=tfmdata.parameters.designsize
end
end
if not tfmdata then
report_defining("font with asked name %a is not found using lookup %a",specification.name,specification.lookup)
end
return tfmdata
end
local function checkvirtual(tfmdata)
local fonts=tfmdata.fonts
local selfid=font.nextid()
if fonts and #fonts>0 then
for i=1,#fonts do
if fonts[i][2]==0 then
fonts[i][2]=selfid
end
end
else
tfmdata.fonts={ "id",selfid }
end
end
function constructors.readanddefine(name,size)
local specification=definers.analyze(name,size)
local method=specification.method
if method and variants[method] then
specification=variants[method](specification)
end
specification=definers.resolve(specification)
local hash=constructors.hashinstance(specification)
local id=definers.registered(hash)
if not id then
local tfmdata=definers.loadfont(specification)
if tfmdata then
checkvirtual(tfmdata)
id=font.define(tfmdata)
definers.register(tfmdata,id)
else
id=0
end
end
return fontdata[id],id
end
local lastdefined=nil
local internalized={}
function definers.current()
return lastdefined
end
function definers.registered(hash)
local id=internalized[hash]
return id,id and fontdata[id]
end
function definers.register(tfmdata,id)
if tfmdata and id then
local hash=tfmdata.properties.hash
if not internalized[hash] then
internalized[hash]=id
if trace_defining then
report_defining("registering font, id %s, hash %a",id,hash)
end
fontdata[id]=tfmdata
end
end
end
function definers.read(specification,size,id)
statistics.starttiming(fonts)
if type(specification)=="string" then
specification=definers.analyze(specification,size)
end
local method=specification.method
if method and variants[method] then
specification=variants[method](specification)
end
specification=definers.resolve(specification)
local hash=constructors.hashinstance(specification)
local tfmdata=definers.registered(hash)
if tfmdata then
if trace_defining then
report_defining("already hashed: %s",hash)
end
else
tfmdata=definers.loadfont(specification)
if tfmdata then
if trace_defining then
report_defining("loaded and hashed: %s",hash)
end
tfmdata.properties.hash=hash
if id then
definers.register(tfmdata,id)
end
else
if trace_defining then
report_defining("not loaded and hashed: %s",hash)
end
end
end
lastdefined=tfmdata or id
if not tfmdata then
report_defining("unknown font %a, loading aborted",specification.name)
elseif trace_defining and type(tfmdata)=="table" then
local properties=tfmdata.properties or {}
local parameters=tfmdata.parameters or {}
report_defining("using %s font with id %a, name %a, size %a, bytes %a, encoding %a, fullname %a, filename %a",
properties.format,id,properties.name,parameters.size,properties.encodingbytes,
properties.encodingname,properties.fullname,file.basename(properties.filename))
end
statistics.stoptiming(fonts)
return tfmdata
end
function font.getfont(id)
return fontdata[id]
end
callbacks.register('define_font',definers.read,"definition of fonts (tfmdata preparation)")
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['luatex-font-def']={
version=1.001,
comment="companion to luatex-*.tex",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
if context then
texio.write_nl("fatal error: this module is not for context")
os.exit()
end
local fonts=fonts
fonts.constructors.namemode="specification"
function fonts.definers.getspecification(str)
return "",str,"",":",str
end
local list={}
local function issome () list.lookup='name' end
local function isfile () list.lookup='file' end
local function isname () list.lookup='name' end
local function thename(s) list.name=s end
local function issub (v) list.sub=v end
local function iscrap (s) list.crap=string.lower(s) end
local function iskey (k,v) list[k]=v end
local function istrue (s) list[s]=true end
local function isfalse(s) list[s]=false end
local P,S,R,C=lpeg.P,lpeg.S,lpeg.R,lpeg.C
local spaces=P(" ")^0
local namespec=(1-S("/:("))^0
local crapspec=spaces*P("/")*(((1-P(":"))^0)/iscrap)*spaces
local filename_1=P("file:")/isfile*(namespec/thename)
local filename_2=P("[")*P(true)/isname*(((1-P("]"))^0)/thename)*P("]")
local fontname_1=P("name:")/isname*(namespec/thename)
local fontname_2=P(true)/issome*(namespec/thename)
local sometext=(R("az","AZ","09")+S("+-."))^1
local truevalue=P("+")*spaces*(sometext/istrue)
local falsevalue=P("-")*spaces*(sometext/isfalse)
local keyvalue=(C(sometext)*spaces*P("=")*spaces*C(sometext))/iskey
local somevalue=sometext/istrue
local subvalue=P("(")*(C(P(1-S("()"))^1)/issub)*P(")")
local option=spaces*(keyvalue+falsevalue+truevalue+somevalue)*spaces
local options=P(":")*spaces*(P(";")^0*option)^0
local pattern=(filename_1+filename_2+fontname_1+fontname_2)*subvalue^0*crapspec^0*options^0
local function colonized(specification)
list={}
lpeg.match(pattern,specification.specification)
list.crap=nil
if list.name then
specification.name=list.name
list.name=nil
end
if list.lookup then
specification.lookup=list.lookup
list.lookup=nil
end
if list.sub then
specification.sub=list.sub
list.sub=nil
end
specification.features.normal=fonts.handlers.otf.features.normalize(list)
return specification
end
fonts.definers.registersplit(":",colonized,"cryptic")
fonts.definers.registersplit("",colonized,"more cryptic")
function fonts.definers.applypostprocessors(tfmdata)
local postprocessors=tfmdata.postprocessors
if postprocessors then
for i=1,#postprocessors do
local extrahash=postprocessors[i](tfmdata)
if type(extrahash)=="string" and extrahash~="" then
extrahash=string.gsub(lower(extrahash),"[^a-z]","-")
tfmdata.properties.fullname=format("%s-%s",tfmdata.properties.fullname,extrahash)
end
end
end
return tfmdata
end
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['luatex-fonts-ext']={
version=1.001,
comment="companion to luatex-*.tex",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
if context then
texio.write_nl("fatal error: this module is not for context")
os.exit()
end
local fonts=fonts
local otffeatures=fonts.constructors.newfeatures("otf")
local function initializeitlc(tfmdata,value)
if value then
local parameters=tfmdata.parameters
local italicangle=parameters.italicangle
if italicangle and italicangle~=0 then
local properties=tfmdata.properties
local factor=tonumber(value) or 1
properties.hasitalics=true
properties.autoitalicamount=factor*(parameters.uwidth or 40)/2
end
end
end
otffeatures.register {
name="itlc",
description="italic correction",
initializers={
base=initializeitlc,
node=initializeitlc,
}
}
local function initializeslant(tfmdata,value)
value=tonumber(value)
if not value then
value=0
elseif value>1 then
value=1
elseif value<-1 then
value=-1
end
tfmdata.parameters.slantfactor=value
end
otffeatures.register {
name="slant",
description="slant glyphs",
initializers={
base=initializeslant,
node=initializeslant,
}
}
local function initializeextend(tfmdata,value)
value=tonumber(value)
if not value then
value=0
elseif value>10 then
value=10
elseif value<-10 then
value=-10
end
tfmdata.parameters.extendfactor=value
end
otffeatures.register {
name="extend",
description="scale glyphs horizontally",
initializers={
base=initializeextend,
node=initializeextend,
}
}
fonts.protrusions=fonts.protrusions or {}
fonts.protrusions.setups=fonts.protrusions.setups or {}
local setups=fonts.protrusions.setups
local function initializeprotrusion(tfmdata,value)
if value then
local setup=setups[value]
if setup then
local factor,left,right=setup.factor or 1,setup.left or 1,setup.right or 1
local emwidth=tfmdata.parameters.quad
tfmdata.parameters.protrusion={
auto=true,
}
for i,chr in next,tfmdata.characters do
local v,pl,pr=setup[i],nil,nil
if v then
pl,pr=v[1],v[2]
end
if pl and pl~=0 then chr.left_protruding=left*pl*factor end
if pr and pr~=0 then chr.right_protruding=right*pr*factor end
end
end
end
end
otffeatures.register {
name="protrusion",
description="shift characters into the left and or right margin",
initializers={
base=initializeprotrusion,
node=initializeprotrusion,
}
}
fonts.expansions=fonts.expansions or {}
fonts.expansions.setups=fonts.expansions.setups or {}
local setups=fonts.expansions.setups
local function initializeexpansion(tfmdata,value)
if value then
local setup=setups[value]
if setup then
local factor=setup.factor or 1
tfmdata.parameters.expansion={
stretch=10*(setup.stretch or 0),
shrink=10*(setup.shrink or 0),
step=10*(setup.step or 0),
auto=true,
}
for i,chr in next,tfmdata.characters do
local v=setup[i]
if v and v~=0 then
chr.expansion_factor=v*factor
else
chr.expansion_factor=factor
end
end
end
end
end
otffeatures.register {
name="expansion",
description="apply hz optimization",
initializers={
base=initializeexpansion,
node=initializeexpansion,
}
}
function fonts.loggers.onetimemessage() end
local byte=string.byte
fonts.expansions.setups['default']={
stretch=2,shrink=2,step=.5,factor=1,
[byte('A')]=0.5,[byte('B')]=0.7,[byte('C')]=0.7,[byte('D')]=0.5,[byte('E')]=0.7,
[byte('F')]=0.7,[byte('G')]=0.5,[byte('H')]=0.7,[byte('K')]=0.7,[byte('M')]=0.7,
[byte('N')]=0.7,[byte('O')]=0.5,[byte('P')]=0.7,[byte('Q')]=0.5,[byte('R')]=0.7,
[byte('S')]=0.7,[byte('U')]=0.7,[byte('W')]=0.7,[byte('Z')]=0.7,
[byte('a')]=0.7,[byte('b')]=0.7,[byte('c')]=0.7,[byte('d')]=0.7,[byte('e')]=0.7,
[byte('g')]=0.7,[byte('h')]=0.7,[byte('k')]=0.7,[byte('m')]=0.7,[byte('n')]=0.7,
[byte('o')]=0.7,[byte('p')]=0.7,[byte('q')]=0.7,[byte('s')]=0.7,[byte('u')]=0.7,
[byte('w')]=0.7,[byte('z')]=0.7,
[byte('2')]=0.7,[byte('3')]=0.7,[byte('6')]=0.7,[byte('8')]=0.7,[byte('9')]=0.7,
}
fonts.protrusions.setups['default']={
factor=1,left=1,right=1,
[0x002C]={ 0,1 },
[0x002E]={ 0,1 },
[0x003A]={ 0,1 },
[0x003B]={ 0,1 },
[0x002D]={ 0,1 },
[0x2013]={ 0,0.50 },
[0x2014]={ 0,0.33 },
[0x3001]={ 0,1 },
[0x3002]={ 0,1 },
[0x060C]={ 0,1 },
[0x061B]={ 0,1 },
[0x06D4]={ 0,1 },
}
fonts.handlers.otf.features.normalize=function(t)
if t.rand then
t.rand="random"
end
return t
end
function fonts.helpers.nametoslot(name)
local t=type(name)
if t=="string" then
local tfmdata=fonts.hashes.identifiers[currentfont()]
local shared=tfmdata and tfmdata.shared
local fntdata=shared and shared.rawdata
return fntdata and fntdata.resources.unicodes[name]
elseif t=="number" then
return n
end
end
fonts.encodings=fonts.encodings or {}
local reencodings={}
fonts.encodings.reencodings=reencodings
local function specialreencode(tfmdata,value)
local encoding=value and reencodings[value]
if encoding then
local temp={}
local char=tfmdata.characters
for k,v in next,encoding do
temp[k]=char[v]
end
for k,v in next,temp do
char[k]=temp[k]
end
return string.format("reencoded:%s",value)
end
end
local function reencode(tfmdata,value)
tfmdata.postprocessors=tfmdata.postprocessors or {}
table.insert(tfmdata.postprocessors,
function(tfmdata)
return specialreencode(tfmdata,value)
end
)
end
otffeatures.register {
name="reencode",
description="reencode characters",
manipulators={
base=reencode,
node=reencode,
}
}
end -- closure
do -- begin closure to overcome local limits and interference
if not modules then modules={} end modules ['luatex-fonts-cbk']={
version=1.001,
comment="companion to luatex-*.tex",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
if context then
texio.write_nl("fatal error: this module is not for context")
os.exit()
end
local fonts=fonts
local nodes=nodes
local traverse_id=node.traverse_id
local glyph_code=nodes.nodecodes.glyph
function nodes.handlers.characters(head)
local fontdata=fonts.hashes.identifiers
if fontdata then
local usedfonts,done,prevfont={},false,nil
for n in traverse_id(glyph_code,head) do
local font=n.font
if font~=prevfont then
prevfont=font
local used=usedfonts[font]
if not used then
local tfmdata=fontdata[font]
if tfmdata then
local shared=tfmdata.shared
if shared then
local processors=shared.processes
if processors and #processors>0 then
usedfonts[font]=processors
done=true
end
end
end
end
end
end
if done then
for font,processors in next,usedfonts do
for i=1,#processors do
local h,d=processors[i](head,font,0)
head,done=h or head,done or d
end
end
end
return head,true
else
return head,false
end
end
function nodes.simple_font_handler(head)
head=nodes.handlers.characters(head)
nodes.injections.handler(head)
nodes.handlers.protectglyphs(head)
head=node.ligaturing(head)
head=node.kerning(head)
return head
end
end -- closure
|