forked from lualatex/luamplib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathluamplib.dtx
More file actions
2831 lines (2708 loc) · 93.8 KB
/
luamplib.dtx
File metadata and controls
2831 lines (2708 loc) · 93.8 KB
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
% \iffalse meta-comment -- by the way, this file contains UTF-8
%
% Copyright (C) 2008-2022 by Hans Hagen, Taco Hoekwater, Elie Roux,
% Manuel Pégourié-Gonnard, Philipp Gesang and Kim Dohyun.
% Currently maintained by the LuaLaTeX development team.
% Support: <lualatex-dev@tug.org>
%
% 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}%
[2022/01/12 v2.23.0 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[Ligatures=TeX,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\\
% Maintainer: LuaLaTeX Maintainers ---
% Support: \email{lualatex-dev@tug.org}}
% \date{2022/01/12 v2.23.0}
%
% \maketitle
%
% \begin{abstract}
% Package to have metapost code typeset directly in a document with \LuaTeX.
% \end{abstract}
%
% \section{Documentation}
%
% This packages aims at providing a simple way to typeset directly metapost
% code in a document with \LuaTeX. \LuaTeX\ is built with the lua
% \texttt{mplib} library, that runs metapost code. This package is basically a
% wrapper (in Lua) for the Lua \texttt{mplib} functions and some \TeX\
% functions to have the output of the \texttt{mplib} functions in the pdf.
%
% In the past,
% the package required PDF mode in order to output something.
% Starting with version 2.7 it works in DVI mode as well, though
% DVIPDFMx is the only DVI tool currently supported.
%
% The metapost figures are put in a \TeX\ \texttt{hbox} with dimensions
% adjusted to the metapost code.
%
% 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 code is from the \texttt{luatex-mplib.lua} and \texttt{luatex-mplib.tex} files
% from \ConTeXt, they have been adapted to \LaTeX\ and Plain by Elie Roux and
% Philipp Gesang, new functionalities have been added by Kim Dohyun.
% The changes are:
%
% \begin{itemize}
% \item a \LaTeX\ environment
% \item all \TeX\ macros start by |mplib|
% \item use of luatexbase for errors, warnings and declaration
% \item possibility to use |btex ... etex| to typeset \TeX\ code.
% |textext()| is a more versatile macro equivalent to |TEX()| from TEX.mp.
% |TEX()| is also allowed and is a synomym of |textext()|.\par\smallskip
% \textsc{n.b.} Since v2.5, |btex ... etex| input from external |mp| files
% will also be processed by \textsf{luamplib}.\par\smallskip
% \textsc{n.b.} Since v2.20, |verbatimtex ... etex| from external |mp| files
% will be also processed by \textsf{luamplib}. Warning: This is a change
% from previous version.
% \end{itemize}
%
% Some more changes and cautions are:
%
% \paragraph{\cs{mplibforcehmode}}
% When this macro is declared, every mplibcode 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 define this command with anything suitable before a box.)
%
% \paragraph{\cs{mpliblegacybehavior\{enable\}}}
% By default, |\mpliblegacybehavior{enable}| is already declared,
% in which case
% a |verbatimtex ... etex| that comes just before |beginfig()|
% is not ignored, but the \TeX\ code will be inserted before the
% following mplib hbox. Using this command,
% each mplib box can be freely moved horizontally and/or vertically.
% Also, a box number might be assigned to mplib box, allowing it to be
% reused later (see test files).
% \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|.
%
% By contrast, \TeX\ code in |VerbatimTeX(...)| or |verbatimtex ... etex|
% between |beginfig()| and |endfig| will be inserted
% after flushing out the mplib figure.
% \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}
%
% \paragraph{\cs{mpliblegacybehavior\{disable\}}}
% If |\mpliblegacybehavior{disabled}| is declared by user, 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
% |btex ... etex| codes that follows.
% \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{About figure box metrics}
% Notice that, after each figure is processed, macro \cs{MPwidth} stores
% the width value of 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 latest figure
% without the unit |bp|.
%
% \paragraph{\cs{everymplib}, \cs{everyendmplib}}
% Since v2.3, new macros \cs{everymplib} and \cs{everyendmplib} redefine
% the lua table containing MetaPost code
% which will
% be automatically inserted at the beginning and ending of each |mplibcode|.
% \begin{verbatim}
% \everymplib{ beginfig(0); }
% \everyendmplib{ endfig; }
% \mplibcode % beginfig/endfig not needed
% draw fullcircle scaled 1cm;
% \endmplibcode
% \end{verbatim}
%
% \paragraph{\cs{mpdim}}
% Since v2.3, \cs{mpdim} and other raw \TeX\ commands are allowed
% inside mplib code. This feature is inpired by gmp.sty authored by
% Enrico Gregorio. Please refer the manual of gmp package for details.
% \begin{verbatim}
% \begin{mplibcode}
% draw origin--(\mpdim{\linewidth},0) withpen pencircle scaled 4
% dashed evenly scaled 4 withcolor \mpcolor{orange};
% \end{mplibcode}
% \end{verbatim}
% \textsc{n.b.} Users should not use the protected variant of
% |btex ... etex| as provided by gmp package. As \textsf{luamplib}
% automatically protects \TeX\ code inbetween, \cs{btex} is not supported
% here.
%
% \paragraph{\cs{mpcolor}}
% With \cs{mpcolor} command, color names or expressions of
% \textsf{color}/\textsf{xcolor} packages can be used inside mplibcode
% enviroment (after |withcolor| operator),
% though \textsf{luamplib} does not automatically load these
% packages. See the example code above. For spot colors, \textsf{(x)spotcolor}
% (in PDF mode) and \textsf{xespotcolor} (in DVI mode) packages are supported
% as well.
%
% \paragraph{\cs{mplibnumbersystem}}
% Users can choose |numbersystem| option since v2.4.
% The default value |scaled| can be changed to |double| or |decimal|
% by declaring |\mplibnumbersystem{double}| or |\mplibnumbersystem{decimal}|.
% For details see
% \url{http://github.com/lualatex/luamplib/issues/21}.
%
% \paragraph{Settings regarding cache files}
% To support |btex ... etex| in external |.mp| files, \textsf{luamplib}
% inspects the content of each and every |.mp| input files and makes caches
% if nececcsary, before returning their paths to \LuaTeX's mplib library.
% This would make the compilation time longer wastefully, as most |.mp| files
% do not contain |btex ... etex| command. So \textsf{luamplib} provides
% macros as follows, so that users can give instruction about files
% that do not require this functionality.
% \begin{itemize}
% \item |\mplibmakenocache{<filename>[,<filename>,...]}|
% \item |\mplibcancelnocache{<filename>[,<filename>,...]}|
% \end{itemize}
% where |<filename>| is a file name 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, in the same directory as where pdf/dvi output file
% is saved. This however can be changed 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{\cs{mplibtextextlabel}}
% Starting with v2.6, |\mplibtextextlabel{enable}| enables
% string 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,
% \textsf{luamplib} redefines |infont| operator so that the right side
% argument (the font part) is totally ignored. Every string label
% therefore will be typeset with 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}}
% Starting with v2.9, |\mplibcodeinherit{enable}| enables the inheritance
% of variables, constants, and macros defined by previous |mplibcode| chunks.
% On the contrary, the default value |\mplibcodeinherit{disable}| will make
% each code chunks being treated as an independent instance, and never
% affected by previous code chunks.
%
% \paragraph{Separate instances for \LaTeX{} environment}
% v2.22 has added the support for several named MetaPost instances
% in \LaTeX{} |mplibcode| environment.
% Syntax is like so:
% \begin{verbatim}
% \begin{mplibcode}[instanceName]
% % some mp code
% \end{mplibcode}
% \end{verbatim}
% Behaviour is as follows.
% \begin{itemize}
% \item All the variables and functions are shared
% only among all the environments belonging to the same instance.
% \item |\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| labels still exist separately and
% require |\mplibglobaltextext|.
% \item When an instance names is set,
% respective |\currentmpinstancename| is set.
% \end{itemize}
% In parellel with this functionality, v2.23 and after supports
% 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}.
% Syntax is:
% \begin{verbatim}
% \everymplib[instanceName]{...}
% \everyendmplib[instanceName]{...}
% \end{verbatim}
%
% \paragraph{\cs{mplibglobaltextext}}
% To inherit |btex ... etex| labels as well as metapost variables,
% it is necessary to declare \cs{mplibglobaltextext\{enable\}} in advance.
% On this case, be careful that normal \TeX\ boxes can conflict with
% |btex ... etex| boxes, though this would occur very rarely.
% Notwithstanding the danger, it is a `must' option to activate
% \cs{mplibglobaltextext} if you want to use |graph.mp|
% with \cs{mplibcodeinherit} functionality.
% \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}}
% Starting with v2.11, users can issue |\mplibverbatim{enable}|, after which
% the contents of mplibcode environment will be read verbatim. As a result,
% except for |\mpdim| and |\mpcolor|, all other \TeX\ commands outside
% |btex ... etex| or |verbatimtex ... etex| are not expanded and will be fed
% literally into the mplib process.
%
% \paragraph{\cs{mplibshowlog}}
% When |\mplibshowlog{enable}| is declared, log messages returned by
% |mplib| instance will be printed into the |.log| file.
% |\mplibshowlog{disable}| will revert this functionality.
% This is a \TeX{} side interface for |luamplib.showlog|. (v2.20.8)
%
% \paragraph{luamplib.cfg}
% At the end of package loading, \textsf{luamplib} searches
% |luamplib.cfg| and, if found, reads the file in automatically.
% Frequently used settings such as \cs{everymplib} or \cs{mplibforcehmode}
% are suitable for going into this file.
%
% \bigskip
%
% 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
% \cs{mplibsetformat}\marg{format name}.
%
% \section{Implementation}
%
% \subsection{Lua module}
%
% \iffalse
%<*lua>
% \fi
%
% \begin{macrocode}
luatexbase.provides_module {
name = "luamplib",
version = "2.23.0",
date = "2022/01/12",
description = "Lua package to typeset Metapost with LuaTeX's MPLib.",
}
local format, abs = string.format, math.abs
local err = function(...)
return luatexbase.module_error ("luamplib", select("#",...) > 1 and format(...) or ...)
end
local warn = function(...)
return luatexbase.module_warning("luamplib", select("#",...) > 1 and format(...) or ...)
end
local info = function(...)
return luatexbase.module_info ("luamplib", select("#",...) > 1 and format(...) or ...)
end
% \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
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 texsprint = tex.sprint
local textprint = tex.tprint
local texget = tex.get
local texgettoks = tex.gettoks
local texgetbox = tex.getbox
local texruntoks = tex.runtoks
% \end{macrocode}
%
% We don't use |tex.scantoks| anymore. See below reagrding |tex.runtoks|.
% \begin{verbatim}
% local texscantoks = tex.scantoks
% \end{verbatim}
% \begin{macrocode}
if not texruntoks then
err("Your LuaTeX version is too old. Please upgrade it to the latest")
end
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 stripsuffix = file.stripsuffix or function(filename)
return (filename:gsub("%.[%a%d]+$",""))
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.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
if lfstouch then
local texmfvar = kpse.expand_var('$TEXMFVAR')
if texmfvar and texmfvar ~= "" and texmfvar ~= '$TEXMFVAR' then
for _,dir in next, texmfvar:explode(os.type == "windows" and ";" or ":") do
if not lfsisdir(dir) then
mk_full_path(dir)
end
if is_writable(dir) then
local cached = format("%s/luamplib_cache",dir)
lfsmkdir(cached)
outputdir = cached
break
end
end
end
end
if not outputdir then
outputdir = "."
for _,v in ipairs(arg) do
local t = v:match("%-output%-directory=(.+)")
if t then
outputdir = t
break
end
end
end
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
luamplib.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,
}
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 cachedir = luamplib.cachedir or outputdir
local newfile = name:gsub("%W","_")
newfile = cachedir .."/luamplib_input_"..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 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",
}
local function finder(name, mode, ftype)
if mode == "w" then
return name
else
ftype = special_ftype[ftype] or ftype
local file = mpkpse:find_file(name,ftype)
if file then
if not lfstouch or ftype ~= "mp" or noneedtoreplace[name] then
return file
end
return replaceinputmpfile(name,file)
end
return mpkpse:find_file(name, name:match("%a+$"))
end
end
luamplib.finder = finder
% \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}
if tonumber(mplib.version()) <= 1.50 then
err("luamplib no longer supports mplib v1.50 or lower. "..
"Please upgrade to the latest version of LuaTeX")
end
local preamble = [[
boolean mplib ; mplib := true ;
let dump = endinput ;
let normalfontsize = fontsize;
input %s ;
]]
local logatload
local function reporterror (result, indeed)
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
warn(log)
if result.status > 1 then
err(e or "see above messages")
end
elseif indeed then
local log = logatload..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 but just prints a warning,
% even if output has no figure.
% \begin{macrocode}
if log:find"\n>>" then
warn(log)
elseif log:find"%g" then
if luamplib.showlog then
info(log)
elseif not result.fig then
info(log)
end
end
logatload = ""
else
logatload = log
end
return log
end
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,
random_seed = math.random(4095),
extensions = 1,
}
% \end{macrocode}
%
% Append our own MetaPost preamble to the preamble above.
% \begin{macrocode}
local preamble = preamble .. luamplib.mplibcodepreamble
if luamplib.legacy_verbatimtex then
preamble = preamble .. luamplib.legacyverbatimtexpreamble
end
if luamplib.textextlabel then
preamble = preamble .. luamplib.textextlabelpreamble
end
local result
if not mpx then
result = { status = 99, error = "out of memory"}
else
result = mpx:execute(format(preamble, replacesuffix(name,"mp")))
end
reporterror(result)
return mpx, result
end
% \end{macrocode}
%
% |plain| or |metafun|,
% though we cannot support |metafun| format fully.
% \begin{macrocode}
local currentformat = "plain"
local function setformat (name)
currentformat = name
end
luamplib.setformat = setformat
% \end{macrocode}
%
% Here, excute each |mplibcode| data,
% ie |\begin{mplibcode} ... \end{mplibcode}|.
% \begin{macrocode}
local function process_indeed (mpx, data)
local converted, result = false, {}
if mpx and data then
result = mpx:execute(data)
local log = reporterror(result, true)
if log then
if result.fig then
converted = luamplib.convert(result)
else
warn("No figure output. Maybe no beginfig/endfig")
end
end
else
err("Mem file unloadable. Maybe generated with a different version of mplib?")
end
return converted, result
end
% \end{macrocode}
%
% v2.9 has introduced the concept of ``code inherit''
% \begin{macrocode}
luamplib.codeinherit = false
local mplibinstances = {}
local function process (data, instancename)
% \end{macrocode}
%
% The workaround of issue \#70 seems to be unnecessary, as we use
% |make_text| now.
% \begin{verbatim}
% if not data:find(name_b.."beginfig%s*%([%+%-%s]*%d[%.%d%s]*%)") then
% data = data .. "beginfig(-1);endfig;"
% end
% \end{verbatim}
% \begin{macrocode}
local defaultinstancename = currentformat .. (luamplib.numbersystem or "scaled")
.. tostring(luamplib.textextlabel) .. tostring(luamplib.legacy_verbatimtex)
local currfmt = instancename or defaultinstancename
if #currfmt == 0 then
currfmt = defaultinstancename
end
local mpx = mplibinstances[currfmt]
local standalone = false
if currfmt == defaultinstancename then
standalone = not luamplib.codeinherit
end
if mpx and standalone then
mpx:finish()
end
if standalone or not mpx then
mpx = luamplibload(currentformat)
mplibinstances[currfmt] = mpx
end
return process_indeed(mpx, data)
end
% \end{macrocode}
%
% |make_text| and some |run_script| uses \LuaTeX's |tex.runtoks|,
% which made possible running \TeX\ code snippets inside |\directlua|.
% \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.script| seems to work nicely.
% \begin{verbatim}
% local function run_tex_code_no_use (str, cat)
% cat = cat or catlatex
% texscantoks("mplibtmptoks", cat, str)
% texruntoks("mplibtmptoks")
% end
% \end{verbatim}
% \begin{macrocode}
local function run_tex_code (str, cat)
cat = cat or catlatex
texruntoks(function() texsprint(cat, str) end)
end
% \end{macrocode}
%
% Indefinite number of boxes are needed for |btex ... etex|.
% So starts at somewhat huge number of box registry. Of course,
% this may conflict with other packages using many many boxes.
% (When |codeinherit| feature is enabled, boxes must be globally defined.)
% But I don't know any reliable way to escape this danger.
% \begin{macrocode}
local tex_box_id = 2047
% \end{macrocode}
%
% For conversion of |sp| to |bp|.
% \begin{macrocode}
local factor = 65536*(7227/7200)
local textext_fmt = [[image(addto currentpicture doublepath unitsquare ]]..
[[xscaled %f yscaled %f shifted (0,-%f) ]]..
[[withprescript "mplibtexboxid=%i:%f:%f")]]
local function process_tex_text (str)
if str then
tex_box_id = tex_box_id + 1
local global = luamplib.globaltextext and "\\global" or ""
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.
% \begin{macrocode}
local mplibcolor_fmt = [[\begingroup\let\XC@mcolor\relax]]..
[[\def\set@color{\global\mplibtmptoks\expandafter{\current@color}}]]..
[[\color %s \endgroup]]
local function process_color (str)
if str then
if not str:find("{.-}") then
str = format("{%s}",str)
end
run_tex_code(mplibcolor_fmt:format(str), catat11)
return format('1 withprescript "MPlibOverrideColor=%s"', texgettoks"mplibtmptoks")
end
return ""
end
% \end{macrocode}
%
% \cs{mpdim} is expanded before MPLib process, so code below will not be
% used for |mplibcode| data. But who knows anyone would want it
% in |.mp| input file. If then, you can say |mplibdimen(".5\textwidth")|
% for example.
% \begin{macrocode}