summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/source/luatex/luamplib/luamplib.dtx
blob: fe20a1ccf5cf13d83eda77547162a1c7114bbecf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
% \iffalse meta-comment -- by the way, this file contains UTF-8
%
% Copyright (C) 2008-2024 by Hans Hagen, Taco Hoekwater, Elie Roux,
% Manuel Pégourié-Gonnard, Philipp Gesang and Kim Dohyun.
% Currently maintained by Kim Dohyun.
% Support: <https://github.com/lualatex/luamplib>
%
% This work is under the GPL v2.0 license.
%
% This work consists of the main source file luamplib.dtx
% and the derived files
%    luamplib.sty, luamplib.lua and luamplib.pdf.
%
% Unpacking:
%    tex luamplib.dtx
%
% Documentation:
%    lualatex luamplib.dtx
%
%<*ignore>
\begingroup
  \def\x{LaTeX2e}%
\expandafter\endgroup
\ifcase 0\ifx\install y1\fi\expandafter
         \ifx\csname processbatchFile\endcsname\relax\else1\fi
         \ifx\fmtname\x\else 1\fi\relax
\else\csname fi\endcsname
%</ignore>
%<*install>
\input docstrip.tex
\Msg{************************************************************************}
\Msg{* Installation}
\Msg{* Package: luamplib - metapost package for LuaTeX.}
\Msg{************************************************************************}

\keepsilent
\askforoverwritefalse

\let\MetaPrefix\relax

\preamble

See source file '\inFileName' for licencing and contact information.

\endpreamble

\let\MetaPrefix\DoubleperCent

\generate{%
  \usedir{tex/luatex/luamplib}%
  \file{luamplib.sty}{\from{luamplib.dtx}{package}}%
}

\def\MetaPrefix{-- }

\def\luapostamble{%
  \MetaPrefix^^J%
  \MetaPrefix\space End of File `\outFileName'.%
}

\def\currentpostamble{\luapostamble}%

\generate{%
  \usedir{tex/luatex/luamplib}%
  \file{luamplib.lua}{\from{luamplib.dtx}{lua}}%
}

\obeyspaces
\Msg{************************************************************************}
\Msg{*}
\Msg{* To finish the installation you have to move the following}
\Msg{* files into a directory searched by TeX:}
\Msg{*}
\Msg{*     luamplib.sty luamplib.lua}
\Msg{*}
\Msg{* Happy TeXing!}
\Msg{*}
\Msg{************************************************************************}

\endbatchfile
%</install>
%<*ignore>
\fi
%</ignore>
%<*driver>
\NeedsTeXFormat{LaTeX2e}
\ProvidesFile{luamplib.drv}%
  [2024/07/19 v2.34.1 Interface for using the mplib library]%
\documentclass{ltxdoc}
\usepackage{metalogo,multicol,mdwlist,fancyvrb,xspace}
\usepackage[x11names]{xcolor}
%
\def\primarycolor{DodgerBlue4}  %%-> rgb  16  78 139 | #104e8b
\def\secondarycolor{Goldenrod4} %%-> rgb 139 105 200 | #8b6914
%
\usepackage[
    bookmarks=true,
   colorlinks=true,
    linkcolor=\primarycolor,
     urlcolor=\secondarycolor,
    citecolor=\primarycolor,
     pdftitle={The luamplib package},
   pdfsubject={Interface for using the mplib library},
    pdfauthor={Hans Hagen, Taco Hoekwater, Elie Roux, Philipp Gesang \& Kim Dohyun},
  pdfkeywords={luatex, lualatex, mplib, metapost}
]{hyperref}
\usepackage{fontspec}
\setmainfont[
  Numbers     = OldStyle,
  Ligatures   = TeX,
  BoldFont    = {Linux Libertine O Bold},
  ItalicFont  = {Linux Libertine O Italic},
  SlantedFont = {Linux Libertine O Italic},
]{Linux Libertine O}
\setmonofont[Scale=MatchLowercase]{InconsolataN}
%setsansfont[Ligatures=TeX]{Linux Biolinum O}
\setsansfont[Ligatures=TeX,Scale=MatchLowercase]{Iwona Medium}
%setmathfont{XITS Math}

\usepackage{hologo}

\newcommand\ConTeXt {Con\TeX t\xspace}

\newcommand*\email [1] {<\href{mailto:#1}{#1}>}
\newcommand \file       {\nolinkurl}
\newcommand \pk         {\textsf}

\begin{document}
  \DocInput{luamplib.dtx}%
\end{document}
%</driver>
% \fi
%
% \CheckSum{0}
%
% \CharacterTable
%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%   Digits        \0\1\2\3\4\5\6\7\8\9
%   Exclamation   \!     Double quote  \"     Hash (number) \#
%   Dollar        \$     Percent       \%     Ampersand     \&
%   Acute accent  \'     Left paren    \(     Right paren   \)
%   Asterisk      \*     Plus          \+     Comma         \,
%   Minus         \-     Point         \.     Solidus       \/
%   Colon         \:     Semicolon     \;     Less than     \<
%   Equals        \=     Greater than  \>     Question mark \?
%   Commercial at \@     Left bracket  \[     Backslash     \\
%   Right bracket \]     Circumflex    \^     Underscore    \_
%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%   Right brace   \}     Tilde         \~}
%
% \title{The \textsf{luamplib} package}
% \author{Hans Hagen, Taco Hoekwater, Elie Roux, Philipp Gesang and Kim Dohyun\\
% Current Maintainer: Kim Dohyun\\
% Support: \url{https://github.com/lualatex/luamplib}}
% \date{2024/07/19 v2.34.1}
%
% \maketitle
%
% \begin{abstract}
% Package to have metapost code typeset directly in a document with \LuaTeX.
% \end{abstract}
%
% \section{Documentation}
%
% This package aims at providing a simple way to typeset directly metapost
% code in a document with \LuaTeX. \LuaTeX\ is built with the Lua
% \textsf{mplib} library, that runs metapost code. This package is basically a
% wrapper for the Lua \textsf{mplib} functions and some \TeX\
% functions to have the output of the \textsf{mplib} functions in the pdf.
%
% Using this package is easy: in Plain, type your metapost code between the
% macros \cs{mplibcode} and \cs{endmplibcode}, and in \LaTeX\ in the
% \texttt{mplibcode} environment.
%
% The resulting metapost figures are put in a \TeX\ \texttt{hbox} with dimensions
% adjusted to the metapost code.
%
% The code of luamplib is basically from the |luatex-mplib.lua| and |luatex-mplib.tex| files
% from \ConTeXt. They have been adapted to \LaTeX\ and Plain by Elie Roux and
% Philipp Gesang and new functionalities have been added by Kim Dohyun.
% The most notable changes are:
%
% \begin{itemize}
% \item possibility to use |btex ... etex| to typeset \TeX\ code.
%   |textext()| is a more versatile macro equivalent to |TEX()| from \textsf{TEX.mp}.
%   |TEX()| is also allowed and is a synonym of |textext()|.
%   The argument of
%   \textsf{mplib}'s primitive |maketext| will also be processed by the same routine.
%
% \item possibility to use |verbatimtex ... etex|, though it's behavior cannot
%   be the same as the stand-alone \textsf{mpost}.
%   Of course you cannot include \cs{documentclass}, \cs{usepackage} etc.
%   When these \TeX\ commands are found in |verbatimtex ... etex|, the entire code will be
%   ignored.
%   The treatment of |verbatimtex| command has changed a lot since v2.20;
%   see below regarding \cs{mpliblegacybehavior}.
%
% \item in the past,
%   the package required PDF mode in order to have some output.
%   Starting with version 2.7 it works in DVI mode as well, though
%   DVIPDFMx is the only DVI tool currently supported.
% \end{itemize}
%
% It seems to be convenient to divide the explanations of some more changes and cautions
% into three parts: \TeX, MetaPost, and Lua interfaces.
%
% \subsection{\TeX}
%
% \paragraph{\cs{mplibforcehmode}}
%   When this macro is declared, every metapost figure box will be
%   typeset in horizontal mode, so \cs{centering}, \cs{raggedleft} etc
%   will have effects. |\mplibnoforcehmode|, being default, reverts this
%   setting. (Actually these commands redefine |\prependtomplibbox|; you
%   can redefine this command with anything suitable before a box.)
%
% \paragraph{\cs{everymplib\{...\}}, \cs{everyendmplib\{...\}}}
%   \cs{everymplib} and \cs{everyendmplib} redefine
%   the lua table containing metapost code
%   which will
%   be automatically inserted at the beginning and ending of each metapost code chunk.
%\begin{verbatim}
%     \everymplib{ beginfig(0); }
%     \everyendmplib{ endfig; }
%     \begin{mplibcode}
%       % beginfig/endfig not needed
%       draw fullcircle scaled 1cm;
%     \end{mplibcode}
%\end{verbatim}
%
% \paragraph{\cs{mplibsetformat\{plain\char"7C metafun\}}}
%   There are (basically) two formats for metapost: \emph{plain} and
%   \emph{metafun}. By default, the \emph{plain} format is used, but you can set
%   the format to be used by future figures at any time using
%   |\mplibsetformat{|\emph{<format name>}|}|.
%
%   \textsc{n.b.} As \emph{metafun} is such a complicated format,
%   we cannot support all the functionalities producing special effects provided by \emph{metafun}.
%   At least, however, transparency (actually opacity), transparency group, and shading (gradient colors)
%   are fully supported,
%   and outlinetext is supported by our own alternative |mpliboutlinetext| (see below \S\,1.2).
%
%   \leavevmode\llap{\textcolor{red}{☞}\kern1.2\parindent}\relax
%   Among these, transparency is so simple that you can apply it to an object,
%   even with the \emph{plain} format,
%   just by appending |withprescript "tr_transparency=|\emph{<number>}|"| to the sentence.
%   ($0 \le \hbox{\emph{<number>}} \le 1$)
%
%   As for transparency group, the current \emph{metafun} document \S\,8.8 is not correct.
%   The true syntax is:
%\begin{verbatim}
%     draw <picture>|<path> asgroup <string>
%\end{verbatim}
%   where \emph{<string>} should be |""| (empty), |"isolated"|, |"knockout"|, or |"isolated,knockout"|.
%   Beware that currently many of the PDF rendering applications, except Adobe Acrobat Reader,
%   cannot properly render the isolated or knockout effect.
%   Transparency group is available with \emph{plain} format as well, with extended functionality.
%   See below \S\,1.2.
%
%   One thing worth mentioning about shading is:
%   when a color expression is given in string type,
%   it is regarded by luamplib as
%   a color expression of \TeX\ side.
%   For instance, when |withshadecolors("orange", 2/3red)| is given, the first color |"orange"| will be
%   interpreted as an \textsf{xcolor}'s or \textsf{l3color}'s expression.
%
% \paragraph{\cs{mplibnumbersystem\{scaled\char"7C double\char"7C decimal\}}}
%   Users can choose |numbersystem| option.
%   The default value is |scaled|, which can be changed
%   by declaring \cs{mplibnumbersystem\{double\}} or
%   \cs{mplibnumbersystem\{decimal\}}.
%
% \paragraph{\cs{mplibshowlog\{enable\char"7C disable\}}}
%   Default: |disable|.
%   When |\mplibshowlog{enable}|\footnote{As for user's setting,
%   |enable|, |true| and |yes| are identical;
%   |disable|, |false| and |no| are identical.} is declared, log messages returned by
%   the metapost process will be printed to the |.log| file.
%   This is the \TeX{} side interface for |luamplib.showlog|.
%
% \paragraph{\cs{mpliblegacybehavior\{enable\char"7C disable\}}}
%   By default, |\mpliblegacybehavior{enable}|
%   is already declared for backward compatibility,
%   in which case \TeX\ code in
%   |verbatimtex| |...| |etex| that comes just before |beginfig()|
%   will be inserted before the
%   following metapost figure box.  In this way,
%   each figure box can be freely moved horizontally or vertically.
%   Also, a box number can be assigned to a figure box, allowing it to be
%   reused later.
%\begin{verbatim}
%     \mplibcode
%     verbatimtex \moveright 3cm etex; beginfig(0); ... endfig;
%     verbatimtex \leavevmode etex; beginfig(1); ... endfig;
%     verbatimtex \leavevmode\lower 1ex etex; beginfig(2); ... endfig;
%     verbatimtex \endgraf\moveright 1cm etex; beginfig(3); ... endfig;
%     \endmplibcode
%\end{verbatim}
%   \textsc{n.b.} \cs{endgraf} should be used instead of \cs{par} inside
%   |verbatimtex ... etex|.
%
%   On the other hand, \TeX\ code in |verbatimtex ... etex|
%   between |beginfig()| and |endfig| will be inserted
%   after flushing out the metapost figure.
%   As shown in the example below, |VerbatimTeX()| is a synonym of |verbatimtex| |...| |etex|.
%\begin{verbatim}
%     \mplibcode
%       D := sqrt(2)**7;
%       beginfig(0);
%       draw fullcircle scaled D;
%       VerbatimTeX("\gdef\Dia{" & decimal D & "}");
%       endfig;
%     \endmplibcode
%     diameter: \Dia bp.
%\end{verbatim}
%
%   By contrast,
%   when |\mpliblegacybehavior{disabled}| is declared, any
%   |verbatimtex| |...| |etex| will be executed, along with |btex| |...| |etex|,
%   sequentially one by one.
%   So, some \TeX\ code in |verbatimtex ... etex| will have effects on
%   following |btex| |...| |etex| codes.
%\begin{verbatim}
%     \begin{mplibcode}
%       beginfig(0);
%       draw btex ABC etex;
%       verbatimtex \bfseries etex;
%       draw btex DEF etex shifted (1cm,0); % bold face
%       draw btex GHI etex shifted (2cm,0); % bold face
%       endfig;
%     \end{mplibcode}
%\end{verbatim}
%
% \paragraph{\cs{mplibtextextlabel\{enable\char"7C disable\}}}
%   Default: |disable|.
%   |\mplibtextextlabel{enable}| enables
%   the labels typeset via |textext| instead of |infont| operator.
%   So, |label("my text",origin)| thereafter is exactly the same as
%   |label(textext("my text"),origin)|.
%
%   \textsc{n.b.} In the background,
%   luamplib redefines |infont| operator so that the right side
%   argument (the font part) is totally ignored. Therefore the left side arguemnt
%   will be typeset with the current \TeX\ font.
%   Also take care of |char| operator in the left side argument,
%   as this might bring unpermitted characters into \TeX.
%
% \paragraph{\cs{mplibcodeinherit\{enable\char"7C disable\}}}
%   Default: |disable|.
%   |\mplibcodeinherit{enable}| enables the inheritance
%   of variables, constants, and macros defined by previous metapost code chunks.
%   On the contrary, |\mplibcodeinherit{disable}| will make
%   each code chunk being treated as an independent instance, never
%   affected by previous code chunks.
%
% \paragraph{Separate MetaPost instances}
%   luamplib v2.22 has added the support for several named metapost instances
%   in \LaTeX{} |mplibcode| environment.
%   Plain \TeX\ users also can use this functionality.
%   The syntax for \LaTeX\ is:
%\begin{verbatim}
%   \begin{mplibcode}[instanceName]
%     % some mp code
%   \end{mplibcode}
%\end{verbatim}
%   The behavior is as follows.
%   \begin{itemize}
%   \item  All the variables and functions are shared
%     only among all the environments belonging to the same instance.
%   \item  \cs{mplibcodeinherit} only affects environments
%     with no instance name set (since if a name is set,
%     the code is intended to be reused at some point).
%   \item |btex ... etex| boxes are also shared and do not
%     require \cs{mplibglobaltextext}.
%   \item  When an instance names is set,
%     respective \cs{currentmpinstancename} is set as well.
%   \end{itemize}
%   In parellel with this functionality, we support
%   optional argument of instance name for \cs{everymplib} and
%   \cs{everyendmplib}, affecting only those |mplibcode| environments
%   of the same name.
%   Unnamed \cs{everymplib} affects not only those instances with no name,
%   but also those with name but with no corresponding \cs{everymplib}.
%   The syntax is:
%\begin{verbatim}
%     \everymplib[instanceName]{...}
%     \everyendmplib[instanceName]{...}
%\end{verbatim}
%
% \paragraph{\cs{mplibglobaltextext\{enable\char"7C disable\}}}
%   Default: |disable|.
%   Formerly, to inherit |btex| |...| |etex| boxes as well as other metapost macros, variables and constants,
%   it was necessary to declare \cs{mplibglobaltextext\{enable\}} in advance.
%   But from v2.27, this is implicitly enabled when \cs{mplibcodeinherit}
%   is enabled.
%   This optional command still remains mostly for backward compatibility.
%\begin{verbatim}
%   \mplibcodeinherit{enable}
%   %\mplibglobaltextext{enable}
%   \everymplib{ beginfig(0);} \everyendmplib{ endfig;}
%   \mplibcode
%     label(btex $\sqrt{2}$ etex, origin);
%     draw fullcircle scaled 20;
%     picture pic; pic := currentpicture;
%   \endmplibcode
%   \mplibcode
%     currentpicture := pic scaled 2;
%   \endmplibcode
%\end{verbatim}
%
% \paragraph{\cs{mplibverbatim\{enable\char"7C disable\}}}
%   Default: |disable|.
%   Users can issue |\mplibverbatim{enable}|, after which
%   the contents of mplibcode environment will be read verbatim. As a result,
%   except for |\mpdim| and |\mpcolor| (see below), all other \TeX\ commands outside of the
%   |btex| or |verbatimtex| |...| |etex| are not expanded and will be fed
%   literally to the \textsf{mplib} library.
%
% \paragraph{\cs{mpdim\{...\}}}
%   Besides other \TeX\ commands, \cs{mpdim} is specially allowed
%   in the mplibcode environment. This feature is inpired by \textsf{gmp} package authored by
%   Enrico Gregorio. Please refer to the manual of \textsf{gmp} package for details.
%\begin{verbatim}
%     \begin{mplibcode}
%       beginfig(1)
%       draw origin--(.6\mpdim{\linewidth},0) withpen pencircle scaled 4
%       dashed evenly scaled 4 withcolor \mpcolor{orange};
%       endfig;
%     \end{mplibcode}
%\end{verbatim}
%
% \paragraph{\cs{mpcolor[...]\{...\}}}
%   With \cs{mpcolor} command, color names or expressions of
%   \textsf{color}, \textsf{xcolor} and \textsf{l3color} module/packages can be used in the mplibcode
%   enviroment (after |withcolor| operator).
%   See the example above.
%   The optional |[...]| means the option of \textsf{xcolor}'s \cs{color} command.
%   For spot colors, \textsf{l3color} (in PDF/DVI mode),
%   \textsf{colorspace}, \textsf{spotcolor}
%   (in PDF mode) and \textsf{xespotcolor} (in DVI mode) packages are supported
%   as well.
%
% \paragraph{\cs{mpfig} \ldots\ \cs{endmpfig}}
%   Besides the |mplibcode| environment (for \LaTeX) and
%   \cs{mplibcode ...} \cs{endmplibcode} (for Plain),
%   we also provide unexpandable \TeX\ macros |\mpfig ... \endmpfig| and its starred version
%   |\mpfig* ... \endmpfig| to save typing toil.
%   The former is roughly the same as follows:
%\begin{verbatim}
%     \begin{mplibcode}[@mpfig]
%     beginfig(0)
%     token list declared by \everymplib[@mpfig]
%     ...
%     token list declared by \everyendmplib[@mpfig]
%     endfig;
%     \end{mplibcode}
%\end{verbatim}
%   and the starred version is roughly the same as follows:
%\begin{verbatim}
%     \begin{mplibcode}[@mpfig]
%     ...
%     \end{mplibcode}
%\end{verbatim}
%   In these macros |\mpliblegacybehavior{disable}|
%   is forcibly declared.
%   Again, as both share the same instance name, metapost codes are inherited among them.
%   A simple example:
%\begin{verbatim}
%     \everymplib[@mpfig]{ drawoptions(withcolor .5[red,white]); }
%     \mpfig* input boxes \endmpfig
%     \mpfig
%       circleit.a(btex Box 1 etex); drawboxed(a);
%     \endmpfig
%\end{verbatim}
%   The instance name (default: |@mpfig|) can be changed by redefining
%   \cs{mpfiginstancename}, after which a new mplib instance will start and
%   code inheritance too will begin anew.  |\let\mpfiginstancename\empty| will
%   prevent code inheritance if |\mplibcodeinherit{true}| is not declared.
%
% \paragraph{About cache files}
%   To support |btex ... etex| in external |.mp| files, luamplib
%   inspects the content of each and every |.mp| file and makes caches
%   if nececcsary, before returning their paths to \LuaTeX's \textsf{mplib} library.
%   This could waste the compilation time, as most |.mp| files
%   do not contain |btex ... etex| commands.  So luamplib provides
%   macros as follows, so that users can give instructions about files
%   that do not require this functionality.
%   \begin{itemize}
%   \item |\mplibmakenocache{<filename>[,<filename>,...]}|
%   \item |\mplibcancelnocache{<filename>[,<filename>,...]}|
%   \end{itemize}
%   where |<filename>| is a filename excluding |.mp| extension.
%   Note that |.mp| files under |$TEXMFMAIN/metapost/base| and
%   |$TEXMFMAIN/metapost/context/base| are already registered by default.
%
%   By default, cache files will be stored in |$TEXMFVAR/luamplib_cache| or,
%   if it's not available (mostly not writable),
%   in the directory where output files are saved:
%   to be specific, |$TEXMF_OUTPUT_DIRECTORY/luamplib_cache|,
%   |./luamplib_cache|, |$TEXMFOUTPUT/luamplib_cache|, and |.|, in this order.
%   |$TEXMF_OUTPUT_DIRECTORY| is normally the value of |--output-directory|
%   command-line option.
%
%   Users can change this behavior by the command
%   |\mplibcachedir{<directory path>}|, where tilde (|~|) is interpreted
%   as the user's home directory (on a windows machine as well).
%   As backslashes (|\|) should be escaped by users, it would be easier to use
%   slashes (|/|) instead.
%
% \paragraph{About figure box metric}
%   Notice that, after each figure is processed, the macro \cs{MPwidth} stores
%   the width value of the latest figure; \cs{MPheight}, the height value.
%   Incidentally, also note that \cs{MPllx}, \cs{MPlly}, \cs{MPurx}, and
%   \cs{MPury} store the bounding box information of the latest figure
%   without the unit |bp|.
%
% \paragraph{luamplib.cfg}
%   At the end of package loading, luamplib searches
%   |luamplib.cfg| and, if found, reads the file in automatically.
%   Frequently used settings such as \cs{everymplib}, \cs{mplibforcehmode}
%   or \cs{mplibcodeinherit} are suitable for going into this file.
%
% \subsection{MetaPost}
%
% \paragraph{\texttt{mplibdimen(...)}, \texttt{mplibcolor(...)}}
%   These are MetaPost interfaces for the \TeX\ commands \cs{mpdim} and \cs{mpcolor}. For example,
%   |mplibdimen("\linewidth")| is basically the same as |\mpdim{\linewidth}|, and
%   |mplibcolor("red!50")| is basically the same as |\mpcolor{red!50}|.
%   The difference is that these metapost operators can also be used in external |.mp| files,
%   which cannot have \TeX\ commands outside of the |btex| or |verbatimtex| |...| |etex|.
%
% \paragraph{\texttt{mplibtexcolor ...}, \texttt{mplibrgbtexcolor ...}}
%   |mplibtexcolor|, which accepts a string argument, is a metapost operator that converts a \TeX\ color expression
%   to a MetaPost color expression, that can be used anywhere color expression is expected
%   as well as after the |withcolor| operator.
%   For instance:
%\begin{verbatim}
%     color col;
%     col := mplibtexcolor "olive!50";
%\end{verbatim}
%   But the result may vary in its color model (gray/rgb/cmyk)
%   according to the given \TeX\ color. (Spot colors are forced to
%   cmyk model, so this operator is not recommended for spot colors.)
%   Therefore the example shown above would raise a metapost error:
%   |cmykcolor col;| should have been declared.
%   By contrast, |mplibrgbtexcolor| \emph{<string>} always returns rgb model expressions.
%
% \paragraph{\texttt{mplibgraphictext ...}}
%   |mplibgraphictext| is a metapost operator, the effect of which is similar to that of
%   \ConTeXt's |graphictext| or our own |mpliboutlinetext| (see below).
%   However the syntax is somewhat different.
%\begin{verbatim}
%     mplibgraphictext "Funny"
%       fakebold 2.3                        % fontspec option
%       drawcolor .7blue fillcolor "red!50" % color expressions
%\end{verbatim}
%   |fakebold|, |drawcolor| and |fillcolor| are optional;
%   default values are |2|, |"black"| and |"white"| respectively.
%   When the color expressions are given in string type, they are regarded as
%   \textsf{xcolor}'s or \textsf{l3color}'s expressions.
%   All from |mplibgraphictext| to the end of sentence will compose an
%   anonymous |picture|, which can be drawn or assigned to a variable.
%   Incidentally, |withdrawcolor| and |withfillcolor| are synonyms of
%   |drawcolor| and |fillcolor|, hopefully to be compatible with |graphictext|.
%
%   \textsc{n.b.}
%   In some cases, |mplibgraphictext| will produce better results than \ConTeXt\
%   or even than our own |mpliboutlinetext|,
%   especially when processing complicated \TeX\ code
%   such as the vertical writing in Chinese or Japanese.
%   However, because the implementation is quite different from others,
%   there are some limitations such that you can't
%   apply shading (gradient colors) to the text. Again,
%   in DVI mode, \textsf{unicode-math} package is needed for math formula,
%   as we cannot embolden type1 fonts in DVI mode.
%
%   \paragraph{\texttt{mplibglyph ... of ...}}
%   From v2.30, we provide a new metapost operator |mplibglyph|, which returns a metapost picture
%   containing outline paths of a glyph in opentype, truetype or type1 fonts.
%   When a type1 font is specified, metapost primitive |glyph| will be called.
%\begin{verbatim}
%      mplibglyph 50  of \fontid\font          % slot 50 of current font
%      mplibglyph "Q" of "TU/TeXGyrePagella(0)/m/n/10"    % font csname
%      mplibglyph "Q" of "texgyrepagella-regular.otf"     % raw filename
%      mplibglyph "Q" of "Times.ttc(2)"                   % subfont number
%      mplibglyph "Q" of "SourceHanSansK-VF.otf[Regular]" % instance name
%\end{verbatim}
%   Both arguments before and after of ``|of|'' can be either a number or a string.
%   Number arguments are regarded as a glyph slot (GID) and a font id number, repectively.
%   String argument at the left side is regarded as a glyph name in the font or a unicode character.
%   String argument at the right side is regarded as a \TeX\ font csname (without backslash) or
%   the raw filename of a font. When it is a font filename, a number within parentheses
%   after the filename denotes a
%   subfont number (starting from zero) of a TTC font; a string within brackets denotes
%   an instance name of a variable font.
%
%   \paragraph{\texttt{mplibdrawglyph ...}}
%   The picture returned by |mplibglyph| will be quite similar to the result of |glyph| primitive in its structure.
%   So, metapost's |draw| command will fill the inner path of the picture with the background color.
%   In contrast, |mplibdrawglyph| \emph{<picture>} command fills the paths according to the nonzero winding
%   number rule. As a result, for instance, the area surrounded by inner path of ``O''
%   will remain transparent.
%
%   \leavevmode\llap{\textcolor{red}{☞}\kern1.2\parindent}\relax
%   To apply the nonzero winding number rule to a picture containg paths,
%   luamplib appends |withpostscript| |"collect"|
%   to the paths except the last one in the picture.
%   If you want the even-odd rule instead, you can, even with \emph{plain} format,
%   additionally declare |withpostscript| |"evenodd"| to the last path in the picture.
%
% \paragraph{\texttt{mpliboutlinetext (...)}}
%   From v2.31, a new metapost operator |mpliboutlinetext| is available, which mimicks
%   metafun's |outlinetext|. So the syntax is the same as metafun's. See the metafun
%   manual \S\,8.7 (|texdoc metafun|). A simple example:
%\begin{verbatim}
%     draw mpliboutlinetext.b ("$\sqrt{2+\alpha}$")
%         (withcolor \mpcolor{red!50})
%         (withpen pencircle scaled .2 withcolor red)
%         scaled 2 ;
%\end{verbatim}
%   After the process, |mpliboutlinepic[]|
%   and |mpliboutlinenum| will be preserved as global variables;
%   |mpliboutlinepic[1]| \ldots{} |mpliboutlinepic[mpliboutlinenum]|
%   will be an array of images each of which containing a glyph or a rule.
%
%   \textsc{n.b.} As Unicode grapheme cluster is not considered in the array, a unit that must be
%   a single cluster might be separated apart.
%
% \paragraph{\cs{mppattern\{...\}} \texttt{...} \cs{endmppattern}, \texttt{... withpattern ...}}
%   \TeX\ macros
%   |\mppattern{<name>}| \ldots\ |\endmppattern| define a tiling pattern
%   associated with the |<name>|.
%   MetaPost operator |withpattern|, the syntax being
%   \emph{<path>} |withpattern| \emph{<string>}, will return a metapost picture which fills
%   the given path with a tiling pattern of the |<name>|
%   by replicating it horizontally and vertically.
%   An example:
%\begin{verbatim}
%     \mppattern{mypatt}           % or \begin{mppattern}{mypatt}
%       [                          % options: see below
%         xstep = 10, ystep = 12,
%         matrix = {0,1,-1,0},     % or "0 1 -1 0"
%       ]
%       \mpfig                     % or any other TeX code,
%         picture q;
%         q := btex Q etex;
%         fill bbox q withcolor .8[red,white];
%         draw q withcolor .8red;
%       \endmpfig
%     \endmppattern                % or \end{mppattern}
%
%     \mpfig
%       fill fullcircle scaled 100
%         withpostscript "collect" ;
%       draw unitsquare shifted - center unitsquare scaled 45
%         withpattern "mypatt"
%         withpostscript "evenodd" ;
%     \endmpfig
%\end{verbatim}
%
%   The available options are listed in Table~\ref{tab:mppatternoptions}.
%   \begin{table}
%   \centering
%   \caption{options for \cs{mppattern}}\label{tab:mppatternoptions}
%   \begin{tabular}{lll}\hline
%     Key   & Value Type & Explanation\\\hline
%     |xstep|    &\emph{number} & horizontal spacing between pattern cells\\
%     |ystep|    &\emph{number} & vertical spacing between pattern cells\\
%     |xshift|   &\emph{number} & horizontal shifting of pattern cells\\
%     |yshift|   &\emph{number} & vertical shifting of pattern cells\\
%     |matrix|   &\emph{table} or \emph{string} & |xx|, |yx|, |xy|, |yy| values\kern1pt* or MP transform code\\
%     |bbox|     &\emph{table} or \emph{string} & |llx|, |lly|, |urx|, |ury| values\kern1pt*\\
%     |resources|&\emph{string} & PDF resources if needed\\
%     |colored| or |coloured| &\emph{boolean}& |false| for uncolored pattern. default: |true|\\\hline
%                &                & \small *\,in string type, numbers are separated by spaces\\
%   \end{tabular}
%   \end{table}
%
%   For the sake of convenience, the width and height values of tiling patterns will be written down
%   into the log file. (depth is always zero.) Users can refer to them for option setting.
%
%   As for |matrix| option, metapost code such as `|rotated 30 slanted .2|' is allowed as well
%   as string or table of four numbers. You can also set |xshift| and |yshift|
%   values by using `|shifted|' operator. But when |xshift| or |yshift| option is explicitly
%   given, they have precedence over the effect of `|shifted|' operator.
%
%   When you use special effects such as transparency in a pattern,
%   |resources| option is needed: for instance, |resources="/ExtGState 1 0 R"|.
%   However, as luamplib automatically includes the resources of the current page, this option
%   is not needed in most cases.
%
%   Option |colored=false| (|coloured| is a synonym of |colored|) will generate an uncolored pattern which shall have no color at all.
%   Uncolored pattern will be painted later by the color of a metapost object.
%   An example:
%\begin{verbatim}
%      \begin{mppattern}{pattuncolored}
%        [
%          colored = false,
%          matrix = "slanted .3 rotated 30",
%        ]
%        \tiny\TeX
%      \end{mppattern}
%
%      \begin{mplibcode}
%        beginfig(1)
%        picture tex;
%        tex = mpliboutlinetext.p ("\bfseries \TeX");
%        for i=1 upto mpliboutlinenum:
%          j:=0;
%          for item within mpliboutlinepic[i]:
%            j:=j+1;
%            draw pathpart item scaled 10
%            if j < length mpliboutlinepic[i]:
%                withpostscript "collect"
%            else:
%                withpattern "pattuncolored"
%                withpen pencircle scaled 1/2
%                withcolor (i/4)[red,blue]          % paints the pattern
%            fi;
%          endfor
%        endfor
%        endfig;
%      \end{mplibcode}
%\end{verbatim}
%
% \paragraph{\texttt{... withfademethod ...}, and related macros}
%   |withfademethod| is a metapost operator which makes the color of an object gradiently transparent.
%   The syntax is \emph{<path>}\texttt{\char"7C}\emph{<picture>} |withfademethod| \emph{<string>},
%   the latter being either |"linear"| or |"circular"|.
%   Though it is similar to the |withshademethod| provided by metafun,
%   the differences are: (1) the operand of |withfademethod| can be a picture as well as a path;
%   (2) you cannot make gradient colors, but can only make gradient opacity.
%
%   Related macros to control optional values are:
%   \begin{description}
%     \let\bfseries\relax
%   \item [|withfadeopacity (|\emph{number, number}|)|]
%     sets the starting opacity and the ending opacity, default value being |(1,0)|.
%     `|1|' denotes full color; `|0|' full transparency.
%   \item [|withfadevector (|\emph{pair, pair}|)|]
%     sets the starting and ending points. Default value in the linear mode is
%     |(llcorner p, lrcorner p)|, where |p| is the operand,
%     meaning that fading starts from the left edge and ends at the right edge.
%     Default value in the circular mode is |(center p, center p)|, which means
%     centers of both starting and ending circles are the center of the bounding box.
%   \item [|withfadecenter|] is a synonym of |withfadevector|.
%   \item [|withfaderadius (|\emph{number, number}|)|]
%     sets the radii of starting and ending circles. This is no-op in the linear mode.
%     Default value is |(0, abs(center p - urcorner p))|, meaning that fading starts from the
%     center and ends at the four corners of the bounding box.
%   \item [|withfadebbox (|\emph{pair, pair}|)|]
%     sets the bounding box of the fading area, default value being |(llcorner p, urcorner p)|.
%     Though this option is not needed in most cases, there could be cases when users want to
%     explicitly control the bounding box.
%   \end{description}
%   An example:
%\begin{verbatim}
%     \mpfig
%       picture mill;
%       mill = btex \includegraphics[width=100bp]{mill} etex;
%       draw mill
%         withfademethod  "circular"
%         withfadecenter  (center mill, center mill)
%         withfaderadius  (20, 50)
%         withfadeopacity (1, 0)
%         ;
%     \endmpfig
%\end{verbatim}
%
% \paragraph{Transparency Group}
% As said before,
% transparency group is available with \emph{plain} as well as \emph{metafun} format.
% The syntax is exactly the same:
% \emph{<picture>} \char"7C\ \emph{<path>} |asgroup|
% |""| \char"7C\ |"isolated"| \char"7C\ |"knockout"| \char"7C\ |"isolated,knockout"|,
% which will return a metapost picture.
%
% The additional feature provided by luamplib is that
% you can reuse the group as many times as you want
% in the \TeX{} code or in other MetaPost code chunks,
% with infinitesimal increase in the size of PDF file.
% For this functionality we provide \TeX{} and MetaPost macros as follows:
% \begin{description}
%   \let\bfseries\relax
% \item[|withgroupname| \emph{<string>}] associates a transparency group with the given name.
%   When this is not appended to the sentense with |asgroup| operator,
%   the default group name `|lastmplibgroup|' will be used.
%
% \item[\cs{usemplibgroup\{...\}}] is a \TeX\ command to reuse a transparency group of the name
%   once used.
%   Note that the position of the group will be origin-based:
%   in other words, lower-left corner of the group will be shifted to the origin.
%
% \item[|usemplibgroup| \emph{<string>}] is a MetaPost command which will add
%   a transparency group of the name to the |currentpicture|.
%   Contrary to the \TeX\ command just mentioned,
%   the position of the group is the same as the original transparency group.
% \end{description}
% An example showing the difference between the \TeX\ and MetaPost commands:
%\begin{verbatim}
%   \mpfig
%     draw image(
%       fill fullcircle scaled 100 shifted 25right withcolor .5[blue,white];
%       fill fullcircle scaled 100 withcolor .5[red,white] ;
%     ) asgroup "" withgroupname "mygroup";
%     draw (left--right) scaled 10;
%     draw (up--down) scaled 10;
%   \endmpfig
%
%   \noindent
%   \llap{\vrule width 10pt height .25pt depth .25pt}%
%   \clap{\vrule width .5pt height 10pt depth 10pt}%
%   \rlap{\vrule width 10pt height .25pt depth .25pt}%
%   \usemplibgroup{mygroup}
%
%   \mpfig
%     usemplibgroup "mygroup" rotated 15;
%     draw (left--right) scaled 10;
%     draw (up--down) scaled 10;
%   \endmpfig
%\end{verbatim}
% Also note that reused transparency groups are not affected by color commands,
% transparency/fading commands will have effects though.
%
% \subsection{Lua}
%
% \paragraph{\texttt{runscript ...}}
%   Using the primitive |runscript| \emph{<string>}, you can run a Lua code chunk from MetaPost side
%   and get some metapost code returned by Lua if you want.
%   As the functionality is provided by the \textsf{mplib} library itself,
%   luamplib does not have much to say about it.
%
%   One thing is worth mentioning, however:
%   if you return a Lua \emph{table} to the metapost process,
%   it is automatically converted to a relevant metapost value type
%   such as pair, color, cmykcolor or transform.
%   So users can save some extra toil of converting a table to a string, though it's not a big deal.
%   For instance, |runscript "return {1,0,0}"| will give you the metapost color expression |(1,0,0)|
%   automatically.
%
% \paragraph{Lua table \texttt{luamplib.instances}}
%   Users can access the Lua table containing mplib instances, |luamplib.instances|,
%   through which metapost variables are also easily accessible from Lua side,
%   as documented in Lua\TeX{} manual \S\,11.2.8.4 (|texdoc luatex|).
%   The following will print |false|, |3.0|, |MetaPost| and
%   the knots and the cyclicity of the path |unitsquare|, consecutively.
%\begin{verbatim}
%   \begin{mplibcode}[instance1]
%     boolean b; b = 1 > 2;
%     numeric n; n = 3;
%     string s; s = "MetaPost";
%     path p; p = unitsquare;
%   \end{mplibcode}
%
%   \directlua{
%     local instance1 = luamplib.instances.instance1
%     print( instance1:get_boolean "b" )
%     print( instance1:get_number  "n" )
%     print( instance1:get_string  "s" )
%     local t = instance1:get_path "p"
%     for k,v in pairs(t) do
%       print(k, type(v)=='table' and table.concat(v,' ') or v)
%     end
%   }
%\end{verbatim}
%
% \paragraph{Lua function \texttt{luamplib.process\_mplibcode}}
%   Users can execute a MetaPost code chunk from Lua side by using this function:
%\begin{verbatim}
%     luamplib.process_mplibcode (<string> metapost code, <string> instance name)
%\end{verbatim}
%   The second argument cannot be absent, but can be an empty string (|""|) which
%   means that it has no instance name.
%
%   Some other elements in the |luamplib| namespace, listed in Table~\ref{tab:elementsinluamplib},
%   can have effects on the process of |process_mplibcode|.
%   \begin{table}
%     \centering
%     \caption{elements in \texttt{luamplib} table (partial)}\label{tab:elementsinluamplib}
%   \begin{tabular}{lll}\hline
%     Key & Type & Related \TeX\ macro \\\hline
%     |codeinherit|	& \emph{boolean} & \cs{mplibcodeinherit}\\
%     |everyendmplib|	& \emph{table} & \cs{everyendmplib}\\
%     |everymplib| & \emph{table} & \cs{everymplib}\\
%     |getcachedir|	& \emph{function} (\emph{<string>}) & \cs{mplibcachedir}\\
%     |globaltextext|	& \emph{boolean} & \cs{mplibglobaltextext}\\
%     |legacyverbatimtex| & \emph{boolean} & \cs{mpliblegacybehavior}\\
%     |noneedtoreplace|	& \emph{table} & \cs{mplibmakenocache}\\
%     |numbersystem|	& \emph{string} & \cs{mplibnumbersystem}\\
%     |setformat|	& \emph{function} (\emph{<string>}) & \cs{mplibsetformat}\\
%     |showlog|	& \emph{boolean} & \cs{mplibshowlog}\\
%     |textextlabel| & \emph{boolean} & \cs{mplibtextextlabel}\\
%     |verbatiminput| & \emph{boolean} & \cs{mplibverbatim}\\\hline
%   \end{tabular}
%   \end{table}
%
%
%    \section{Implementation}
%
%    \subsection{Lua module}
%
% \iffalse
%<*lua>
% \fi
%
%    \begin{macrocode}

luatexbase.provides_module {
  name          = "luamplib",
  version       = "2.34.1",
  date          = "2024/07/19",
  description   = "Lua package to typeset Metapost with LuaTeX's MPLib.",
}

%    \end{macrocode}
%
%    Use the |luamplib| namespace, since |mplib| is for the metapost library
%    itself. \ConTeXt{} uses |metapost|.
%    \begin{macrocode}
luamplib          = luamplib or { }
local luamplib    = luamplib

local format, abs = string.format, math.abs

%    \end{macrocode}
%
%    Use our own function for warn/info/err.
%    \begin{macrocode}
local function termorlog (target, text, kind)
  if text then
    local mod, write, append = "luamplib", texio.write_nl, texio.write
    kind = kind
        or target == "term" and "Warning (more info in the log)"
        or target == "log" and "Info"
        or target == "term and log" and "Warning"
        or "Error"
    target = kind == "Error" and "term and log" or target
    local t = text:explode"\n+"
    write(target, format("Module %s %s:", mod, kind))
    if #t == 1 then
      append(target, format(" %s", t[1]))
    else
      for _,line in ipairs(t) do
        write(target, line)
      end
      write(target, format("(%s)     ", mod))
    end
    append(target, format(" on input line %s", tex.inputlineno))
    write(target, "")
    if kind == "Error" then error() end
  end
end

local function warn (...) -- beware '%' symbol
  termorlog("term and log", select("#",...) > 1 and format(...) or ...)
end
local function info (...)
  termorlog("log", select("#",...) > 1 and format(...) or ...)
end
local function err (...)
  termorlog("error", select("#",...) > 1 and format(...) or ...)
end

luamplib.showlog  = luamplib.showlog or false

%    \end{macrocode}
%
%    This module is a stripped down version of libraries that are used by
%    \ConTeXt. Provide a few ``shortcuts'' expected by the imported code.
%    \begin{macrocode}
local tableconcat = table.concat
local tableinsert = table.insert
local tableunpack = table.unpack
local texsprint   = tex.sprint
local texgettoks  = tex.gettoks
local texgetbox   = tex.getbox
local texruntoks  = tex.runtoks

if not texruntoks then
  err("Your LuaTeX version is too old. Please upgrade it to the latest")
end

local is_defined  = token.is_defined
local get_macro   = token.get_macro

local mplib = require ('mplib')
local kpse  = require ('kpse')
local lfs   = require ('lfs')

local lfsattributes = lfs.attributes
local lfsisdir      = lfs.isdir
local lfsmkdir      = lfs.mkdir
local lfstouch      = lfs.touch
local ioopen        = io.open

%    \end{macrocode}
%
%    Some helper functions, prepared for the case when |l-file| etc
%    is not loaded.
%    \begin{macrocode}
local file = file or { }
local replacesuffix = file.replacesuffix or function(filename, suffix)
  return (filename:gsub("%.[%a%d]+$","")) .. "." .. suffix
end

local is_writable = file.is_writable or function(name)
  if lfsisdir(name) then
    name = name .. "/_luam_plib_temp_file_"
    local fh = ioopen(name,"w")
    if fh then
      fh:close(); os.remove(name)
      return true
    end
  end
end
local mk_full_path = lfs.mkdirp or lfs.mkdirs or function(path)
  local full = ""
  for sub in path:gmatch("(/*[^\\/]+)") do
    full = full .. sub
    lfsmkdir(full)
  end
end

%    \end{macrocode}
%
%    |btex ... etex| in input |.mp| files will be replaced in finder.
%    Because of the limitation of MPLib regarding |make_text|,
%    we might have to make cache files modified from input files.
%    \begin{macrocode}
local luamplibtime = kpse.find_file("luamplib.lua")
luamplibtime = luamplibtime and lfsattributes(luamplibtime,"modification")

local currenttime = os.time()

local outputdir, cachedir
if lfstouch then
  for i,v in ipairs{'TEXMFVAR','TEXMF_OUTPUT_DIRECTORY','.','TEXMFOUTPUT'} do
    local var = i == 3 and v or kpse.var_value(v)
    if var and var ~= "" then
      for _,vv in next, var:explode(os.type == "unix" and ":" or ";") do
        local dir = format("%s/%s",vv,"luamplib_cache")
        if not lfsisdir(dir) then
          mk_full_path(dir)
        end
        if is_writable(dir) then
          outputdir = dir
          break
        end
      end
      if outputdir then break end
    end
  end
end
outputdir = outputdir or '.'
function luamplib.getcachedir(dir)
  dir = dir:gsub("##","#")
  dir = dir:gsub("^~",
    os.type == "windows" and os.getenv("UserProfile") or os.getenv("HOME"))
  if lfstouch and dir then
    if lfsisdir(dir) then
      if is_writable(dir) then
        cachedir = dir
      else
        warn("Directory '%s' is not writable!", dir)
      end
    else
      warn("Directory '%s' does not exist!", dir)
    end
  end
end

%    \end{macrocode}
%
%    Some basic MetaPost files not necessary to make cache files.
%    \begin{macrocode}
local noneedtoreplace = {
  ["boxes.mp"] = true, --  ["format.mp"] = true,
  ["graph.mp"] = true, ["marith.mp"] = true, ["mfplain.mp"] = true,
  ["mpost.mp"] = true, ["plain.mp"] = true, ["rboxes.mp"] = true,
  ["sarith.mp"] = true, ["string.mp"] = true, -- ["TEX.mp"] = true,
  ["metafun.mp"] = true, ["metafun.mpiv"] = true, ["mp-abck.mpiv"] = true,
  ["mp-apos.mpiv"] = true, ["mp-asnc.mpiv"] = true, ["mp-bare.mpiv"] = true,
  ["mp-base.mpiv"] = true, ["mp-blob.mpiv"] = true, ["mp-butt.mpiv"] = true,
  ["mp-char.mpiv"] = true, ["mp-chem.mpiv"] = true, ["mp-core.mpiv"] = true,
  ["mp-crop.mpiv"] = true, ["mp-figs.mpiv"] = true, ["mp-form.mpiv"] = true,
  ["mp-func.mpiv"] = true, ["mp-grap.mpiv"] = true, ["mp-grid.mpiv"] = true,
  ["mp-grph.mpiv"] = true, ["mp-idea.mpiv"] = true, ["mp-luas.mpiv"] = true,
  ["mp-mlib.mpiv"] = true, ["mp-node.mpiv"] = true, ["mp-page.mpiv"] = true,
  ["mp-shap.mpiv"] = true, ["mp-step.mpiv"] = true, ["mp-text.mpiv"] = true,
  ["mp-tool.mpiv"] = true, ["mp-cont.mpiv"] = true,
}
luamplib.noneedtoreplace = noneedtoreplace

%    \end{macrocode}
%
%    |format.mp| is much complicated, so specially treated.
%    \begin{macrocode}
local function replaceformatmp(file,newfile,ofmodify)
  local fh = ioopen(file,"r")
  if not fh then return file end
  local data = fh:read("*all"); fh:close()
  fh = ioopen(newfile,"w")
  if not fh then return file end
  fh:write(
    "let normalinfont = infont;\n",
    "primarydef str infont name = rawtextext(str) enddef;\n",
    data,
    "vardef Fmant_(expr x) = rawtextext(decimal abs x) enddef;\n",
    "vardef Fexp_(expr x) = rawtextext(\"$^{\"&decimal x&\"}$\") enddef;\n",
    "let infont = normalinfont;\n"
  ); fh:close()
  lfstouch(newfile,currenttime,ofmodify)
  return newfile
end

%    \end{macrocode}
%
%    Replace |btex ... etex| and |verbatimtex ... etex| in input files,
%    if needed.
%    \begin{macrocode}
local name_b = "%f[%a_]"
local name_e = "%f[^%a_]"
local btex_etex = name_b.."btex"..name_e.."%s*(.-)%s*"..name_b.."etex"..name_e
local verbatimtex_etex = name_b.."verbatimtex"..name_e.."%s*(.-)%s*"..name_b.."etex"..name_e

local function replaceinputmpfile (name,file)
  local ofmodify = lfsattributes(file,"modification")
  if not ofmodify then return file end
  local newfile = name:gsub("%W","_")
  newfile = format("%s/luamplib_input_%s", cachedir or outputdir, newfile)
  if newfile and luamplibtime then
    local nf = lfsattributes(newfile)
    if nf and nf.mode == "file" and
      ofmodify == nf.modification and luamplibtime < nf.access then
      return nf.size == 0 and file or newfile
    end
  end

  if name == "format.mp" then return replaceformatmp(file,newfile,ofmodify) end

  local fh = ioopen(file,"r")
  if not fh then return file end
  local data = fh:read("*all"); fh:close()

%    \end{macrocode}
%    ``|etex|'' must be preceded by a space and followed by a space or semicolon as specified in
%    \LuaTeX\ manual, which is not the case of standalone MetaPost though.
%    \begin{macrocode}
  local count,cnt = 0,0
  data, cnt = data:gsub(btex_etex, "btex %1 etex ") -- space
  count = count + cnt
  data, cnt = data:gsub(verbatimtex_etex, "verbatimtex %1 etex;") -- semicolon
  count = count + cnt

  if count == 0 then
    noneedtoreplace[name] = true
    fh = ioopen(newfile,"w");
    if fh then
      fh:close()
      lfstouch(newfile,currenttime,ofmodify)
    end
    return file
  end

  fh = ioopen(newfile,"w")
  if not fh then return file end
  fh:write(data); fh:close()
  lfstouch(newfile,currenttime,ofmodify)
  return newfile
end

%    \end{macrocode}
%
%    As the finder function for MPLib, use the |kpse| library and
%    make it behave like as if MetaPost was used. And replace it with
%    cache files if needed.
%    See also \#74, \#97.
%    \begin{macrocode}
local mpkpse
do
  local exe = 0
  while arg[exe-1] do
    exe = exe-1
  end
  mpkpse = kpse.new(arg[exe], "mpost")
end

local special_ftype = {
  pfb = "type1 fonts",
  enc = "enc files",
}

function luamplib.finder (name, mode, ftype)
  if mode == "w" then
    if name and name ~= "mpout.log" then
      kpse.record_output_file(name) -- recorder
    end
    return name
  else
    ftype = special_ftype[ftype] or ftype
    local file = mpkpse:find_file(name,ftype)
    if file then
      if lfstouch and ftype == "mp" and not noneedtoreplace[name] then
        file = replaceinputmpfile(name,file)
      end
    else
      file = mpkpse:find_file(name, name:match("%a+$"))
    end
    if file then
      kpse.record_input_file(file) -- recorder
    end
    return file
  end
end

%    \end{macrocode}
%
%    Create and load MPLib instances.
%    We do not support ancient version of MPLib any more.
%    (Don't know which version of MPLib started to support
%    |make_text| and |run_script|; let the users find it.)
%    \begin{macrocode}
local preamble = [[
  boolean mplib ; mplib := true ;
  let dump = endinput ;
  let normalfontsize = fontsize;
  input %s ;
]]

%    \end{macrocode}
%
%    |plain| or |metafun|,
%    though we cannot support |metafun| format fully.
%    \begin{macrocode}
local currentformat = "plain"
function luamplib.setformat (name)
  currentformat = name
end

%    \end{macrocode}
%
%    v2.9 has introduced the concept of ``code inherit''
%    \begin{macrocode}
luamplib.codeinherit = false
local mplibinstances = {}
luamplib.instances = mplibinstances
local has_instancename = false

local function reporterror (result, prevlog)
  if not result then
    err("no result object returned")
  else
    local t, e, l = result.term, result.error, result.log
%    \end{macrocode}
%    log has more information than term, so log first (2021/08/02)
%    \begin{macrocode}
    local log = l or t or "no-term"
    log = log:gsub("%(Please type a command or say `end'%)",""):gsub("\n+","\n")
    if result.status > 0 then
      local first = log:match"(.-\n! .-)\n! "
      if first then
        termorlog("term", first)
        termorlog("log", log, "Warning")
      else
        warn(log)
      end
      if result.status > 1 then
        err(e or "see above messages")
      end
    elseif prevlog then
      log = prevlog..log
%    \end{macrocode}
%    v2.6.1: now luamplib does not disregard |show| command,
%    even when |luamplib.showlog| is false.  Incidentally,
%    it does not raise error nor prints an info,
%    even if output has no figure.
%    \begin{macrocode}
      local show = log:match"\n>>? .+"
      if show then
        termorlog("term", show, "Info (more info in the log)")
        info(log)
      elseif luamplib.showlog and log:find"%g" then
        info(log)
      end
    end
    return log
  end
end

%    \end{macrocode}
%
%     |lualibs-os.lua| installs a randomseed. When this file is not loaded,
%     we should explicitly seed a unique integer to get random randomseed for each run.
%    \begin{macrocode}
if not math.initialseed then math.randomseed(currenttime) end
local function luamplibload (name)
  local mpx = mplib.new {
    ini_version = true,
    find_file   = luamplib.finder,
%    \end{macrocode}
%    Make use of |make_text| and |run_script|, which will co-operate
%    with \LuaTeX's |tex.runtoks|. And we
%    provide |numbersystem| option since v2.4. Default value ``|scaled|''
%    can be changed by declaring |\mplibnumbersystem{double}|
%    or |\mplibnumbersystem{decimal}|.
%    See \url{https://github.com/lualatex/luamplib/issues/21}.
%    \begin{macrocode}
    make_text   = luamplib.maketext,
    run_script  = luamplib.runscript,
    math_mode   = luamplib.numbersystem,
    job_name    = tex.jobname,
    random_seed = math.random(4095),
    extensions  = 1,
  }
%    \end{macrocode}
%    Append our own MetaPost preamble to the preamble above.
%    \begin{macrocode}
  local preamble = tableconcat{
    format(preamble, replacesuffix(name,"mp")),
    luamplib.preambles.mplibcode,
    luamplib.legacyverbatimtex and luamplib.preambles.legacyverbatimtex or "",
    luamplib.textextlabel and luamplib.preambles.textextlabel or "",
  }
  local result, log
  if not mpx then
    result = { status = 99, error = "out of memory"}
  else
    result = mpx:execute(preamble)
  end
  log = reporterror(result)
  return mpx, result, log
end

%    \end{macrocode}
%
%    Here, excute each |mplibcode| data,
%    ie |\begin{mplibcode} ... \end{mplibcode}|.
%    \begin{macrocode}
local function process (data, instancename)
  local currfmt
  if instancename and instancename ~= "" then
    currfmt = instancename
    has_instancename = true
  else
    currfmt = tableconcat{
      currentformat,
      luamplib.numbersystem or "scaled",
      tostring(luamplib.textextlabel),
      tostring(luamplib.legacyverbatimtex),
    }
    has_instancename = false
  end
  local mpx = mplibinstances[currfmt]
  local standalone = not (has_instancename or luamplib.codeinherit)
  if mpx and standalone then
    mpx:finish()
  end
  local log = ""
  if standalone or not mpx then
    mpx, _, log = luamplibload(currentformat)
    mplibinstances[currfmt] = mpx
  end
  local converted, result = false, {}
  if mpx and data then
    result = mpx:execute(data)
    local log = reporterror(result, log)
    if log then
      if result.fig then
        converted = luamplib.convert(result)
      end
    end
  else
    err"Mem file unloadable. Maybe generated with a different version of mplib?"
  end
  return converted, result
end

%    \end{macrocode}
%
%    |dvipdfmx| is supported, though nobody seems to use it.
%    \begin{macrocode}
local pdfmode = tex.outputmode > 0
%    \end{macrocode}
%
%    |make_text| and some |run_script| uses \LuaTeX's |tex.runtoks|.
%    \begin{macrocode}
local catlatex = luatexbase.registernumber("catcodetable@latex")
local catat11  = luatexbase.registernumber("catcodetable@atletter")

%    \end{macrocode}
%
%    |tex.scantoks| sometimes fail to read catcode properly, especially
%    |\#|, |\&|, or |\%|. After some experiment, we dropped using it.
%    Instead, a function containing |tex.sprint| seems to work nicely.
%    \begin{macrocode}
local function run_tex_code (str, cat)
  texruntoks(function() texsprint(cat or catlatex, str) end)
end

%    \end{macrocode}
%
%    Prepare textext box number containers, locals and globals.
%    |localid| can be any number. They are local anyway.
%    The number will be reset at the start of a new code chunk.
%    Global boxes will use |\newbox| command in |tex.runtoks| process.
%    This is the same when |codeinherit| is true.
%    Boxes in instances with name will also be global, so that
%    their tex boxes can be shared among instances of the same name.
%    \begin{macrocode}
local texboxes = { globalid = 0, localid = 4096 }
%    \end{macrocode}
%    For conversion of |sp| to |bp|.
%    \begin{macrocode}
local factor = 65536*(7227/7200)

local textext_fmt = 'image(addto currentpicture doublepath unitsquare \z
xscaled %f yscaled %f shifted (0,-%f) \z
withprescript "mplibtexboxid=%i:%f:%f")'

local function process_tex_text (str)
  if str then
    local global = (has_instancename or luamplib.globaltextext or luamplib.codeinherit)
                   and "\\global" or ""
    local tex_box_id
    if global == "" then
      tex_box_id = texboxes.localid + 1
      texboxes.localid = tex_box_id
    else
      local boxid = texboxes.globalid + 1
      texboxes.globalid = boxid
      run_tex_code(format([[\expandafter\newbox\csname luamplib.box.%s\endcsname]], boxid))
      tex_box_id = tex.getcount'allocationnumber'
    end
    run_tex_code(format("%s\\setbox%i\\hbox{%s}", global, tex_box_id, str))
    local box = texgetbox(tex_box_id)
    local wd  = box.width  / factor
    local ht  = box.height / factor
    local dp  = box.depth  / factor
    return textext_fmt:format(wd, ht+dp, dp, tex_box_id, wd, ht+dp)
  end
  return ""
end

%    \end{macrocode}
%
%    Make |color| or |xcolor|'s color expressions usable,
%    with \cs{mpcolor} or |mplibcolor|. These commands should be used
%    with graphical objects.
%    Attempt to support l3color as well.
%    \begin{macrocode}
local mplibcolorfmt = {
  xcolor = tableconcat{
    [[\begingroup\let\XC@mcolor\relax]],
    [[\def\set@color{\global\mplibtmptoks\expandafter{\current@color}}]],
    [[\color%s\endgroup]],
  },
  l3color = tableconcat{
    [[\begingroup\def\__color_select:N#1{\expandafter\__color_select:nn#1}]],
    [[\def\__color_backend_select:nn#1#2{\global\mplibtmptoks{#1 #2}}]],
    [[\def\__kernel_backend_literal:e#1{\global\mplibtmptoks\expandafter{\expanded{#1}}}]],
    [[\color_select:n%s\endgroup]],
  },
}

local colfmt = is_defined'color_select:n' and "l3color" or "xcolor"
if colfmt == "l3color" then
  run_tex_code{
    "\\newcatcodetable\\luamplibcctabexplat",
    "\\begingroup",
    "\\catcode`@=11 ",
    "\\catcode`_=11 ",
    "\\catcode`:=11 ",
    "\\savecatcodetable\\luamplibcctabexplat",
    "\\endgroup",
  }
end
local ccexplat = luatexbase.registernumber"luamplibcctabexplat"

local function process_color (str)
  if str then
    if not str:find("%b{}") then
      str = format("{%s}",str)
    end
    local myfmt = mplibcolorfmt[colfmt]
    if colfmt == "l3color" and is_defined"color" then
      if str:find("%b[]") then
        myfmt = mplibcolorfmt.xcolor
      else
        for _,v in ipairs(str:match"{(.+)}":explode"!") do
          if not v:find("^%s*%d+%s*$") then
            local pp = get_macro(format("l__color_named_%s_prop",v))
            if not pp or pp == "" then
              myfmt = mplibcolorfmt.xcolor
              break
            end
          end
        end
      end
    end
    run_tex_code(myfmt:format(str), ccexplat or catat11)
    local t = texgettoks"mplibtmptoks"
    if not pdfmode and not t:find"^pdf" then
      t = t:gsub("%a+ (.+)","pdf:bc [%1]")
    end
    return format('1 withprescript "mpliboverridecolor=%s"', t)
  end
  return ""
end

%    \end{macrocode}
%
%    for \cs{mpdim} or |mplibdimen|
%    \begin{macrocode}
local function process_dimen (str)
  if str then
    str = str:gsub("{(.+)}","%1")
    run_tex_code(format([[\mplibtmptoks\expandafter{\the\dimexpr %s\relax}]], str))
    return format("begingroup %s endgroup", texgettoks"mplibtmptoks")
  end
  return ""
end

%    \end{macrocode}
%
%    Newly introduced method of processing |verbatimtex ... etex|.
%    This function is used when |\mpliblegacybehavior{false}| is declared.
%    \begin{macrocode}
local function process_verbatimtex_text (str)
  if str then
    run_tex_code(str)
  end
  return ""
end

%    \end{macrocode}
%
%    For legacy verbatimtex process.
%    |verbatimtex ... etex| before |beginfig()| is not ignored,
%    but the \TeX\ code is inserted just before the mplib box. And
%    \TeX\ code inside |beginfig() ... endfig| is inserted after the mplib box.
%    \begin{macrocode}
local tex_code_pre_mplib = {}
luamplib.figid = 1
luamplib.in_the_fig = false

local function process_verbatimtex_prefig (str)
  if str then
    tex_code_pre_mplib[luamplib.figid] = str
  end
  return ""
end

local function process_verbatimtex_infig (str)
  if str then
    return format('special "postmplibverbtex=%s";', str)
  end
  return ""
end

local runscript_funcs = {
  luamplibtext    = process_tex_text,
  luamplibcolor   = process_color,
  luamplibdimen   = process_dimen,
  luamplibprefig  = process_verbatimtex_prefig,
  luamplibinfig   = process_verbatimtex_infig,
  luamplibverbtex = process_verbatimtex_text,
}

%    \end{macrocode}
%
%    For |metafun| format. see issue \#79.
%    \begin{macrocode}
mp = mp or {}
local mp = mp
mp.mf_path_reset = mp.mf_path_reset or function() end
mp.mf_finish_saving_data = mp.mf_finish_saving_data or function() end
mp.report = mp.report or info

%    \end{macrocode}
%
%    metafun 2021-03-09 changes crashes luamplib.
%    \begin{macrocode}
catcodes = catcodes or {}
local catcodes = catcodes
catcodes.numbers = catcodes.numbers or {}
catcodes.numbers.ctxcatcodes = catcodes.numbers.ctxcatcodes or catlatex
catcodes.numbers.texcatcodes = catcodes.numbers.texcatcodes or catlatex
catcodes.numbers.luacatcodes = catcodes.numbers.luacatcodes or catlatex
catcodes.numbers.notcatcodes = catcodes.numbers.notcatcodes or catlatex
catcodes.numbers.vrbcatcodes = catcodes.numbers.vrbcatcodes or catlatex
catcodes.numbers.prtcatcodes = catcodes.numbers.prtcatcodes or catlatex
catcodes.numbers.txtcatcodes = catcodes.numbers.txtcatcodes or catlatex

%    \end{macrocode}
%
%    A function from \ConTeXt\ general.
%    \begin{macrocode}
local function mpprint(buffer,...)
  for i=1,select("#",...) do
    local value = select(i,...)
    if value ~= nil then
      local t = type(value)
      if t == "number" then
        buffer[#buffer+1] = format("%.16f",value)
      elseif t == "string" then
        buffer[#buffer+1] = value
      elseif t == "table" then
        buffer[#buffer+1] = "(" .. tableconcat(value,",") .. ")"
      else -- boolean or whatever
        buffer[#buffer+1] = tostring(value)
      end
    end
  end
end

function luamplib.runscript (code)
  local id, str = code:match("(.-){(.*)}")
  if id and str then
    local f = runscript_funcs[id]
    if f then
      local t = f(str)
      if t then return t end
    end
  end
  local f = loadstring(code)
  if type(f) == "function" then
    local buffer = {}
    function mp.print(...)
      mpprint(buffer,...)
    end
    local res = {f()}
    buffer = tableconcat(buffer)
    if buffer and buffer ~= "" then
      return buffer
    end
    buffer = {}
    mpprint(buffer, tableunpack(res))
    return tableconcat(buffer)
  end
  return ""
end

%    \end{macrocode}
%
%    |make_text| must be one liner, so comment sign is not allowed.
%    \begin{macrocode}
local function protecttexcontents (str)
  return str:gsub("\\%%", "\0PerCent\0")
            :gsub("%%.-\n", "")
            :gsub("%%.-$",  "")
            :gsub("%zPerCent%z", "\\%%")
            :gsub("%s+", " ")
end

luamplib.legacyverbatimtex = true

function luamplib.maketext (str, what)
  if str and str ~= "" then
    str = protecttexcontents(str)
    if what == 1 then
      if not str:find("\\documentclass"..name_e) and
         not str:find("\\begin%s*{document}") and
         not str:find("\\documentstyle"..name_e) and
         not str:find("\\usepackage"..name_e) then
        if luamplib.legacyverbatimtex then
          if luamplib.in_the_fig then
            return process_verbatimtex_infig(str)
          else
            return process_verbatimtex_prefig(str)
          end
        else
          return process_verbatimtex_text(str)
        end
      end
    else
      return process_tex_text(str)
    end
  end
  return ""
end

%    \end{macrocode}
%
%    luamplib's metapost color operators
%    \begin{macrocode}
local function colorsplit (res)
  local t, tt = { }, res:gsub("[%[%]]",""):explode()
  local be = tt[1]:find"^%d" and 1 or 2
  for i=be, #tt do
    if tt[i]:find"^%a" then break end
    t[#t+1] = tt[i]
  end
  return t
end

luamplib.gettexcolor = function (str, rgb)
  local res = process_color(str):match'"mpliboverridecolor=(.+)"'
  if res:find" cs " or res:find"@pdf.obj" then
    if not rgb then
      warn("%s is a spot color. Forced to CMYK", str)
    end
    run_tex_code({
      "\\color_export:nnN{",
      str,
      "}{",
      rgb and "space-sep-rgb" or "space-sep-cmyk",
      "}\\mplib_@tempa",
    },ccexplat)
    return get_macro"mplib_@tempa":explode()
  end
  local t = colorsplit(res)
  if #t == 3 or not rgb then return t end
  if #t == 4 then
    return { 1 - math.min(1,t[1]+t[4]), 1 - math.min(1,t[2]+t[4]), 1 - math.min(1,t[3]+t[4]) }
  end
  return { t[1], t[1], t[1] }
end

luamplib.shadecolor = function (str)
  local res = process_color(str):match'"mpliboverridecolor=(.+)"'
  if res:find" cs " or res:find"@pdf.obj" then -- spot color shade: l3 only
%    \end{macrocode}
%   An example of spot color shading:
%\begin{verbatim}
%     \documentclass{article}
%     \usepackage{luamplib}
%     \mplibsetformat{metafun}
%     \ExplSyntaxOn
%     \color_model_new:nnn { pantone3005 }
%       { Separation }
%       { name = PANTONE~3005~U ,
%         alternative-model = cmyk ,
%         alternative-values = {1, 0.56, 0, 0}
%       }
%       \color_set:nnn{spotA}{pantone3005}{1}
%       \color_set:nnn{spotB}{pantone3005}{0.6}
%     \color_model_new:nnn { pantone1215 }
%       { Separation }
%       { name = PANTONE~1215~U ,
%         alternative-model = cmyk ,
%         alternative-values = {0, 0.15, 0.51, 0}
%       }
%       \color_set:nnn{spotC}{pantone1215}{1}
%     \color_model_new:nnn { pantone2040 }
%       { Separation }
%       { name = PANTONE~2040~U ,
%         alternative-model = cmyk ,
%         alternative-values = {0, 0.28, 0.21, 0.04}
%       }
%       \color_set:nnn{spotD}{pantone2040}{1}
%     \ExplSyntaxOff
%     \begin{document}
%     \begin{mplibcode}
%     beginfig(1)
%       fill unitsquare xyscaled (\mpdim\textwidth,1cm)
%            withshademethod "linear"
%            withshadevector (0,1)
%            withshadestep (
%                withshadefraction .5
%                withshadecolors ("spotB","spotC")
%            )
%            withshadestep (
%                withshadefraction 1
%                withshadecolors ("spotC","spotD")
%            )
%       ;
%     endfig;
%     \end{mplibcode}
%     \end{document}
%\end{verbatim}
%   another one: user-defined DeviceN colorspace
%\begin{verbatim}
%    \DocumentMetadata{ }
%    \documentclass{article}
%    \usepackage{luamplib}
%    \mplibsetformat{metafun}
%    \ExplSyntaxOn
%    \color_model_new:nnn { pantone1215 }
%      { Separation }
%      { name = PANTONE~1215~U ,
%        alternative-model = cmyk ,
%        alternative-values = {0, 0.15, 0.51, 0}
%      }
%    \color_model_new:nnn { pantone+black }
%      { DeviceN }
%      {
%        names = {pantone1215,black}
%      }
%    \color_set:nnn{purepantone}{pantone+black}{1,0}
%    \color_set:nnn{pureblack} {pantone+black}{0,1}
%    \ExplSyntaxOff
%    \begin{document}
%    \mpfig
%    fill unitsquare xscaled \mpdim{\textwidth} yscaled 30
%        withshademethod "linear"
%        withshadecolors ("purepantone","pureblack")
%        ;
%    \endmpfig
%    \end{document}
%\end{verbatim}
%    \begin{macrocode}
    run_tex_code({
      [[\color_export:nnN{]], str, [[}{backend}\mplib_@tempa]],
    },ccexplat)
    local name, value = get_macro'mplib_@tempa':match'{(.-)}{(.-)}'
    local t, obj = res:explode()
    if pdfmode then
      obj = format("%s 0 R", ltx.pdf.object_id( t[1]:sub(2,-1) ))
    else
      obj = t[2]
    end
    return format('(1) withprescript"mplib_spotcolor=%s:%s:%s"', value,obj,name)
  end
  return colorsplit(res)
end

%    \end{macrocode}
%
%    luamplib's mplibgraphictext operator
%    \begin{macrocode}
local running = -1073741824
local emboldenfonts = { }
local function getemboldenwidth (curr, fakebold)
  local width = emboldenfonts.width
  if not width then
    local f
    local function getglyph(n)
      while n do
        if n.head then
          getglyph(n.head)
        elseif n.font and n.font > 0 then
          f = n.font; break
        end
        n = node.getnext(n)
      end
    end
    getglyph(curr)
    width = font.getcopy(f or font.current()).size * fakebold / factor * 10
    emboldenfonts.width = width
  end
  return width
end
local function getrulewhatsit (line, wd, ht, dp)
  line, wd, ht, dp = line/1000, wd/factor, ht/factor, dp/factor
  local pl
  local fmt = "%f w %f %f %f %f re %s"
  if pdfmode then
    pl = node.new("whatsit","pdf_literal")
    pl.mode = 0
  else
    fmt = "pdf:content "..fmt
    pl = node.new("whatsit","special")
  end
  pl.data = fmt:format(line, 0, -dp, wd, ht+dp, "B")
  local ss = node.new"glue"
  node.setglue(ss, 0, 65536, 65536, 2, 2)
  pl.next = ss
  return pl
end
local function getrulemetric (box, curr, bp)
  local wd,ht,dp = curr.width, curr.height, curr.depth
  wd = wd == running and box.width  or wd
  ht = ht == running and box.height or ht
  dp = dp == running and box.depth  or dp
  if bp then
    return wd/factor, ht/factor, dp/factor
  end
  return wd, ht, dp
end
local function embolden (box, curr, fakebold)
  local head = curr
  while curr do
    if curr.head then
      curr.head = embolden(curr, curr.head, fakebold)
    elseif curr.replace then
      curr.replace = embolden(box, curr.replace, fakebold)
    elseif curr.leader then
      if curr.leader.head then
        curr.leader.head = embolden(curr.leader, curr.leader.head, fakebold)
      elseif curr.leader.id == node.id"rule" then
        local glue = node.effective_glue(curr, box)
        local line = getemboldenwidth(curr, fakebold)
        local wd,ht,dp = getrulemetric(box, curr.leader)
        if box.id == node.id"hlist" then
          wd = glue
        else
          ht, dp = 0, glue
        end
        local pl = getrulewhatsit(line, wd, ht, dp)
        local pack = box.id == node.id"hlist" and node.hpack or node.vpack
        local list = pack(pl, glue, "exactly")
        head = node.insert_after(head, curr, list)
        head, curr = node.remove(head, curr)
      end
    elseif curr.id == node.id"rule" and curr.subtype == 0 then
      local line = getemboldenwidth(curr, fakebold)
      local wd,ht,dp = getrulemetric(box, curr)
      if box.id == node.id"vlist" then
        ht, dp = 0, ht+dp
      end
      local pl = getrulewhatsit(line, wd, ht, dp)
      local list
      if box.id == node.id"hlist" then
        list = node.hpack(pl, wd, "exactly")
      else
        list = node.vpack(pl, ht+dp, "exactly")
      end
      head = node.insert_after(head, curr, list)
      head, curr = node.remove(head, curr)
    elseif curr.id == node.id"glyph" and curr.font > 0 then
      local f = curr.font
      local i = emboldenfonts[f]
      if not i then
        local ft = font.getfont(f) or font.getcopy(f)
        if pdfmode then
          width = ft.size * fakebold / factor * 10
          emboldenfonts.width = width
          ft.mode, ft.width = 2, width
          i = font.define(ft)
        else
          if ft.format ~= "opentype" and ft.format ~= "truetype" then
            goto skip_type1
          end
          local name = ft.name:gsub('"',''):gsub(';$','')
          name = format('%s;embolden=%s;',name,fakebold)
          _, i = fonts.constructors.readanddefine(name,ft.size)
        end
        emboldenfonts[f] = i
      end
      curr.font = i
    end
    ::skip_type1::
    curr = node.getnext(curr)
  end
  return head
end
local function graphictextcolor (col, filldraw)
  if col:find"^[%d%.:]+$" then
    col = col:explode":"
    if pdfmode then
      local op = #col == 4 and "k" or #col == 3 and "rg" or "g"
      col[#col+1] = filldraw == "fill" and op or op:upper()
      return tableconcat(col," ")
    end
    return format("[%s]", tableconcat(col," "))
  end
  col = process_color(col):match'"mpliboverridecolor=(.+)"'
  if pdfmode then
    local t, tt = col:explode(), { }
    local b = filldraw == "fill" and 1 or #t/2+1
    local e = b == 1 and #t/2 or #t
    for i=b,e do
      tt[#tt+1] = t[i]
    end
    return tableconcat(tt," ")
  end
  return col:gsub("^.- ","")
end
luamplib.graphictext = function (text, fakebold, fc, dc)
  local fmt = process_tex_text(text):sub(1,-2)
  local id = tonumber(fmt:match"mplibtexboxid=(%d+):")
  emboldenfonts.width = nil
  local box = texgetbox(id)
  box.head = embolden(box, box.head, fakebold)
  local fill = graphictextcolor(fc,"fill")
  local draw = graphictextcolor(dc,"draw")
  local bc = pdfmode and "" or "pdf:bc "
  return format('%s withprescript "mpliboverridecolor=%s%s %s")', fmt, bc, fill, draw)
end

%    \end{macrocode}
%
%    luamplib's mplibglyph operator
%    \begin{macrocode}
local function mperr (str)
  return format("hide(errmessage %q)", str)
end
local function getangle (a,b,c)
  local r = math.deg(math.atan(c.y-b.y, c.x-b.x) - math.atan(b.y-a.y, b.x-a.x))
  if r > 180 then
    r = r - 360
  elseif r < -180 then
    r = r + 360
  end
  return r
end
local function turning (t)
  local r, n = 0, #t
  for i=1,2 do
    tableinsert(t, t[i])
  end
  for i=1,n do
    r = r + getangle(t[i], t[i+1], t[i+2])
  end
  return r/360
end
local function glyphimage(t, fmt)
  local q,p,r = {{},{}}
  for i,v in ipairs(t) do
    local cmd = v[#v]
    if cmd == "m" then
      p = {format('(%s,%s)',v[1],v[2])}
      r = {{x=v[1],y=v[2]}}
    else
      local nt = t[i+1]
      local last = not nt or nt[#nt] == "m"
      if cmd == "l" then
        local pt = t[i-1]
        local seco = pt[#pt] == "m"
        if (last or seco) and r[1].x == v[1] and r[1].y == v[2] then
        else
          tableinsert(p, format('--(%s,%s)',v[1],v[2]))
          tableinsert(r, {x=v[1],y=v[2]})
        end
        if last then
          tableinsert(p, '--cycle')
        end
      elseif cmd == "c" then
        tableinsert(p, format('..controls(%s,%s)and(%s,%s)',v[1],v[2],v[3],v[4]))
        if last and r[1].x == v[5] and r[1].y == v[6] then
          tableinsert(p, '..cycle')
        else
          tableinsert(p, format('..(%s,%s)',v[5],v[6]))
          if last then
            tableinsert(p, '--cycle')
          end
          tableinsert(r, {x=v[5],y=v[6]})
        end
      else
        return mperr"unknown operator"
      end
      if last then
        tableinsert(q[ turning(r) > 0 and 1 or 2 ], tableconcat(p))
      end
    end
  end
  r = { }
  if fmt == "opentype" then
    for _,v in ipairs(q[1]) do
      tableinsert(r, format('addto currentpicture contour %s;',v))
    end
    for _,v in ipairs(q[2]) do
      tableinsert(r, format('addto currentpicture contour %s withcolor background;',v))
    end
  else
    for _,v in ipairs(q[2]) do
      tableinsert(r, format('addto currentpicture contour %s;',v))
    end
    for _,v in ipairs(q[1]) do
      tableinsert(r, format('addto currentpicture contour %s withcolor background;',v))
    end
  end
  return format('image(%s)', tableconcat(r))
end
if not table.tofile then require"lualibs-lpeg"; require"lualibs-table"; end
function luamplib.glyph (f, c)
  local filename, subfont, instance, kind, shapedata
  local fid = tonumber(f) or font.id(f)
  if fid > 0 then
    local fontdata = font.getfont(fid) or font.getcopy(fid)
    filename, subfont, kind = fontdata.filename, fontdata.subfont, fontdata.format
    instance = fontdata.specification and fontdata.specification.instance
    filename = filename and filename:gsub("^harfloaded:","")
  else
    local name
    f = f:match"^%s*(.+)%s*$"
    name, subfont, instance = f:match"(.+)%((%d+)%)%[(.-)%]$"
    if not name then
      name, instance = f:match"(.+)%[(.-)%]$" -- SourceHanSansK-VF.otf[Heavy]
    end
    if not name then
      name, subfont = f:match"(.+)%((%d+)%)$" -- Times.ttc(2)
    end
    name = name or f
    subfont = (subfont or 0)+1
    instance = instance and instance:lower()
    for _,ftype in ipairs{"opentype", "truetype"} do
      filename = kpse.find_file(name, ftype.." fonts")
      if filename then
        kind = ftype; break
      end
    end
  end
  if kind ~= "opentype" and kind ~= "truetype" then
    f = fid and fid > 0 and tex.fontname(fid) or f
    if kpse.find_file(f, "tfm") then
      return format("glyph %s of %q", tonumber(c) or format("%q",c), f)
    else
      return mperr"font not found"
    end
  end
  local time = lfsattributes(filename,"modification")
  local k = format("shapes_%s(%s)[%s]", filename, subfont or "", instance or "")
  local h = format(string.rep('%02x', 256/8), string.byte(sha2.digest256(k), 1, -1))
  local newname = format("%s/%s.lua", cachedir or outputdir, h)
  local newtime = lfsattributes(newname,"modification") or 0
  if time == newtime then
    shapedata = require(newname)
  end
  if not shapedata then
    shapedata = fonts and fonts.handlers.otf.readers.loadshapes(filename,subfont,instance)
    if not shapedata then return mperr"loadshapes() failed. luaotfload not loaded?" end
    table.tofile(newname, shapedata, "return")
    lfstouch(newname, time, time)
  end
  local gid = tonumber(c)
  if not gid then
    local uni = utf8.codepoint(c)
    for i,v in pairs(shapedata.glyphs) do
      if c == v.name or uni == v.unicode then
        gid = i; break
      end
    end
  end
  if not gid then return mperr"cannot get GID (glyph id)" end
  local fac = 1000 / (shapedata.units or 1000)
  local t = shapedata.glyphs[gid].segments
  if not t then return "image()" end
  for i,v in ipairs(t) do
    if type(v) == "table" then
      for ii,vv in ipairs(v) do
        if type(vv) == "number" then
          t[i][ii] = format("%.0f", vv * fac)
        end
      end
    end
  end
  kind = shapedata.format or kind
  return glyphimage(t, kind)
end

%    \end{macrocode}
%
%    mpliboutlinetext : based on mkiv's font-mps.lua
%    \begin{macrocode}
local rulefmt = "mpliboutlinepic[%i]:=image(addto currentpicture contour \z
unitsquare shifted - center unitsquare;) xscaled %f yscaled %f shifted (%f,%f);"
local outline_horz, outline_vert
function outline_vert (res, box, curr, xshift, yshift)
  local b2u = box.dir == "LTL"
  local dy = (b2u and -box.depth or box.height)/factor
  local ody = dy
  while curr do
    if curr.id == node.id"rule" then
      local wd, ht, dp = getrulemetric(box, curr, true)
      local hd = ht + dp
      if hd ~= 0 then
        dy = dy + (b2u and dp or -ht)
        if wd ~= 0 and curr.subtype == 0 then
          res[#res+1] = rulefmt:format(#res+1, wd, hd, xshift+wd/2, yshift+dy+(ht-dp)/2)
        end
        dy = dy + (b2u and ht or -dp)
      end
    elseif curr.id == node.id"glue" then
      local vwidth = node.effective_glue(curr,box)/factor
      if curr.leader then
        local curr, kind = curr.leader, curr.subtype
        if curr.id == node.id"rule" then
          local wd = getrulemetric(box, curr, true)
          if wd ~= 0 then
            local hd = vwidth
            local dy = dy + (b2u and 0 or -hd)
            if hd ~= 0 and curr.subtype == 0 then
              res[#res+1] = rulefmt:format(#res+1, wd, hd, xshift+wd/2, yshift+dy+hd/2)
            end
          end
        elseif curr.head then
          local hd = (curr.height + curr.depth)/factor
          if hd <= vwidth then
            local dy, n, iy = dy, 0, 0
            if kind == 100 or kind == 103 then -- todo: gleaders
              local ady = abs(ody - dy)
              local ndy = math.ceil(ady / hd) * hd
              local diff = ndy - ady
              n = (vwidth-diff) // hd
              dy = dy + (b2u and diff or -diff)
            else
              n = vwidth // hd
              if kind == 101 then
                local side = vwidth % hd / 2
                dy = dy + (b2u and side or -side)
              elseif kind == 102 then
                iy = vwidth % hd / (n+1)
                dy = dy + (b2u and iy or -iy)
              end
            end
            dy = dy + (b2u and curr.depth or -curr.height)/factor
            hd = b2u and hd or -hd
            iy = b2u and iy or -iy
            local func = curr.id == node.id"hlist" and outline_horz or outline_vert
            for i=1,n do
              res = func(res, curr, curr.head, xshift+curr.shift/factor, yshift+dy)
              dy = dy + hd + iy
            end
          end
        end
      end
      dy = dy + (b2u and vwidth or -vwidth)
    elseif curr.id == node.id"kern" then
      dy = dy + curr.kern/factor * (b2u and 1 or -1)
    elseif curr.id == node.id"vlist" then
      dy = dy + (b2u and curr.depth or -curr.height)/factor
      res = outline_vert(res, curr, curr.head, xshift+curr.shift/factor, yshift+dy)
      dy = dy + (b2u and curr.height or -curr.depth)/factor
    elseif curr.id == node.id"hlist" then
      dy = dy + (b2u and curr.depth or -curr.height)/factor
      res = outline_horz(res, curr, curr.head, xshift+curr.shift/factor, yshift+dy)
      dy = dy + (b2u and curr.height or -curr.depth)/factor
    end
    curr = node.getnext(curr)
  end
  return res
end
function outline_horz (res, box, curr, xshift, yshift, discwd)
  local r2l = box.dir == "TRT"
  local dx = r2l and (discwd or box.width/factor) or 0
  local dirs = { { dir = r2l, dx = dx } }
  while curr do
    if curr.id == node.id"dir" then
      local sign, dir = curr.dir:match"(.)(...)"
      local level, newdir = curr.level, r2l
      if sign == "+" then
        newdir = dir == "TRT"
        if r2l ~= newdir then
          local n = node.getnext(curr)
          while n do
            if n.id == node.id"dir" and n.level+1 == level then break end
            n = node.getnext(n)
          end
          n = n or node.tail(curr)
          dx = dx + node.rangedimensions(box, curr, n)/factor * (newdir and 1 or -1)
        end
        dirs[level] = { dir = r2l, dx = dx }
      else
        local level = level + 1
        newdir = dirs[level].dir
        if r2l ~= newdir then
          dx = dirs[level].dx
        end
      end
      r2l = newdir
    elseif curr.char and curr.font and curr.font > 0 then
      local ft = font.getfont(curr.font) or font.getcopy(curr.font)
      local gid = ft.characters[curr.char].index or curr.char
      local scale = ft.size / factor / 1000
      local slant   = (ft.slant or 0)/1000
      local extend  = (ft.extend or 1000)/1000
      local squeeze = (ft.squeeze or 1000)/1000
      local expand  = 1 + (curr.expansion_factor or 0)/1000000
      local xscale = scale * extend * expand
      local yscale = scale * squeeze
      dx = dx - (r2l and curr.width/factor*expand or 0)
      local xpos = dx + xshift + (curr.xoffset or 0)/factor
      local ypos = yshift + (curr.yoffset or 0)/factor
      local vertical = ft.shared and ft.shared.features.vertical and "rotated 90" or ""
      if vertical ~= "" then -- luatexko
        for _,v in ipairs(ft.characters[curr.char].commands or { }) do
          if v[1] == "down" then
            ypos = ypos - v[2] / factor
          elseif v[1] == "right" then
            xpos = xpos + v[2] / factor
          else
            break
          end
        end
      end
      local image
      if ft.format == "opentype" or ft.format == "truetype" then
        image = luamplib.glyph(curr.font, gid)
      else
        local name, scale = ft.name, 1
        local vf = font.read_vf(name, ft.size)
        if vf and vf.characters[gid] then
          local cmds = vf.characters[gid].commands or {}
          for _,v in ipairs(cmds) do
            if v[1] == "char" then
              gid = v[2]
            elseif v[1] == "font" and vf.fonts[v[2]] then
              name  = vf.fonts[v[2]].name
              scale = vf.fonts[v[2]].size / ft.size
            end
          end
        end
        image = format("glyph %s of %q scaled %f", gid, name, scale)
      end
      res[#res+1] = format("mpliboutlinepic[%i]:=%s xscaled %f yscaled %f slanted %f %s shifted (%f,%f);",
                           #res+1, image, xscale, yscale, slant, vertical, xpos, ypos)
      dx = dx + (r2l and 0 or curr.width/factor*expand)
    elseif curr.replace then
      local width = node.dimensions(curr.replace)/factor
      dx = dx - (r2l and width or 0)
      res = outline_horz(res, box, curr.replace, xshift+dx, yshift, width)
      dx = dx + (r2l and 0 or width)
    elseif curr.id == node.id"rule" then
      local wd, ht, dp = getrulemetric(box, curr, true)
      if wd ~= 0 then
        local hd = ht + dp
        dx = dx - (r2l and wd or 0)
        if hd ~= 0 and curr.subtype == 0 then
          res[#res+1] = rulefmt:format(#res+1, wd, hd, xshift+dx+wd/2, yshift+(ht-dp)/2)
        end
        dx = dx + (r2l and 0 or wd)
      end
    elseif curr.id == node.id"glue" then
      local width = node.effective_glue(curr, box)/factor
      dx = dx - (r2l and width or 0)
      if curr.leader then
        local curr, kind = curr.leader, curr.subtype
        if curr.id == node.id"rule" then
          local wd, ht, dp = getrulemetric(box, curr, true)
          local hd = ht + dp
          if hd ~= 0 then
            wd = width
            if wd ~= 0 and curr.subtype == 0 then
              res[#res+1] = rulefmt:format(#res+1, wd, hd, xshift+dx+wd/2, yshift+(ht-dp)/2)
            end
          end
        elseif curr.head then
          local wd = curr.width/factor
          if wd <= width then
            local dx = r2l and dx+width or dx
            local n, ix = 0, 0
            if kind == 100 or kind == 103 then -- todo: gleaders
              local adx = abs(dx-dirs[1].dx)
              local ndx = math.ceil(adx / wd) * wd
              local diff = ndx - adx
              n = (width-diff) // wd
              dx = dx + (r2l and -diff-wd or diff)
            else
              n = width // wd
              if kind == 101 then
                local side = width % wd /2
                dx = dx + (r2l and -side-wd or side)
              elseif kind == 102 then
                ix = width % wd / (n+1)
                dx = dx + (r2l and -ix-wd or ix)
              end
            end
            wd = r2l and -wd or wd
            ix = r2l and -ix or ix
            local func = curr.id == node.id"hlist" and outline_horz or outline_vert
            for i=1,n do
              res = func(res, curr, curr.head, xshift+dx, yshift-curr.shift/factor)
              dx = dx + wd + ix
            end
          end
        end
      end
      dx = dx + (r2l and 0 or width)
    elseif curr.id == node.id"kern" then
      dx = dx + curr.kern/factor * (r2l and -1 or 1)
    elseif curr.id == node.id"math" then
      dx = dx + curr.surround/factor * (r2l and -1 or 1)
    elseif curr.id == node.id"vlist" then
      dx = dx - (r2l and curr.width/factor or 0)
      res = outline_vert(res, curr, curr.head, xshift+dx, yshift-curr.shift/factor)
      dx = dx + (r2l and 0 or curr.width/factor)
    elseif curr.id == node.id"hlist" then
      dx = dx - (r2l and curr.width/factor or 0)
      res = outline_horz(res, curr, curr.head, xshift+dx, yshift-curr.shift/factor)
      dx = dx + (r2l and 0 or curr.width/factor)
    end
    curr = node.getnext(curr)
  end
  return res
end
function luamplib.outlinetext (text)
  local fmt = process_tex_text(text)
  local id  = tonumber(fmt:match"mplibtexboxid=(%d+):")
  local box = texgetbox(id)
  local res = outline_horz({ }, box, box.head, 0, 0)
  if #res == 0 then res = { "mpliboutlinepic[1]:=image();" } end
  return tableconcat(res) .. format("mpliboutlinenum:=%i;", #res)
end

%    \end{macrocode}
%
%    Our MetaPost preambles
%    \begin{macrocode}
luamplib.preambles = {
  mplibcode = [[
texscriptmode := 2;
def rawtextext (expr t) = runscript("luamplibtext{"&t&"}") enddef;
def mplibcolor (expr t) = runscript("luamplibcolor{"&t&"}") enddef;
def mplibdimen (expr t) = runscript("luamplibdimen{"&t&"}") enddef;
def VerbatimTeX (expr t) = runscript("luamplibverbtex{"&t&"}") enddef;
if known context_mlib:
  defaultfont := "cmtt10";
  let infont = normalinfont;
  let fontsize = normalfontsize;
  vardef thelabel@#(expr p,z) =
    if string p :
      thelabel@#(p infont defaultfont scaled defaultscale,z)
    else :
      p shifted (z + labeloffset*mfun_laboff@# -
        (mfun_labxf@#*lrcorner p + mfun_labyf@#*ulcorner p +
        (1-mfun_labxf@#-mfun_labyf@#)*llcorner p))
    fi
  enddef;
else:
  vardef textext@# (text t) = rawtextext (t) enddef;
  def message expr t =
    if string t: runscript("mp.report[=["&t&"]=]") else: errmessage "Not a string" fi
  enddef;
fi
def resolvedcolor(expr s) =
  runscript("return luamplib.shadecolor('"& s &"')")
enddef;
def colordecimals primary c =
  if cmykcolor c:
    decimal cyanpart c & ":" & decimal magentapart c & ":" &
    decimal yellowpart c & ":" & decimal blackpart c
  elseif rgbcolor c:
    decimal redpart c & ":" & decimal greenpart c & ":" & decimal bluepart c
  elseif string c:
    if known graphictextpic: c else: colordecimals resolvedcolor(c) fi
  else:
    decimal c
  fi
enddef;
def externalfigure primary filename =
  draw rawtextext("\includegraphics{"& filename &"}")
enddef;
def TEX = textext enddef;
def mplibtexcolor primary c =
  runscript("return luamplib.gettexcolor('"& c &"')")
enddef;
def mplibrgbtexcolor primary c =
  runscript("return luamplib.gettexcolor('"& c &"','rgb')")
enddef;
def mplibgraphictext primary t =
  begingroup;
  mplibgraphictext_ (t)
enddef;
def mplibgraphictext_ (expr t) text rest =
  save fakebold, scale, fillcolor, drawcolor, withfillcolor, withdrawcolor,
    fb, fc, dc, graphictextpic;
  picture graphictextpic; graphictextpic := nullpicture;
  numeric fb; string fc, dc; fb:=2; fc:="white"; dc:="black";
  let scale = scaled;
  def fakebold  primary c = hide(fb:=c;) enddef;
  def fillcolor primary c = hide(fc:=colordecimals c;) enddef;
  def drawcolor primary c = hide(dc:=colordecimals c;) enddef;
  let withfillcolor = fillcolor; let withdrawcolor = drawcolor;
  addto graphictextpic doublepath origin rest; graphictextpic:=nullpicture;
  def fakebold  primary c = enddef;
  let fillcolor = fakebold; let drawcolor = fakebold;
  let withfillcolor = fillcolor; let withdrawcolor = drawcolor;
  image(draw runscript("return luamplib.graphictext([===["&t&"]===],"
    & decimal fb &",'"& fc &"','"& dc &"')") rest;)
  endgroup;
enddef;
def mplibglyph expr c of f =
  runscript (
    "return luamplib.glyph('"
    & if numeric f: decimal fi f
    & "','"
    & if numeric c: decimal fi c
    & "')"
  )
enddef;
def mplibdrawglyph expr g =
  draw image(
    save i; numeric i; i:=0;
    for item within g:
      i := i+1;
      fill pathpart item
      if i < length g: withpostscript "collect" fi;
    endfor
  )
enddef;
def mplib_do_outline_text_set_b (text f) (text d) text r =
  def mplib_do_outline_options_f = f enddef;
  def mplib_do_outline_options_d = d enddef;
  def mplib_do_outline_options_r = r enddef;
enddef;
def mplib_do_outline_text_set_f (text f) text r =
  def mplib_do_outline_options_f = f enddef;
  def mplib_do_outline_options_r = r enddef;
enddef;
def mplib_do_outline_text_set_u (text f) text r =
  def mplib_do_outline_options_f = f enddef;
enddef;
def mplib_do_outline_text_set_d (text d) text r =
  def mplib_do_outline_options_d = d enddef;
  def mplib_do_outline_options_r = r enddef;
enddef;
def mplib_do_outline_text_set_r (text d) (text f) text r =
  def mplib_do_outline_options_d = d enddef;
  def mplib_do_outline_options_f = f enddef;
  def mplib_do_outline_options_r = r enddef;
enddef;
def mplib_do_outline_text_set_n text r =
  def mplib_do_outline_options_r = r enddef;
enddef;
def mplib_do_outline_text_set_p = enddef;
def mplib_fill_outline_text =
  for n=1 upto mpliboutlinenum:
    i:=0;
    for item within mpliboutlinepic[n]:
      i:=i+1;
      fill pathpart item mplib_do_outline_options_f withpen pencircle scaled 0
      if (n<mpliboutlinenum) or (i<length mpliboutlinepic[n]): withpostscript "collect"; fi
    endfor
  endfor
enddef;
def mplib_draw_outline_text =
  for n=1 upto mpliboutlinenum:
    for item within mpliboutlinepic[n]:
      draw pathpart item mplib_do_outline_options_d;
    endfor
  endfor
enddef;
def mplib_filldraw_outline_text =
  for n=1 upto mpliboutlinenum:
    i:=0;
    for item within mpliboutlinepic[n]:
      i:=i+1;
      if (n<mpliboutlinenum) or (i<length mpliboutlinepic[n]):
        fill pathpart item mplib_do_outline_options_f withpostscript "collect";
      else:
        draw pathpart item mplib_do_outline_options_f withpostscript "both";
      fi
    endfor
  endfor
enddef;
vardef mpliboutlinetext@# (expr t) text rest =
  save kind; string kind; kind := str @#;
  save i; numeric i;
  picture mpliboutlinepic[]; numeric mpliboutlinenum;
  def mplib_do_outline_options_d = enddef;
  def mplib_do_outline_options_f = enddef;
  def mplib_do_outline_options_r = enddef;
  runscript("return luamplib.outlinetext[===["&t&"]===]");
  image ( addto currentpicture also image (
    if kind = "f":
      mplib_do_outline_text_set_f rest;
      mplib_fill_outline_text;
    elseif kind = "d":
      mplib_do_outline_text_set_d rest;
      mplib_draw_outline_text;
    elseif kind = "b":
      mplib_do_outline_text_set_b rest;
      mplib_fill_outline_text;
      mplib_draw_outline_text;
    elseif kind = "u":
      mplib_do_outline_text_set_u rest;
      mplib_filldraw_outline_text;
    elseif kind = "r":
      mplib_do_outline_text_set_r rest;
      mplib_draw_outline_text;
      mplib_fill_outline_text;
    elseif kind = "p":
      mplib_do_outline_text_set_p;
      mplib_draw_outline_text;
    else:
      mplib_do_outline_text_set_n rest;
      mplib_fill_outline_text;
    fi;
  ) mplib_do_outline_options_r; )
enddef ;
primarydef t withpattern p =
  image( fill t withprescript "mplibpattern=" & if numeric p: decimal fi p; )
enddef;
vardef mplibtransformmatrix (text e) =
  save t; transform t;
  t = identity e;
  runscript("luamplib.transformmatrix = {"
  & decimal xxpart t & ","
  & decimal yxpart t & ","
  & decimal xypart t & ","
  & decimal yypart t & ","
  & decimal xpart  t & ","
  & decimal ypart  t & ","
  & "}");
enddef;
primarydef p withfademethod s =
  if picture p:
    image(
      draw p;
      draw center p withprescript "mplibfadestate=stop";
    )
  else:
    p withprescript "mplibfadestate=stop"
  fi
    withprescript "mplibfadetype=" & s
    withprescript "mplibfadebbox=" &
      decimal xpart llcorner p & ":" &
      decimal ypart llcorner p & ":" &
      decimal xpart urcorner p & ":" &
      decimal ypart urcorner p
enddef;
def withfadeopacity (expr a,b) =
  withprescript "mplibfadeopacity=" &
    decimal a & ":" &
    decimal b
enddef;
def withfadevector (expr a,b) =
  withprescript "mplibfadevector=" &
    decimal xpart a & ":" &
    decimal ypart a & ":" &
    decimal xpart b & ":" &
    decimal ypart b
enddef;
let withfadecenter = withfadevector;
def withfaderadius (expr a,b) =
  withprescript "mplibfaderadius=" &
    decimal a & ":" &
    decimal b
enddef;
def withfadebbox (expr a,b) =
  withprescript "mplibfadebbox=" &
    decimal xpart a & ":" &
    decimal ypart a & ":" &
    decimal xpart b & ":" &
    decimal ypart b
enddef;
primarydef p asgroup s =
  image(
    fill llcorner p--lrcorner p--urcorner p--ulcorner p--cycle
      withprescript "gr_state=start"
      withprescript "gr_type=" & s;
    draw p;
    draw center p withprescript "gr_state=stop";
  )
enddef;
def withgroupname expr s =
  withprescript "mplibgroupname=" & s
enddef;
def usemplibgroup primary s =
  draw maketext("\usemplibgroup{" & s & "}")
    shifted runscript("return luamplib.trgroupshifts['" & s & "']")
enddef;
]],
  legacyverbatimtex = [[
def specialVerbatimTeX (text t) = runscript("luamplibprefig{"&t&"}") enddef;
def normalVerbatimTeX  (text t) = runscript("luamplibinfig{"&t&"}") enddef;
let VerbatimTeX = specialVerbatimTeX;
extra_beginfig := extra_beginfig & " let VerbatimTeX = normalVerbatimTeX;"&
  "runscript(" &ditto& "luamplib.in_the_fig=true" &ditto& ");";
extra_endfig := extra_endfig & " let VerbatimTeX = specialVerbatimTeX;"&
  "runscript(" &ditto&
  "if luamplib.in_the_fig then luamplib.figid=luamplib.figid+1 end "&
  "luamplib.in_the_fig=false" &ditto& ");";
]],
  textextlabel = [[
primarydef s infont f = rawtextext(s) enddef;
def fontsize expr f =
  begingroup
  save size; numeric size;
  size := mplibdimen("1em");
  if size = 0: 10pt else: size fi
  endgroup
enddef;
]],
}

%    \end{macrocode}
%
%    When \cs{mplibverbatim} is enabled, do not expand |mplibcode| data.
%    \begin{macrocode}
luamplib.verbatiminput = false

%    \end{macrocode}
%
%    Do not expand |btex ... etex|, |verbatimtex ... etex|, and
%    string expressions.
%    \begin{macrocode}
local function protect_expansion (str)
  if str then
    str = str:gsub("\\","!!!Control!!!")
             :gsub("%%","!!!Comment!!!")
             :gsub("#", "!!!HashSign!!!")
             :gsub("{", "!!!LBrace!!!")
             :gsub("}", "!!!RBrace!!!")
    return format("\\unexpanded{%s}",str)
  end
end

local function unprotect_expansion (str)
  if str then
    return str:gsub("!!!Control!!!", "\\")
              :gsub("!!!Comment!!!", "%%")
              :gsub("!!!HashSign!!!","#")
              :gsub("!!!LBrace!!!",  "{")
              :gsub("!!!RBrace!!!",  "}")
  end
end

luamplib.everymplib    = setmetatable({ [""] = "" },{ __index = function(t) return t[""] end })
luamplib.everyendmplib = setmetatable({ [""] = "" },{ __index = function(t) return t[""] end })

function luamplib.process_mplibcode (data, instancename)
  texboxes.localid = 4096

%    \end{macrocode}
%    This is needed for legacy behavior
%    \begin{macrocode}
  if luamplib.legacyverbatimtex then
    luamplib.figid, tex_code_pre_mplib = 1, {}
  end

  local everymplib    = luamplib.everymplib[instancename]
  local everyendmplib = luamplib.everyendmplib[instancename]
  data = format("\n%s\n%s\n%s\n",everymplib, data, everyendmplib)
  :gsub("\r","\n")

%    \end{macrocode}
%    These five lines are needed for |mplibverbatim| mode.
%    \begin{macrocode}
  if luamplib.verbatiminput then
    data = data:gsub("\\mpcolor%s+(.-%b{})","mplibcolor(\"%1\")")
    :gsub("\\mpdim%s+(%b{})", "mplibdimen(\"%1\")")
    :gsub("\\mpdim%s+(\\%a+)","mplibdimen(\"%1\")")
    :gsub(btex_etex, "btex %1 etex ")
    :gsub(verbatimtex_etex, "verbatimtex %1 etex;")
%    \end{macrocode}
%    If not |mplibverbatim|, expand |mplibcode| data,
%    so that users can use \TeX\ codes in it.
%    It has turned out that no comment sign is allowed.
%    \begin{macrocode}
  else
    data = data:gsub(btex_etex, function(str)
      return format("btex %s etex ", protect_expansion(str)) -- space
    end)
    :gsub(verbatimtex_etex, function(str)
      return format("verbatimtex %s etex;", protect_expansion(str)) -- semicolon
    end)
    :gsub("\".-\"", protect_expansion)
    :gsub("\\%%", "\0PerCent\0")
    :gsub("%%.-\n","\n")
    :gsub("%zPerCent%z", "\\%%")
    run_tex_code(format("\\mplibtmptoks\\expandafter{\\expanded{%s}}",data))
    data = texgettoks"mplibtmptoks"
%    \end{macrocode}
%    Next line to address issue \#55
%    \begin{macrocode}
    :gsub("##", "#")
    :gsub("\".-\"", unprotect_expansion)
    :gsub(btex_etex, function(str)
      return format("btex %s etex", unprotect_expansion(str))
    end)
    :gsub(verbatimtex_etex, function(str)
      return format("verbatimtex %s etex", unprotect_expansion(str))
    end)
  end

  process(data, instancename)
end

%    \end{macrocode}
%
%    For parsing |prescript| materials.
%    \begin{macrocode}
local further_split_keys = {
  mplibtexboxid = true,
  sh_color_a    = true,
  sh_color_b    = true,
}
local function script2table(s)
  local t = {}
  for _,i in ipairs(s:explode("\13+")) do
    local k,v = i:match("(.-)=(.*)") -- v may contain = or empty.
    if k and v and k ~= "" and not t[k] then
      if further_split_keys[k] or further_split_keys[k:sub(1,10)] then
        t[k] = v:explode(":")
      else
        t[k] = v
      end
    end
  end
  return t
end

%    \end{macrocode}
%
%     pdfliterals will be stored in |figcontents| table, and written to pdf in one go
%     at the end of the flushing figure.
%     Subtable |post| is for the legacy behavior.
%    \begin{macrocode}
local figcontents = { post = { } }
local function put2output(a,...)
  figcontents[#figcontents+1] = type(a) == "string" and format(a,...) or a
end

local function pdf_startfigure(n,llx,lly,urx,ury)
  put2output("\\mplibstarttoPDF{%f}{%f}{%f}{%f}",llx,lly,urx,ury)
end

local function pdf_stopfigure()
  put2output("\\mplibstoptoPDF")
end

%    \end{macrocode}
%
%    |tex.sprint| with catcode regime -2, as sometimes |#| gets doubled
%    in the argument of pdfliteral.
%    \begin{macrocode}
local function pdf_literalcode (fmt,...)
  put2output{-2, format(fmt,...)}
end

local function start_pdf_code()
  if pdfmode then
    pdf_literalcode("q")
  else
    put2output"\\special{pdf:bcontent}"
  end
end
local function stop_pdf_code()
  if pdfmode then
    pdf_literalcode("Q")
  else
    put2output"\\special{pdf:econtent}"
  end
end

%    \end{macrocode}
%
%    Now we process hboxes created from |btex ... etex| or
%    |textext(...)| or |TEX(...)|, all being the same internally.
%    \begin{macrocode}
local function put_tex_boxes (object,prescript)
  local box = prescript.mplibtexboxid
  local n,tw,th = box[1],tonumber(box[2]),tonumber(box[3])
  if n and tw and th then
    local op = object.path
    local first, second, fourth = op[1], op[2], op[4]
    local tx, ty = first.x_coord, first.y_coord
    local sx, rx, ry, sy = 1, 0, 0, 1
    if tw ~= 0 then
      sx = (second.x_coord - tx)/tw
      rx = (second.y_coord - ty)/tw
      if sx == 0 then sx = 0.00001 end
    end
    if th ~= 0 then
      sy = (fourth.y_coord - ty)/th
      ry = (fourth.x_coord - tx)/th
      if sy == 0 then sy = 0.00001 end
    end
    start_pdf_code()
    pdf_literalcode("%f %f %f %f %f %f cm",sx,rx,ry,sy,tx,ty)
    put2output("\\mplibputtextbox{%i}",n)
    stop_pdf_code()
  end
end

%    \end{macrocode}
%
%    Colors
%    \begin{macrocode}
local prev_override_color
local function do_preobj_CR(object,prescript)
  if object.postscript == "collect" then return end
  local override = prescript and prescript.mpliboverridecolor
  if override then
    if pdfmode then
      pdf_literalcode(override)
      override = nil
    else
      put2output("\\special{%s}",override)
      prev_override_color = override
    end
  else
    local cs = object.color
    if cs and #cs > 0 then
      pdf_literalcode(luamplib.colorconverter(cs))
      prev_override_color = nil
    elseif not pdfmode then
      override = prev_override_color
      if override then
        put2output("\\special{%s}",override)
      end
    end
  end
  return override
end

%    \end{macrocode}
%
%    For transparency and shading
%    \begin{macrocode}
local pdfmanagement = is_defined'pdfmanagement_add:nnn'
local pdfobjs, pdfetcs = {}, {}
pdfetcs.pgfextgs = "pgf@sys@addpdfresource@extgs@plain"
pdfetcs.pgfpattern = "pgf@sys@addpdfresource@patterns@plain"
pdfetcs.pgfcolorspace = "pgf@sys@addpdfresource@colorspaces@plain"

local function update_pdfobjs (os, stream)
  local key = os
  if stream then key = key..stream end
  local on = pdfobjs[key]
  if on then
    return on,false
  end
  if pdfmode then
    if stream then
      on = pdf.immediateobj("stream",stream,os)
    else
      on = pdf.immediateobj(os)
    end
  else
    on = pdfetcs.cnt or 1
    if stream then
      texsprint(format("\\special{pdf:stream @mplibpdfobj%s (%s) <<%s>>}",on,stream,os))
    else
      texsprint(format("\\special{pdf:obj @mplibpdfobj%s %s}",on,os))
    end
    pdfetcs.cnt = on + 1
  end
  pdfobjs[key] = on
  return on,true
end
pdfetcs.resfmt = pdfmode and "%s 0 R" or "@mplibpdfobj%s"

if pdfmode then
  pdfetcs.getpageres = pdf.getpageresources or function() return pdf.pageresources end
  local getpageres = pdfetcs.getpageres
  local setpageres = pdf.setpageresources or function(s) pdf.pageresources = s end
  local initialize_resources = function (name)
    local tabname = format("%s_res",name)
    pdfetcs[tabname] = { }
    if luatexbase.callbacktypes.finish_pdffile then -- ltluatex
      local obj = pdf.reserveobj()
      setpageres(format("%s/%s %i 0 R", getpageres() or "", name, obj))
      luatexbase.add_to_callback("finish_pdffile", function()
        pdf.immediateobj(obj, format("<<%s>>", tableconcat(pdfetcs[tabname])))
      end,
      format("luamplib.%s.finish_pdffile",name))
    end
  end
  pdfetcs.fallback_update_resources = function (name, res)
    local tabname = format("%s_res",name)
    if not pdfetcs[tabname] then
      initialize_resources(name)
    end
    if luatexbase.callbacktypes.finish_pdffile then
      local t = pdfetcs[tabname]
      t[#t+1] = res
    else
      local tpr, n = getpageres() or "", 0
      tpr, n = tpr:gsub(format("/%s<<",name), "%1"..res)
      if n == 0 then
        tpr = format("%s/%s<<%s>>", tpr, name, res)
      end
      setpageres(tpr)
    end
  end
else
  texsprint {
    "\\special{pdf:obj @MPlibTr<<>>}",
    "\\special{pdf:obj @MPlibSh<<>>}",
    "\\special{pdf:obj @MPlibCS<<>>}",
    "\\special{pdf:obj @MPlibPt<<>>}",
  }
  pdfetcs.resadded = { }
end

%    \end{macrocode}
%
%    Transparency
%    \begin{macrocode}
local transparancy_modes = { [0] = "Normal",
  "Normal",       "Multiply",     "Screen",       "Overlay",
  "SoftLight",    "HardLight",    "ColorDodge",   "ColorBurn",
  "Darken",       "Lighten",      "Difference",   "Exclusion",
  "Hue",          "Saturation",   "Color",        "Luminosity",
  "Compatible",
}
local function add_extgs_resources (on, new)
  local key = format("MPlibTr%s", on)
  if new then
    local val = format(pdfetcs.resfmt, on)
    if pdfmanagement then
      texsprint {
        "\\csname pdfmanagement_add:nnn\\endcsname{Page/Resources/ExtGState}{", key, "}{", val, "}"
      }
    else
      local tr = format("/%s %s", key, val)
      if is_defined(pdfetcs.pgfextgs) then
        texsprint { "\\csname ", pdfetcs.pgfextgs, "\\endcsname{", tr, "}" }
      elseif pdfmode then
        if is_defined"TRP@list" then
          texsprint(catat11,{
            [[\if@filesw\immediate\write\@auxout{]],
            [[\string\g@addto@macro\string\TRP@list{]],
            tr,
            [[}}\fi]],
          })
          if not get_macro"TRP@list":find(tr) then
            texsprint(catat11,[[\global\TRP@reruntrue]])
          end
        else
          pdfetcs.fallback_update_resources("ExtGState", tr)
        end
      else
        texsprint { "\\special{pdf:put @MPlibTr<<", tr, ">>}" }
      end
    end
  end
  if not pdfmode and not pdfmanagement and not is_defined(pdfetcs.pgfextgs) then
    texsprint"\\special{pdf:put @resources <</ExtGState @MPlibTr>>}"
    pdfetcs.resadded.ExtGState = "@MPlibTr"
  end
  return key
end
local function do_preobj_TR(object,prescript)
  if object.postscript == "collect" then return end
  local opaq = prescript and prescript.tr_transparency
  if opaq then
    local key, on, os, new
    local mode = prescript.tr_alternative or 1
    mode = transparancy_modes[tonumber(mode)] or mode
    for i,v in ipairs{ {mode,opaq},{"Normal",1} } do
      mode, opaq = v[1], v[2]
      os = format("<</BM /%s/ca %.3f/CA %.3f/AIS false>>",mode,opaq,opaq)
      on, new = update_pdfobjs(os)
      key = add_extgs_resources(on,new)
      if i == 1 then
        pdf_literalcode("/%s gs",key)
      else
        return format("/%s gs",key)
      end
    end
  end
end

%    \end{macrocode}
%
%    Shading with |metafun| format.
%    \begin{macrocode}
local function sh_pdfpageresources(shtype,domain,colorspace,ca,cb,coordinates,steps,fractions)
  local fun2fmt,os = "<</FunctionType 2/Domain [%s]/C0 [%s]/C1 [%s]/N 1>>"
  if steps > 1 then
    local list,bounds,encode = { },{ },{ }
    for i=1,steps do
      if i < steps then
        bounds[i] = fractions[i] or 1
      end
      encode[2*i-1] = 0
      encode[2*i]   = 1
      os = fun2fmt:format(domain,tableconcat(ca[i],' '),tableconcat(cb[i],' '))
      list[i] = format(pdfetcs.resfmt, update_pdfobjs(os))
    end
    os = tableconcat {
      "<</FunctionType 3",
      format("/Bounds [%s]",    tableconcat(bounds,' ')),
      format("/Encode [%s]",    tableconcat(encode,' ')),
      format("/Functions [%s]", tableconcat(list,  ' ')),
      format("/Domain [%s]>>",  domain),
    }
  else
    os = fun2fmt:format(domain,tableconcat(ca[1],' '),tableconcat(cb[1],' '))
  end
  local objref = format(pdfetcs.resfmt, update_pdfobjs(os))
  os = tableconcat {
    format("<</ShadingType %i", shtype),
    format("/ColorSpace %s",    colorspace),
    format("/Function %s",      objref),
    format("/Coords [%s]",      coordinates),
    "/Extend [true true]/AntiAlias true>>",
  }
  local on, new = update_pdfobjs(os)
  if new then
    local key, val = format("MPlibSh%s", on), format(pdfetcs.resfmt, on)
    if pdfmanagement then
      texsprint {
        "\\csname pdfmanagement_add:nnn\\endcsname{Page/Resources/Shading}{", key, "}{", val, "}"
      }
    else
      local res = format("/%s %s", key, val)
      if pdfmode then
        pdfetcs.fallback_update_resources("Shading", res)
      else
        texsprint { "\\special{pdf:put @MPlibSh<<", res, ">>}" }
      end
    end
  end
  if not pdfmode and not pdfmanagement then
    texsprint"\\special{pdf:put @resources <</Shading @MPlibSh>>}"
    pdfetcs.resadded.Shading = "@MPlibSh"
  end
  return on
end

local function color_normalize(ca,cb)
  if #cb == 1 then
    if #ca == 4 then
      cb[1], cb[2], cb[3], cb[4] = 0, 0, 0, 1-cb[1]
    else -- #ca = 3
      cb[1], cb[2], cb[3] = cb[1], cb[1], cb[1]
    end
  elseif #cb == 3 then -- #ca == 4
    cb[1], cb[2], cb[3], cb[4] = 1-cb[1], 1-cb[2], 1-cb[3], 0
  end
end

pdfetcs.clrspcs = setmetatable({ }, { __index = function(t,names)
  run_tex_code({
    [[\color_model_new:nnn]],
    format("{mplibcolorspace_%s}", names:gsub(",","_")),
    format("{DeviceN}{names={%s}}", names),
    [[\edef\mplib_@tempa{\pdf_object_ref_last:}]],
  }, ccexplat)
  local colorspace = get_macro'mplib_@tempa'
  t[names] = colorspace
  return colorspace
end })

local function do_preobj_SH(object,prescript)
  local shade_no
  local sh_type = prescript and prescript.sh_type
  if not sh_type then
    return
  else
    local domain  = prescript.sh_domain or "0 1"
    local centera = prescript.sh_center_a or "0 0"; centera = centera:explode()
    local centerb = prescript.sh_center_b or "0 0"; centerb = centerb:explode()
    local transform = prescript.sh_transform == "yes"
    local sx,sy,sr,dx,dy = 1,1,1,0,0
    if transform then
      local first = prescript.sh_first or "0 0"; first = first:explode()
      local setx = prescript.sh_set_x or "0 0";  setx = setx:explode()
      local sety = prescript.sh_set_y or "0 0";  sety = sety:explode()
      local x,y = tonumber(setx[1]) or 0, tonumber(sety[1]) or 0
      if x ~= 0 and y ~= 0 then
        local path = object.path
        local path1x = path[1].x_coord
        local path1y = path[1].y_coord
        local path2x = path[x].x_coord
        local path2y = path[y].y_coord
        local dxa = path2x - path1x
        local dya = path2y - path1y
        local dxb = setx[2] - first[1]
        local dyb = sety[2] - first[2]
        if dxa ~= 0 and dya ~= 0 and dxb ~= 0 and dyb ~= 0 then
          sx = dxa / dxb ; if sx < 0 then sx = - sx end
          sy = dya / dyb ; if sy < 0 then sy = - sy end
          sr = math.sqrt(sx^2 + sy^2)
          dx = path1x - sx*first[1]
          dy = path1y - sy*first[2]
        end
      end
    end
    local ca, cb, colorspace, steps, fractions
    ca = { prescript.sh_color_a_1 or prescript.sh_color_a or {0} }
    cb = { prescript.sh_color_b_1 or prescript.sh_color_b or {1} }
    steps = tonumber(prescript.sh_step) or 1
    if steps > 1 then
      fractions = { prescript.sh_fraction_1 or 0 }
      for i=2,steps do
        fractions[i] = prescript[format("sh_fraction_%i",i)] or (i/steps)
        ca[i] = prescript[format("sh_color_a_%i",i)] or {0}
        cb[i] = prescript[format("sh_color_b_%i",i)] or {1}
      end
    end
    if prescript.mplib_spotcolor then
      ca, cb = { }, { }
      local names, pos, objref = { }, -1, ""
      local script = object.prescript:explode"\13+"
      for i=#script,1,-1 do
        if script[i]:find"mplib_spotcolor" then
          local t, name, value = script[i]:explode"="[2]:explode":"
          value, objref, name = t[1], t[2], t[3]
          if not names[name] then
            pos = pos+1
            names[name] = pos
            names[#names+1] = name
          end
          t = { }
          for j=1,names[name] do t[#t+1] = 0 end
          t[#t+1] = value
          tableinsert(#ca == #cb and ca or cb, t)
        end
      end
      for _,t in ipairs{ca,cb} do
        for _,tt in ipairs(t) do
          for i=1,#names-#tt do tt[#tt+1] = 0 end
        end
      end
      if #names == 1 then
        colorspace = objref
      else
        colorspace = pdfetcs.clrspcs[ tableconcat(names,",") ]
      end
    else
      local model = 0
      for _,t in ipairs{ca,cb} do
        for _,tt in ipairs(t) do
          model = model > #tt and model or #tt
        end
      end
      for _,t in ipairs{ca,cb} do
        for _,tt in ipairs(t) do
          if #tt < model then
            color_normalize(model == 4 and {1,1,1,1} or {1,1,1},tt)
          end
        end
      end
      colorspace = model == 4 and "/DeviceCMYK"
                or model == 3 and "/DeviceRGB"
                or model == 1 and "/DeviceGray"
                or err"unknown color model"
    end
    if sh_type == "linear" then
      local coordinates = format("%f %f %f %f",
        dx + sx*centera[1], dy + sy*centera[2],
        dx + sx*centerb[1], dy + sy*centerb[2])
      shade_no = sh_pdfpageresources(2,domain,colorspace,ca,cb,coordinates,steps,fractions)
    elseif sh_type == "circular" then
      local factor = prescript.sh_factor or 1
      local radiusa = factor * prescript.sh_radius_a
      local radiusb = factor * prescript.sh_radius_b
      local coordinates = format("%f %f %f %f %f %f",
        dx + sx*centera[1], dy + sy*centera[2], sr*radiusa,
        dx + sx*centerb[1], dy + sy*centerb[2], sr*radiusb)
      shade_no = sh_pdfpageresources(3,domain,colorspace,ca,cb,coordinates,steps,fractions)
    else
      err"unknown shading type"
    end
    pdf_literalcode("q /Pattern cs")
  end
  return shade_no
end

%    \end{macrocode}
%
%    Patterns
%    \begin{macrocode}
pdfetcs.patterns = { }
local patterns = pdfetcs.patterns
local function gather_resources (optres)
  local t, do_pattern = { }, not optres
  local names = {"ExtGState","ColorSpace","Shading"}
  if do_pattern then
    names[#names+1] = "Pattern"
  end
  if pdfmode then
    if pdfmanagement then
      for _,v in ipairs(names) do
        local pp = get_macro(format("g__pdfdict_/g__pdf_Core/Page/Resources/%s_prop",v))
        if pp and pp:find"__prop_pair" then
          t[#t+1] = format("/%s %s 0 R", v, ltx.pdf.object_id("__pdf/Page/Resources/"..v))
        end
      end
    else
      local res = pdfetcs.getpageres() or ""
      run_tex_code[[\mplibtmptoks\expandafter{\the\pdfvariable pageresources}]]
      res = res .. texgettoks'mplibtmptoks'
      if do_pattern then return res end
      res = res:explode"/+"
      for _,v in ipairs(res) do
        v = v:match"^%s*(.-)%s*$"
        if not v:find"Pattern" and not optres:find(v) then
          t[#t+1] = "/" .. v
        end
      end
    end
  else
    if pdfmanagement then
      for _,v in ipairs(names) do
        local pp = get_macro(format("g__pdfdict_/g__pdf_Core/Page/Resources/%s_prop",v))
        if pp and pp:find"__prop_pair" then
          run_tex_code {
            "\\mplibtmptoks\\expanded{{",
            format("/%s \\csname pdf_object_ref:n\\endcsname{__pdf/Page/Resources/%s}",v,v),
            "}}",
          }
          t[#t+1] = texgettoks'mplibtmptoks'
        end
      end
    elseif is_defined(pdfetcs.pgfextgs) then
      run_tex_code ({
        "\\mplibtmptoks\\expanded{{",
        "\\ifpgf@sys@pdf@extgs@exists /ExtGState @pgfextgs\\fi",
        "\\ifpgf@sys@pdf@colorspaces@exists /ColorSpace @pgfcolorspaces\\fi",
        do_pattern and "\\ifpgf@sys@pdf@patterns@exists /Pattern @pgfpatterns \\fi" or "",
        "}}",
      }, catat11)
      t[#t+1] = texgettoks'mplibtmptoks'
    elseif do_pattern then
      for _,v in ipairs(names) do
        local vv = pdfetcs.resadded[v]
        if vv then
          t[#t+1] = format("/%s %s", v, vv)
        end
      end
    end
  end
  return tableconcat(t)
end
function luamplib.registerpattern ( boxid, name, opts )
  local box = texgetbox(boxid)
  local wd = format("%.3f",box.width/factor)
  local hd = format("%.3f",(box.height+box.depth)/factor)
  info("w/h/d of '%s': %s %s 0.0", name, wd, hd)
  if opts.xstep == 0 then opts.xstep = nil end
  if opts.ystep == 0 then opts.ystep = nil end
  if opts.colored == nil then
    opts.colored = opts.coloured
    if opts.colored == nil then
      opts.colored = true
    end
  end
  if type(opts.matrix) == "table" then opts.matrix = tableconcat(opts.matrix," ") end
  if type(opts.bbox) == "table" then opts.bbox = tableconcat(opts.bbox," ") end
  if opts.matrix and opts.matrix:find"%a" then
    local data = format("mplibtransformmatrix(%s);",opts.matrix)
    process(data,"@mplibtransformmatrix")
    local t = luamplib.transformmatrix
    opts.matrix = format("%s %s %s %s", t[1], t[2], t[3], t[4])
    opts.xshift = opts.xshift or t[5]
    opts.yshift = opts.yshift or t[6]
  end
  local attr = {
    "/Type/Pattern",
    "/PatternType 1",
    format("/PaintType %i", opts.colored and 1 or 2),
    "/TilingType 2",
    format("/XStep %s", opts.xstep or wd),
    format("/YStep %s", opts.ystep or hd),
    format("/Matrix [%s %s %s]", opts.matrix or "1 0 0 1", opts.xshift or 0, opts.yshift or 0),
  }
  local optres = opts.resources or ""
  optres = optres .. gather_resources(optres)
  if pdfmode then
    if opts.bbox then
      attr[#attr+1] = format("/BBox [%s]", opts.bbox)
    end
    local index = tex.saveboxresource(boxid, tableconcat(attr), optres, true, opts.bbox and 4 or 1)
    patterns[name] = { id = index, colored = opts.colored }
  else
    local objname = "@mplibpattern"..name
    local metric = format("bbox %s", opts.bbox or format("0 0 %s %s",wd,hd))
    texsprint {
      "\\ifvmode\\nointerlineskip\\fi\\vbox to0pt{\\vss\\hbox to0pt{",
      "\\special{pdf:bcontent}",
      "\\special{pdf:bxobj ", objname, " ", metric, "}",
      "\\raise\\dp ", boxid, "\\box ", boxid,
      "\\special{pdf:put @resources <<", optres, ">>}",
      "\\special{pdf:exobj <<", tableconcat(attr), ">>}",
      "\\special{pdf:econtent}",
      "\\hss}}",
    }
    patterns[#patterns+1] = objname
    patterns[name] = { id = #patterns, colored = opts.colored }
  end
end
local function pattern_colorspace (cs)
  local on, new = update_pdfobjs(format("[/Pattern %s]", cs))
  if new then
    local key, val = format("MPlibCS%i",on), format(pdfetcs.resfmt,on)
    if pdfmanagement then
      texsprint {
        "\\csname pdfmanagement_add:nnn\\endcsname{Page/Resources/ColorSpace}{", key, "}{", val, "}"
      }
    else
      local res = format("/%s %s", key, val)
      if is_defined(pdfetcs.pgfcolorspace) then
        texsprint { "\\csname ", pdfetcs.pgfcolorspace, "\\endcsname{", res, "}" }
      elseif pdfmode then
        pdfetcs.fallback_update_resources("ColorSpace", res)
      else
        texsprint { "\\special{pdf:put @MPlibCS<<", res, ">>}" }
      end
    end
  end
  if not pdfmode and not pdfmanagement and not is_defined(pdfetcs.pgfcolorspace) then
    texsprint"\\special{pdf:put @resources <</ColorSpace @MPlibCS>>}"
    pdfetcs.resadded.ColorSpace = "@MPlibCS"
  end
  return on
end
local function do_preobj_PAT(object, prescript)
  local name = prescript and prescript.mplibpattern
  if not name then return end
  local patt = patterns[name]
  local index = patt and patt.id or err("cannot get pattern object '%s'", name)
  local key = format("MPlibPt%s",index)
  if patt.colored then
    pdf_literalcode("/Pattern cs /%s scn", key)
  else
    local color = prescript.mpliboverridecolor
    if not color then
      local t = object.color
      color = t and #t>0 and luamplib.colorconverter(t)
    end
    if not color then return end
    local cs
    if color:find" cs " or color:find"@pdf.obj" then
      local t = color:explode()
      if pdfmode then
        cs = format("%s 0 R", ltx.pdf.object_id( t[1]:sub(2,-1) ))
        color = t[3]
      else
        cs = t[2]
        color = t[3]:match"%[(.+)%]"
      end
    else
      local t = colorsplit(color)
      cs = #t == 4 and "/DeviceCMYK" or #t == 3 and "/DeviceRGB" or "/DeviceGray"
      color = tableconcat(t," ")
    end
    pdf_literalcode("/MPlibCS%i cs %s /%s scn", pattern_colorspace(cs), color, key)
  end
  if not patt.done then
    local val = pdfmode and format("%s 0 R",index) or patterns[index]
    if pdfmanagement then
      texsprint {
        "\\csname pdfmanagement_add:nnn\\endcsname{Page/Resources/Pattern}{", key, "}{", val, "}"
      }
    else
      local res = format("/%s %s", key, val)
      if is_defined(pdfetcs.pgfpattern) then
        texsprint { "\\csname ", pdfetcs.pgfpattern, "\\endcsname{", res, "}" }
      elseif pdfmode then
        pdfetcs.fallback_update_resources("Pattern", res)
      else
        texsprint { "\\special{pdf:put @MPlibPt<<", res, ">>}" }
      end
    end
  end
  if not pdfmode and not pdfmanagement and not is_defined(pdfetcs.pgfpattern) then
    texsprint"\\special{pdf:put @resources <</Pattern @MPlibPt>>}"
    pdfetcs.resadded.Pattern = "@MPlibPt"
  end
  patt.done = true
end

%    \end{macrocode}
%
%    Fading
%    \begin{macrocode}
pdfetcs.fading = { }
local function do_preobj_FADE (object, prescript)
  local fd_type = prescript and prescript.mplibfadetype
  local fd_stop = prescript and prescript.mplibfadestate
  if not fd_type then
    return fd_stop -- returns "stop" (if picture) or nil
  end
  local bbox = prescript.mplibfadebbox:explode":"
  local dx, dy = -bbox[1], -bbox[2]
  local vec = prescript.mplibfadevector; vec = vec and vec:explode":"
  if not vec then
    if fd_type == "linear" then
      vec = {bbox[1], bbox[2], bbox[3], bbox[2]} -- left to right
    else
      local centerx, centery = (bbox[1]+bbox[3])/2, (bbox[2]+bbox[4])/2
      vec = {centerx, centery, centerx, centery} -- center for both circles
    end
  end
  local coords = { vec[1]+dx, vec[2]+dy, vec[3]+dx, vec[4]+dy }
  if fd_type == "linear" then
    coords = format("%f %f %f %f", tableunpack(coords))
  elseif fd_type == "circular" then
    local width, height = bbox[3]-bbox[1], bbox[4]-bbox[2]
    local radius = (prescript.mplibfaderadius or "0:"..math.sqrt(width^2+height^2)/2):explode":"
    tableinsert(coords, 3, radius[1])
    tableinsert(coords, radius[2])
    coords = format("%f %f %f %f %f %f", tableunpack(coords))
  else
    err("unknown fading method '%s'", fd_type)
  end
  bbox = format("0 0 %f %f", bbox[3]+dx, bbox[4]+dy)
  fd_type = fd_type == "linear" and 2 or 3
  local opaq = (prescript.mplibfadeopacity or "1:0"):explode":"
  local on, os, new
  on = sh_pdfpageresources(fd_type, "0 1", "/DeviceGray", {{opaq[1]}}, {{opaq[2]}}, coords, 1)
  os = format("<</PatternType 2/Shading %s>>", format(pdfetcs.resfmt, on))
  on = update_pdfobjs(os)
  local streamtext = format("q /Pattern cs/MPlibFd%s scn %s re f Q", on, bbox)
  os = format("<</Pattern<</MPlibFd%s %s>>>>", on, format(pdfetcs.resfmt, on))
  on = update_pdfobjs(os)
  local resources = "/Resources " .. format(pdfetcs.resfmt, on)
  on = update_pdfobjs"<</S/Transparency/CS/DeviceGray>>"
  local attr = tableconcat{
    "/Subtype/Form",
    format("/BBox[%s]", bbox),
    format("/Matrix[1 0 0 1 %f %f]", -dx, -dy),
    resources,
    "/Group ", format(pdfetcs.resfmt, on),
  }
  on = update_pdfobjs(attr, streamtext)
  os = "<</SMask<</S/Luminosity/G " .. format(pdfetcs.resfmt, on) .. ">>>>"
  on, new = update_pdfobjs(os)
  local key = add_extgs_resources(on,new)
  start_pdf_code()
  pdf_literalcode("/%s gs", key)
  if fd_stop then return "standalone" end
  return "start"
end

%    \end{macrocode}
%
%    Transparency Group
%    \begin{macrocode}
pdfetcs.tr_group = { shifts = { } }
luamplib.trgroupshifts = pdfetcs.tr_group.shifts
local function do_preobj_GRP (object, prescript)
  local grstate = prescript and prescript.gr_state
  if not grstate then return end
  local trgroup = pdfetcs.tr_group
  if grstate == "start" then
    trgroup.name = prescript.mplibgroupname or "lastmplibgroup"
    trgroup.isolated, trgroup.knockout = false, false
    for _,v in ipairs(prescript.gr_type:explode",+") do
      trgroup[v] = true
    end
    local p = object.path
    trgroup.bbox = {
      math.min(p[1].x_coord, p[2].x_coord, p[3].x_coord, p[4].x_coord),
      math.min(p[1].y_coord, p[2].y_coord, p[3].y_coord, p[4].y_coord),
      math.max(p[1].x_coord, p[2].x_coord, p[3].x_coord, p[4].x_coord),
      math.max(p[1].y_coord, p[2].y_coord, p[3].y_coord, p[4].y_coord),
    }
    put2output[[\begingroup\setbox\mplibscratchbox\hbox\bgroup]]
  elseif grstate == "stop" then
    local llx,lly,urx,ury = tableunpack(trgroup.bbox)
    local grattr = format("/Group<</S/Transparency/I %s/K %s>>",trgroup.isolated,trgroup.knockout)
    local res = gather_resources()
    put2output(tableconcat{
      "\\egroup",
      format("\\wd\\mplibscratchbox %fbp", urx-llx),
      format("\\ht\\mplibscratchbox %fbp", ury-lly),
      "\\dp\\mplibscratchbox 0pt",
    })
    if pdfmode then
      put2output(tableconcat{
        "\\saveboxresource type 2 attr{/Type/XObject/Subtype/Form/FormType 1",
        format("/BBox[%f %f %f %f]", llx,lly,urx,ury),
        grattr, "} resources{", res, "}\\mplibscratchbox",
        [[\setbox\mplibscratchbox\hbox{\useboxresource\lastsavedboxresourceindex}]],
        [[\wd\mplibscratchbox 0pt\ht\mplibscratchbox 0pt\dp\mplibscratchbox 0pt]],
        [[\box\mplibscratchbox\endgroup]],
        "\\expandafter\\xdef\\csname luamplib.group.", trgroup.name, "\\endcsname{",
        "\\noexpand\\mplibstarttoPDF{",llx,"}{",lly,"}{",urx,"}{",ury,"}",
        "\\useboxresource \\the\\lastsavedboxresourceindex\\noexpand\\mplibstoptoPDF}",
      })
    else
      trgroup.cnt = (trgroup.cnt or 0) + 1
      local objname = format("@mplibtrgr%s", trgroup.cnt)
      put2output(tableconcat{
        "\\special{pdf:bxobj ", objname, " bbox ", format("%f %f %f %f", llx,lly,urx,ury), "}",
        "\\unhbox\\mplibscratchbox",
        "\\special{pdf:put @resources <<", res, ">>}",
        "\\special{pdf:exobj <<", grattr, ">>}",
        "\\special{pdf:uxobj ", objname, "}\\endgroup",
        "\\expandafter\\gdef\\csname luamplib.group.", trgroup.name, "\\endcsname{",
        "\\mplibstarttoPDF{",llx,"}{",lly,"}{",urx,"}{",ury,"}",
        "\\special{pdf:uxobj ", objname, "}\\mplibstoptoPDF}",
      })
    end
    trgroup.shifts[trgroup.name] = { llx, lly }
  end
  return grstate
end

local function stop_special_effects(fade,opaq,over)
  if fade then -- fading
    stop_pdf_code()
  end
  if opaq then -- opacity
    pdf_literalcode(opaq)
  end
  if over then -- color
    put2output"\\special{pdf:ec}"
  end
end

%    \end{macrocode}
%
%    Codes below for inserting PDF lieterals are mostly from ConTeXt general,
%    with small changes when needed.
%    \begin{macrocode}
local function getobjects(result,figure,f)
  return figure:objects()
end

function luamplib.convert (result, flusher)
  luamplib.flush(result, flusher)
  return true -- done
end

local function pdf_textfigure(font,size,text,width,height,depth)
  text = text:gsub(".",function(c)
    return format("\\hbox{\\char%i}",string.byte(c)) -- kerning happens in metapost : false
  end)
  put2output("\\mplibtextext{%s}{%f}{%s}{%s}{%s}",font,size,text,0,0)
end

local bend_tolerance = 131/65536

local rx, sx, sy, ry, tx, ty, divider = 1, 0, 0, 1, 0, 0, 1

local function pen_characteristics(object)
  local t = mplib.pen_info(object)
  rx, ry, sx, sy, tx, ty = t.rx, t.ry, t.sx, t.sy, t.tx, t.ty
  divider = sx*sy - rx*ry
  return not (sx==1 and rx==0 and ry==0 and sy==1 and tx==0 and ty==0), t.width
end

local function concat(px, py) -- no tx, ty here
  return (sy*px-ry*py)/divider,(sx*py-rx*px)/divider
end

local function curved(ith,pth)
  local d = pth.left_x - ith.right_x
  if abs(ith.right_x - ith.x_coord - d) <= bend_tolerance and abs(pth.x_coord - pth.left_x - d) <= bend_tolerance then
    d = pth.left_y - ith.right_y
    if abs(ith.right_y - ith.y_coord - d) <= bend_tolerance and abs(pth.y_coord - pth.left_y - d) <= bend_tolerance then
      return false
    end
  end
  return true
end

local function flushnormalpath(path,open)
  local pth, ith
  for i=1,#path do
    pth = path[i]
    if not ith then
      pdf_literalcode("%f %f m",pth.x_coord,pth.y_coord)
    elseif curved(ith,pth) then
      pdf_literalcode("%f %f %f %f %f %f c",ith.right_x,ith.right_y,pth.left_x,pth.left_y,pth.x_coord,pth.y_coord)
    else
      pdf_literalcode("%f %f l",pth.x_coord,pth.y_coord)
    end
    ith = pth
  end
  if not open then
    local one = path[1]
    if curved(pth,one) then
      pdf_literalcode("%f %f %f %f %f %f c",pth.right_x,pth.right_y,one.left_x,one.left_y,one.x_coord,one.y_coord )
    else
      pdf_literalcode("%f %f l",one.x_coord,one.y_coord)
    end
  elseif #path == 1 then -- special case .. draw point
    local one = path[1]
    pdf_literalcode("%f %f l",one.x_coord,one.y_coord)
  end
end

local function flushconcatpath(path,open)
  pdf_literalcode("%f %f %f %f %f %f cm", sx, rx, ry, sy, tx ,ty)
  local pth, ith
  for i=1,#path do
    pth = path[i]
    if not ith then
      pdf_literalcode("%f %f m",concat(pth.x_coord,pth.y_coord))
    elseif curved(ith,pth) then
      local a, b = concat(ith.right_x,ith.right_y)
      local c, d = concat(pth.left_x,pth.left_y)
      pdf_literalcode("%f %f %f %f %f %f c",a,b,c,d,concat(pth.x_coord, pth.y_coord))
    else
      pdf_literalcode("%f %f l",concat(pth.x_coord, pth.y_coord))
    end
    ith = pth
  end
  if not open then
    local one = path[1]
    if curved(pth,one) then
      local a, b = concat(pth.right_x,pth.right_y)
      local c, d = concat(one.left_x,one.left_y)
      pdf_literalcode("%f %f %f %f %f %f c",a,b,c,d,concat(one.x_coord, one.y_coord))
    else
      pdf_literalcode("%f %f l",concat(one.x_coord,one.y_coord))
    end
  elseif #path == 1 then -- special case .. draw point
    local one = path[1]
    pdf_literalcode("%f %f l",concat(one.x_coord,one.y_coord))
  end
end

%    \end{macrocode}
%
%    Finally, flush figures by inserting PDF literals.
%    \begin{macrocode}
function luamplib.flush (result,flusher)
  if result then
    local figures = result.fig
    if figures then
      for f=1, #figures do
        info("flushing figure %s",f)
        local figure = figures[f]
        local objects = getobjects(result,figure,f)
        local fignum = tonumber(figure:filename():match("([%d]+)$") or figure:charcode() or 0)
        local miterlimit, linecap, linejoin, dashed = -1, -1, -1, false
        local bbox = figure:boundingbox()
        local llx, lly, urx, ury = bbox[1], bbox[2], bbox[3], bbox[4] -- faster than unpack
        if urx < llx then
%    \end{macrocode}
%    luamplib silently ignores this invalid figure for those
%    that do not contain |beginfig ... endfig|. (issue \#70)
%    Original code of ConTeXt general was:
%\begin{verbatim}
%    -- invalid
%    pdf_startfigure(fignum,0,0,0,0)
%    pdf_stopfigure()
%\end{verbatim}
%    \begin{macrocode}
        else
%    \end{macrocode}
%    For legacy behavior, insert `pre-fig' \TeX\ code here.
%    \begin{macrocode}
          if tex_code_pre_mplib[f] then
            put2output(tex_code_pre_mplib[f])
          end
          pdf_startfigure(fignum,llx,lly,urx,ury)
          start_pdf_code()
          if objects then
            local savedpath = nil
            local savedhtap = nil
            for o=1,#objects do
              local object        = objects[o]
              local objecttype    = object.type
%    \end{macrocode}
%    The following 8 lines are part of |btex...etex| patch.
%    Again, colors are processed at this stage.
%    \begin{macrocode}
              local prescript     = object.prescript
              prescript = prescript and script2table(prescript) -- prescript is now a table
              local cr_over = do_preobj_CR(object,prescript) -- color
              local tr_opaq = do_preobj_TR(object,prescript) -- opacity
              local fading_ = do_preobj_FADE(object,prescript) -- fading
              local trgroup = do_preobj_GRP(object,prescript) -- transparency group
              if prescript and prescript.mplibtexboxid then
                put_tex_boxes(object,prescript)
              elseif objecttype == "start_bounds" or objecttype == "stop_bounds" then --skip
              elseif objecttype == "start_clip" then
                local evenodd = not object.istext and object.postscript == "evenodd"
                start_pdf_code()
                flushnormalpath(object.path,false)
                pdf_literalcode(evenodd and "W* n" or "W n")
              elseif objecttype == "stop_clip" then
                stop_pdf_code()
                miterlimit, linecap, linejoin, dashed = -1, -1, -1, false
              elseif objecttype == "special" then
%    \end{macrocode}
%    Collect \TeX\ codes that will be executed after flushing.
%    Legacy behavior.
%    \begin{macrocode}
                if prescript and prescript.postmplibverbtex then
                  figcontents.post[#figcontents.post+1] = prescript.postmplibverbtex
                end
              elseif objecttype == "text" then
                local ot = object.transform -- 3,4,5,6,1,2
                start_pdf_code()
                pdf_literalcode("%f %f %f %f %f %f cm",ot[3],ot[4],ot[5],ot[6],ot[1],ot[2])
                pdf_textfigure(object.font,object.dsize,object.text,object.width,object.height,object.depth)
                stop_pdf_code()
              elseif not trgroup and fading_ ~= "stop" then
                local evenodd, collect, both = false, false, false
                local postscript = object.postscript
                if not object.istext then
                  if postscript == "evenodd" then
                    evenodd = true
                  elseif postscript == "collect" then
                    collect = true
                  elseif postscript == "both" then
                    both = true
                  elseif postscript == "eoboth" then
                    evenodd = true
                    both    = true
                  end
                end
                if collect then
                  if not savedpath then
                    savedpath = { object.path or false }
                    savedhtap = { object.htap or false }
                  else
                    savedpath[#savedpath+1] = object.path or false
                    savedhtap[#savedhtap+1] = object.htap or false
                  end
                else
%    \end{macrocode}
%    Removed from ConTeXt general: color stuff.
%    \begin{macrocode}
                  local ml = object.miterlimit
                  if ml and ml ~= miterlimit then
                    miterlimit = ml
                    pdf_literalcode("%f M",ml)
                  end
                  local lj = object.linejoin
                  if lj and lj ~= linejoin then
                    linejoin = lj
                    pdf_literalcode("%i j",lj)
                  end
                  local lc = object.linecap
                  if lc and lc ~= linecap then
                    linecap = lc
                    pdf_literalcode("%i J",lc)
                  end
                  local dl = object.dash
                  if dl then
                    local d = format("[%s] %f d",tableconcat(dl.dashes or {}," "),dl.offset)
                    if d ~= dashed then
                      dashed = d
                      pdf_literalcode(dashed)
                    end
                  elseif dashed then
                    pdf_literalcode("[] 0 d")
                    dashed = false
                  end
%    \end{macrocode}
%    Added : shading and pattern
%    \begin{macrocode}
                  local shade_no = do_preobj_SH(object,prescript) -- shading
                  local pattern_ = do_preobj_PAT(object,prescript) -- pattern
                  local path = object.path
                  local transformed, penwidth = false, 1
                  local open = path and path[1].left_type and path[#path].right_type
                  local pen = object.pen
                  if pen then
                    if pen.type == 'elliptical' then
                      transformed, penwidth = pen_characteristics(object) -- boolean, value
                      pdf_literalcode("%f w",penwidth)
                      if objecttype == 'fill' then
                        objecttype = 'both'
                      end
                    else -- calculated by mplib itself
                      objecttype = 'fill'
                    end
                  end
                  if transformed then
                    start_pdf_code()
                  end
                  if path then
                    if savedpath then
                      for i=1,#savedpath do
                        local path = savedpath[i]
                        if transformed then
                          flushconcatpath(path,open)
                        else
                          flushnormalpath(path,open)
                        end
                      end
                      savedpath = nil
                    end
                    if transformed then
                      flushconcatpath(path,open)
                    else
                      flushnormalpath(path,open)
                    end
%    \end{macrocode}
%    Shading seems to conflict with these ops
%    \begin{macrocode}
                    if not shade_no then -- conflict with shading
                      if objecttype == "fill" then
                        pdf_literalcode(evenodd and "h f*" or "h f")
                      elseif objecttype == "outline" then
                        if both then
                          pdf_literalcode(evenodd and "h B*" or "h B")
                        else
                          pdf_literalcode(open and "S" or "h S")
                        end
                      elseif objecttype == "both" then
                        pdf_literalcode(evenodd and "h B*" or "h B")
                      end
                    end
                  end
                  if transformed then
                    stop_pdf_code()
                  end
                  local path = object.htap
                  if path then
                    if transformed then
                      start_pdf_code()
                    end
                    if savedhtap then
                      for i=1,#savedhtap do
                        local path = savedhtap[i]
                        if transformed then
                          flushconcatpath(path,open)
                        else
                          flushnormalpath(path,open)
                        end
                      end
                      savedhtap = nil
                      evenodd   = true
                    end
                    if transformed then
                      flushconcatpath(path,open)
                    else
                      flushnormalpath(path,open)
                    end
                    if objecttype == "fill" then
                      pdf_literalcode(evenodd and "h f*" or "h f")
                    elseif objecttype == "outline" then
                      pdf_literalcode(open and "S" or "h S")
                    elseif objecttype == "both" then
                      pdf_literalcode(evenodd and "h B*" or "h B")
                    end
                    if transformed then
                      stop_pdf_code()
                    end
                  end
%    \end{macrocode}
%    Added to ConTeXt general: post-object colors and shading stuff.
%    We should beware the |q ... Q| scope.
%    \begin{macrocode}
                  if shade_no then -- shading
                    pdf_literalcode("W n /MPlibSh%s sh Q",shade_no)
                  end
                end
              end
              if fading_ == "start" then
                pdfetcs.fading.specialeffects = {fading_, tr_opaq, cr_over}
              elseif trgroup == "start" then
                pdfetcs.tr_group.specialeffects = {fading_, tr_opaq, cr_over}
              elseif fading_ == "stop" then
                local se = pdfetcs.fading.specialeffects
                if se then stop_special_effects(se[1], se[2], se[3]) end
              elseif trgroup == "stop" then
                local se = pdfetcs.tr_group.specialeffects
                if se then stop_special_effects(se[1], se[2], se[3]) end
              else
                stop_special_effects(fading_, tr_opaq, cr_over)
              end
              if fading_ or trgroup then -- extgs resetted
                miterlimit, linecap, linejoin, dashed = -1, -1, -1, false
              end
            end
          end
          stop_pdf_code()
          pdf_stopfigure()
%    \end{macrocode}
%    output collected materials to PDF, plus legacy |verbatimtex| code.
%    \begin{macrocode}
          for _,v in ipairs(figcontents) do
            if type(v) == "table" then
              texsprint"\\mplibtoPDF{"; texsprint(v[1], v[2]); texsprint"}"
            else
              texsprint(v)
            end
          end
          if #figcontents.post > 0 then texsprint(figcontents.post) end
          figcontents = { post = { } }
        end
      end
    end
  end
end

function luamplib.colorconverter (cr)
  local n = #cr
  if n == 4 then
    local c, m, y, k = cr[1], cr[2], cr[3], cr[4]
    return format("%.3f %.3f %.3f %.3f k %.3f %.3f %.3f %.3f K",c,m,y,k,c,m,y,k), "0 g 0 G"
  elseif n == 3 then
    local r, g, b = cr[1], cr[2], cr[3]
    return format("%.3f %.3f %.3f rg %.3f %.3f %.3f RG",r,g,b,r,g,b), "0 g 0 G"
  else
    local s = cr[1]
    return format("%.3f g %.3f G",s,s), "0 g 0 G"
  end
end
%    \end{macrocode}
%
% \iffalse
%</lua>
% \fi
%
%    \subsection{\texorpdfstring{\TeX}{TeX} package}
%
%
% \iffalse
%<*package>
% \fi
%
%    First we need to load some packages.
%
%    \begin{macrocode}
\bgroup\expandafter\expandafter\expandafter\egroup
\expandafter\ifx\csname selectfont\endcsname\relax
  \input ltluatex
\else
  \NeedsTeXFormat{LaTeX2e}
  \ProvidesPackage{luamplib}
    [2024/07/19 v2.34.1 mplib package for LuaTeX]
  \ifx\newluafunction\@undefined
  \input ltluatex
  \fi
\fi
%    \end{macrocode}
%
%    Loading of lua code.
%    \begin{macrocode}
\directlua{require("luamplib")}
%    \end{macrocode}
%
%    legacy commands. Seems we don't need it, but no harm.
%    \begin{macrocode}
\ifx\pdfoutput\undefined
  \let\pdfoutput\outputmode
\fi
\ifx\pdfliteral\undefined
  \protected\def\pdfliteral{\pdfextension literal}
\fi
%    \end{macrocode}
%
%    Set the format for metapost.
%    \begin{macrocode}
\def\mplibsetformat#1{\directlua{luamplib.setformat("#1")}}
%    \end{macrocode}
%
%    luamplib works in both PDF and DVI mode,
%    but only DVIPDFMx is supported currently among a number of DVI tools.
%    So we output a info.
%    \begin{macrocode}
\ifnum\pdfoutput>0
  \let\mplibtoPDF\pdfliteral
\else
  \def\mplibtoPDF#1{\special{pdf:literal direct #1}}
  \ifcsname PackageInfo\endcsname
    \PackageInfo{luamplib}{only dvipdfmx is supported currently}
  \else
    \immediate\write-1{luamplib Info: only dvipdfmx is supported currently}
  \fi
\fi
%    \end{macrocode}
%
%    To make |mplibcode| typeset always in horizontal mode.
%    \begin{macrocode}
\def\mplibforcehmode{\let\prependtomplibbox\leavevmode}
\def\mplibnoforcehmode{\let\prependtomplibbox\relax}
\mplibnoforcehmode
%    \end{macrocode}
%
%    Catcode. We want to allow comment sign in |mplibcode|.
%    \begin{macrocode}
\def\mplibsetupcatcodes{%
  %catcode`\{=12 %catcode`\}=12
  \catcode`\#=12 \catcode`\^=12 \catcode`\~=12 \catcode`\_=12
  \catcode`\&=12 \catcode`\$=12 \catcode`\%=12 \catcode`\^^M=12
}
%    \end{macrocode}
%
%    Make |btex...etex| box zero-metric.
%    \begin{macrocode}
\def\mplibputtextbox#1{\vbox to 0pt{\vss\hbox to 0pt{\raise\dp#1\copy#1\hss}}}
%    \end{macrocode}
%
%    use Transparency Group
%    \begin{macrocode}
\protected\def\usemplibgroup#1{\csname luamplib.group.#1\endcsname}
%    \end{macrocode}
%
%    Patterns
%    \begin{macrocode}
{\def\:{\global\let\mplibsptoken= } \: }
\protected\def\mppattern#1{%
  \begingroup
  \def\mplibpatternname{#1}%
  \mplibpatterngetnexttok
}
\def\mplibpatterngetnexttok{\futurelet\nexttok\mplibpatternbranch}
\def\mplibpatternskipspace{\afterassignment\mplibpatterngetnexttok\let\nexttok= }
\def\mplibpatternbranch{%
  \ifx [\nexttok
    \expandafter\mplibpatternopts
  \else
    \ifx\mplibsptoken\nexttok
      \expandafter\expandafter\expandafter\mplibpatternskipspace
    \else
      \let\mplibpatternoptions\empty
      \expandafter\expandafter\expandafter\mplibpatternmain
    \fi
  \fi
}
\def\mplibpatternopts[#1]{%
  \def\mplibpatternoptions{#1}%
  \mplibpatternmain
}
\def\mplibpatternmain{%
  \setbox\mplibscratchbox\hbox\bgroup\ignorespaces
}
\protected\def\endmppattern{%
  \egroup
  \directlua{ luamplib.registerpattern(
    \the\mplibscratchbox, '\mplibpatternname', {\mplibpatternoptions}
  )}%
  \endgroup
}
%    \end{macrocode}
%
%    simple way to use mplib:
%    |\mpfig draw fullcircle scaled 10; \endmpfig|
%    \begin{macrocode}
\def\mpfiginstancename{@mpfig}
\protected\def\mpfig{%
  \begingroup
  \futurelet\nexttok\mplibmpfigbranch
}
\def\mplibmpfigbranch{%
  \ifx *\nexttok
    \expandafter\mplibprempfig
  \else
    \expandafter\mplibmainmpfig
  \fi
}
\def\mplibmainmpfig{%
  \begingroup
  \mplibsetupcatcodes
  \mplibdomainmpfig
}
\long\def\mplibdomainmpfig#1\endmpfig{%
  \endgroup
  \directlua{
    local legacy = luamplib.legacyverbatimtex
    local everympfig = luamplib.everymplib["\mpfiginstancename"] or ""
    local everyendmpfig = luamplib.everyendmplib["\mpfiginstancename"] or ""
    luamplib.legacyverbatimtex = false
    luamplib.everymplib["\mpfiginstancename"] = ""
    luamplib.everyendmplib["\mpfiginstancename"] = ""
    luamplib.process_mplibcode(
    "beginfig(0) "..everympfig.." "..[===[\unexpanded{#1}]===].." "..everyendmpfig.." endfig;",
    "\mpfiginstancename")
    luamplib.legacyverbatimtex = legacy
    luamplib.everymplib["\mpfiginstancename"] = everympfig
    luamplib.everyendmplib["\mpfiginstancename"] = everyendmpfig
  }%
  \endgroup
}
\def\mplibprempfig#1{%
  \begingroup
  \mplibsetupcatcodes
  \mplibdoprempfig
}
\long\def\mplibdoprempfig#1\endmpfig{%
  \endgroup
  \directlua{
    local legacy = luamplib.legacyverbatimtex
    local everympfig = luamplib.everymplib["\mpfiginstancename"]
    local everyendmpfig = luamplib.everyendmplib["\mpfiginstancename"]
    luamplib.legacyverbatimtex = false
    luamplib.everymplib["\mpfiginstancename"] = ""
    luamplib.everyendmplib["\mpfiginstancename"] = ""
    luamplib.process_mplibcode([===[\unexpanded{#1}]===],"\mpfiginstancename")
    luamplib.legacyverbatimtex = legacy
    luamplib.everymplib["\mpfiginstancename"] = everympfig
    luamplib.everyendmplib["\mpfiginstancename"] = everyendmpfig
  }%
  \endgroup
}
\protected\def\endmpfig{endmpfig}
%    \end{macrocode}
%
%    The Plain-specific stuff.
%    \begin{macrocode}
\unless\ifcsname ver@luamplib.sty\endcsname
  \def\mplibcodegetinstancename[#1]{\gdef\currentmpinstancename{#1}\mplibcodeindeed}
  \protected\def\mplibcode{%
    \begingroup
    \futurelet\nexttok\mplibcodebranch
  }
  \def\mplibcodebranch{%
    \ifx [\nexttok
      \expandafter\mplibcodegetinstancename
    \else
      \global\let\currentmpinstancename\empty
      \expandafter\mplibcodeindeed
    \fi
  }
  \def\mplibcodeindeed{%
    \begingroup
    \mplibsetupcatcodes
    \mplibdocode
  }
  \long\def\mplibdocode#1\endmplibcode{%
    \endgroup
    \directlua{luamplib.process_mplibcode([===[\unexpanded{#1}]===],"\currentmpinstancename")}%
    \endgroup
  }
  \protected\def\endmplibcode{endmplibcode}
\else
%    \end{macrocode}
%
%    The \LaTeX-specific part: a new environment.
%    \begin{macrocode}
  \newenvironment{mplibcode}[1][]{%
    \global\def\currentmpinstancename{#1}%
    \mplibtmptoks{}\ltxdomplibcode
  }{}
  \def\ltxdomplibcode{%
    \begingroup
    \mplibsetupcatcodes
    \ltxdomplibcodeindeed
  }
  \def\mplib@mplibcode{mplibcode}
  \long\def\ltxdomplibcodeindeed#1\end#2{%
    \endgroup
    \mplibtmptoks\expandafter{\the\mplibtmptoks#1}%
    \def\mplibtemp@a{#2}%
    \ifx\mplib@mplibcode\mplibtemp@a
      \directlua{luamplib.process_mplibcode([===[\the\mplibtmptoks]===],"\currentmpinstancename")}%
      \end{mplibcode}%
    \else
      \mplibtmptoks\expandafter{\the\mplibtmptoks\end{#2}}%
      \expandafter\ltxdomplibcode
    \fi
  }
\fi
%    \end{macrocode}
%
%    User settings.
%    \begin{macrocode}
\def\mplibshowlog#1{\directlua{
    local s = string.lower("#1")
    if s == "enable" or s == "true" or s == "yes" then
      luamplib.showlog = true
    else
      luamplib.showlog = false
    end
}}
\def\mpliblegacybehavior#1{\directlua{
    local s = string.lower("#1")
    if s == "enable" or s == "true" or s == "yes" then
      luamplib.legacyverbatimtex = true
    else
      luamplib.legacyverbatimtex = false
    end
}}
\def\mplibverbatim#1{\directlua{
    local s = string.lower("#1")
    if s == "enable" or s == "true" or s == "yes" then
      luamplib.verbatiminput = true
    else
      luamplib.verbatiminput = false
    end
}}
\newtoks\mplibtmptoks
%    \end{macrocode}
%
%    \cs{everymplib} \& \cs{everyendmplib}: macros resetting
%    |luamplib.every(end)mplib| tables
%
%    \begin{macrocode}
\ifcsname ver@luamplib.sty\endcsname
  \protected\def\everymplib{%
    \begingroup
    \mplibsetupcatcodes
    \mplibdoeverymplib
  }
  \protected\def\everyendmplib{%
    \begingroup
    \mplibsetupcatcodes
    \mplibdoeveryendmplib
  }
  \newcommand\mplibdoeverymplib[2][]{%
    \endgroup
    \directlua{
      luamplib.everymplib["#1"] = [===[\unexpanded{#2}]===]
    }%
  }
  \newcommand\mplibdoeveryendmplib[2][]{%
    \endgroup
    \directlua{
      luamplib.everyendmplib["#1"] = [===[\unexpanded{#2}]===]
    }%
  }
\else
  \def\mplibgetinstancename[#1]{\def\currentmpinstancename{#1}}
  \protected\def\everymplib#1#{%
    \ifx\empty#1\empty \mplibgetinstancename[]\else \mplibgetinstancename#1\fi
    \begingroup
    \mplibsetupcatcodes
    \mplibdoeverymplib
  }
  \long\def\mplibdoeverymplib#1{%
    \endgroup
    \directlua{
      luamplib.everymplib["\currentmpinstancename"] = [===[\unexpanded{#1}]===]
    }%
  }
  \protected\def\everyendmplib#1#{%
    \ifx\empty#1\empty \mplibgetinstancename[]\else \mplibgetinstancename#1\fi
    \begingroup
    \mplibsetupcatcodes
    \mplibdoeveryendmplib
  }
  \long\def\mplibdoeveryendmplib#1{%
    \endgroup
    \directlua{
      luamplib.everyendmplib["\currentmpinstancename"] = [===[\unexpanded{#1}]===]
    }%
  }
\fi
%    \end{macrocode}
%
%    Allow \TeX\ dimen/color macros. Now |runscript| does the job,
%    so the following lines are not needed for most cases.
%    \begin{macrocode}
\def\mpdim#1{ runscript("luamplibdimen{#1}") }
\def\mpcolor#1#{\domplibcolor{#1}}
\def\domplibcolor#1#2{ runscript("luamplibcolor{#1{#2}}") }
%    \end{macrocode}
%
%    MPLib's number system. Now |binary| has gone away.
%    \begin{macrocode}
\def\mplibnumbersystem#1{\directlua{
  local t = "#1"
  if t == "binary" then t = "decimal" end
  luamplib.numbersystem = t
}}
%    \end{macrocode}
%
%    Settings for |.mp| cache files.
%    \begin{macrocode}
\def\mplibmakenocache#1{\mplibdomakenocache #1,*,}
\def\mplibdomakenocache#1,{%
  \ifx\empty#1\empty
    \expandafter\mplibdomakenocache
  \else
    \ifx*#1\else
      \directlua{luamplib.noneedtoreplace["#1.mp"]=true}%
      \expandafter\expandafter\expandafter\mplibdomakenocache
    \fi
  \fi
}
\def\mplibcancelnocache#1{\mplibdocancelnocache #1,*,}
\def\mplibdocancelnocache#1,{%
  \ifx\empty#1\empty
    \expandafter\mplibdocancelnocache
  \else
    \ifx*#1\else
      \directlua{luamplib.noneedtoreplace["#1.mp"]=false}%
      \expandafter\expandafter\expandafter\mplibdocancelnocache
    \fi
  \fi
}
\def\mplibcachedir#1{\directlua{luamplib.getcachedir("\unexpanded{#1}")}}
%    \end{macrocode}
%
%    More user settings.
%    \begin{macrocode}
\def\mplibtextextlabel#1{\directlua{
    local s = string.lower("#1")
    if s == "enable" or s == "true" or s == "yes" then
      luamplib.textextlabel = true
    else
      luamplib.textextlabel = false
    end
}}
\def\mplibcodeinherit#1{\directlua{
    local s = string.lower("#1")
    if s == "enable" or s == "true" or s == "yes" then
      luamplib.codeinherit = true
    else
      luamplib.codeinherit = false
    end
}}
\def\mplibglobaltextext#1{\directlua{
    local s = string.lower("#1")
    if s == "enable" or s == "true" or s == "yes" then
      luamplib.globaltextext = true
    else
      luamplib.globaltextext = false
    end
}}
%    \end{macrocode}
%
%    The followings are from ConTeXt general, mostly.
%
%    We use a dedicated scratchbox.
%    \begin{macrocode}
\ifx\mplibscratchbox\undefined \newbox\mplibscratchbox \fi
%    \end{macrocode}
%
%    We encapsulate the literals.
%    \begin{macrocode}
\def\mplibstarttoPDF#1#2#3#4{%
  \prependtomplibbox
  \hbox dir TLT\bgroup
  \xdef\MPllx{#1}\xdef\MPlly{#2}%
  \xdef\MPurx{#3}\xdef\MPury{#4}%
  \xdef\MPwidth{\the\dimexpr#3bp-#1bp\relax}%
  \xdef\MPheight{\the\dimexpr#4bp-#2bp\relax}%
  \parskip0pt%
  \leftskip0pt%
  \parindent0pt%
  \everypar{}%
  \setbox\mplibscratchbox\vbox\bgroup
  \noindent
}
\def\mplibstoptoPDF{%
  \par
  \egroup %
  \setbox\mplibscratchbox\hbox %
    {\hskip-\MPllx bp%
     \raise-\MPlly bp%
     \box\mplibscratchbox}%
  \setbox\mplibscratchbox\vbox to \MPheight
    {\vfill
     \hsize\MPwidth
     \wd\mplibscratchbox0pt%
     \ht\mplibscratchbox0pt%
     \dp\mplibscratchbox0pt%
     \box\mplibscratchbox}%
  \wd\mplibscratchbox\MPwidth
  \ht\mplibscratchbox\MPheight
  \box\mplibscratchbox
  \egroup
}
%    \end{macrocode}
%
%    Text items have a special handler.
%    \begin{macrocode}
\def\mplibtextext#1#2#3#4#5{%
  \begingroup
  \setbox\mplibscratchbox\hbox
    {\font\temp=#1 at #2bp%
     \temp
     #3}%
  \setbox\mplibscratchbox\hbox
    {\hskip#4 bp%
     \raise#5 bp%
     \box\mplibscratchbox}%
  \wd\mplibscratchbox0pt%
  \ht\mplibscratchbox0pt%
  \dp\mplibscratchbox0pt%
  \box\mplibscratchbox
  \endgroup
}
%    \end{macrocode}
%
%    Input |luamplib.cfg| when it exists.
%    \begin{macrocode}
\openin0=luamplib.cfg
\ifeof0 \else
  \closein0
  \input luamplib.cfg
\fi
%    \end{macrocode}
%
%    That's all folks!
%
% \iffalse
%</package>
% \fi
%
% \clearpage
% \section{The GNU GPL License v2}
%
% The GPL requires the complete license text to be distributed along
% with the code. I recommend the canonical source, instead:
% \url{http://www.gnu.org/licenses/old-licenses/gpl-2.0.html}.
% But if you insist on an included copy, here it is.
% You might want to zoom in.
%
% \newsavebox{\gpl}
% \begin{lrbox}{\gpl}
% \begin{minipage}{3\textwidth}
% \columnsep=3\columnsep
% \begin{multicols}{3}
% \begin{center}
% {\Large GNU GENERAL PUBLIC LICENSE\par}
% \bigskip
% {Version 2, June 1991}
% \end{center}
%
% \begin{center}
% {\parindent 0in
%
% Copyright \textcopyright\ 1989, 1991 Free Software Foundation, Inc.
%
% \bigskip
%
% 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
%
% \bigskip
%
% Everyone is permitted to copy and distribute verbatim copies
% of this license document, but changing it is not allowed.
% }
% \end{center}
%
% \begin{center}
% {\bf\large Preamble}
% \end{center}
%
%
% The licenses for most software are designed to take away your freedom to
% share and change it.  By contrast, the GNU General Public License is
% intended to guarantee your freedom to share and change free software---to
% make sure the software is free for all its users.  This General Public
% License applies to most of the Free Software Foundation's software and to
% any other program whose authors commit to using it.  (Some other Free
% Software Foundation software is covered by the GNU Library General Public
% License instead.)  You can apply it to your programs, too.
%
% When we speak of free software, we are referring to freedom, not price.
% Our General Public Licenses are designed to make sure that you have the
% freedom to distribute copies of free software (and charge for this service
% if you wish), that you receive source code or can get it if you want it,
% that you can change the software or use pieces of it in new free programs;
% and that you know you can do these things.
%
% To protect your rights, we need to make restrictions that forbid anyone to
% deny you these rights or to ask you to surrender the rights.  These
% restrictions translate to certain responsibilities for you if you
% distribute copies of the software, or if you modify it.
%
% For example, if you distribute copies of such a program, whether gratis or
% for a fee, you must give the recipients all the rights that you have.  You
% must make sure that they, too, receive or can get the source code.  And
% you must show them these terms so they know their rights.
%
% We protect your rights with two steps: (1) copyright the software, and (2)
% offer you this license which gives you legal permission to copy,
% distribute and/or modify the software.
%
% Also, for each author's protection and ours, we want to make certain that
% everyone understands that there is no warranty for this free software.  If
% the software is modified by someone else and passed on, we want its
% recipients to know that what they have is not the original, so that any
% problems introduced by others will not reflect on the original authors'
% reputations.
%
% Finally, any free program is threatened constantly by software patents.
% We wish to avoid the danger that redistributors of a free program will
% individually obtain patent licenses, in effect making the program
% proprietary.  To prevent this, we have made it clear that any patent must
% be licensed for everyone's free use or not licensed at all.
%
% The precise terms and conditions for copying, distribution and
% modification follow.
%
% \begin{center}
% {\Large \sc Terms and Conditions For Copying, Distribution and
%   Modification}
% \end{center}
%
% \begin{enumerate}
% \item
% This License applies to any program or other work which contains a notice
% placed by the copyright holder saying it may be distributed under the
% terms of this General Public License.  The ``Program'', below, refers to
% any such program or work, and a ``work based on the Program'' means either
% the Program or any derivative work under copyright law: that is to say, a
% work containing the Program or a portion of it, either verbatim or with
% modifications and/or translated into another language.  (Hereinafter,
% translation is included without limitation in the term ``modification''.)
% Each licensee is addressed as ``you''.
%
% Activities other than copying, distribution and modification are not
% covered by this License; they are outside its scope.  The act of
% running the Program is not restricted, and the output from the Program
% is covered only if its contents constitute a work based on the
% Program (independent of having been made by running the Program).
% Whether that is true depends on what the Program does.
%
% \item You may copy and distribute verbatim copies of the Program's source
%   code as you receive it, in any medium, provided that you conspicuously
%   and appropriately publish on each copy an appropriate copyright notice
%   and disclaimer of warranty; keep intact all the notices that refer to
%   this License and to the absence of any warranty; and give any other
%   recipients of the Program a copy of this License along with the Program.
%
% You may charge a fee for the physical act of transferring a copy, and you
% may at your option offer warranty protection in exchange for a fee.
%
% \item
% You may modify your copy or copies of the Program or any portion
% of it, thus forming a work based on the Program, and copy and
% distribute such modifications or work under the terms of Section 1
% above, provided that you also meet all of these conditions:
%
% \begin{enumerate}
%
% \item
% You must cause the modified files to carry prominent notices stating that
% you changed the files and the date of any change.
%
% \item
% You must cause any work that you distribute or publish, that in
% whole or in part contains or is derived from the Program or any
% part thereof, to be licensed as a whole at no charge to all third
% parties under the terms of this License.
%
% \item
% If the modified program normally reads commands interactively
% when run, you must cause it, when started running for such
% interactive use in the most ordinary way, to print or display an
% announcement including an appropriate copyright notice and a
% notice that there is no warranty (or else, saying that you provide
% a warranty) and that users may redistribute the program under
% these conditions, and telling the user how to view a copy of this
% License.  (Exception: if the Program itself is interactive but
% does not normally print such an announcement, your work based on
% the Program is not required to print an announcement.)
%
% \end{enumerate}
%
%
% These requirements apply to the modified work as a whole.  If
% identifiable sections of that work are not derived from the Program,
% and can be reasonably considered independent and separate works in
% themselves, then this License, and its terms, do not apply to those
% sections when you distribute them as separate works.  But when you
% distribute the same sections as part of a whole which is a work based
% on the Program, the distribution of the whole must be on the terms of
% this License, whose permissions for other licensees extend to the
% entire whole, and thus to each and every part regardless of who wrote it.
%
% Thus, it is not the intent of this section to claim rights or contest
% your rights to work written entirely by you; rather, the intent is to
% exercise the right to control the distribution of derivative or
% collective works based on the Program.
%
% In addition, mere aggregation of another work not based on the Program
% with the Program (or with a work based on the Program) on a volume of
% a storage or distribution medium does not bring the other work under
% the scope of this License.
%
% \item
% You may copy and distribute the Program (or a work based on it,
% under Section 2) in object code or executable form under the terms of
% Sections 1 and 2 above provided that you also do one of the following:
%
% \begin{enumerate}
%
% \item
%
% Accompany it with the complete corresponding machine-readable
% source code, which must be distributed under the terms of Sections
% 1 and 2 above on a medium customarily used for software interchange; or,
%
% \item
%
% Accompany it with a written offer, valid for at least three
% years, to give any third party, for a charge no more than your
% cost of physically performing source distribution, a complete
% machine-readable copy of the corresponding source code, to be
% distributed under the terms of Sections 1 and 2 above on a medium
% customarily used for software interchange; or,
%
% \item
%
% Accompany it with the information you received as to the offer
% to distribute corresponding source code.  (This alternative is
% allowed only for noncommercial distribution and only if you
% received the program in object code or executable form with such
% an offer, in accord with Subsection b above.)
%
% \end{enumerate}
%
%
% The source code for a work means the preferred form of the work for
% making modifications to it.  For an executable work, complete source
% code means all the source code for all modules it contains, plus any
% associated interface definition files, plus the scripts used to
% control compilation and installation of the executable.  However, as a
% special exception, the source code distributed need not include
% anything that is normally distributed (in either source or binary
% form) with the major components (compiler, kernel, and so on) of the
% operating system on which the executable runs, unless that component
% itself accompanies the executable.
%
% If distribution of executable or object code is made by offering
% access to copy from a designated place, then offering equivalent
% access to copy the source code from the same place counts as
% distribution of the source code, even though third parties are not
% compelled to copy the source along with the object code.
%
% \item
% You may not copy, modify, sublicense, or distribute the Program
% except as expressly provided under this License.  Any attempt
% otherwise to copy, modify, sublicense or distribute the Program is
% void, and will automatically terminate your rights under this License.
% However, parties who have received copies, or rights, from you under
% this License will not have their licenses terminated so long as such
% parties remain in full compliance.
%
% \item
% You are not required to accept this License, since you have not
% signed it.  However, nothing else grants you permission to modify or
% distribute the Program or its derivative works.  These actions are
% prohibited by law if you do not accept this License.  Therefore, by
% modifying or distributing the Program (or any work based on the
% Program), you indicate your acceptance of this License to do so, and
% all its terms and conditions for copying, distributing or modifying
% the Program or works based on it.
%
% \item
% Each time you redistribute the Program (or any work based on the
% Program), the recipient automatically receives a license from the
% original licensor to copy, distribute or modify the Program subject to
% these terms and conditions.  You may not impose any further
% restrictions on the recipients' exercise of the rights granted herein.
% You are not responsible for enforcing compliance by third parties to
% this License.
%
% \item
% If, as a consequence of a court judgment or allegation of patent
% infringement or for any other reason (not limited to patent issues),
% conditions are imposed on you (whether by court order, agreement or
% otherwise) that contradict the conditions of this License, they do not
% excuse you from the conditions of this License.  If you cannot
% distribute so as to satisfy simultaneously your obligations under this
% License and any other pertinent obligations, then as a consequence you
% may not distribute the Program at all.  For example, if a patent
% license would not permit royalty-free redistribution of the Program by
% all those who receive copies directly or indirectly through you, then
% the only way you could satisfy both it and this License would be to
% refrain entirely from distribution of the Program.
%
% If any portion of this section is held invalid or unenforceable under
% any particular circumstance, the balance of the section is intended to
% apply and the section as a whole is intended to apply in other
% circumstances.
%
% It is not the purpose of this section to induce you to infringe any
% patents or other property right claims or to contest validity of any
% such claims; this section has the sole purpose of protecting the
% integrity of the free software distribution system, which is
% implemented by public license practices.  Many people have made
% generous contributions to the wide range of software distributed
% through that system in reliance on consistent application of that
% system; it is up to the author/donor to decide if he or she is willing
% to distribute software through any other system and a licensee cannot
% impose that choice.
%
% This section is intended to make thoroughly clear what is believed to
% be a consequence of the rest of this License.
%
% \item
% If the distribution and/or use of the Program is restricted in
% certain countries either by patents or by copyrighted interfaces, the
% original copyright holder who places the Program under this License
% may add an explicit geographical distribution limitation excluding
% those countries, so that distribution is permitted only in or among
% countries not thus excluded.  In such case, this License incorporates
% the limitation as if written in the body of this License.
%
% \item
% The Free Software Foundation may publish revised and/or new versions
% of the General Public License from time to time.  Such new versions will
% be similar in spirit to the present version, but may differ in detail to
% address new problems or concerns.
%
% Each version is given a distinguishing version number.  If the Program
% specifies a version number of this License which applies to it and ``any
% later version'', you have the option of following the terms and conditions
% either of that version or of any later version published by the Free
% Software Foundation.  If the Program does not specify a version number of
% this License, you may choose any version ever published by the Free Software
% Foundation.
%
% \item
% If you wish to incorporate parts of the Program into other free
% programs whose distribution conditions are different, write to the author
% to ask for permission.  For software which is copyrighted by the Free
% Software Foundation, write to the Free Software Foundation; we sometimes
% make exceptions for this.  Our decision will be guided by the two goals
% of preserving the free status of all derivatives of our free software and
% of promoting the sharing and reuse of software generally.
%
% \begin{center}
% {\Large\sc
% No Warranty
% }
% \end{center}
%
% \item
% {\sc Because the program is licensed free of charge, there is no warranty
% for the program, to the extent permitted by applicable law.  Except when
% otherwise stated in writing the copyright holders and/or other parties
% provide the program ``as is'' without warranty of any kind, either expressed
% or implied, including, but not limited to, the implied warranties of
% merchantability and fitness for a particular purpose.  The entire risk as
% to the quality and performance of the program is with you.  Should the
% program prove defective, you assume the cost of all necessary servicing,
% repair or correction.}
%
% \item
% {\sc In no event unless required by applicable law or agreed to in writing
% will any copyright holder, or any other party who may modify and/or
% redistribute the program as permitted above, be liable to you for damages,
% including any general, special, incidental or consequential damages arising
% out of the use or inability to use the program (including but not limited
% to loss of data or data being rendered inaccurate or losses sustained by
% you or third parties or a failure of the program to operate with any other
% programs), even if such holder or other party has been advised of the
% possibility of such damages.}
%
% \end{enumerate}
%
%
% \begin{center}
% {\Large\sc End of Terms and Conditions}
% \end{center}
%
%
% \pagebreak[2]
%
% \section*{Appendix: How to Apply These Terms to Your New Programs}
%
% If you develop a new program, and you want it to be of the greatest
% possible use to the public, the best way to achieve this is to make it
% free software which everyone can redistribute and change under these
% terms.
%
%   To do so, attach the following notices to the program.  It is safest to
%   attach them to the start of each source file to most effectively convey
%   the exclusion of warranty; and each file should have at least the
%   ``copyright'' line and a pointer to where the full notice is found.
%
% \begin{quote}
% one line to give the program's name and a brief idea of what it does. \\
% Copyright (C) yyyy  name of author \\
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
% \end{quote}
%
% Also add information on how to contact you by electronic and paper mail.
%
% If the program is interactive, make it output a short notice like this
% when it starts in an interactive mode:
%
% \begin{quote}
% Gnomovision version 69, Copyright (C) yyyy  name of author \\
% Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. \\
% This is free software, and you are welcome to redistribute it
% under certain conditions; type `show c' for details.
% \end{quote}
%
%
% The hypothetical commands {\tt show w} and {\tt show c} should show the
% appropriate parts of the General Public License.  Of course, the commands
% you use may be called something other than {\tt show w} and {\tt show c};
% they could even be mouse-clicks or menu items---whatever suits your
% program.
%
% You should also get your employer (if you work as a programmer) or your
% school, if any, to sign a ``copyright disclaimer'' for the program, if
% necessary.  Here is a sample; alter the names:
%
% \begin{quote}
% Yoyodyne, Inc., hereby disclaims all copyright interest in the program \\
% `Gnomovision' (which makes passes at compilers) written by James Hacker. \\
%
% signature of Ty Coon, 1 April 1989 \\
% Ty Coon, President of Vice
% \end{quote}
%
%
% This General Public License does not permit incorporating your program
% into proprietary programs.  If your program is a subroutine library, you
% may consider it more useful to permit linking proprietary applications
% with the library.  If this is what you want to do, use the GNU Library
% General Public License instead of this License.
%
% \end{multicols}
% \end{minipage}
% \end{lrbox}
%
% \begin{center}
% \scalebox{0.33}{\usebox{\gpl}}
% \end{center}
%
% \Finale
\endinput