Debian Codegraph @

texmf-dist/source/luatex/luamplib/luamplib.dtx

raw
1 % \iffalse meta-comment -- by the way, this file contains UTF-8
2 %
3 % Copyright (C) 2008-2026 by Hans Hagen, Taco Hoekwater, Elie Roux,
4 % Manuel Pégourié-Gonnard, Philipp Gesang and Kim Dohyun.
5 % Currently maintained by Kim Dohyun.
6 % Support: <https://github.com/lualatex/luamplib>
7 %
8 % This work is under the GPL v2.0 license.
9 %
10 % This work consists of the main source file luamplib.dtx
11 % and the derived files
12 % luamplib.sty, luamplib.lua and luamplib.pdf.
13 %
14 % Unpacking:
15 % tex luamplib.dtx
16 %
17 % Documentation:
18 % lualatex luamplib.dtx
19 %
20 %<*ignore>
21 \begingroup
22 \def\x{LaTeX2e}%
23 \expandafter\endgroup
24 \ifcase 0\ifx\install y1\fi\expandafter
25 \ifx\csname processbatchFile\endcsname\relax\else1\fi
26 \ifx\fmtname\x\else 1\fi\relax
27 \else\csname fi\endcsname
28 %</ignore>
29 %<*install>
30 \input docstrip.tex
31 \Msg{************************************************************************}
32 \Msg{* Installation}
33 \Msg{* Package: luamplib - metapost package for LuaTeX.}
34 \Msg{************************************************************************}
35
36 \keepsilent
37 \askforoverwritefalse
38
39 \let\MetaPrefix\relax
40
41 \preamble
42
43 See source file '\inFileName' for licencing and contact information.
44
45 \endpreamble
46
47 \let\MetaPrefix\DoubleperCent
48
49 \generate{%
50 \usedir{tex/luatex/luamplib}%
51 \file{luamplib.sty}{\from{luamplib.dtx}{package}}%
52 }
53
54 \def\MetaPrefix{-- }
55
56 \def\luapostamble{%
57 \MetaPrefix^^J%
58 \MetaPrefix\space End of File `\outFileName'.%
59 }
60
61 \def\currentpostamble{\luapostamble}%
62
63 \generate{%
64 \usedir{tex/luatex/luamplib}%
65 \file{luamplib.lua}{\from{luamplib.dtx}{lua}}%
66 }
67
68 \obeyspaces
69 \Msg{************************************************************************}
70 \Msg{*}
71 \Msg{* To finish the installation you have to move the following}
72 \Msg{* files into a directory searched by TeX:}
73 \Msg{*}
74 \Msg{* luamplib.sty luamplib.lua}
75 \Msg{*}
76 \Msg{* Happy TeXing!}
77 \Msg{*}
78 \Msg{************************************************************************}
79
80 \endbatchfile
81 %</install>
82 %<*ignore>
83 \fi
84 %</ignore>
85 %<*driver>
86 \NeedsTeXFormat{LaTeX2e}
87 \ProvidesFile{luamplib.drv}%
88 [2026/05/26 v2.41.3 Interface for using the mplib library]%
89 \documentclass[11pt,a4paper]{ltxdoc}
90 \usepackage{geometry,graphicx,xspace}
91 \usepackage[x11names]{xcolor}
92 \AssignSocketPlug{build/column/outputbox}{space-floats-footnotes}
93 %
94 \def\primarycolor{DodgerBlue4} %%-> rgb 16 78 139 | #104e8b
95 \def\secondarycolor{Goldenrod4} %%-> rgb 139 105 200 | #8b6914
96 %
97 \usepackage[
98 hyperindex=false,
99 bookmarks=true,
100 colorlinks=true,
101 linkcolor=\primarycolor,
102 urlcolor=\secondarycolor,
103 citecolor=\primarycolor,
104 pdftitle={The luamplib package},
105 pdfsubject={Interface for using the mplib library},
106 pdfauthor={Hans Hagen, Taco Hoekwater, Elie Roux, Philipp Gesang \& Kim Dohyun},
107 pdfkeywords={luatex, lualatex, mplib, metapost}
108 ]{hyperref}
109 \usepackage{fontspec}
110 \setmainfont[
111 Numbers = OldStyle,
112 Ligatures = TeX,
113 BoldFont = {Linux Libertine O Bold},
114 ItalicFont = {Linux Libertine O Italic},
115 SlantedFont = {Linux Libertine O Italic},
116 ]{Linux Libertine O}
117 \setmonofont[Scale=MatchLowercase]{InconsolataN}
118 %setsansfont[Ligatures=TeX]{Linux Biolinum O}
119 \setsansfont[UprightFont=*Medium,BoldFont=*Heavy,Ligatures=TeX,Scale=MatchLowercase]{Iwona}
120 %setmathfont{XITS Math}
121
122 \newcommand\ConTeXt {Con\-\kern-.0667em\TeX t\xspace}
123
124 \newcommand*\email [1] {<\href{mailto:#1}{#1}>}
125 \newcommand \file {\nolinkurl}
126
127 \newcommand*\metapost {\textsc{metapost}\xspace}
128 \newcommand*\mplib {\pkg{mplib}\xspace}
129
130 \protected\def\secref#1{\S\,\ref{sec:#1}}
131 \newcommand*\notabene{\par\textsc{n.b.}\quad}
132
133 \usepackage{luamplib}\mplibforcehmode
134 \newcount\vln
135 \def\startmpfig{\setbox0\vbox\bgroup\raggedleft
136 \leftskip=0pt plus1fill\relax \parfillskip=0pt plus1fil\relax }
137 \def\stopmpfig#1{\egroup \vln=0\relax
138 \AddToHook{para/begin}[mpfig/example]{\advance\vln 1\relax
139 \ifnum #1=\vln \vadjust{\vbox to 0pt{\vskip-2ex \vss \unvbox0 \vss}}\fi }\relax
140 \AddToHookNext{env/verbatim/after}{\RemoveFromHook{para/begin}[mpfig/example]}}
141
142 \def\bsx{\leavevmode\begingroup\begingroup\color{Goldenrod4}}
143 \def\esx{\endgroup\endgroup}
144
145 \let\descriptionlabelorig\descriptionlabel
146 \def\descriptionlabel#1{\descriptionlabelorig{\textsf{#1}}}
147
148 \flushbottom
149 \begin{document}
150 \DocInput{luamplib.dtx}%
151 \end{document}
152 %</driver>
153 % \fi
154 %
155 % \CheckSum{0}
156 %
157 % \CharacterTable
158 % {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
159 % 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
160 % Digits \0\1\2\3\4\5\6\7\8\9
161 % Exclamation \! Double quote \" Hash (number) \#
162 % Dollar \$ Percent \% Ampersand \&
163 % Acute accent \' Left paren \( Right paren \)
164 % Asterisk \* Plus \+ Comma \,
165 % Minus \- Point \. Solidus \/
166 % Colon \: Semicolon \; Less than \<
167 % Equals \= Greater than \> Question mark \?
168 % Commercial at \@ Left bracket \[ Backslash \\
169 % Right bracket \] Circumflex \^ Underscore \_
170 % Grave accent \` Left brace \{ Vertical bar \|
171 % Right brace \} Tilde \~}
172 %
173 % \title{The \pkg{luamplib} package}
174 % \author{Hans Hagen, Taco Hoekwater, Elie Roux, Philipp Gesang and Kim Dohyun\\
175 % Current Maintainer: Kim Dohyun\\
176 % Support: \url{https://github.com/lualatex/luamplib}}
177 % \date{2026/05/26 v2.41.3}
178 %
179 % \maketitle
180 %
181 % \begin{abstract}
182 % \centering
183 % Package to have \metapost code typeset directly in a document with \LuaTeX
184 % \end{abstract}
185 %
186 % \tableofcontents
187 %
188 % \section{Documentation}
189 %
190 % This package aims at providing a simple way to typeset directly \metapost
191 % code in a document with \LuaTeX. \LuaTeX\ is built with the Lua
192 % \mplib library, that runs \metapost code. This package is basically a
193 % wrapper for the Lua \mplib functions and some \TeX\
194 % functions to have the output of the \mplib functions in the PDF.
195 %
196 % Using this package is easy: in Plain, type your \metapost code between the
197 % macros \cs{mplibcode} and \cs{endmplibcode}, and in \LaTeX\ in the
198 % |mplibcode| environment.
199 %
200 % The resulting \metapost figures are put in a \TeX\ |hbox| with dimensions
201 % adjusted to the \metapost code.
202 %
203 % The code of \pkg{luamplib} is basically from the |luatex-mplib.lua| and |luatex-mplib.tex| files
204 % from \ConTeXt. They have been adapted to \LaTeX\ and Plain by Elie Roux and
205 % Philipp Gesang and new functionalities have been added by Kim Dohyun.
206 % The most notable changes are:
207 %
208 % \begin{itemize}
209 % \item Possibility to use |btex| |...| |etex| to typeset \TeX\ code.
210 % \bsx|textext| \meta{string}\esx\ is a more versatile macro equivalent to \bsx|TEX| \meta{string}\esx\ from \pkg{TEX.mp}.
211 % |TEX| is also allowed and is a synonym of |textext|.
212 % The argument of
213 % \mplib's primitive |maketext| will also be processed by the same routine.
214 %
215 % \item Possibility to use |verbatimtex| |...| |etex| to run a \TeX\ code.
216 % \bsx|VerbatimTeX| \meta{string}\esx\ is a more versatile macro corresponding to |verbatimtex| command.
217 % Of course the behavior cannot be the same as the stand-alone \pkg{mpost}, so that
218 % you cannot include \cs{documentclass}, \cs{usepackage} etc.
219 % When these \TeX\ commands are found in |verbatimtex| |...| |etex|, the entire code will be
220 % ignored.
221 %
222 % The treatment of |verbatimtex| command has changed a lot since v2.20:
223 % see below \secref{mpliblegacybehavior}.
224 %
225 % \item In the past,
226 % the package required PDF mode in order to have some output.
227 % Starting with v2.7 it works in DVI mode as well, though
228 % DVIPDFMx is the only DVI tool currently supported.
229 % \end{itemize}
230 %
231 % It seems to be convenient to divide the explanations of some more changes and cautions
232 % into three parts: \TeX, \textsc{MetaPost}, and Lua interfaces.
233 %
234 % \subsection{\TeX}
235 %
236 % \subsubsection{\cs{mplibforcehmode}}\label{sec:mplibforcehmode}
237 % When this macro is declared, every \metapost figure box will be
238 % typeset in horizontal mode, so that \cs{centering}, \cs{raggedleft} etc.\
239 % will have effects. \cs{mplibnoforcehmode}, being default for backward compatibility,
240 % reverts this setting.\footnote{Actually these commands redefine \cs{prependtomplibbox}. So you
241 % can redefine this macro with anything suitable before a box.
242 % But see \secref{taggedPDF} on Tagged PDF. }
243 %
244 % \subsubsection[\cs{everymplib}, \cs{everyendmplib}]{\cs{everymplib\{...\}}, \cs{everyendmplib\{...\}}}
245 % \label{sec:everymplib}
246 % \cs{everymplib} and \cs{everyendmplib} redefine
247 % the Lua table entry containing \metapost code
248 % which will
249 % be automatically inserted at the beginning and ending of each \metapost code chunk.
250 %\startmpfig
251 %\mpfig draw fullcircle scaled 1cm; \endmpfig
252 %\stopmpfig{3}
253 %\begin{verbatim}
254 % \everymplib{ beginfig(0); }
255 % \everyendmplib{ endfig; }
256 % \begin{mplibcode}
257 % % beginfig/endfig not needed
258 % draw fullcircle scaled 1cm;
259 % \end{mplibcode}
260 %\end{verbatim}
261 %
262 % \subsubsection[\cs{mplibsetformat}]{\cs{mplibsetformat\{plain\textbar metafun\}}}
263 % \label{sec:mplibsetformat}
264 % There are (basically) two formats for \metapost: \emph{plain} and
265 % \emph{metafun}. By default, the \emph{plain} format is used, but you can set
266 % the format to be used by future figures at any time using
267 % \bsx\cs{mplibsetformat}\allowbreak\marg{format name}\esx.
268 %
269 % \notabene As \emph{metafun} is such a complicated format,
270 % we cannot support all the special effects provided by \emph{metafun}.
271 % At least, however, transparency (actually opacity), shading (gradient colors) and transparency group
272 % are fully supported,
273 % and outlinetext is supported by our own alternative |mpliboutlinetext|
274 % (see below \secref{mpliboutlinetext}).
275 % You can try other effects as well, though we did not fully tested their proper functioning.
276 %
277 % \begin{description}
278 % \item[transparency]
279 % (|texdoc metafun| \S\,8.2) Transparency is so simple that you can apply it to an object,
280 % with \emph{plain} format as well as \emph{metafun},
281 % just by appending \bsx|withprescript| |"tr_transparency=|\allowbreak\meta{numeric}|"|\esx\ to the sentence.
282 % ($0 \le \meta{numeric} \le 1$)
283 %
284 % From v2.36, |withtransparency| is available with \emph{plain} format as well.
285 % See below \secref{luamplibtransparency}.
286 %
287 % \item[shading]
288 % (|texdoc metafun| \S\,8.3) One thing worth mentioning about shading is:
289 % when a color expression is given in string type,
290 % it is regarded by \pkg{luamplib} as
291 % a color expression of \TeX\ side.
292 % For instance, when |withshadecolors("orange",| |2/3red)| is given, the first color |"orange"| will be
293 % interpreted as a \pkg{color}, \pkg{xcolor} or \pkg{l3color}'s expression.
294 %
295 % From v2.36, shading is available with \emph{plain} format as well with extended functionality.
296 % See below \secref{luamplibshading}.
297 %
298 % \item[transparency group]
299 % \hypertarget{metafunformat}{}\relax
300 % (|texdoc metafun| \S\,8.8)
301 % As for transparency group, the current \emph{metafun} document is not correct.
302 % The true syntax is:
303 %\begin{verbatim}
304 % draw <picture>|<path> asgroup <string>
305 %\end{verbatim}
306 % where \meta{string} should be |""| (empty), |"isolated"|, |"knockout"|, or |"isolated,knockout"|.
307 % Beware that currently many of the PDF rendering applications,
308 % except Adobe Acrobat, Foxit Editor and \TeX works,
309 % cannot properly render the isolated or knockout effect.
310 %
311 % Transparency group is available with \emph{plain} format as well with extended functionality.
312 % See below \secref{transparencygroup}.
313 % \end{description}
314 %
315 % \subsubsection[\cs{mplibnumbersystem}]{\cs{mplibnumbersystem\{scaled\textbar double\textbar decimal\}}}
316 % \label{sec:mplibnumbersystem}
317 % Users can choose |numbersystem| option.
318 % The default value is |scaled|, which can be changed
319 % by declaring \bsx\cs{mplibnumbersystem\{double\}}\esx\ or
320 % \bsx\cs{mplibnumbersystem\{decimal\}}\esx.
321 %
322 % \subsubsection[\cs{mplibshowlog}]{\cs{mplibshowlog\{enable\textbar disable\}}}
323 % \label{sec:mplibshowlog}
324 % Default: |disable|.
325 % When \bsx\cs{mplibshowlog\{enable\}}\esx\footnote{As for user's setting,
326 % |enable|, |true| and |yes| are identical;
327 % all others are identical to |disable|.} is declared, log messages returned by
328 % the \metapost process will be printed to the |.log| file.
329 % This is the \TeX{} side interface for |luamplib.showlog|.
330 %
331 % \subsubsection[\cs{mpliblegacybehavior}]{\cs{mpliblegacybehavior\{enable\textbar disable\}}}
332 % \label{sec:mpliblegacybehavior}
333 % \paragraph{Legacy behavior}
334 % By default, \cs{mpliblegacybehavior\{enable\}}
335 % is already declared for backward compatibility,
336 % in which case \TeX\ code in
337 % |verbatimtex| |...| |etex| that comes just before |beginfig()|
338 % will be inserted before the
339 % following \metapost figure box. In this way,
340 % each figure box can be freely moved horizontally or vertically.
341 % Also, a box number can be assigned to a figure box, allowing it to be
342 % reused later.\footnote{But
343 % the recommended way to reuse a figure is using \cs{mplibgroup} command.
344 % See below \secref{mplibgroupendmplibgroup}.
345 % }
346 %\begin{verbatim}
347 % \mplibcode
348 % verbatimtex \moveright 3cm etex; beginfig(0); ... endfig;
349 % verbatimtex \leavevmode etex; beginfig(1); ... endfig;
350 % verbatimtex \leavevmode\lower 1ex etex; beginfig(2); ... endfig;
351 % verbatimtex \endgraf\moveright 1cm etex; beginfig(3); ... endfig;
352 % \endmplibcode
353 %\end{verbatim}
354 % \notabene \cs{endgraf} should be used instead of \cs{par} inside
355 % mplibcode environment.
356 %
357 % On the other hand, \TeX\ code in |verbatimtex| |...| |etex|
358 % between |beginfig()| and |endfig| will be inserted
359 % after flushing out the \metapost figure. An example:\footnote{\relax
360 % But the recommended way to access \metapost variables
361 % from \TeX\ (or Lua) side is to use Lua code via |luamplib.instances|.
362 % For details see below \secref{luamplibinstances}.}
363 %\startmpfig
364 %\mpfig D:=sqrt(2)**9; draw fullcircle scaled D; VerbatimTeX("\gdef\Dia{"&decimal D&"}");\endmpfig
365 %\par diameter: \Dia bp.
366 %\stopmpfig{4}
367 %\begin{verbatim}
368 % \mplibcode
369 % D := sqrt(2)**9;
370 % beginfig(0);
371 % draw fullcircle scaled D;
372 % VerbatimTeX("\gdef\Dia{" & decimal D & "}");
373 % endfig;
374 % \endmplibcode
375 % diameter: \Dia bp.
376 %\end{verbatim}
377 %
378 % \paragraph{New and recommended way}
379 % By contrast,
380 % when \bsx\cs{mpliblegacybehavior\{disable\}}\esx\ is declared, any
381 % |verbatimtex| |...| |etex|, along with |btex| |...| |etex|, will be run
382 % sequentially one by one.
383 % So, some \TeX\ code in |verbatimtex| |...| |etex| will have effect on
384 % |btex| |...| |etex| codes thereafter.
385 %\startmpfig
386 %\mpfig draw btex ABC etex; verbatimtex \bfseries etex; draw btex DEF etex shifted (1cm,0); draw btex GHI etex shifted (2cm,0); \endmpfig
387 %\stopmpfig{4}
388 %\begin{verbatim}
389 % \begin{mplibcode}
390 % beginfig(0);
391 % draw btex ABC etex;
392 % verbatimtex \bfseries etex;
393 % draw btex DEF etex shifted (1cm,0); % bold face
394 % draw btex GHI etex shifted (2cm,0); % bold face
395 % endfig;
396 % \end{mplibcode}
397 %\end{verbatim}
398 %
399 % \subsubsection[\cs{mplibtextextlabel}]{\cs{mplibtextextlabel\{enable\textbar disable\}}}
400 % \label{sec:mplibtextextlabel}
401 % Default: |disable|.
402 % \bsx\cs{mplibtextextlabel\{enable\}}\esx\ enables
403 % the labels typeset via |textext| instead of |infont| operator.
404 % So, |label("my text",| |origin)| thereafter is exactly the same as
405 % |label(textext| |"my text",| |origin)|.
406 %
407 % \notabene In the background,
408 % \pkg{luamplib} redefines |infont| operator so that the right side
409 % argument (the font part) is totally ignored. Therefore the left side arguemnt (the text part)
410 % will be typeset with the current \TeX\ font.
411 %
412 % From v2.35, however, the redefinition of |infont| operator has been revised:
413 % when the character code of the text argument is less than $32$~(control characters),
414 % or is equal to $35$~(|#|), $36$~(|$|), \iffalse |$|\fi
415 % $37$~(|%|), $38$~(|&|), $92$~(|\|), $94$~(|^|),
416 % $95$~(|_|), $123$~(|{|), $125$~(|}|), $126$~(|~|) or $127$~(DEL),
417 % the original |infont| operator will be used instead of |textext| operator
418 % so that the font part will be honored.
419 % Despite the revision, please take care of |char| operator in the text argument,
420 % as this might bring unpermitted characters into \TeX.
421 %
422 % \subsubsection[\cs{mplibcodeinherit}]{\cs{mplibcodeinherit\{enable\textbar disable\}}}
423 % \label{sec:mplibcodeinherit}
424 % Default: |disable|.
425 % \bsx\cs{mplibcodeinherit\{enable\}}\esx\ enables the inheritance
426 % of variables, constants, and macros defined by previous \metapost code chunks.
427 % On the other hand, \cs{mplibcodeinherit}\allowbreak|{disable}| will make
428 % each code chunk being treated as an independent instance, never
429 % affected by previous code chunks.
430 %
431 % \subsubsection[\cs{mplibglobaltextext}]{\cs{mplibglobaltextext\{enable\textbar disable\}}}
432 % \label{sec:mplibglobaltextext}
433 % Default: |disable|.
434 % Formerly, to inherit |btex| |...| |etex| boxes as well as other \metapost macros, variables and constants,
435 % it was necessary to declare \cs{mplibglobaltextext}\allowbreak|{enable}| in advance.
436 % But from v2.27, this is implicitly enabled when \cs{mplibcodeinherit}
437 % is enabled.
438 % The command still remains mostly for backward compatibility.
439 %\startmpfig
440 %\mpfig label(btex $\sqrt{2}$ etex, origin); draw fullcircle scaled 20; picture pic; pic := currentpicture; \endmpfig
441 %\par\mpfig currentpicture := pic scaled 2; \endmpfig
442 %\stopmpfig{6}
443 %\begin{verbatim}
444 % \mplibcodeinherit{enable}
445 % %\mplibglobaltextext{enable}
446 % \everymplib{ beginfig(0);} \everyendmplib{ endfig;}
447 % \mplibcode
448 % label(btex $\sqrt{2}$ etex, origin);
449 % draw fullcircle scaled 20;
450 % picture pic; pic := currentpicture;
451 % \endmplibcode
452 % \mplibcode
453 % currentpicture := pic scaled 2;
454 % \endmplibcode
455 %\end{verbatim}
456 %
457 % \subsubsection{Separate \metapost instances}
458 % \pkg{luamplib} v2.22 has added the support for several named \metapost instances
459 % in \LaTeX\ environment |mplibcode| or
460 % Plain \TeX\ commands \cs{mplibcode} |...| \cs{endmplibcode}.
461 % The syntax for \LaTeX\ is:
462 %\begin{verbatim}
463 % \begin{mplibcode}[instanceName]
464 % % some mp code
465 % \end{mplibcode}
466 %\end{verbatim}
467 % The behavior is as follows.
468 % \begin{itemize}
469 % \item All the variables and functions are shared
470 % only among all the environments belonging to the same instance.
471 % \item \cs{mplibcodeinherit} only affects the environments
472 % with no instance name set (since if a name is set,
473 % the code is intended to be reused at some point).
474 % \item |btex| |...| |etex| boxes are also shared and do not
475 % require \cs{mplibglobaltextext}.
476 % \item When an instance names is set,
477 % respective \cs{currentmpinstancename} is set as well.
478 % \end{itemize}
479 % In parellel with this functionality, we support
480 % optional argument of instance name for \cs{everymplib} and
481 % \cs{everyendmplib}, affecting only those |mplibcode| environments
482 % of the same name.
483 % Unnamed \cs{everymplib} affects not only those instances with no name,
484 % but also those with name but with no corresponding \cs{everymplib}.
485 % The syntax is:
486 %\begin{verbatim}
487 % \everymplib[instanceName]{...}
488 % \everyendmplib[instanceName]{...}
489 %\end{verbatim}
490 %
491 % \subsubsection[\cs{mplibverbatim}]{\cs{mplibverbatim\{enable\textbar disable\}}}
492 % \label{sec:mplibverbatim}
493 % Default: |disable|.
494 % Users can issue \bsx\cs{mplibverbatim\{enable\}}\esx, after which
495 % the contents of mplibcode environment will be read verbatim. As a result,
496 % except for \cs{mpdim} and \cs{mpcolor} (see \secref{mpdim} and \secref{mpcolor}),
497 % all other \TeX\ commands outside of the
498 % |btex| or |verbatimtex| |...| |etex| are not expanded and will be fed
499 % literally to the \mplib library.
500 %
501 % \subsubsection[\cs{mpdim}]{\cs{mpdim\{...\}}}\label{sec:mpdim}
502 % Besides other \TeX\ commands, \cs{mpdim} is specially allowed
503 % in the mplibcode environment. This feature is inpired by \pkg{gmp} package authored by
504 % Enrico Gregorio. Please refer to the manual of \pkg{gmp} package for details.
505 %\startmpfig
506 %\mpfig draw origin--(.4\mpdim{\linewidth},0) withpen pencircle scaled 4 dashed evenly scaled 4 withcolor \mpcolor{orange}; \endmpfig
507 %\stopmpfig{3}
508 %\begin{verbatim}
509 % draw origin--(.4\mpdim{\linewidth},0)
510 % withpen pencircle scaled 4 dashed evenly scaled 4
511 % withcolor \mpcolor{orange} ;
512 %\end{verbatim}
513 %
514 % \subsubsection[\cs{mpcolor}]{\cs{mpcolor[...]\{...\}}}\label{sec:mpcolor}
515 % With \cs{mpcolor} command, color names or expressions of
516 % \pkg{color}, \pkg{xcolor} and \pkg{l3color} module/packages can be used in the mplibcode
517 % environment (after |withcolor| command, in principle).
518 % See the example above at \secref{mpdim}.
519 % The optional |[...]| denotes the option of \pkg{xcolor}'s \cs{color} command.
520 % For spot colors, \pkg{l3color} module is well supported in PDF and DVI mode.
521 % Package \pkg{colorspace} is supported as well in PDF mode,
522 % but could conflict with \pkg{luamplib}'s special features such as shading
523 % when \cs{DocumentMetadata}, i.e.\ PDF management code, is not loaded.
524 %
525 % \notabene Formerly,
526 % only the first object would have been colored as intended
527 % among multiple graphical objects in a \metapost image,
528 % because \cs{mpcolor} always produced |withprescript| command internally.
529 % Since v2.38.1, now that \cs{mpcolor} returns a \metapost color expression if possible,
530 % users can issue the sentence as follows
531 % without worrying about the location of the color command:
532 %\startmpfig
533 %\mpfig draw image (drawarrow (left--right) scaled 5) scaled 8 withcolor \mpcolor{red!50};\endmpfig
534 %\stopmpfig{2}
535 %\begin{verbatim}
536 % draw image (drawarrow (left--right) scaled 5)
537 % scaled 8
538 % withcolor \mpcolor{red!50} ;
539 %\end{verbatim}
540 % \notabene Be aware, however, that even after v2.38.1 \cs{mpcolor} still inserts
541 % |withprescript| command when the color specified is a spot color
542 % (or named color in DVI mode).
543 % Users therefore have to revise the code so that the color can have effect inside the image.
544 % For instance:
545 %\begin{verbatim}
546 % draw image (drawarrow (left--right) scaled 5)
547 % scaled 8
548 % withcolor \mpcolor{spotA}
549 % withoutcolor ;
550 %\end{verbatim}
551 % or preferably,
552 %\begin{verbatim}
553 % draw image (drawarrow (left--right) scaled 5 withcolor \mpcolor{spotA})
554 % scaled 8 ;
555 %\end{verbatim}
556 %
557 %
558 % \subsubsection[\cs{mpfig}, \cs{endmpfig}]{\cs{mpfig ...} \cs{endmpfig}}
559 % Besides the |mplibcode| environment (for \LaTeX) and
560 % \cs{mplibcode ...} \cs{endmplibcode} (for Plain),
561 % we also provide unexpandable \TeX\ macros \cs{mpfig} |...| \cs{endmpfig} and its starred version
562 % \cs{mpfig*} |...| \cs{endmpfig} to save typing toil.
563 % The former is roughly the same as follows:
564 %\begin{verbatim}
565 % \begin{mplibcode}[@mpfig]
566 % beginfig(0)
567 % token list declared by \everymplib[@mpfig]
568 % ...
569 % token list declared by \everyendmplib[@mpfig]
570 % endfig;
571 % \end{mplibcode}
572 %\end{verbatim}
573 % and the starred version is roughly the same as follows:
574 %\begin{verbatim}
575 % \begin{mplibcode}[@mpfig]
576 % ...
577 % \end{mplibcode}
578 %\end{verbatim}
579 % In these macros \cs{mpliblegacybehavior\{disable\}}
580 % is forcibly declared.
581 % Again, as both share the same instance name, \metapost codes are inherited among them.
582 % A simple example:
583 %\startmpfig
584 %\mpfig* input boxes \endmpfig \mpfig drawoptions(withcolor 1/3[red,white]); circleit.a(btex Box 1 etex); drawboxed(a); \endmpfig
585 %\stopmpfig{3}
586 %\begin{verbatim}
587 % \everymplib[@mpfig]{ drawoptions(withcolor 1/3[red,white]); }
588 % \mpfig* input boxes \endmpfig
589 % \mpfig
590 % circleit.a(btex Box 1 etex); drawboxed(a);
591 % \endmpfig
592 %\end{verbatim}
593 % Users can change the instance name (default value:\ |@mpfig|) by redefining
594 % \cs{mpfiginstancename}, after which a new \mplib instance will start and
595 % code inheritance too will begin anew.
596 % \cs{let}\allowbreak\cs{mpfiginstancename}\allowbreak\cs{empty} will
597 % prevent code inheritance if \cs{mplibcodeinherit} is not true.
598 %
599 % \subsubsection{About cache files}
600 % \label{sec:mplibcachedir}
601 % To support |btex| |...| |etex| in external |.mp| files, \pkg{luamplib}
602 % inspects the content of each and every |.mp| file and makes caches
603 % if nececcsary before returning their paths to the \mplib library.
604 % This could waste the compilation time, as most |.mp| files
605 % do not contain |btex| |...| |etex| commands. So \pkg{luamplib} provides
606 % macros as follows, so that users can give instructions about files
607 % that do not require this functionality.
608 % \begin{itemize}
609 % \item \cs{mplibmakenocache}|{|\meta{filename}|[,|\meta{filename}|,...]}|
610 % \item \cs{mplibcancelnocache}|{|\meta{filename}|[,|\meta{filename}|,...]}|
611 % \end{itemize}
612 % where \meta{filename} is a filename without |.mp| extension.
613 % Note that |.mp| files under |$TEXMFMAIN/|\allowbreak|metapost/|\allowbreak|base| and
614 % |$TEXMFMAIN/metapost/context/base| are already registered by default.
615 % \notabene \bsx\cs{mplibmakenocache}|{*}|\esx\ will suppress making cache files.
616 % Use it at your own risk.
617 %
618 % By default, cache files will be stored in |$TEXMFVAR/luamplib_cache| or,
619 % if it's not available (mostly not writable),
620 % in the directory where output files are saved:
621 % to be specific, |$TEXMF_OUTPUT_DIRECTORY/luamplib_cache|,
622 % |./luamplib_cache|, |$TEXMFOUTPUT/luamplib_cache|, and |.|, in this order.
623 % |$TEXMF_OUTPUT_DIRECTORY| is normally the value of |--output-directory|
624 % command-line option.
625 %
626 % Users can change this behavior by the command
627 % \bsx\cs{mplibcachedir}\marg{directory path}\esx, where tilde (|~|) is interpreted
628 % as the user's home directory (on a windows machine as well).
629 % As backslashes (\cs{}) should be escaped by users, it would be easier to use
630 % slashes (|/|) instead.
631 %
632 % \subsubsection{About figure box metric}
633 % Notice that, after each figure is processed, the macro \cs{MPwidth} stores
634 % the width value of the latest figure; \cs{MPheight}, the height value.
635 % Incidentally, also note that \cs{MPllx}, \cs{MPlly}, \cs{MPurx}, and
636 % \cs{MPury} store the bounding box information of the latest figure
637 % without the unit |bp|.
638 %
639 % \subsubsection{luamplib.cfg}
640 % At the end of package loading, \pkg{luamplib} searches
641 % |luamplib.cfg| and, if found, reads the file in automatically.
642 % Frequently used settings such as \cs{everymplib}, \cs{mplibforcehmode}
643 % or \cs{mplibcodeinherit} are suitable for going into this file.
644 %
645 % \subsubsection{Tagged PDF}\label{sec:taggedPDF}
646 % When \pkg{tagpdf} package is loaded and activated, |mplibcode| environment accepts additional options for tagged PDF\@.
647 % The code related to this functionality is currently in experimental stage, not guaranteeing backward compatibility.
648 % Available optional keys are similar to those of the \LaTeX's |picture| environment
649 % (|texdoc| |latex-lab-graphic|).
650 % The default tagging mode is the |alt| key with |Figure| structure.
651 % \begin{description}
652 % \item[alt=\meta{text}] starts a |Figure| tag by default and
653 % sets an alternate text of the figure from the \meta{text}.
654 % BBox info will be added automatically to the PDF\@.
655 % This key is needed for ordinary \metapost figures, for which,
656 % if no |alt| text is given, a default text will be used with a warning issued.
657 % You can change the alternate text within \metapost code as well:
658 % \bsx|VerbatimTeX| |"\mplibalttext|\marg{text}|";|\esx
659 % \item[actualtext=\meta{text}] starts a |Span| tag implicitly and sets a
660 % replacement text (a.k.a.\ actual text) from the \meta{text}.
661 % If in vertical mode, horizontal mode will be forced by \cs{noindent} command.\footnote{\relax
662 % It is not recommended to personally redefine \cs{prependtomplibbox}.
663 % Apart from using \cs{mplibforcehmode} or \cs{mplibnoforcehmode},
664 % the redefinition might be incompatible with |actualtext| key.
665 % See \secref{mplibforcehmode} on these commands. }
666 % BBox info will not be added.
667 % This key is intended for figures which can be represented by a character or
668 % a small sequence of characters.
669 % You can change the actual text within \metapost code as well:
670 % \bsx|VerbatimTeX| |"\mplibactualtext|\marg{text}|";|\esx
671 % \item[artifact] starts an |Artifact| MC (marked content).
672 % BBox info will not be added.
673 % This key is intended for decorative figures which have no semantic meaning.
674 % \item[text] starts an |Artifact| MC but enables tagging on \TeX-text boxes
675 % (such as |btex| |...| |etex|, excluding pictures made by |infont| operator).
676 % If in vertical mode, horizontal mode will be forced by \cs{noindent} command.\footnote{\relax
677 % The key |text| also shares the limitation mentioned in the previous footnote.}
678 % BBox info will not be added.
679 % This key is intended for figures the meaning of which is the sequence of texts in the
680 % \TeX-text boxes in the order they are drawn in the figure.
681 %
682 % \notabene Within |text|-mode figures, reusing \TeX-text boxes is strongly discouraged.
683 %
684 % Note that the text in a \TeX-text box which starts with |[taggingoff]| will not be tagged
685 % at all, and
686 % of course |[taggingoff]| and its trailing spaces will be gobbled by \pkg{luamplib}.
687 % For example, the first and the third boxes in the following figure will not be tagged,
688 % and still remain in the |Artifact| MC-chunks.
689 %\startmpfig
690 %\mpfig draw btex [taggingoff] $\sqrt 2$ etex; draw textext "$\sqrt 3$" shifted 12down; draw TEX "[taggingoff] $\sqrt 5$" shifted 24down; draw maketext "$\sqrt 7$" shifted 36down; draw mplibgraphictext "$\sqrt x$" shifted 48down; \endmpfig
691 %\stopmpfig{5}
692 %\begin{verbatim}
693 % \begin{mplibcode}[text]
694 % beginfig(1)
695 % draw btex [taggingoff] $\sqrt 2$ etex ;
696 % draw textext "$\sqrt 3$" shifted 12down ;
697 % draw TEX "[taggingoff] $\sqrt 5$" shifted 24down ;
698 % draw maketext "$\sqrt 7$" shifted 36down ;
699 % draw mplibgraphictext "$\sqrt x$" shifted 48down ;
700 % endfig;
701 % \end{mplibcode}
702 %\end{verbatim}
703 % \item[off] Given this key, nothing will be tagged by \pkg{luamplib}.
704 % \item[tag=\meta{name}] You can choose a tag name, default value being |Figure|.\relax
705 % \footnote{The option |tag=false|, however, is a synonym of the |off| key.}
706 % For instance, you can set \bsx|tag=Formula,| |alt=|\meta{text}\esx\ to get
707 % a |Formula| element with its alternate text.\footnote{Beware that this bypasses
708 % \LaTeX's regular math formula tagging, for which the |text| key is needed.}
709 % \item[adjust-BBox=\meta{dimens}] You can correct the BBox attribute of the figure
710 % by space-separated four dimensional values, which will be added to the
711 % automatically calculated BBox values.
712 % To draw the bounding box for checking with half-transparent red color, you can add
713 % |debug=|\allowbreak|BBox| to the argument of \cs{DocumentMetadata} command.
714 % \item[tagging-setup=\meta{key-val list}]
715 % This key accepts as its value the list of key-value options mentioned so far.
716 % \end{description}
717 % You can set these options anywhere in the document by declaring
718 % \bsx\cs{SetKeys}\allowbreak |[luamplib/tagging]|\allowbreak \marg{key-val list}\esx,
719 % which will affect \pkg{mplib} figures thereafter in the scope.
720 % And the options listed above are provided for \cs{mpfig} and \cs{usemplibgroup}
721 % (see \hyperlink{usemplibgroup}{below} \secref{transparencygroup}) commands as well.
722 %\begin{verbatim}
723 % \begin{mplibcode}[myInstanceName, alt=drawing of a circle]
724 % ...
725 % \end{mplibcode}
726 %
727 % \mpfig[alt=drawing of a square box]
728 % ...
729 % \endmpfig
730 %
731 % \mppattern{...} % see below
732 % \mpfig[off] % do not tag this figure
733 % ...
734 % \endmpfig
735 % \endmppattern
736 %
737 % \mplibgroup{...} % see below
738 % \mpfig[off] % do not tag this figure
739 % ...
740 % \endmpfig
741 % \endmplibgroup
742 %
743 % \usemplibgroup[alt=drawing of a triangle]{...}
744 %\end{verbatim}
745 % As for the instance name of |mplibcode| environment,
746 % \bsx|instance=|\meta{name}\esx\ or \bsx|instancename=|\allowbreak\meta{name}\esx\ is also allowed
747 % in addition to the raw instance name as shown above.
748 %
749 %
750 % \subsection{\textsc{MetaPost}}
751 %
752 % \subsubsection[\ttfamily mplibdimen, mplibcolor]{\ttfamily mplibdimen ..., mplibcolor ...}
753 % \bsx|mplibdimen| \meta{string}\esx\ and \bsx|mplibcolor| \meta{string}\esx\
754 % are \metapost interfaces for the \TeX\ commands
755 % \cs{mpdim} and \cs{mpcolor} (see above \secref{mpdim} and \secref{mpcolor}). For example,
756 % |mplibdimen| |"\linewidth"| is basically the same as \cs{mpdim\{\cs{linewidth}\}}, and
757 % |mplibcolor| |"red!50"| is basically the same as \cs{mpcolor\{red!50\}}.
758 % The difference is that these \metapost operators can also be used in external |.mp| files,
759 % which cannot have \TeX\ commands outside of the |btex| or |verbatimtex| |...| |etex|.
760 %
761 % \subsubsection[\ttfamily mplibtexcolor, mplibrgbtexcolor]{\ttfamily mplibtexcolor ..., mplibrgbtexcolor ...}
762 % \label{sec:mplibtexcolor}
763 % \bsx|mplibtexcolor| \meta{string}\esx\ is a \metapost operator that converts a \TeX\ color expression
764 % to a \metapost color expression, that can be used anywhere color expression is expected
765 % as well as after the |withcolor| command.\footnote{\relax
766 % Since v2.38.1, the operation of |mplibtexcolor| is the same as that of |mplibcolor|
767 % if the color specified is not a spot color or a named color in DVI mode.
768 % }
769 % For instance:
770 %\begin{verbatim}
771 % color col;
772 % col := mplibtexcolor "olive!50";
773 %\end{verbatim}
774 % But the result may vary in its color model (gray/rgb/cmyk)
775 % according to the given \TeX\ color.
776 % Therefore the example shown above would raise a \metapost error:
777 % |cmykcolor col;| should have been declared.
778 % By contrast, \bsx|mplibrgbtexcolor| \meta{string}\esx\ always returns rgb-model expressions.
779 %
780 % \notabene Spot colors are forced to cmyk or rgb model,
781 % so these operators are not recommended for spot colors.
782 %
783 % \subsubsection[\ttfamily withmplibcolors]{\ttfamily withmplibcolors (..., ...)}
784 % \label{sec:withmplibcolors}
785 % Unlike the |withcolor| command, users can specify one color for filling
786 % and another color for stroking using the macro |withmplibcolors| at the end of a sentence.
787 % The syntax is \bsx|withmplibcolors| |(|\meta{fill color expr}|,| \meta{stroke color expr}|)|\esx.
788 % When the argument is in string type, it is regarded as the color expression of \TeX\ side.
789 % A simple example (see also the example at \secref{mplibdrawglyph}):
790 %\startmpfig
791 %\mpfig filldraw fullcircle scaled 40 withpen pencircle scaled 2 withmplibcolors ("orange!60", 2/3red); \endmpfig
792 %\stopmpfig{2}
793 %\begin{verbatim}
794 % filldraw fullcircle scaled 40
795 % withpen pencircle scaled 2
796 % withmplibcolors ("orange!60", 2/3red) ;
797 %\end{verbatim}
798 % The PDF file size is much smaller than issueing two sentences with different colors,
799 % though the apparent effect is the same.
800 %
801 % \subsubsection[\ttfamily withtransparency]{\ttfamily withtransparency (..., ...)}
802 % \label{sec:luamplibtransparency}
803 % \bsx|withtransparency(|\meta{number} \textbar\ \meta{string}|,| \meta{numeric}|)|\esx\
804 % is provided for \emph{plain} format as well as \emph{metafun}.
805 % The first argument accepts a number or a name among
806 % alternative transparency methods (see |texdoc| |metafun| \S\,8.2 Figure~8.1).
807 % The second argument accepts a numeric expression denoting opacity.
808 %\startmpfig
809 %\mpfig fill unitsquare scaled 40 withcolor 1/3[blue,white] withtransparency(1,0.5); fill fullcircle scaled 40 withcolor 1/3[red,white] withtransparency (1,0.5); \endmpfig
810 %\stopmpfig{6}
811 %\begin{verbatim}
812 % \mpfig
813 % fill unitsquare scaled 40
814 % withcolor 1/3[blue,white]
815 % withtransparency (1, 0.5) % or ("normal", 0.5)
816 % ;
817 % fill fullcircle scaled 40
818 % withcolor 1/3[red,white]
819 % withtransparency (1, 0.5)
820 % ;
821 % \endmpfig
822 %\end{verbatim}
823 %
824 % \subsubsection[\ttfamily withmplibopacities]{\ttfamily withmplibopacities (..., ..., ...)}
825 % \label{sec:withmplibopacities}
826 % By analogy with the macro |withmplibcolors| (see above \secref{withmplibcolors}),
827 % the macro |withmplibopacities| is also provided.
828 % The syntax is \bsx|withmplibopacities|
829 % |(|\meta{number} \textbar\ \meta{string}|,| \meta{numeric}, \meta{numeric}|)|\esx.
830 % The first argument is the same as that of |withtransparency| command
831 % described above at \secref{luamplibtransparency};
832 % the latter two arguments are numeric expressions denoting
833 % \emph{fill opacity} and \emph{stroke opacity} respectively.
834 % It is more efficient than issueing two sentences with different opacities.
835 %\startmpfig
836 %\mpfig pickup pencircle scaled 2; filldraw unitsquare scaled 40 withcolor 1/3[blue,white] withmplibopacities (1, 1/2, 1); filldraw fullcircle scaled 40 withcolor 1/3[red,white] withmplibopacities (1, 1/2, 1); \endmpfig
837 %\stopmpfig{6}
838 %\begin{verbatim}
839 % \mpfig
840 % pickup pencircle scaled 2;
841 % filldraw unitsquare scaled 40
842 % withcolor 1/3[blue,white]
843 % withmplibopacities (1, 1/2, 1) % or ("normal", 1/2, 1)
844 % ;
845 % filldraw fullcircle scaled 40
846 % withcolor 1/3[red,white]
847 % withmplibopacities (1, 1/2, 1)
848 % ;
849 % \endmpfig
850 %\end{verbatim}
851 %
852 % \subsubsection[\ttfamily withshadingmethod]{\ttfamily ... withshadingmethod ...}
853 % \label{sec:luamplibshading}
854 % The syntax is exactly the same as \emph{metafun}'s new shading method (|texdoc metafun| \S\,8.3.3), except that
855 % the `|shade|' contained in each and every macro name has changed to
856 % `|shading|' in \pkg{luamplib}: for instance, while |withshademethod| is
857 % a macro name which only works with \emph{metafun} format,
858 % the equivalent provided by \pkg{luamplib}, |withshadingmethod|, works with \emph{plain} as well.
859 % Other differences to the \emph{metafun}'s and some cautions are:
860 % \begin{itemize}
861 % \item \emph{Textual pictures} as well as paths can have shading effect.
862 % The term \emph{textual picture} here means
863 % a picture generated by |btex| |...| |etex|, |textext|, |TEX|, |maketext|,
864 % |mplibgraphictext| (see below \secref{mplibgraphictext}), or |infont| operator,
865 % though technically only the last one is a true textual picture.
866 % Note that the picture, including transparency group,
867 % in which the objects are filled \emph{without} color
868 % can also be regarded as a textual picture.\footnote{\relax
869 % See below \secref{mplibdrawglyph},
870 % particularly the first \hyperlink{firstpatternexample}{example} of tiling pattern
871 % at \secref{mppattern}.
872 % See also \secref{transparencygroup} and \secref{mplibgroupendmplibgroup},
873 % particularly the example in the \hyperlink{para:pictureshading}{note}
874 % about picture shading and transparency group.}
875 %\startmpfig
876 %\mpfig draw btex \bfseries\TeX etex rotated 15 scaled 6 withshadingmethod "linear" withshadingvector (0,3) withshadingstep ( withshadingfraction 1/2 withshadingcolors (red,green)) withshadingstep ( withshadingfraction 1 withshadingcolors (green,blue)); \endmpfig
877 %\stopmpfig{6}
878 %\begin{verbatim}
879 % draw btex \bfseries\TeX etex rotated 15 scaled 6
880 % withshadingmethod "linear"
881 % withshadingvector (0,3)
882 % withshadingstep (
883 % withshadingfraction 1/2
884 % withshadingcolors (red,green)
885 % )
886 % withshadingstep (
887 % withshadingfraction 1
888 % withshadingcolors (green,blue)
889 % ) ;
890 %\end{verbatim}
891 % \item When shading a picture generated by `|infont|' operator or that has multiple components,
892 % the effect of |withshadingvector| and that of |withshadingdirection| will be the same,
893 % as \pkg{luamplib} considers only the bounding box of the picture.
894 % \item A few more optional macros are available in addition to the \emph{metafun}'s:
895 % |withshadingpoints|, |withshadingcenters|, |withshadingextend|, |withshadingmatrix|,
896 % and |withshadingstroke|.
897 % \end{itemize}
898 % The syntax is \bsx\meta{path} \textbar\ \meta{textual picture} |withshadingmethod| \meta{string}\esx,
899 % where the latter shall be either |"linear"| or |"circular"|.
900 % The balance of this subsection is to explain additional optional macros.
901 % Above all, there are two ways in specifying the shading coordinates, of which
902 % you can choose the more convenient one.
903 % First, the way that mimicks the \emph{metafun}'s:
904 % \begin{description}
905 % \item[withshadingvector \meta{pair}]
906 % Starting and ending points (as time value) on the path.
907 % \item[withshadingdirection \meta{pair}]
908 % Starting and ending points (as time value) on the bounding box,
909 % default value being |(0,2)|.
910 % \item[withshadingorigin \meta{pair}]
911 % The center of both starting and ending circles,
912 % default value being |center p|, where |p| is the operand of |withshadingmethod|.
913 % \item[withshadingcenter \meta{pair}]
914 % Value to specify the starting center.
915 % For instance,
916 % |(0,0)| means that the center of starting circle is |center p|;
917 % |(1,1)| means |urcorner p|; |(-1,-1)| means |llcorner p|.
918 % \item[withshadingradius \meta{pair}]
919 % Radii of starting and ending circles. This is no-op in linear mode.
920 % Default value: |(0,| |abs(center p -| |urcorner p))|
921 % \item[withshadingfactor \meta{numeric}]
922 % Multiplier of the radii, default value being |1.2|.
923 % This is no-op in linear mode.
924 % \item[withshadingtransform \meta{string}]
925 % where \meta{string} shall be |"yes"| (respect transform) or |"no"| (ignore transform).
926 % Default value: |"no"| for pictures made by |infont| operator or having multiple components;
927 % |"yes"| for all other cases.
928 % \end{description}
929 % Secondly, the way provided by \pkg{luamplib} only:
930 % \begin{description}
931 % \item[withshadingpoints (\meta{pair}, \meta{pair})]
932 % In linear mode, values to specify directly the starting and ending points:
933 % you can use it instead of |withshadingvector| or |withshadingdirection|.
934 % In circular mode, the centers of starting and ending circles:
935 % it could be easier than issueing two macros
936 % |withshadingorigin| and |withshadingcenter|.
937 % Note that, within the macro, both \bsx|withshadingfactor| |1|\esx\ and
938 % \bsx|withshadingtransform| |"no"|\esx\ are already decalred.
939 % \item[withshadingcenters (\meta{pair}, \meta{pair})]
940 % Synonym of |withshadingpoints|.
941 % Normally accompanied by |withshadingradius| which has the same meaning as described above.
942 % \end{description}
943 % Now, optional macros common to the both ways:
944 % \begin{description}
945 % \item[withshadingstep (|...|)]
946 % For combined shading of more than two colors.
947 % \item[withshadingfraction \meta{numeric}]
948 % Fractional number of each shading step,
949 % and so only meaningful within |withshadingstep|.
950 % \item[withshadingcolors (\meta{color expr}, \meta{color expr})]
951 % Starting and ending colors,
952 % default value being |(white,| |black)|.
953 % String-type argument is regarded as the color expression of \TeX\ side.
954 % \item[withshadingdomain \meta{pair}]
955 % Limiting values of parametric variable
956 % that varies on the axis of color gradient,
957 % default value being |(0,1)|. Of course the values can be negative or greater than $1$.
958 % \item[withshadingextend (\meta{boolean}, \meta{boolean})]
959 % Values specifying whether to extend the shading
960 % beyond the starting and ending points or circles, default value being |(true,| |true)|.
961 % An example just to show the concept:
962 %\startmpfig
963 %\mpfig path p[]; p1 = fullcircle scaled 50; p2 = fullcircle scaled 50 shifted 40right; fill (subpath (2,6) of p1 -- subpath (-2,2) of p2 -- cycle) rotated 10 withshadingmethod "circular" withshadingcenters (center p1, center p2 rotated 10) withshadingradius (25,25) withshadingcolors (3/4[red,white], red) withshadingextend (false, false) ; \endmpfig
964 %\stopmpfig{8}
965 %\begin{verbatim}
966 % \mpfig
967 % path p[];
968 % p1 = fullcircle scaled 50;
969 % p2 = fullcircle scaled 50 shifted 40 right;
970 % fill (subpath (2,6) of p1 -- subpath (-2,2) of p2 -- cycle) rotated 10
971 % withshadingmethod "circular"
972 % withshadingcenters (center p1, center p2 rotated 10)
973 % withshadingradius (25, 25)
974 % withshadingcolors (3/4[red,white], red)
975 % withshadingextend (false, false) ;
976 % \endmpfig
977 %\end{verbatim}
978 % \item[withshadingmatrix \meta{string}]
979 % \metapost code for transformation of shading, such as |"xscaled 1.2| |yscaled 0.8"|;
980 % or six numerics separated by spaces, such as |"1.2 0 0 0.8 0 0"|.
981 % Only meaningful when the object is a \meta{picture}.
982 % \item[withshadingstroke \meta{string}]
983 % where \meta{string} shall be |"yes"| or |"no"|.
984 % Only meaningful when the shading object is a \meta{path};
985 % if |"yes"|, we get the path stroked and \emph{then} shaded.
986 % It is more efficient than issueing two sentences.
987 % \end{description}
988 %
989 % \subsubsection[\ttfamily withfademethod]{\ttfamily ... withfademethod ...}
990 % This is a \metapost command which makes the color of an object gradiently transparent,
991 % a.k.a.\ \emph{fading}.
992 % The syntax is \bsx\meta{path} \textbar\ \meta{picture} |withfademethod| \meta{string}\esx,
993 % the latter being either |"linear"| or |"circular"|.
994 % Though it is similar to the |withshademethod| from \emph{metafun},
995 % the differences are: (1)~the object of fading can be a picture as well as a path;
996 % (2)~you cannot make gradient colors, but can only make gradient opacity.
997 % Technically speaking, this command generates and applies a special kind of
998 % masking transparency group described below at \secref{withmaskinggroup}.
999 %
1000 % Related macros to control optional values are:
1001 % \begin{description}
1002 % \item [withfadeopacity (\meta{numeric}, \meta{numeric})]
1003 % sets the starting opacity and the ending opacity, default value being |(1,0)|.
1004 % `|1|' denotes full color; `|0|' full transparency.
1005 % \item [withfadevector (\meta{pair}, \meta{pair})]
1006 % sets the starting and ending points. Default value in the linear mode is
1007 % |(llcorner p,| |lrcorner p)|, where |p| is the operand,
1008 % meaning that fading starts from the left edge and ends at the right edge.
1009 % Default value in the circular mode is |(center p,| |center p)|, which means
1010 % centers of both starting and ending circles are the center of the bounding box.
1011 % \item [withfadecenter] is a synonym of |withfadevector|.
1012 % \item [withfaderadius (\meta{numeric}, \meta{numeric})]
1013 % sets the radii of starting and ending circles. This is no-op in the linear mode.
1014 % Default value is |(0, abs(center p - urcorner p))|, meaning that fading starts from the
1015 % center and ends at the four corners of the bounding box.
1016 % \item [withfadestep (|...|)]
1017 % for combined fading of more than two opacities.
1018 % \item [withfadefraction \meta{numeric}]
1019 % Fractional number of each fading step. Only meaningful within |withfadestep|.
1020 % \item [withfadeextend (\meta{boolean}, \meta{boolean})]
1021 % specifies whether to extend the fading
1022 % beyond the starting and ending points or circles, default value being |(true,| |true)|.
1023 % \item [withfadematrix \meta{string}]
1024 % \metapost code for transformation of fading, such as |"xscaled 1.2| |yscaled 0.8"|;
1025 % or six numerics separated by spaces, such as |"1.2 0 0 0.8 0 0"|.
1026 % \item [withfadebbox (\meta{pair}, \meta{pair})]
1027 % sets the bounding box of the fading area, default value being |(llcorner p,| |urcorner p)|.
1028 % Though this option is not needed in most cases, there could be cases when users want to
1029 % explicitly control the bounding box.
1030 % Particularly, see the description \hyperlink{withgroupbbox}{below}
1031 % at \secref{transparencygroup} on the analogous macro |withgroupbbox|.
1032 % \end{description}
1033 % An example:
1034 %\startmpfig
1035 %\mpfig draw btex \includegraphics[width=100bp]{mill} etex withfademethod "circular" withfaderadius (20, 50) withfadeopacity (1, 0); \endmpfig
1036 %\stopmpfig{3}
1037 %\begin{verbatim}
1038 % draw
1039 % btex \includegraphics[width=100bp]{mill} etex
1040 % withfademethod "circular"
1041 % withfaderadius (20, 50)
1042 % withfadeopacity (1, 0) ;
1043 %\end{verbatim}
1044 %
1045 % \subsubsection[\ttfamily mplibgraphictext]{\ttfamily mplibgraphictext ...}
1046 % \label{sec:mplibgraphictext}
1047 % \bsx|mplibgraphictext| \meta{string}\esx\ is a \metapost operator,
1048 % the effect of which is similar to that of
1049 % \ConTeXt's |graphictext| or our own |mpliboutlinetext|
1050 % (see below \secref{mpliboutlinetext}).
1051 % However the syntax is somewhat different.
1052 %\startmpfig
1053 %\mpfig draw mplibgraphictext "$\sqrt{2+x}$" rotated 10 scaled 3 fakebold 2.5 fillcolor "red!50" drawcolor 2/3 red; \endmpfig
1054 %\stopmpfig{3}
1055 %\begin{verbatim}
1056 % draw mplibgraphictext "$\sqrt{2+x}$"
1057 % rotated 10 scaled 3
1058 % fakebold 2.5 % fontspec option
1059 % fillcolor "red!50" % color expression
1060 % drawcolor 2/3 red % or strokecolor 2/3 red
1061 % ;
1062 %\end{verbatim}
1063 % |fakebold|, |fillcolor| and |drawcolor| (or |strokecolor|) are optional;
1064 % default values are |2|, |"white"| and |"black"| respectively.\footnote{Users can
1065 % use the |withmplibcolors| macro instead of |fillcolor| and |drawcolor| options.
1066 % See \secref{withmplibcolors} on this macro.}
1067 % When the color expression is given in string type, it is regarded as
1068 % \pkg{color}, \pkg{xcolor} or \pkg{l3color}'s expression.
1069 % All from |mplibgraphictext| to the end of sentence will compose an
1070 % anonymous picture, which can be drawn or assigned to a variable.
1071 % Incidentally, |withfillcolor| and |withdrawcolor| are synonyms of
1072 % |fillcolor| and |drawcolor|, hopefully to be compatible with |graphictext|.
1073 %
1074 % \notabene
1075 % In some cases,
1076 % especially when processing complicated \TeX\ code,
1077 % |mplibgraphictext| will produce better results than \ConTeXt\
1078 % or even than our own |mpliboutlinetext|, not to mention the much smaller PDF file size.
1079 % There are, however, some limitations such that you can't
1080 % apply shading (gradient colors) to the text with \emph{metafun}'s |withshademethod|.\relax
1081 % \footnote{But this limitation is now lifted by the introduction of |withshadingmethod|.
1082 % See above \secref{luamplibshading}.}
1083 % Again,
1084 % in DVI mode, \pkg{unicode-math} package is needed for math formulae,
1085 % as we cannot embolden type1 fonts in DVI mode.
1086 % But the most critical limitation is that, unlike |mpliboutlinetext|,
1087 % you cannot manipulate the shape of outline paths,
1088 % because the returned picture is basically a |btex| |...| |etex| picture.
1089 %
1090 % \subsubsection[\ttfamily mplibglyph]{\ttfamily mplibglyph ... of ...}
1091 % \metapost operator \bsx|mplibglyph|
1092 % \meta{number} \textbar\ \meta{string} |of| \meta{number} \textbar\ \meta{string}\esx\
1093 % returns a \metapost picture
1094 % containing outline paths of a glyph in OpenType, TrueType or Type1 (|.pfb|) fonts.
1095 % When a TFM font is specified, \metapost primitive |glyph| will be called.
1096 %\begin{verbatim}
1097 % mplibglyph 50 of \fontid\font % slot 50 of current font
1098 % mplibglyph "Q" of "TU/TeXGyrePagella(0)/m/n/10" % font csname
1099 % mplibglyph "Q" of "texgyrepagella-regular.otf" % raw filename
1100 % mplibglyph "R" of "utmr8a.pfb" % raw filename (type1 font)
1101 % mplibglyph "Q" of "Times.ttc(2)" % subfont number
1102 % mplibglyph "Q" of "SourceHanSansK-VF.otf[Regular]" % instance name
1103 % mplibglyph "R" of "SourceHanSansK-VF.otf[wght=800]" % axis names & values
1104 %\end{verbatim}
1105 % Both arguments before and after `|of|' can be either a number or a string.
1106 % Number arguments are regarded as a glyph slot (GID) and a font id number, repectively.
1107 % String argument at the left side is regarded as a glyph name in the font or a unicode character.
1108 % String argument at the right side is regarded as a \TeX\ font csname (without backslash) or
1109 % the raw filename of a font. When it is a font filename, a number within parentheses
1110 % after the filename denotes a
1111 % subfont number (starting from zero) of a TTC font; a string within brackets denotes
1112 % an instance name, or names and values for |axis| feature, of a variable font.
1113 %
1114 % \notabene Regrettably we have some bug in processing
1115 % not a few glyphs in |cmr10.pfb| and its family (or maybe other) Type1 fonts.\relax
1116 % \footnote{The bug seems to be fixed in |font-cff.lmt| contained in \ConTeXt mkxl, but
1117 % current \pkg{luaotfload} is based on |font-cff.lua| from \ConTeXt mkiv.
1118 % As you see, |mplibglyph| operator requires \pkg{luaotfload} package loaded,
1119 % which however is done automatically by \LaTeX\ format.}
1120 % If that happens, consider using |glyph| operator instead of |mplibglyph|.
1121 %
1122 % \subsubsection[\texttt{mplibdrawglyph}, and its friends]{\ttfamily mplibdrawglyph ...,
1123 % mplibstrokeglyph ..., mplibfillandstrokeglyph ...}
1124 % \label{sec:mplibdrawglyph}
1125 % As the structure of the picture returned by |mplibglyph| is quite similar to
1126 % the result of |glyph| primitive,
1127 % \metapost's |draw| command will fill the inner path of the picture with the background color.
1128 % In contrast, \bsx|mplibdrawglyph| \meta{picture}\esx\ command fills the paths
1129 % according to the nonzero winding number rule.
1130 % As a result, for instance, the area surrounded by inner path of ``O'' will remain transparent.
1131 %
1132 % \notabene
1133 % To apply the nonzero winding number rule to a picture containing paths,
1134 % \pkg{luamplib} appends |withpostscript| |"collect"|
1135 % to the paths except the last one in the picture.
1136 % If you want the even-odd rule instead, you can
1137 % additionally declare |withpostscript| |"evenodd"| to the last path.
1138 %
1139 % \notabene
1140 % By the way, when you want fill-and-stroke effect,
1141 % issueing |filldraw| command to the last path will not always produce what you want:
1142 % in such cases, you have to issue the command
1143 % |draw| \meta{the last path} |withpostscript| |"both"|
1144 % (or |"eoboth"| to apply even-odd rule).\footnote{\emph{metafun} provides macros
1145 % |nofill|, |eofill|, |fillup|, |eofillup| etc.\ (see \emph{metafun} manual \S\,2.11),
1146 % which \pkg{luamplib} with \emph{plain} format does not provide currently. }
1147 %
1148 % As this could be somewhat annoying to users, \pkg{luamplib} v2.38.0 or later provides the following commands as well:
1149 % \bsx|mplibfillandstrokeglyph| \meta{picture}\esx, \bsx|mplibstrokeglyph| \meta{picture}\esx,
1150 % and \bsx|mplibfillglyph| \meta{picture}\esx, the last one being a synonym of |mplibdrawglyph| command.
1151 %
1152 % An example:
1153 %\startmpfig
1154 %\mpfig mplibfillandstrokeglyph mplibglyph "R" of \fontid\font scaled 1/12 withpen pencircle scaled 1 withmplibcolors ("orange", 2/3red); \endmpfig
1155 %\stopmpfig{3}
1156 %\begin{verbatim}
1157 % mplibfillandstrokeglyph
1158 % mplibglyph "R" of \fontid\font scaled 1/12
1159 % withpen pencircle scaled 1
1160 % withmplibcolors ("orange", 2/3red) ;
1161 %\end{verbatim}
1162 %
1163 %
1164 % \subsubsection[\ttfamily mpliboutlinetext]{\ttfamily mpliboutlinetext (...)}
1165 % \label{sec:mpliboutlinetext}
1166 % As said before at \secref{mplibsetformat}, \pkg{luamplib} provides
1167 % the \metapost operator \bsx|mpliboutlinetext| |(|\meta{string}|)|\esx\ which mimicks
1168 % \emph{metafun}'s |outlinetext|,
1169 % but with some enhancements including the support for right-to-left writing direction.
1170 % The syntax is the same as that of \emph{metafun}: see the \emph{metafun}
1171 % documentation \S\,8.7 (|texdoc| |metafun|).
1172 %
1173 % A simple example:
1174 %\startmpfig
1175 %\mpfig draw mpliboutlinetext.b ("$\sqrt{2+\alpha}$") (withcolor \mpcolor{red!50}) (withpen pencircle scaled .25 withcolor 2/3red) scaled 3; \endmpfig
1176 %\stopmpfig{2}
1177 %\begin{verbatim}
1178 % draw mpliboutlinetext.b ("$\sqrt{2+\alpha}$")
1179 % (withcolor \mpcolor{red!50})
1180 % (withpen pencircle scaled .25 withcolor 2/3red)
1181 % scaled 3 ;
1182 %\end{verbatim}
1183 % After the process, |mpliboutlinepic[]|
1184 % and |mpliboutlinenum| will be preserved as global variables;
1185 % |mpliboutlinepic[1]| |...| |mpliboutlinepic[mpliboutlinenum]|
1186 % will be an array of images, each of which containing outline paths of a glyph or a rule.
1187 %
1188 % \notabene As Unicode grapheme cluster is not considered in the array, a unit that must be
1189 % a single cluster might be separated apart.
1190 %
1191 % \subsubsection[\cs{mppattern}, \ttfamily withmppattern]{\cs{mppattern\{...\} ...}
1192 % \cs{endmppattern}, \ttfamily ... withmppattern ...}
1193 % \label{sec:mppattern}
1194 % \TeX\ macros
1195 % \bsx\cs{mppattern}\marg{name}\esx\ |...| \bsx\cs{endmppattern}\esx\ define a tiling pattern cell
1196 % associated with the \meta{name}.
1197 % \metapost command |withmppattern|, the syntax being
1198 % \bsx\meta{cyclic path} \textbar\ \meta{textual picture} |withmppattern| \meta{string}\esx, will fill
1199 % the given path or text with the tiling pattern cell of the \meta{name}
1200 % by replicating it horizontally and vertically.\footnote{\relax
1201 % |withpattern| is an operator virtually the same as |withmppattern|,
1202 % but the former forces a \metapost picture. Therefore
1203 % you cannot but use |draw| command with |withpattern| operator.
1204 % On the other hand,
1205 % \meta{cyclic path} |withmppattern| \meta{string} works as intended
1206 % only with |fill| or |filldraw| command.
1207 % }
1208 % As said before at \secref{luamplibshading},
1209 % the \emph{textual picture} here means basically any text typeset by \TeX, mostly the result
1210 % of the |btex| command (and its derivatives) or the |infont| operator.
1211 %
1212 % An \hypertarget{firstpatternexample}{example}:
1213 %\begin{verbatim}
1214 % \mppattern{mypatt} % or \begin{mppattern}{mypatt}
1215 % [ % options: see below
1216 % xstep = 10,
1217 % ystep = 7,
1218 % matrix = "rotated 45", % or "0.7 0.7 -0.7 0.7" or {0.7, 0.7, -0.7, 0.7}
1219 % ]
1220 % \mpfig % or any other TeX code
1221 % draw (up--down) scaled 5
1222 % withcolor 2/3[blue,white] ;
1223 % draw (left--right) scaled 5
1224 % withcolor 2/3[red,white] ;
1225 % \endmpfig
1226 % \endmppattern % or \end{mppattern}
1227 %\end{verbatim}
1228 %\startmpfig
1229 %\mppattern{mypatt}[xstep=10, ystep=7, matrix="rotated 45",]\mpfig draw (up--down) scaled 5 withcolor 2/3[blue,white]; draw (left--right) scaled 5 withcolor 2/3[red,white];\endmpfig\endmppattern
1230 %\mpfig mplibdrawglyph image(draw fullcircle scaled 100; draw reverse fullcircle scaled 40;) withmppattern "mypatt" withpen pencircle scaled 1 withcolor \mpcolor{red!50!blue!50}; \endmpfig
1231 %\stopmpfig{4}
1232 %\begin{verbatim}
1233 % \mpfig
1234 % mplibdrawglyph image(
1235 % draw fullcircle scaled 100;
1236 % draw reverse fullcircle scaled 40;
1237 % )
1238 % withmppattern "mypatt"
1239 % withpen pencircle scaled 1
1240 % withcolor \mpcolor{red!50!blue!50} ;
1241 % \endmpfig
1242 %\end{verbatim}
1243 %
1244 % The available options, actually elements of a Lua \emph{table},
1245 % are listed in Table~\ref{tab:mppatternoptions}.
1246 % For the sake of convenience, the width and height values of the tiling pattern cell will be written down
1247 % into the log file (depth is always zero). Users can refer to them for option setting.
1248 %
1249 % \begin{table}
1250 % \centering
1251 % \caption{options for \cs{mppattern}}\label{tab:mppatternoptions}
1252 % \begin{tabular}{lll}\hline
1253 % Key & Value Type & Explanation\\\hline
1254 % |xstep| &\emph{number} & horizontal spacing between pattern cells\\
1255 % |ystep| &\emph{number} & vertical spacing between pattern cells\\
1256 % |xshift| &\emph{number} & horizontal shifting of pattern cells\\
1257 % |yshift| &\emph{number} & vertical shifting of pattern cells\\
1258 % |bbox| &\emph{table} or \emph{string} & |llx|, |lly|, |urx|, |ury| values\kern1pt*\\
1259 % |matrix| &\emph{table} or \emph{string} & |xx|, |yx|, |xy|, |yy| values\kern1pt* or MP transform code\\
1260 % |resources|&\emph{string} & PDF resources if needed\\
1261 % |colored| or |coloured| &\emph{boolean}& |false| for uncolored pattern. default: |true|\\\hline
1262 % & & \small *\,in string type, numbers are separated by spaces\\
1263 % \end{tabular}
1264 % \end{table}
1265 %
1266 % As for |matrix| option, \metapost code such as |"rotated 30 slanted .2"| is allowed as well
1267 % as the string or table of four numbers. You can also set |xshift| and |yshift|
1268 % values by using `|shifted|' operator. But when |xshift| or |yshift| option is explicitly
1269 % given, they have precedence over the effect of `|shifted|' operator.
1270 %
1271 % When you use special effect such as transparency in a pattern cell,
1272 % |resources| option is needed: for instance, |resources="/ExtGState| |<</MyObj| |5 0 R>>"|.
1273 % However, as \pkg{luamplib} automatically includes the resources of the current page, this option
1274 % is not needed in most cases.
1275 %
1276 % Option \bsx|colored=false|\esx\ (or |coloured=false|) will generate an uncolored pattern cell which
1277 % shall have no color at all (i.e.\ |withoutcolor| command is needed for \metapost code).\relax
1278 % \footnote{When using DVI mode, |-c| option might be needed to the |dvipdfmx| command.}
1279 % Uncolored pattern will be painted later by the color of a \metapost object.
1280 % An example:
1281 %\startmpfig
1282 %\begin{mppattern}{pattnocolor}[colored=false, matrix="slanted .3 rotated 15",]\tiny\TeX\end{mppattern}
1283 %\mpfig picture tex; tex = mpliboutlinetext("\bfseries \TeX"); for i=1 upto mpliboutlinenum: mplibfillandstrokeglyph mpliboutlinepic[i] scaled 8 withmppattern "pattnocolor" withpen pencircle scaled 1/2 withcolor (i/4)[red,blue]; endfor \endmpfig
1284 %\stopmpfig{15}
1285 %\begin{verbatim}
1286 % \begin{mppattern}{pattnocolor}
1287 % [
1288 % colored = false,
1289 % matrix = "slanted .3 rotated 15",
1290 % ]
1291 % \tiny\TeX
1292 % \end{mppattern}
1293 %
1294 % \begin{mplibcode}
1295 % beginfig(1)
1296 % picture tex;
1297 % tex = mpliboutlinetext ("\bfseries \TeX");
1298 % for i=1 upto mpliboutlinenum:
1299 % mplibfillandstrokeglyph mpliboutlinepic[i]
1300 % scaled 8
1301 % withmppattern "pattnocolor"
1302 % withpen pencircle scaled 1/2
1303 % withcolor (i/4)[red,blue] % paints the pattern
1304 % ;
1305 % endfor
1306 % endfig;
1307 % \end{mplibcode}
1308 %\end{verbatim}
1309 % A much simpler and efficient way to obtain a similar result
1310 % (but without colorful characters in this example)
1311 % is to give a \emph{textual picture} as the operand of |withmppattern|:
1312 %\startmpfig
1313 %\mpfig draw mplibgraphictext "\bfseries\TeX" fakebold 1/2 rotated 10 scaled 8 withmppattern "pattnocolor" withmplibcolors(2/3[red,white], 2/3red); \endmpfig
1314 %\stopmpfig{7}
1315 %\begin{verbatim}
1316 % \begin{mplibcode}
1317 % beginfig(2)
1318 % draw mplibgraphictext "\bfseries\TeX"
1319 % fakebold 1/2
1320 % rotated 10 scaled 8
1321 % withmppattern "pattnocolor"
1322 % withmplibcolors (
1323 % 2/3[red,white], % paints the pattern
1324 % 2/3 red
1325 % ) ;
1326 % endfig;
1327 % \end{mplibcode}
1328 %\end{verbatim}
1329 %
1330 % \subsubsection[\ttfamily asgroup]{\ttfamily ... asgroup ...}\label{sec:transparencygroup}
1331 % As said \hyperlink{metafunformat}{before} at \secref{mplibsetformat},
1332 % transparency group is available with \emph{plain} as well as \emph{metafun}.
1333 % It is called \emph{Transparency Group} because the objects contained in the group are composited
1334 % to produce a single object, so that outer transparency effect, if any,
1335 % will be applied to the group as a whole, not to the individual objects cumulatively.
1336 %
1337 % The syntax is basically the same as \emph{metafun}'s:
1338 % \bsx\meta{picture} \textbar\ \meta{path} |asgroup| \meta{string}\esx, the latter being
1339 % |""| (empty string)
1340 % or any comma-separated combination of |isolated|, |knockout|, |wrapped| and |off|
1341 % (for example, |"isolated,knockout,wrapped"|),
1342 % which will return a \metapost picture.
1343 % The additional features provided by \pkg{luamplib} are:
1344 % \begin{itemize}
1345 % \item As mentioned, in addition to those arguments mimicking \emph{metafun}'s,
1346 % we allow other optional arguments at the right-hand side:
1347 % \begin{itemize}
1348 % \item |asgroup| |"off"| will produce an ordinary \emph{form XObject}
1349 % rather than a transparency group XObject.
1350 % By contranst, a transparency group will be produced
1351 % when `|off|' is not given, including |""| (empty string)
1352 % in which case both of the PDF keys |/I| and |/K| are |false|.
1353 % \item |asgroup| |"wrapped"| will produce a transparency group XObject
1354 % in which an ordinary form XObject is wrapped up.
1355 % This option could be useful when a picture shading (\emph{shading pattern} in technical terms)
1356 % is used in the object of |asgroup|.
1357 % See the note about picture shading described \hyperlink{para:pictureshading}{below}.
1358 % \end{itemize}
1359 % \item You can reuse the XObject as many times as you want
1360 % in the \TeX{} code or in other \metapost code chunks,
1361 % with infinitesimal increase in the size of PDF file.
1362 % For this functionality we provide \TeX{} and \metapost macros as follows:
1363 % \end{itemize}
1364 % \begin{description}
1365 % \item[withgroupname \meta{string}] associates an XObject with the given name.
1366 % When this command is not appended to the sentence with |asgroup| operator,
1367 % the default name `|lastmplibgroup|' will be used.
1368 %
1369 % \item[\textbackslash usemplibgroup\marg{name}]
1370 % \hypertarget{usemplibgroup}{}\relax
1371 % is a \TeX\ command to reuse an XObject of the name
1372 % once used.
1373 % Note that the position of the XObject will be origin-based:
1374 % in other words, lower-left corner of the bounding box will be shifted to the origin.
1375 %
1376 % \item[usemplibgroup \meta{string}] is a \metapost command which will add
1377 % an XObject of the name to the |currentpicture|.
1378 % Contrary to the \TeX\ command just mentioned,
1379 % the position of the XObject is the same as the original XObject.
1380 %
1381 % \item[withgroupbbox (\meta{pair}, \meta{pair})]
1382 % \hypertarget{withgroupbbox}{}\relax
1383 % sets the bounding box of the XObject,
1384 % default value being |(llcorner p, urcorner p)|.
1385 % This option might be needed especially when you draw with a thick pen
1386 % a path that touches the boundary;
1387 % you would probably want to append to the sentence
1388 % `|withgroupbbox| |(bot| |lft| |llcorner| |p,| |top| |rt| |urcorner| |p)|',
1389 % supposing that the pen was selected by the |pickup| command.
1390 %
1391 % \end{description}
1392 % An example showing the effect of transparency group and
1393 % the difference between the \TeX\ and \metapost commands:
1394 %\startmpfig
1395 % \hypertarget{noasgroupexample}{}\relax
1396 %\mpfig picture pic; pic = image(drawarrow (left--right) scaled 5 withcolor red) scaled 10; draw pic asgroup "off" withtransparency (1, 1/2);\endmpfig
1397 %\stopmpfig{5}
1398 %\begin{verbatim}
1399 % \mpfig
1400 % picture pic;
1401 % pic = image(drawarrow (left--right) scaled 5 withcolor red) scaled 10 ;
1402 % draw pic
1403 % asgroup "off"
1404 % withtransparency (1, 1/2) ;
1405 % \endmpfig
1406 %\end{verbatim}
1407 %\startmpfig
1408 %\mpfig draw pic asgroup "" withgroupname "mygroup" withtransparency (1, 1/2); draw (left--right) scaled 5; draw (up--down) scaled 5;\endmpfig
1409 %\stopmpfig{5}
1410 %\begin{verbatim}
1411 % \mpfig
1412 % draw pic
1413 % asgroup ""
1414 % withgroupname "mygroup"
1415 % withtransparency (1, 1/2) ;
1416 % draw (left--right) scaled 5 ;
1417 % draw (up--down) scaled 5 ;
1418 % \endmpfig
1419 %\end{verbatim}
1420 %\startmpfig
1421 %\noindent\clap{\vrule width 10bp height .25bp depth .25bp}\clap{\vrule width .5bp height 5bp depth 5bp}\usemplibgroup{mygroup}
1422 %\stopmpfig{3}
1423 %\begin{verbatim}
1424 % \noindent
1425 % \clap{\vrule width 10bp height .25bp depth .25bp}%
1426 % \clap{\vrule width .5bp height 5bp depth 5bp}%
1427 % \usemplibgroup{mygroup}
1428 %\end{verbatim}
1429 %\startmpfig
1430 %\mpfig usemplibgroup "mygroup" withtransparency (1,2/3); draw (left--right) scaled 5; draw (up--down) scaled 5;\endmpfig
1431 %\stopmpfig{4}
1432 %\begin{verbatim}
1433 % \mpfig
1434 % usemplibgroup "mygroup"
1435 % withtransparency (1, 2/3) ;
1436 % draw (left--right) scaled 5 ;
1437 % draw (up--down) scaled 5 ;
1438 % \endmpfig
1439 %\end{verbatim}
1440 %
1441 % Also note that normally the XObjects are not affected by outer color commands.
1442 % However, if you have made the original XObject using |withoutcolor| command,
1443 % colors will have effects on its uncolored objects.
1444 %
1445 % \paragraph{Note on picture shading}
1446 % \hypertarget{para:pictureshading}{When}
1447 % you give shading effect upon a \emph{textual picture} (i.e.\ non-path object)
1448 % inside or outside a transparency group, currently many of the PDF renderers,
1449 % including Mac OS Preview and Foxit Editor, do not interprete PDF coordinates properly.
1450 % If that happens, consider using other PDF viewer such as Adobe Acrobat. An example:
1451 % \mpfig* picture pic[]; pic1 = image(fill fullcircle scaled 60 withoutcolor; fill fullcircle scaled 60 shifted 25right withoutcolor;); pic2 = image(draw pic1 withshadingmethod "linear" withshadingvector (2, 1) withshadingcolors (red, blue)); \endmpfig
1452 %\begin{verbatim}
1453 % \mpfig*
1454 % picture pic[];
1455 % pic1 = image(
1456 % fill fullcircle scaled 60 withoutcolor;
1457 % fill fullcircle scaled 60 shifted 25right withoutcolor;
1458 % ) ;
1459 % pic2 = image(
1460 % draw pic1
1461 % withshadingmethod "linear"
1462 % withshadingvector (2, 1)
1463 % withshadingcolors (red, blue)
1464 % ) ;
1465 % \endmpfig
1466 %\end{verbatim}
1467 % \startmpfig
1468 % \mpfig draw pic2 asgroup "" withtransparency (1, 2/3); \endmpfig\vskip15pt
1469 % \stopmpfig{3}
1470 %\begin{verbatim}
1471 % \mpfig % shading inside group
1472 % draw pic2
1473 % asgroup ""
1474 % withtransparency (1, 2/3) ;
1475 % \endmpfig
1476 %\end{verbatim}
1477 % \startmpfig
1478 % \mpfig draw pic1 asgroup "" withshadingmethod "linear" withshadingvector (2, 1) withshadingcolors (red, blue) withtransparency (1, 2/3); \endmpfig
1479 % \stopmpfig{4}
1480 %\begin{verbatim}
1481 % \mpfig % shading outside group
1482 % draw pic1
1483 % asgroup ""
1484 % withshadingmethod "linear"
1485 % withshadingvector (2, 1)
1486 % withshadingcolors (red, blue)
1487 % withtransparency (1, 2/3) ;
1488 % \endmpfig
1489 %\end{verbatim}
1490 % After some experiment, however, it turned out that
1491 % the best way to get picture shading with transparency group
1492 % is to give shading effect within an ordinary form XObject
1493 % and then wrap it up in a transparency group XObject.
1494 % This sort of double wrapping will be done automatically when you specify `|wrapped|'
1495 % as an optional argument of |asgroup|.
1496 % Most PDF renderers do render it properly:
1497 %\startmpfig
1498 %\mpfig draw pic2 asgroup "wrapped" withtransparency (1, 2/3); \endmpfig
1499 %\stopmpfig{3}
1500 %\begin{verbatim}
1501 % \mpfig
1502 % draw pic2
1503 % asgroup "wrapped"
1504 % withtransparency (1, 2/3) ;
1505 % \endmpfig
1506 %\end{verbatim}
1507 % or preferably (see next subsection \secref{mplibgroupendmplibgroup} on \cs{mplibgroup}):
1508 %\startmpfig
1509 %\mplibgroup{myshading}[asgroup="wrapped"]
1510 %\mpfig draw pic2; \endmpfig
1511 %\endmplibgroup
1512 %\mpfig usemplibgroup "myshading" rotated 15 withtransparency (1, 2/3); \endmpfig
1513 %\stopmpfig{7}
1514 % \hypertarget{doublewrappingexample}{}\relax
1515 %\begin{verbatim}
1516 % \mplibgroup{myshading}[asgroup="wrapped"]
1517 % \mpfig
1518 % draw pic2 ;
1519 % \endmpfig
1520 % \endmplibgroup
1521 %
1522 % \mpfig
1523 % usemplibgroup "myshading" rotated 15
1524 % withtransparency (1, 2/3) ;
1525 % \endmpfig
1526 %\end{verbatim}
1527 %
1528 % \subsubsection[\cs{mplibgroup}]{\cs{mplibgroup\{...\} ...} \cs{endmplibgroup}}
1529 % \label{sec:mplibgroupendmplibgroup}
1530 % These \TeX\ macros are described here in this subsection, as they are
1531 % deeply related to the |asgroup| operator described just above at \secref{transparencygroup}.
1532 % With these, users can define a transparency group or an ordinary \emph{form XObject}
1533 % from \TeX\ side.
1534 % The syntax is similar to the \cs{mppattern} command described above at \secref{mppattern}.
1535 %
1536 % An example:\footnote{Note that, here again by the option |asgroup="wrapped"|,
1537 % within a transparency group XObject
1538 % a tiling pattern is wrapped up in an inner, ordinary XObject.
1539 % This annoyance is especially for Mac OS Preview which misapplies
1540 % the transformation matrix to tiling or shading patterns
1541 % directly wrapped in a transparency group.
1542 % Most other PDF renderers seem to behave properly even with single wrapping. }
1543 %\startmpfig
1544 %\mplibgroup{texpatt}[asgroup="wrapped",]\mpfig filldraw fullcircle xscaled 100 yscaled 50 withmppattern "pattnocolor" withcolor 2/3red;\endmpfig \endmplibgroup
1545 %\usemplibgroup{texpatt}
1546 %\stopmpfig{10}
1547 %\begin{verbatim}
1548 % \mplibgroup{texpatt} % or \begin{mplibgroup}{texpatt}
1549 % [ % options: see below
1550 % asgroup="wrapped",
1551 % ]
1552 % \mpfig % or any other TeX code
1553 % filldraw fullcircle
1554 % xscaled 100 yscaled 50
1555 % withmppattern "pattnocolor"
1556 % withcolor 2/3 red ;
1557 % \endmpfig
1558 % \endmplibgroup % or \end{mplibgroup}
1559 %
1560 % \usemplibgroup{texpatt}
1561 %\end{verbatim}
1562 %\startmpfig
1563 %\mpfig usemplibgroup "texpatt" rotated -15 scaled 1.2 withtransparency(1,2/3); \endmpfig
1564 %\stopmpfig{2}
1565 %\begin{verbatim}
1566 % \mpfig
1567 % usemplibgroup "texpatt"
1568 % rotated -15 scaled 1.2
1569 % withtransparency (1, 2/3) ;
1570 % \endmpfig
1571 %\end{verbatim}
1572 %
1573 % Availabe options
1574 % are listed in Table~\ref{tab:mplibgroupoptions}.
1575 % Again, the width/height/depth values of the mplibgroup will be written down into the log file.
1576 %
1577 % \begin{table}
1578 % \centering
1579 % \caption{options for \cs{mplibgroup}}\label{tab:mplibgroupoptions}
1580 % \begin{tabular}{lll}
1581 % \hline
1582 % Key & Value Type & Explanation\\
1583 % \hline
1584 % |asgroup| &\emph{string} & \parbox{236bp}{\strut
1585 % |""|, or any comma-separated combination of |isolated|,\\[-1pt]
1586 % |knockout|, |wrapped| and |off|, or |"masking"|\strut}\\
1587 % |colorspace| &\emph{string} & \parbox{250bp}{\strut
1588 % |/CS| entry to a transparency group, such as |"/DeviceGray"|,\\[-1pt]
1589 % |"/DeviceRGB"| or |"/DeviceCMYK"|\strut}\\
1590 % |bbox| &\emph{table} or \emph{string} & |llx|, |lly|, |urx|, |ury| values\kern1pt*\\
1591 % |matrix| &\emph{table} or \emph{string} & |xx|, |yx|, |xy|, |yy| values\kern1pt*
1592 % or MP transform code\\
1593 % |resources| &\emph{string} & PDF resources if needed\\
1594 % \hline
1595 % & & \small *\,in string type, numbers are separated by spaces\\
1596 % \end{tabular}
1597 % \end{table}
1598 %
1599 % When |asgroup| option is not given or is given as |"off"|,
1600 % an ordinary form XObject will be generated rather than a transparency group.
1601 % Thus the individual objects, not the XObject as a whole, will be affected
1602 % by outer transparency command, just like the first figure
1603 % in the \hyperlink{noasgroupexample}{example} above at \secref{transparencygroup}.
1604 %
1605 % Option |asgroup="wrapped"| can be regarded as a shortcut of double \cs{mplibgroup} command.
1606 % The content will be wrapped up in an ordinary form XObject
1607 % before being wrapped again in a transparency group.
1608 % This option could be useful when a tiling pattern
1609 % (see the example just above)
1610 % or a picture shading
1611 % (see the \hyperlink{doublewrappingexample}{example} above at \secref{transparencygroup})
1612 % is used in the content.
1613 %
1614 % As for the option |asgroup="masking"|, see the next subsection \secref{withmaskinggroup}.
1615 %
1616 % With |colorspace| option,
1617 % which is no-op for ordinary form XObject,
1618 % users can specify the color space of a transparency group.
1619 % For instance, the mplibgroup will be painted in grayscale model
1620 % when |colorspace=|\allowbreak|"/DeviceGray"| is given to an \emph{isolated} transparency group.\relax
1621 % \footnote{Note that some PDF renderers such as Mac OS Preview or Firefox
1622 % do not render properly this option.}
1623 %
1624 % As shown, you can reuse the mplibgroup
1625 % using the \TeX\ command \cs{usemplibgroup} or
1626 % the \metapost command |usemplibgroup|.
1627 % The behavior of these commands is the same as that described \hyperlink{usemplibgroup}{above}
1628 % at \secref{transparencygroup},
1629 % excepting that the mplibgroup made by \TeX\ code (not by \metapost code) respects original height and depth.
1630 %
1631 %
1632 % \subsubsection[\ttfamily withmaskinggroup]{\ttfamily ... withmaskinggroup ...}
1633 % \label{sec:withmaskinggroup}
1634 % Using this command,
1635 % the mplibgroup (see above \secref{mplibgroupendmplibgroup})
1636 % generated by the option \bsx|asgroup=|\allowbreak|"masking"|\esx\ (see Table~\ref{tab:mplibgroupoptions})
1637 % can be utilized as a masking transparency group upon a picture or a path object.
1638 % The syntax is \bsx\meta{picture} \textbar\ \meta{path} |withmaskinggroup| \meta{string}\esx,
1639 % the latter being the name of a pre-defined masking group.
1640 %
1641 % Basically, the masking group should be prepared in \emph{grayscale} color model:
1642 % the area painted with |1| ($\approx$ white: full luminosity) will preserve
1643 % the full color of the object;
1644 % the area painted with |0| ($\approx$ black: zero luminosity) will force
1645 % full transparency, masking it invisibly.\relax
1646 % \footnote{In fact, colors in other color models are also allowed
1647 % (such as |white|, |black|, |red|, |green|, |blue|).
1648 % But they will be converted to grayscale model by the PDF renderer, so that
1649 % |"/DeviceGray"| is the default value of |colorspace| option to a masking transparency group
1650 % (see Table~\ref{tab:mplibgroupoptions} at \secref{mplibgroupendmplibgroup}). }
1651 %
1652 % By default, the background color of a masking group is |0| ($\approx$ black),
1653 % which you can change by this macro:
1654 % \begin{description}
1655 % \item[withmaskingbgcolor \meta{color expr}] sets the background color of the masking group.
1656 % |0| denotes full transparency (masking invisibly); |1|, full color.\relax
1657 % \footnote{Color expressions in rgb or cmyk model are also allowed,
1658 % in accordance with the option |colorspace=|\allowbreak|"/DeviceRGB"|
1659 % or |colorspace=|\allowbreak|"/DeviceCMYK"| given to the masking transparency group.
1660 % This however we do not recommend as the luminosity is difficult to understand intuitively. }
1661 % \end{description}
1662 % An example:
1663 %\begin{verbatim}
1664 % \mpfig*
1665 % picture pic;
1666 % pic = image(
1667 % fill fullcircle scaled 80 withcolor blue ;
1668 % fill fullcircle scaled 80 shifted (25,0) withcolor green ;
1669 % fill fullcircle scaled 80 shifted (50,0) withcolor red ;
1670 % );
1671 % \endmpfig
1672 %
1673 % \mplibgroup{mymask}[asgroup="masking"]
1674 % \mpfig
1675 % label(TEX "\sffamily\bfseries\scshape\Huge Meta" scaled 2, center pic)
1676 % withcolor 1 ;
1677 % \endmpfig
1678 % \endmplibgroup
1679 %\end{verbatim}
1680 %\startmpfig
1681 %\mpfig* picture pic; pic = image(fill fullcircle scaled 80 withcolor blue; fill fullcircle scaled 80 shifted (25,0) withcolor green; fill fullcircle scaled 80 shifted (50,0) withcolor red;);\endmpfig
1682 %\mplibgroup{mymask}[asgroup="masking"]
1683 %\mpfig label(TEX "\sffamily\bfseries\scshape\Huge Meta" scaled 2, center pic) withcolor 1;\endmpfig
1684 %\endmplibgroup
1685 %\mpfig fill bbox pic withshadingmethod "linear" withshadingcolors(red, blue); draw pic withmaskinggroup "mymask" withmaskingbgcolor 1/10 withtransparency (1, 0.8);\endmpfig
1686 %\stopmpfig{1}
1687 %\begin{verbatim}
1688 % \mpfig
1689 % fill bbox pic
1690 % withshadingmethod "linear"
1691 % withshadingcolors (red, blue) ;
1692 % draw pic
1693 % withmaskinggroup "mymask"
1694 % withmaskingbgcolor 1/10
1695 % withtransparency (1, 0.8) ;
1696 % \endmpfig
1697 %\end{verbatim}
1698 %
1699 %
1700 % \subsubsection[\ttfamily mpliblength, mplibuclength]{\ttfamily mpliblength ..., mplibuclength ...}
1701 % \bsx|mpliblength| \meta{string}\esx\ returns the number of unicode characters in the string.
1702 % This is a unicode-aware version equivalent to the \metapost primitive |length|, but
1703 % accepts only a string-type argument.
1704 % For instance, |mpliblength| |"abçdéf"| returns |6|, not |8|.
1705 %
1706 % On the other hand,
1707 % \bsx|mplibuclength| \meta{string}\esx\ returns the number of unicode grapheme clusters in the string.
1708 % For instance, |mplibuclength| |"Äpfel"|,
1709 % where |Ä| is encoded using two codepoints (U+0041 and U+0308),
1710 % returns |5|, not |6| or |7|.
1711 % This operator requires \pkg{lua-uni-algos} package installed.
1712 %
1713 % \subsubsection[\ttfamily mplibsubstring, mplibucsubstring]{\ttfamily mplibsubstring ... of ..., mplibucsubstring ... of ...}
1714 % \bsx|mplibsubstring| \meta{pair} |of| \meta{string}\esx\ is a unicode-aware version equivalent to the
1715 % \metapost's |substring ... of ...| primitive. The syntax is the same as the latter,
1716 % but the string is indexed by unicode characters.
1717 % For instance, |mplibsubstring| |(2,5)| |of| |"abçdéf"| returns |"çdé"|,
1718 % and |mplibsubstring| |(5,2)| |of| |"abçdéf"| returns |"édç"|.
1719 %
1720 % On the other hand,
1721 % \bsx|mplibucsubstring| \meta{pair} |of| \meta{string}\esx\ returns the part of the string indexed
1722 % by unicode grapheme clusters.
1723 % For instance, |mplibucsubstring| |(0,1)| |of| |"Äpfel"|,
1724 % where |Ä| is encoded using two codepoints (U+0041 and U+0308),
1725 % returns |"Ä"|, not |"A"|.
1726 % This operator requires \pkg{lua-uni-algos} package installed.
1727 %
1728 % \subsection{Lua}
1729 %
1730 % \subsubsection[\ttfamily runscript]{\ttfamily runscript ...}
1731 % A good many \metapost macros described in this documentation have been implemented
1732 % using the primitive |runscript|.
1733 % With \bsx|runscript| \meta{string}\esx, you can run a Lua code chunk from \metapost side
1734 % and get some \metapost code returned by Lua if you want.
1735 % As the functionality is provided by the \mplib library itself,
1736 % \pkg{luamplib} does not have much to say about it.
1737 %
1738 % One thing is worth mentioning, however:
1739 % if you return a Lua \emph{table} to the \metapost process,
1740 % it is automatically converted to a relevant \metapost data type
1741 % such as pair, color, cmykcolor or transform.
1742 % So users can save some extra toil of converting a table to a string, though it's not a big deal.
1743 % For instance, |runscript| |"return {1,0,0}"| will give you the \metapost color expression |(1,0,0)|
1744 % automatically.
1745 %
1746 % \subsubsection[\ttfamily luamplib.instances]{Lua table \ttfamily luamplib.instances}
1747 % \label{sec:luamplibinstances}
1748 % Users can access the Lua table containing \mplib instances, |luamplib.instances|,
1749 % through which \metapost variables are also easily accessible from Lua side,
1750 % as documented in Lua\TeX{} manual \S\,11.2.8.4 (|texdoc luatex|).
1751 % The following example will print |false|, |3.0|, |MetaPost| and
1752 % the knots and the cyclicity of the path |unitsquare|.
1753 %\begin{verbatim}
1754 % \begin{mplibcode}[myinstance]
1755 % boolean b; b = 1 > 2;
1756 % numeric n; n = 3;
1757 % string s; s = "MetaPost";
1758 % path p; p = unitsquare;
1759 % \end{mplibcode}
1760 %
1761 % \directlua{
1762 % local myinstance = luamplib.instances.myinstance
1763 % print( myinstance:get_boolean "b" )
1764 % print( myinstance:get_numeric "n" )
1765 % print( myinstance:get_string "s" )
1766 % local t = myinstance:get_path "p"
1767 % for k,v in pairs(t) do
1768 % print(k, type(v)=='table' and table.concat(v,' ') or v)
1769 % end
1770 % }
1771 %\end{verbatim}
1772 % Of course, this sort of Lua code can also be run inside \metapost code using |runscript|
1773 % command.
1774 % Again, of course you can access a \metapost variable using your own \TeX\ macro. For example:
1775 %\startmpfig
1776 %\mpfig* numeric n; n = 3;\endmpfig
1777 %\def\mpnumeric#1#2{\directlua{tex.sprint(tostring(luamplib.instances["#1"]:get_numeric"#2"))}}
1778 %\mpnumeric{@mpfig}{n}\relax
1779 %\stopmpfig{4}
1780 %\begin{verbatim}
1781 % \def\mpnumeric#1#2{\directlua{
1782 % tex.sprint(tostring(luamplib.instances["#1"]:get_numeric"#2"))
1783 % }}
1784 % \mpnumeric{myinstance}{n}\relax
1785 %\end{verbatim}
1786 %
1787 % \subsubsection[\ttfamily luamplib.process\_mplibcode]{Lua function \ttfamily luamplib.process\_mplibcode}
1788 % Users can run a \metapost code chunk from Lua side by using this function:
1789 %\begin{verbatim}
1790 % luamplib.process_mplibcode (<string> metapost code, <string> instance name)
1791 %\end{verbatim}
1792 %
1793 % The second argument cannot be absent, but can be an empty string (|""|) which
1794 % means that it has no instance name.
1795 %
1796 % Some other elements in the |luamplib| namespace, listed in Table~\ref{tab:elementsinluamplib},
1797 % can affect the process of |process_mplibcode|.
1798 %
1799 % \begin{table}
1800 % \centering
1801 % \caption{elements in \texttt{luamplib} table (partial)}\label{tab:elementsinluamplib}
1802 % \begin{tabular}{llll}\hline
1803 % Key & Type & Related \TeX\ macro & Cf. \\\hline
1804 % |codeinherit| & \emph{boolean} & \cs{mplibcodeinherit} & \secref{mplibcodeinherit}\\
1805 % |everyendmplib| & \emph{table} & \cs{everyendmplib} & \secref{everymplib}\\
1806 % |everymplib| & \emph{table} & \cs{everymplib} & \secref{everymplib}\\
1807 % |getcachedir| & \emph{function} \parg{string} & \cs{mplibcachedir} & \secref{mplibcachedir}\\
1808 % |globaltextext| & \emph{boolean} & \cs{mplibglobaltextext} & \secref{mplibglobaltextext}\\
1809 % |legacyverbatimtex| & \emph{boolean} & \cs{mpliblegacybehavior} & \secref{mpliblegacybehavior}\\
1810 % |noneedtoreplace| & \emph{table} & \cs{mplibmakenocache} & \secref{mplibcachedir}\\
1811 % |numbersystem| & \emph{string} & \cs{mplibnumbersystem} & \secref{mplibnumbersystem}\\
1812 % |setformat| & \emph{function} \parg{string} & \cs{mplibsetformat} & \secref{mplibsetformat}\\
1813 % |showlog| & \emph{boolean} & \cs{mplibshowlog} & \secref{mplibshowlog}\\
1814 % |textextlabel| & \emph{boolean} & \cs{mplibtextextlabel} & \secref{mplibtextextlabel}\\
1815 % |verbatiminput| & \emph{boolean} & \cs{mplibverbatim} & \secref{mplibverbatim}\\\hline
1816 % \end{tabular}
1817 % \end{table}
1818 %
1819 % \subsubsection[\ttfamily luamplib.registerpattern]{Lua function \ttfamily luamplib.registerpattern}
1820 % This is the Lua interface for \cs{mppattern} |...| \cs{endmppattern}
1821 % described above at \secref{mppattern}.
1822 %\begin{verbatim}
1823 % luamplib.registerpattern (<number> box register, <string> pattern name, <table> options)
1824 %\end{verbatim}
1825 %
1826 % The first argument is the register of a box containing a pattern cell,
1827 % which should be prepared in advance by the user. For instance,
1828 % \cs{setbox0=}\allowbreak\cs{hbox}\allowbreak|{\tiny\TeX}|,
1829 % or corresponding Lua code using |tex.setbox| function; then the argument should be |0|.\relax
1830 % \footnote{In DVI mode, \TeX\ macro `|mplibpatternname|' should be set as \meta{pattern name}
1831 % before preparing the box, if shading pattern (i.e.\ shading on picture) is used
1832 % in the pattern cell. }
1833 %
1834 % As for the third argument, see above Table~\ref{tab:mppatternoptions}.
1835 % The argument cannot be absent, but can be an empty table, i.e.\ |{ }|.
1836 %
1837 % \subsubsection[\ttfamily luamplib.registergroup]{Lua function \ttfamily luamplib.registergroup}
1838 % This is the Lua interface for \cs{mplibgroup} |...| \cs{endmplibgroup}
1839 % described above at \secref{mplibgroupendmplibgroup}.
1840 %\begin{verbatim}
1841 % luamplib.registergroup (<number> box register, <string> group name, <table> options)
1842 %\end{verbatim}
1843 %
1844 % The first argument is the register of a box prepared in advance by the user.
1845 % When the contents of the box have been generated from \TeX\ (not \metapost) code,
1846 % please make sure that both of the \TeX\ macros `|MPllx|' and `|MPlly|' are defined as `|0|'
1847 % before invoking the Lua function.\footnote{\relax
1848 % In DVI mode, \TeX\ macro `|mplibgroupname|' also should be set as \meta{group name} before
1849 % preparing the box, if shading pattern (i.e.\ shading on picture) is used in the mplibgroup. }
1850 %
1851 % As for the third argument, see above Table~\ref{tab:mplibgroupoptions}.
1852 % The argument cannot be absent, but can be an empty table, i.e.\ |{ }|.
1853 %
1854 % Reusing an mplibgroup, \cs{usemplibgroup}\marg{name}, is basically the same as
1855 % running the \TeX\ macro `|luamplib.group.|\meta{name}'.
1856 % If you need the boxresource index,
1857 % inspect this macro using |token.get_macro| function.
1858 %
1859 %
1860 % \section{Implementation}
1861 %
1862 % \subsection{Lua module}
1863 %
1864 % \iffalse
1865 %<*lua>
1866 % \fi
1867 %
1868 % \begin{macrocode}
1869
1870 luatexbase.provides_module {
1871 name = "luamplib",
1872 version = "2.41.3",
1873 date = "2026/05/26",
1874 description = "Lua package to typeset Metapost with LuaTeX's MPLib.",
1875 }
1876
1877 % \end{macrocode}
1878 %
1879 % Use the |luamplib| namespace, since |mplib| is for the \metapost library
1880 % itself. \ConTeXt{} uses |metapost|.
1881 % \begin{macrocode}
1882 luamplib = luamplib or { }
1883 local luamplib = luamplib
1884
1885 local format, abs = string.format, math.abs
1886
1887 % \end{macrocode}
1888 %
1889 % Use our own function for warn/info/err.
1890 % \begin{macrocode}
1891 local function termorlog (target, text, kind)
1892 if text then
1893 local mod, write, append = "luamplib", texio.write_nl, texio.write
1894 kind = kind
1895 or target == "term" and "Warning (more info in the log)"
1896 or target == "log" and "Info"
1897 or target == "term and log" and "Warning"
1898 or "Error"
1899 target = kind == "Error" and "term and log" or target
1900 local t = text:explode"\n+"
1901 write(target, format("Module %s %s:", mod, kind))
1902 if #t == 1 then
1903 append(target, format(" %s", t[1]))
1904 else
1905 for _,line in ipairs(t) do
1906 write(target, line)
1907 end
1908 write(target, format("(%s) ", mod))
1909 end
1910 append(target, format(" on input line %s", tex.inputlineno))
1911 write(target, "")
1912 if kind == "Error" then error() end
1913 end
1914 end
1915 local function warn (...) -- beware '%' symbol
1916 termorlog("term and log", select("#",...) > 1 and format(...) or ...)
1917 end
1918 local function info (...)
1919 termorlog("log", select("#",...) > 1 and format(...) or ...)
1920 end
1921 local function err (...)
1922 termorlog("error", select("#",...) > 1 and format(...) or ...)
1923 end
1924
1925 luamplib.showlog = luamplib.showlog or false
1926
1927 % \end{macrocode}
1928 %
1929 % Provide a few ``shortcuts'' expected by the code.
1930 % \begin{macrocode}
1931 local tableconcat = table.concat
1932 local tableinsert = table.insert
1933 local tableunpack = table.unpack
1934 local texsprint = tex.sprint
1935 local texgettoks = tex.gettoks
1936 local texgetbox = tex.getbox
1937 local texruntoks = tex.runtoks
1938 if not texruntoks then
1939 err("Your LuaTeX version is too old. Please upgrade it to the latest")
1940 end
1941 local is_defined = token.is_defined
1942 local get_macro = token.get_macro
1943 local mplib = require ('mplib')
1944 local kpse = require ('kpse')
1945 local lfs = require ('lfs')
1946 local lfsattributes = lfs.attributes
1947 local lfsisdir = lfs.isdir
1948 local lfsmkdir = lfs.mkdir
1949 local lfstouch = lfs.touch
1950 local ioopen = io.open
1951
1952 % \end{macrocode}
1953 %
1954 % Some helper functions, prepared for the case when |l-file| etc
1955 % is not loaded.
1956 % \begin{macrocode}
1957 local file = file or { }
1958 local replacesuffix = file.replacesuffix or function(filename, suffix)
1959 return (filename:gsub("%.[%a%d]+$","")) .. "." .. suffix
1960 end
1961 local is_writable = file.is_writable or function(name)
1962 if lfsisdir(name) then
1963 name = name .. "/_luam_plib_temp_file_"
1964 local fh = ioopen(name,"w")
1965 if fh then
1966 fh:close(); os.remove(name)
1967 return true
1968 end
1969 end
1970 end
1971 local mk_full_path = lfs.mkdirp or lfs.mkdirs or function(path)
1972 local full = ""
1973 for sub in path:gmatch("(/*[^\\/]+)") do
1974 full = full .. sub
1975 lfsmkdir(full)
1976 end
1977 end
1978
1979 % \end{macrocode}
1980 %
1981 % |btex| |...| |etex| in input |.mp| files will be replaced in finder.
1982 % Because of the limitation of \mplib regarding |make_text|,
1983 % we might have to make cache files modified from input files.
1984 %
1985 % First of all, determine the directory to store cache files.
1986 % \begin{macrocode}
1987 local cachedir
1988 local function outputdir ()
1989 if lfstouch then
1990 for i,v in ipairs{'TEXMFVAR','TEXMF_OUTPUT_DIRECTORY','.','TEXMFOUTPUT'} do
1991 local var = i == 3 and v or kpse.var_value(v)
1992 if var and var ~= "" then
1993 for _,vv in ipairs(var:explode(os.type == "unix" and ":" or ";")) do
1994 local dir = format("%s/%s",vv,"luamplib_cache")
1995 if not lfsisdir(dir) then
1996 mk_full_path(dir)
1997 end
1998 if is_writable(dir) then
1999 cachedir = dir; return cachedir
2000 end
2001 end
2002 end
2003 end
2004 end
2005 cachedir = "."; return cachedir
2006 end
2007 function luamplib.getcachedir(dir)
2008 dir = dir:gsub("##","#")
2009 dir = dir:gsub("^~",
2010 os.type == "windows" and os.getenv("UserProfile") or os.getenv("HOME"))
2011 if lfstouch and dir then
2012 if lfsisdir(dir) then
2013 if is_writable(dir) then
2014 cachedir = dir
2015 else
2016 warn("Directory '%s' is not writable!", dir)
2017 end
2018 else
2019 warn("Directory '%s' does not exist!", dir)
2020 end
2021 end
2022 end
2023 % \end{macrocode}
2024 % Some basic \metapost files not necessary to make cache files.
2025 % \begin{macrocode}
2026 local noneedtoreplace = {
2027 ["boxes.mp"] = true, -- ["format.mp"] = true,
2028 ["graph.mp"] = true, ["marith.mp"] = true, ["mfplain.mp"] = true,
2029 ["mpost.mp"] = true, ["plain.mp"] = true, ["rboxes.mp"] = true,
2030 ["sarith.mp"] = true, ["string.mp"] = true, -- ["TEX.mp"] = true,
2031 ["metafun.mp"] = true, ["metafun.mpiv"] = true, ["mp-abck.mpiv"] = true,
2032 ["mp-apos.mpiv"] = true, ["mp-asnc.mpiv"] = true, ["mp-bare.mpiv"] = true,
2033 ["mp-base.mpiv"] = true, ["mp-blob.mpiv"] = true, ["mp-butt.mpiv"] = true,
2034 ["mp-char.mpiv"] = true, ["mp-chem.mpiv"] = true, ["mp-core.mpiv"] = true,
2035 ["mp-crop.mpiv"] = true, ["mp-figs.mpiv"] = true, ["mp-form.mpiv"] = true,
2036 ["mp-func.mpiv"] = true, ["mp-grap.mpiv"] = true, ["mp-grid.mpiv"] = true,
2037 ["mp-grph.mpiv"] = true, ["mp-idea.mpiv"] = true, ["mp-luas.mpiv"] = true,
2038 ["mp-mlib.mpiv"] = true, ["mp-node.mpiv"] = true, ["mp-page.mpiv"] = true,
2039 ["mp-shap.mpiv"] = true, ["mp-step.mpiv"] = true, ["mp-text.mpiv"] = true,
2040 ["mp-tool.mpiv"] = true, ["mp-cont.mpiv"] = true,
2041 }
2042 luamplib.noneedtoreplace = noneedtoreplace
2043
2044 % \end{macrocode}
2045 % Pattern formats to replace |btex| and |verbatimtex| |...| |etex| in input files,
2046 % if needed.
2047 % \begin{macrocode}
2048 local name_b = "%f[%a_]"
2049 local name_e = "%f[^%a_]"
2050 local btex_etex = name_b.."btex"..name_e.."%s*(.-)%s*"..name_b.."etex"..name_e
2051 local verbatimtex_etex = name_b.."verbatimtex"..name_e.."%s*(.-)%s*"..name_b.."etex"..name_e
2052
2053 % \end{macrocode}
2054 % Function |luamplib.finder|
2055 % \begin{macrocode}
2056 local currenttime = os.time()
2057 do
2058 local luamplibtime = lfsattributes(kpse.find_file"luamplib.lua", "modification")
2059 % \end{macrocode}
2060 % |format.mp| is much complicated, so specially treated.
2061 % \begin{macrocode}
2062 local function replaceformatmp(file,newfile,ofmodify)
2063 local fh = ioopen(file,"r")
2064 if not fh then return file end
2065 local data = fh:read("*all"); fh:close()
2066 fh = ioopen(newfile,"w")
2067 if not fh then return file end
2068 fh:write(
2069 "let normalinfont = infont;\n",
2070 "primarydef str infont name = rawtextext(str) enddef;\n",
2071 data,
2072 "vardef Fmant_(expr x) = rawtextext(decimal abs x) enddef;\n",
2073 "vardef Fexp_(expr x) = rawtextext(\"$^{\"&decimal x&\"}$\") enddef;\n",
2074 "let infont = normalinfont;\n"
2075 ); fh:close()
2076 lfstouch(newfile,currenttime,ofmodify)
2077 return newfile
2078 end
2079 local function replaceinputmpfile (name,file)
2080 local ofmodify = lfsattributes(file,"modification")
2081 if not ofmodify then return file end
2082 local newfile = name:gsub("%W","_")
2083 newfile = format("%s/luamplib_input_%s", cachedir or outputdir(), newfile)
2084 if newfile and luamplibtime then
2085 local nf = lfsattributes(newfile)
2086 if nf and nf.mode == "file" and
2087 ofmodify == nf.modification and luamplibtime < nf.access then
2088 return nf.size == 0 and file or newfile
2089 end
2090 end
2091 if name == "format.mp" then return replaceformatmp(file,newfile,ofmodify) end
2092 local fh = ioopen(file,"r")
2093 if not fh then return file end
2094 local data = fh:read("*all"); fh:close()
2095 % \end{macrocode}
2096 % ``|etex|'' must be preceded by a space and followed by a space or semicolon as specified in
2097 % \LuaTeX\ manual, which is not the case of standalone \metapost though.
2098 % \begin{macrocode}
2099 local count,cnt = 0,0
2100 data, cnt = data:gsub(btex_etex, "btex %1 etex ") -- space
2101 count = count + cnt
2102 data, cnt = data:gsub(verbatimtex_etex, "verbatimtex %1 etex;") -- semicolon
2103 count = count + cnt
2104 if count == 0 then
2105 noneedtoreplace[name] = true
2106 fh = ioopen(newfile,"w");
2107 if fh then
2108 fh:close()
2109 lfstouch(newfile,currenttime,ofmodify)
2110 end
2111 return file
2112 end
2113 fh = ioopen(newfile,"w")
2114 if not fh then return file end
2115 fh:write(data); fh:close()
2116 lfstouch(newfile,currenttime,ofmodify)
2117 return newfile
2118 end
2119 % \end{macrocode}
2120 % As the finder function for \mplib, use the |kpse| library and
2121 % make it behave like as if \metapost was used. And replace |.mp| files with
2122 % cache files if needed.
2123 % See also \#74, \#97.
2124 % \begin{macrocode}
2125 local mpkpse
2126 do
2127 local exe = 0
2128 while arg[exe-1] do
2129 exe = exe-1
2130 end
2131 mpkpse = kpse.new(arg[exe], "mpost")
2132 end
2133 local special_ftype = {
2134 pfb = "type1 fonts",
2135 enc = "enc files",
2136 }
2137 function luamplib.finder (name, mode, ftype)
2138 if mode == "w" then
2139 if name and name ~= "mpout.log" then
2140 kpse.record_output_file(name) -- recorder
2141 end
2142 return name
2143 else
2144 ftype = special_ftype[ftype] or ftype
2145 local file = mpkpse:find_file(name,ftype)
2146 if file then
2147 if lfstouch and ftype == "mp" and not noneedtoreplace[name] and not noneedtoreplace["*.mp"] then
2148 file = replaceinputmpfile(name,file)
2149 end
2150 else
2151 file = mpkpse:find_file(name, name:match("%a+$"))
2152 end
2153 if file then
2154 kpse.record_input_file(file) -- recorder
2155 end
2156 return file
2157 end
2158 end
2159 end
2160
2161 % \end{macrocode}
2162 %
2163 % For the main function: |process|
2164 %
2165 % \emph{plain} or \emph{metafun},
2166 % though we cannot support \emph{metafun} format fully.
2167 % \begin{macrocode}
2168 local currentformat = "plain"
2169 function luamplib.setformat (name)
2170 currentformat = name
2171 end
2172 % \end{macrocode}
2173 % v2.9 has introduced the concept of ``code inherit''
2174 % \begin{macrocode}
2175 luamplib.codeinherit = false
2176 local mplibinstances = {}
2177 luamplib.instances = mplibinstances
2178 local has_instancename = false
2179
2180 local process
2181 do
2182 local function reporterror (result, prevlog)
2183 if not result then
2184 err("no result object returned")
2185 else
2186 local t, e, l = result.term, result.error, result.log
2187 % \end{macrocode}
2188 % log has more information than term, so log first (2021/08/02)
2189 % \begin{macrocode}
2190 local log = l or t or "no-term"
2191 log = log:gsub("%(Please type a command or say `end'%)",""):gsub("\n+","\n")
2192 if result.status > 0 then
2193 local first = log:match"(.-\n! .-)\n! "
2194 if first then
2195 termorlog("term", first)
2196 termorlog("log", log, "Warning")
2197 else
2198 warn(log)
2199 end
2200 if result.status > 1 then
2201 err(e or "see above messages")
2202 end
2203 elseif prevlog then
2204 log = prevlog..log
2205 % \end{macrocode}
2206 % v2.6.1: now luamplib does not disregard |show| command,
2207 % even when |luamplib.showlog| is false. Incidentally,
2208 % it does not raise error nor prints an info,
2209 % even if output has no figure.
2210 % \begin{macrocode}
2211 local show = log:match"\n>>? .+"
2212 if show then
2213 termorlog("term", show, "Info (more info in the log)")
2214 info(log)
2215 elseif luamplib.showlog and log:find"%g" then
2216 info(log)
2217 end
2218 end
2219 return log
2220 end
2221 end
2222 % \end{macrocode}
2223 % |lualibs-os.lua| installs a randomseed. When this file is not loaded,
2224 % we should explicitly seed a unique integer to get random randomseed for each run.
2225 % \begin{macrocode}
2226 if not math.initialseed then math.randomseed(currenttime) end
2227 local function luamplibload (name)
2228 local mpx = mplib.new {
2229 ini_version = true,
2230 find_file = luamplib.finder,
2231 % \end{macrocode}
2232 % Make use of |make_text| and |run_script|. And we provide |numbersystem| option since v2.4.
2233 % See \url{https://github.com/lualatex/luamplib/issues/21}.
2234 % \begin{macrocode}
2235 make_text = luamplib.maketext,
2236 run_script = luamplib.runscript,
2237 math_mode = luamplib.numbersystem,
2238 job_name = tex.jobname,
2239 random_seed = math.random(4095),
2240 utf8_mode = true,
2241 extensions = 1,
2242 }
2243 % \end{macrocode}
2244 % Append our own \metapost preamble to the preamble loading plain/metafun format.
2245 % \begin{macrocode}
2246 local preamble = tableconcat{
2247 format(luamplib.preambles.preamble, replacesuffix(name,"mp")),
2248 luamplib.preambles.mplibcode,
2249 luamplib.legacyverbatimtex and luamplib.preambles.legacyverbatimtex or "",
2250 luamplib.textextlabel and luamplib.preambles.textextlabel or "",
2251 }
2252 local result, log
2253 if not mpx then
2254 result = { status = 99, error = "out of memory"}
2255 else
2256 result = mpx:execute(preamble)
2257 end
2258 log = reporterror(result)
2259 return mpx, result, log
2260 end
2261 % \end{macrocode}
2262 % Here, excute each |mplibcode| data,
2263 % ie |\begin{mplibcode} ... \end{mplibcode}|.
2264 % \begin{macrocode}
2265 local process_stack = 0
2266 function process (data, instancename)
2267 local currfmt
2268 process_stack = process_stack + 1
2269 if instancename and instancename ~= "" then
2270 currfmt = instancename
2271 has_instancename = true
2272 else
2273 currfmt = tableconcat{
2274 currentformat,
2275 luamplib.numbersystem or "scaled",
2276 tostring(luamplib.textextlabel),
2277 tostring(luamplib.legacyverbatimtex),
2278 tostring(process_stack), -- try to address #63
2279 }
2280 has_instancename = false
2281 end
2282 local mpx = mplibinstances[currfmt]
2283 local standalone = not (has_instancename or luamplib.codeinherit)
2284 if mpx and standalone then
2285 mpx:finish()
2286 end
2287 local log = ""
2288 if standalone or not mpx then
2289 mpx, _, log = luamplibload(currentformat)
2290 mplibinstances[currfmt] = mpx
2291 end
2292 local converted, result = false, {}
2293 if mpx and data then
2294 result = mpx:execute(data)
2295 local log = reporterror(result, log)
2296 if log then
2297 if result.fig then
2298 converted = luamplib.convert(result)
2299 end
2300 end
2301 else
2302 err"Mem file unloadable. Maybe generated with a different version of mplib?"
2303 end
2304 process_stack = process_stack - 1
2305 return converted, result
2306 end
2307 end
2308
2309 % \end{macrocode}
2310 %
2311 % |dvipdfmx| is supported, though nobody seems to use it.
2312 % \begin{macrocode}
2313 local pdfmode = tex.outputmode > 0
2314
2315 % \end{macrocode}
2316 %
2317 % |make_text| and some |run_script| uses \LuaTeX's |tex.runtoks|.
2318 % \begin{macrocode}
2319 local catlatex = luatexbase.registernumber("catcodetable@latex")
2320 local catat11 = luatexbase.registernumber("catcodetable@atletter")
2321 % \end{macrocode}
2322 % |tex.scantoks| sometimes fail to read catcode properly, especially
2323 % |\#|, |\&|, or |\%|. After some experiment, we dropped using it.
2324 % Instead, a function containing |tex.sprint| seems to work nicely.
2325 % \begin{macrocode}
2326 local function run_tex_code (str, cat)
2327 texruntoks(function() texsprint(cat or catlatex, str) end)
2328 end
2329 % \end{macrocode}
2330 % For conversion of |sp| to |bp|.
2331 % \begin{macrocode}
2332 local factor = 65536*(7227/7200)
2333
2334 % \end{macrocode}
2335 %
2336 % Prepare textext box number containers, locals and globals.
2337 % |localid| can be any number. They are local anyway.
2338 % The number will be reset at the start of a new code chunk.
2339 % Global boxes will use |\newbox| command in |tex.runtoks| process.
2340 % This is the same when |codeinherit| is true.
2341 % Boxes in instances with name will also be global, so that
2342 % their tex boxes can be shared among instances of the same name.
2343 % \begin{macrocode}
2344 local texboxes = { globalid = 0, localid = 4096 }
2345 local process_tex_text
2346 do
2347 local textext_fmt = 'image(addto currentpicture doublepath unitsquare \z
2348 xscaled %f yscaled %f shifted (0,-%f) \z
2349 withprescript "mplibtexboxid=%i:%f:%f")'
2350 function process_tex_text (str, maketext)
2351 if str then
2352 if not maketext then str = str:gsub("\r.-$","") end
2353 local global = (has_instancename or luamplib.globaltextext or luamplib.codeinherit)
2354 and "\\global" or ""
2355 local tex_box_id
2356 if global == "" then
2357 tex_box_id = texboxes.localid + 1
2358 texboxes.localid = tex_box_id
2359 else
2360 local boxid = texboxes.globalid + 1
2361 texboxes.globalid = boxid
2362 run_tex_code(format([[\expandafter\newbox\csname luamplib.box.%s\endcsname]], boxid))
2363 tex_box_id = tex.getcount'allocationnumber'
2364 end
2365 if str:find"^%[taggingoff%]" then
2366 str = str:gsub("^%[taggingoff%]%s*","")
2367 run_tex_code(format("\\luamplibnotagtextboxset{%i}{%s\\setbox%i\\hbox{%s}}",
2368 tex_box_id, global, tex_box_id, str))
2369 else
2370 run_tex_code(format("\\luamplibtagtextboxset{%i}{%s\\setbox%i\\hbox{%s}}",
2371 tex_box_id, global, tex_box_id, str))
2372 end
2373 local box = texgetbox(tex_box_id)
2374 local wd = box.width / factor
2375 local ht = box.height / factor
2376 local dp = box.depth / factor
2377 return textext_fmt:format(wd, ht+dp, dp, tex_box_id, wd, ht+dp)
2378 end
2379 return ""
2380 end
2381 end
2382
2383 % \end{macrocode}
2384 %
2385 % Make |color| or |xcolor|'s color expressions usable,
2386 % with \cs{mpcolor} or |mplibcolor|. These commands should be used
2387 % with graphical objects.
2388 % Attempt to support l3color as well.
2389 % \begin{macrocode}
2390 if is_defined'color_select:n' then
2391 run_tex_code{
2392 "\\newcatcodetable\\luamplibcctabexplat",
2393 "\\begingroup",
2394 "\\catcode`@=11 ",
2395 "\\catcode`_=11 ",
2396 "\\catcode`:=11 ",
2397 "\\savecatcodetable\\luamplibcctabexplat",
2398 "\\endgroup",
2399 }
2400 end
2401 local ccexplat = luatexbase.registernumber"luamplibcctabexplat"
2402
2403 local process_color, process_mplibcolor
2404 % \end{macrocode}
2405 % A common function for color functions
2406 % \begin{macrocode}
2407 local function colorsplit (res)
2408 local t, tt = { }, res:gsub("[%[%]]","",2):explode()
2409 local be = tt[1]:find"^%d" and 1 or 2
2410 for i=be, #tt do
2411 if not tonumber(tt[i]) then break end
2412 t[#t+1] = tt[i]
2413 end
2414 if #t == 0 then -- named color in DVI mode with no DocumentMetadata
2415 run_tex_code{"\\extractcolorspecs{", tt[3], "}\\mplibtmpa\\mplibtmpb"}
2416 t = get_macro"mplibtmpb":explode","
2417 end
2418 return t
2419 end
2420 do
2421 local colfmt = ccexplat and "l3color" or "xcolor"
2422 local mplibcolorfmt = {
2423 xcolor = tableconcat{
2424 [[\begingroup\let\XC@mcolor\relax]],
2425 [[\def\set@color{\global\mplibtmptoks\expandafter{\current@color}}]],
2426 [[\color%s\endgroup]],
2427 },
2428 l3color = tableconcat{
2429 [[\begingroup\def\__color_select:N#1{\expandafter\__color_select:nn#1}]],
2430 [[\def\__color_backend_select:nn#1#2{\global\mplibtmptoks{#1 #2}}]],
2431 [[\def\__kernel_backend_literal:e#1{\global\mplibtmptoks\expandafter{\expanded{#1}}}]],
2432 [[\color_select:n%s\endgroup]],
2433 },
2434 }
2435 function process_color (str)
2436 if str then
2437 if not str:find("%b{}") then
2438 str = format("{%s}",str)
2439 end
2440 local myfmt = mplibcolorfmt[colfmt]
2441 if colfmt == "l3color" and is_defined"color" then
2442 if str:find("%b[]") then
2443 myfmt = mplibcolorfmt.xcolor
2444 else
2445 for _,v in ipairs(str:match"{(.+)}":explode"!") do
2446 if not v:find("^%s*%d+%s*$") then
2447 local pp = get_macro(format("l__color_named_%s_prop",v))
2448 if not pp or pp == "" then
2449 myfmt = mplibcolorfmt.xcolor
2450 break
2451 end
2452 end
2453 end
2454 end
2455 end
2456 run_tex_code(myfmt:format(str), ccexplat or catat11)
2457 local t = texgettoks"mplibtmptoks"
2458 if not pdfmode then
2459 if t:find"^hsb" or not t:find"%d" then
2460 t = "color push " .. t
2461 elseif not t:find"^pdf" then
2462 t = t:gsub("%a+ (.+)","pdf:bc [%1]")
2463 end
2464 end
2465 return format('1 withprescript "mpliboverridecolor=%s"', t)
2466 end
2467 return ""
2468 end
2469 function process_mplibcolor(str)
2470 local res = process_color(str)
2471 if res:find" cs " or res:find"@pdf.obj" or res:find"color push" then return res end
2472 res = colorsplit(res:match'"mpliboverridecolor=(.+)"')
2473 return format("(%s)", tableconcat(res, ","))
2474 end
2475 end
2476
2477 % \end{macrocode}
2478 %
2479 % for \cs{mpdim} or |mplibdimen|
2480 % \begin{macrocode}
2481 local function process_dimen (str)
2482 if str then
2483 str = str:gsub("{(.+)}","%1")
2484 run_tex_code(format([[\mplibtmptoks\expandafter{\the\dimexpr %s\relax}]], str))
2485 return format("begingroup %s endgroup", texgettoks"mplibtmptoks")
2486 end
2487 return ""
2488 end
2489
2490 % \end{macrocode}
2491 %
2492 % Newly introduced method of processing |verbatimtex| |...| |etex|.
2493 % This function is used when |\mpliblegacybehavior{false}| is declared.
2494 % \begin{macrocode}
2495 local function process_verbatimtex_text (str)
2496 if str then
2497 run_tex_code(str)
2498 end
2499 return ""
2500 end
2501
2502 % \end{macrocode}
2503 %
2504 % For legacy verbatimtex process.
2505 % |verbatimtex| |...| |etex| before |beginfig()|
2506 % is inserted just before the \mplib box. And
2507 % \TeX\ code inside |beginfig() ... endfig| is inserted after the \mplib box.
2508 % \begin{macrocode}
2509 local tex_code_pre_mplib = {}
2510 luamplib.figid = 1
2511 luamplib.in_the_fig = false
2512 local function process_verbatimtex_prefig (str)
2513 if str then
2514 tex_code_pre_mplib[luamplib.figid] = str
2515 end
2516 return ""
2517 end
2518 local function process_verbatimtex_infig (str)
2519 if str then
2520 return format('special "postmplibverbtex=%s";', str)
2521 end
2522 return ""
2523 end
2524
2525 % \end{macrocode}
2526 %
2527 % For \emph{metafun} format. see issue \#79.
2528 % \begin{macrocode}
2529 mp = mp or {}
2530 local mp = mp
2531 mp.mf_path_reset = mp.mf_path_reset or function() end
2532 mp.mf_finish_saving_data = mp.mf_finish_saving_data or function() end
2533 mp.report = mp.report or info
2534 % \end{macrocode}
2535 % \emph{metafun} 2021-03-09 changes crashes luamplib.
2536 % \begin{macrocode}
2537 catcodes = catcodes or {}
2538 local catcodes = catcodes
2539 catcodes.numbers = catcodes.numbers or {}
2540 catcodes.numbers.ctxcatcodes = catcodes.numbers.ctxcatcodes or catlatex
2541 catcodes.numbers.texcatcodes = catcodes.numbers.texcatcodes or catlatex
2542 catcodes.numbers.luacatcodes = catcodes.numbers.luacatcodes or catlatex
2543 catcodes.numbers.notcatcodes = catcodes.numbers.notcatcodes or catlatex
2544 catcodes.numbers.vrbcatcodes = catcodes.numbers.vrbcatcodes or catlatex
2545 catcodes.numbers.prtcatcodes = catcodes.numbers.prtcatcodes or catlatex
2546 catcodes.numbers.txtcatcodes = catcodes.numbers.txtcatcodes or catlatex
2547
2548 % \end{macrocode}
2549 %
2550 % Now |luamplib.runscript|
2551 % \begin{macrocode}
2552 do
2553 local runscript_funcs = {
2554 luamplibtext = process_tex_text,
2555 luamplibcolor = process_mplibcolor,
2556 luamplibdimen = process_dimen,
2557 luamplibprefig = process_verbatimtex_prefig,
2558 luamplibinfig = process_verbatimtex_infig,
2559 luamplibverbtex = process_verbatimtex_text,
2560 }
2561 % \end{macrocode}
2562 % A function from \ConTeXt\ general.
2563 % \begin{macrocode}
2564 local function mpprint(buffer,...)
2565 for i=1,select("#",...) do
2566 local value = select(i,...)
2567 if value ~= nil then
2568 local t = type(value)
2569 if t == "number" then
2570 buffer[#buffer+1] = format("%.16f",value)
2571 elseif t == "string" then
2572 buffer[#buffer+1] = value
2573 elseif t == "table" then
2574 buffer[#buffer+1] = "(" .. tableconcat(value,",") .. ")"
2575 else -- boolean or whatever
2576 buffer[#buffer+1] = tostring(value)
2577 end
2578 end
2579 end
2580 end
2581 function luamplib.runscript (code)
2582 local id, str = code:match("(.-){(.*)}")
2583 if id and str then
2584 local f = runscript_funcs[id]
2585 if f then
2586 local t = f(str)
2587 if t then return t end
2588 end
2589 end
2590 local f = loadstring(code)
2591 if type(f) == "function" then
2592 local buffer = {}
2593 function mp.print(...)
2594 mpprint(buffer,...)
2595 end
2596 local res = {f()}
2597 buffer = tableconcat(buffer)
2598 if buffer and buffer ~= "" then
2599 return buffer
2600 end
2601 buffer = {}
2602 mpprint(buffer, tableunpack(res))
2603 return tableconcat(buffer)
2604 end
2605 return ""
2606 end
2607 end
2608
2609 % \end{macrocode}
2610 %
2611 % |luamplib.maketext|
2612 % \begin{macrocode}
2613 luamplib.legacyverbatimtex = true
2614 do
2615 % \end{macrocode}
2616 % |make_text| must be one liner, so comment sign is not allowed.
2617 % \begin{macrocode}
2618 local function protecttexcontents (str)
2619 return str:gsub("\\%%", "\0PerCent\0")
2620 :gsub("%%.-\n", "")
2621 :gsub("%%.-$", "")
2622 :gsub("%zPerCent%z", "\\%%")
2623 :gsub("\r.-$", "")
2624 :gsub("%s+", " ")
2625 end
2626 function luamplib.maketext (str, what)
2627 if str and str ~= "" then
2628 str = protecttexcontents(str)
2629 if what == 1 then
2630 if not str:find("\\documentclass"..name_e) and
2631 not str:find("\\begin%s*{document}") and
2632 not str:find("\\documentstyle"..name_e) and
2633 not str:find("\\usepackage"..name_e) then
2634 if luamplib.legacyverbatimtex then
2635 if luamplib.in_the_fig then
2636 return process_verbatimtex_infig(str)
2637 else
2638 return process_verbatimtex_prefig(str)
2639 end
2640 else
2641 return process_verbatimtex_text(str)
2642 end
2643 end
2644 else
2645 return process_tex_text(str, true) -- bool is for 'char13'
2646 end
2647 end
2648 return ""
2649 end
2650 end
2651
2652 % \end{macrocode}
2653 %
2654 % luamplib's \metapost color operators
2655 % \begin{macrocode}
2656 luamplib.gettexcolor = function (str, rgb)
2657 local res = process_color(str):match'"mpliboverridecolor=(.+)"'
2658 if res:find" cs " or res:find"@pdf.obj" then
2659 if not rgb then
2660 warn("%s is a spot color. Forced to CMYK", str)
2661 end
2662 run_tex_code({
2663 "\\color_export:nnN{",
2664 str,
2665 "}{",
2666 rgb and "space-sep-rgb" or "space-sep-cmyk",
2667 "}\\mplib_@tempa",
2668 },ccexplat)
2669 return get_macro"mplib_@tempa":explode()
2670 end
2671 local t = colorsplit(res)
2672 if #t == 3 or not rgb then return t end
2673 if #t == 4 then
2674 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]) }
2675 end
2676 return { t[1], t[1], t[1] }
2677 end
2678
2679 luamplib.shadecolor = function (str)
2680 local res = process_color(str):match'"mpliboverridecolor=(.+)"'
2681 if res:find" cs " or res:find"@pdf.obj" then -- spot color shade: l3 only
2682 % \end{macrocode}
2683 % An example of spot color shading:
2684 %\begin{verbatim}
2685 % \DocumentMetadata{ }
2686 % \documentclass{article}
2687 % \usepackage{luamplib}
2688 % \ExplSyntaxOn
2689 % \color_model_new:nnn { pantone3005 }
2690 % { Separation }
2691 % {
2692 % name = PANTONE~3005~U ,
2693 % alternative-model = cmyk ,
2694 % alternative-values = {1, 0.56, 0, 0}
2695 % }
2696 % \color_set:nnn{spotA}{pantone3005}{1}
2697 % \color_set:nnn{spotB}{pantone3005}{0.6}
2698 % \color_model_new:nnn { pantone1215 }
2699 % { Separation }
2700 % {
2701 % name = PANTONE~1215~U ,
2702 % alternative-model = cmyk ,
2703 % alternative-values = {0, 0.15, 0.51, 0}
2704 % }
2705 % \color_set:nnn{spotC}{pantone1215}{1}
2706 % \color_model_new:nnn { pantone2040 }
2707 % { Separation }
2708 % {
2709 % name = PANTONE~2040~U ,
2710 % alternative-model = cmyk ,
2711 % alternative-values = {0, 0.28, 0.21, 0.04}
2712 % }
2713 % \color_set:nnn{spotD}{pantone2040}{1}
2714 % \ExplSyntaxOff
2715 % \begin{document}
2716 % \begin{mplibcode}
2717 % beginfig(1)
2718 % fill unitsquare xscaled \mpdim\textwidth yscaled 1cm
2719 % withshadingmethod "linear"
2720 % withshadingvector (0,1)
2721 % withshadingstep (
2722 % withshadingfraction .5
2723 % withshadingcolors ("spotB","spotC")
2724 % )
2725 % withshadingstep (
2726 % withshadingfraction 1
2727 % withshadingcolors ("spotC","spotD")
2728 % )
2729 % ;
2730 % endfig;
2731 % \end{mplibcode}
2732 % \end{document}
2733 %\end{verbatim}
2734 % another one: user-defined DeviceN colorspace
2735 %\begin{verbatim}
2736 % \DocumentMetadata{ }
2737 % \documentclass{article}
2738 % \usepackage{luamplib}
2739 % \ExplSyntaxOn
2740 % \color_model_new:nnn { pantone1215 }
2741 % { Separation }
2742 % {
2743 % name = PANTONE~1215~U ,
2744 % alternative-model = cmyk ,
2745 % alternative-values = {0, 0.15, 0.51, 0}
2746 % }
2747 % \color_model_new:nnn { pantone+black }
2748 % { DeviceN }
2749 % { names = {pantone1215,black} }
2750 % \color_set:nnn{purepantone}{pantone+black}{1,0}
2751 % \color_set:nnn{pureblack} {pantone+black}{0,1}
2752 % \ExplSyntaxOff
2753 % \begin{document}
2754 % \mpfig
2755 % fill unitsquare xscaled \mpdim{\textwidth} yscaled 30
2756 % withshadingmethod "linear"
2757 % withshadingcolors ("purepantone","pureblack")
2758 % ;
2759 % \endmpfig
2760 % \end{document}
2761 %\end{verbatim}
2762 % \begin{macrocode}
2763 run_tex_code({
2764 [[\color_export:nnN{]], str, [[}{backend}\mplib_@tempa]],
2765 },ccexplat)
2766 local name, value = get_macro'mplib_@tempa':match'{(.-)}{(.-)}'
2767 local t, obj = res:explode()
2768 if pdfmode then
2769 obj = format("%s 0 R", ltx.pdf.object_id( t[1]:sub(2,-1) ))
2770 else
2771 obj = t[2]
2772 end
2773 return format('(1) withprescript"mplib_spotcolor=%s:%s:%s"', value,obj,name)
2774 end
2775 return colorsplit(res)
2776 end
2777
2778 % \end{macrocode}
2779 % |luamplib.fillandstrokecolor|
2780 % \begin{macrocode}
2781 do
2782 local function graphictextcolor (col, filldraw)
2783 if col:find"^[%d%.:]+$" then
2784 col = col:explode":"
2785 for i=1,#col do
2786 col[i] = format("%.3f", col[i])
2787 end
2788 if pdfmode then
2789 local op = #col == 4 and "k" or #col == 3 and "rg" or "g"
2790 col[#col+1] = filldraw == "fill" and op or op:upper()
2791 return tableconcat(col," ")
2792 end
2793 return format("[%s]", tableconcat(col," "))
2794 end
2795 col = process_color(col):match'"mpliboverridecolor=(.+)"'
2796 if pdfmode then
2797 local t = col:explode()
2798 local b = filldraw == "fill" and 1 or #t/2+1
2799 local e = b == 1 and #t/2 or #t
2800 return tableconcat(t," ", b, e)
2801 end
2802 if col:find"@pdf.obj" then
2803 return col:gsub("pdf:bc%s*","",1)
2804 else
2805 return format("[%s]", tableconcat(colorsplit(col)," "))
2806 end
2807 end
2808 function luamplib.fillandstrokecolor (fill, stroke)
2809 fill = graphictextcolor(fill, "fill")
2810 stroke = graphictextcolor(stroke, "stroke")
2811 local bc = pdfmode and "" or "pdf:bc "
2812 return format('withprescript "mpliboverridecolor=%s%s %s"', bc, fill, stroke)
2813 end
2814 end
2815
2816 % \end{macrocode}
2817 %
2818 % Remove trailing zeros for smaller PDF
2819 % \begin{macrocode}
2820 local decimals = "%.%d+"
2821 local function rmzeros(str) return str:gsub("%.?0+$","") end
2822
2823 % \end{macrocode}
2824 %
2825 % common function for mplibgraphictext and mpliboutlinetext
2826 % \begin{macrocode}
2827 local function getrulemetric (box, curr, bp)
2828 local running = -1073741824
2829 local wd,ht,dp = curr.width, curr.height, curr.depth
2830 wd = wd == running and box.width or wd
2831 ht = ht == running and box.height or ht
2832 dp = dp == running and box.depth or dp
2833 if bp then
2834 return wd/factor, ht/factor, dp/factor
2835 end
2836 return wd, ht, dp
2837 end
2838
2839 % \end{macrocode}
2840 %
2841 % luamplib's mplibgraphictext operator
2842 % \begin{macrocode}
2843 do
2844 if not math.round then
2845 function math.round(x) return x < 0 and -math.floor(-x + 0.5) or math.floor(x + 0.5) end
2846 end
2847 local emboldenfonts = { }
2848 local function roundupwidth (f, fb)
2849 local wd = math.round(f.size * fb / factor * 10)
2850 if wd == 0 and fb ~= 0 then
2851 wd = 1
2852 end
2853 emboldenfonts.width = wd
2854 return wd
2855 end
2856 local function getemboldenwidth (curr, fakebold)
2857 local width = emboldenfonts.width
2858 if not width then
2859 local f
2860 local function getglyph(n)
2861 while n do
2862 if n.head then
2863 getglyph(n.head)
2864 elseif n.font and n.font > 0 then
2865 f = n.font; break
2866 end
2867 n = node.getnext(n)
2868 end
2869 end
2870 getglyph(curr)
2871 width = roundupwidth(font.getcopy(f or font.current()), fakebold)
2872 end
2873 return width
2874 end
2875 local function getrulewhatsit (line, wd, ht, dp)
2876 line, wd, ht, dp = line/1000, wd/factor, ht/factor, dp/factor
2877 line = line == 0 and "" or ("%f w"):format(line)
2878 local pl
2879 local fmt = "q %s %f %f %f %f re B Q"
2880 if pdfmode then
2881 pl = node.new("whatsit","pdf_literal")
2882 pl.mode = 0
2883 else
2884 fmt = "pdf:content "..fmt
2885 pl = node.new("whatsit","special")
2886 end
2887 pl.data = fmt:format(line, 0, -dp, wd, ht+dp) :gsub(decimals,rmzeros)
2888 local ss = node.new"glue"
2889 node.setglue(ss, 0, 65536, 65536, 2, 2)
2890 pl.next = ss
2891 return pl
2892 end
2893 % \end{macrocode}
2894 % copying attributes of rule/glue node to improve tagging of mplibgraphictext
2895 % \begin{macrocode}
2896 local tag_update_attrs
2897 if is_defined"[email protected]" then
2898 tag_update_attrs = function (n, curr)
2899 while n do
2900 n.attr = curr.attr
2901 if n.head then
2902 tag_update_attrs(n.head, curr)
2903 end
2904 n = node.getnext(n)
2905 end
2906 end
2907 else
2908 tag_update_attrs = function() end
2909 end
2910 local function embolden (box, curr, fakebold)
2911 local head = curr
2912 while curr do
2913 if curr.head then
2914 curr.head = embolden(curr, curr.head, fakebold)
2915 elseif curr.replace then
2916 curr.replace = embolden(box, curr.replace, fakebold)
2917 elseif curr.leader then
2918 if curr.leader.head then
2919 curr.leader.head = embolden(curr.leader, curr.leader.head, fakebold)
2920 elseif curr.leader.id == node.id"rule" then
2921 local glue = node.effective_glue(curr, box)
2922 local line = getemboldenwidth(curr, fakebold)
2923 local wd,ht,dp = getrulemetric(box, curr.leader)
2924 if box.id == node.id"hlist" then
2925 wd = glue
2926 else
2927 ht, dp = 0, glue
2928 end
2929 local pl = getrulewhatsit(line, wd, ht, dp)
2930 local pack = box.id == node.id"hlist" and node.hpack or node.vpack
2931 local list = pack(pl, glue, "exactly")
2932 tag_update_attrs(list,curr)
2933 head = node.insert_after(head, curr, list)
2934 head, curr = node.remove(head, curr)
2935 end
2936 elseif curr.id == node.id"rule" and curr.subtype == 0 then
2937 local line = getemboldenwidth(curr, fakebold)
2938 local wd,ht,dp = getrulemetric(box, curr)
2939 if box.id == node.id"vlist" then
2940 ht, dp = 0, ht+dp
2941 end
2942 local pl = getrulewhatsit(line, wd, ht, dp)
2943 local list
2944 if box.id == node.id"hlist" then
2945 list = node.hpack(pl, wd, "exactly")
2946 else
2947 list = node.vpack(pl, ht+dp, "exactly")
2948 end
2949 tag_update_attrs(list,curr)
2950 head = node.insert_after(head, curr, list)
2951 head, curr = node.remove(head, curr)
2952 elseif curr.id == node.id"glyph" and curr.font > 0 then
2953 local f = curr.font
2954 local key = format("%s:%s",f,fakebold)
2955 local i = emboldenfonts[key]
2956 if not i then
2957 local ft = font.getfont(f) or font.getcopy(f)
2958 local width = roundupwidth(ft, fakebold)
2959 if ft.format == "opentype" or ft.format == "truetype" then
2960 local name = ft.name:gsub('"',''):gsub(';$','')
2961 local t = name:gsub("^file:",""):gsub("^name:",""):gsub("^kpse:",""):gsub("^my:","")
2962 name = format('%s%sembolden=%s;',name, t:find":" and ";" or ":", fakebold)
2963 _, i = fonts.constructors.readanddefine(name,ft.size)
2964 elseif pdfmode then
2965 local ft = table.copy(ft)
2966 ft.mode, ft.width = 2, width
2967 i = font.define(ft)
2968 else
2969 goto skip_type1
2970 end
2971 emboldenfonts[key] = i
2972 end
2973 curr.font = i
2974 end
2975 ::skip_type1::
2976 curr = node.getnext(curr)
2977 end
2978 return head
2979 end
2980 luamplib.graphictext = function (text, fakebold, fc, dc)
2981 local fmt = process_tex_text(text):sub(1,-2)
2982 local id = tonumber(fmt:match"mplibtexboxid=(%d+):")
2983 emboldenfonts.width = nil
2984 local box = texgetbox(id)
2985 box.head = embolden(box, box.head, fakebold)
2986 local colors = luamplib.fillandstrokecolor(fc, dc)
2987 return format('%s %s)', fmt, colors)
2988 end
2989 end
2990
2991 % \end{macrocode}
2992 %
2993 % luamplib's mplibglyph operator
2994 % \begin{macrocode}
2995 do
2996 local function mperr (str)
2997 return format("hide(errmessage %q)", str)
2998 end
2999 local function getangle (a,b,c)
3000 local r = math.deg(math.atan(c.y-b.y, c.x-b.x) - math.atan(b.y-a.y, b.x-a.x))
3001 if r > 180 then
3002 r = r - 360
3003 elseif r < -180 then
3004 r = r + 360
3005 end
3006 return r
3007 end
3008 local function turning (t)
3009 local r, n = 0, #t
3010 for i=1,2 do
3011 tableinsert(t, t[i])
3012 end
3013 for i=1,n do
3014 r = r + getangle(t[i], t[i+1], t[i+2])
3015 end
3016 return r/360
3017 end
3018 local function glyphimage(t, fmt)
3019 local q, p, r, towarn = {{},{}}
3020 local function closepath(dots)
3021 tableinsert(p, format("%scycle", dots or "--"))
3022 tableinsert(q[ turning(r) > 0 and 1 or 2 ], tableconcat(p))
3023 end
3024 for i,v in ipairs(t) do
3025 local cmd = v[#v]
3026 local nt = t[i+1]
3027 local final = not nt or nt[#nt] ~= "l" and nt[#nt] ~= "c"
3028 if cmd == "m" then
3029 if final then towarn = true end
3030 p = {format('(%s,%s)',v[1],v[2])}
3031 r = {{x=v[1],y=v[2]}}
3032 else
3033 if cmd == "l" then
3034 local pt = t[i-1]
3035 if (final or pt and pt[#pt] == "m") and r[1].x == v[1] and r[1].y == v[2] then
3036 else
3037 tableinsert(p, format('--(%s,%s)',v[1],v[2]))
3038 tableinsert(r, {x=v[1],y=v[2]})
3039 end
3040 if final then closepath() end
3041 elseif cmd == "c" then
3042 tableinsert(p, format('..controls(%s,%s)and(%s,%s)',v[1],v[2],v[3],v[4]))
3043 if final and r[1].x == v[5] and r[1].y == v[6] then
3044 closepath ".."
3045 else
3046 tableinsert(p, format('..(%s,%s)',v[5],v[6]))
3047 tableinsert(r, {x=v[5],y=v[6]})
3048 if final then closepath() end
3049 end
3050 elseif cmd == "path" or cmd == "move" then
3051 else
3052 return mperr"unknown operator"
3053 end
3054 end
3055 end
3056 r = { }
3057 if fmt == "opentype" then
3058 for _,v in ipairs(q[1]) do
3059 tableinsert(r, format('addto currentpicture contour %s;',v))
3060 end
3061 for _,v in ipairs(q[2]) do
3062 tableinsert(r, format('addto currentpicture contour %s withcolor background;',v))
3063 end
3064 else
3065 for _,v in ipairs(q[2]) do
3066 tableinsert(r, format('addto currentpicture contour %s;',v))
3067 end
3068 for _,v in ipairs(q[1]) do
3069 tableinsert(r, format('addto currentpicture contour %s withcolor background;',v))
3070 end
3071 end
3072 return format('image(%s)', tableconcat(r)), towarn
3073 end
3074 if not table.tofile then require"lualibs-lpeg"; require"lualibs-table"; end
3075 function luamplib.glyph (f, c)
3076 local filename, subfont, instance, kind, shapedata
3077 local fid = tonumber(f) or font.id(f)
3078 if fid > 0 then
3079 local fontdata = font.getfont(fid) or font.getcopy(fid)
3080 filename, subfont, kind = fontdata.filename, fontdata.subfont, fontdata.format
3081 instance = fontdata.specification and fontdata.specification.instance
3082 or fontdata.shared and fontdata.shared.features.axis
3083 filename = filename and filename:gsub("^harfloaded:","")
3084 else
3085 local name
3086 f = f:match"^%s*(.+)%s*$"
3087 name, subfont, instance = f:match"(.+)%((%d+)%)%[(.-)%]$"
3088 if not name then
3089 name, instance = f:match"(.+)%[(.-)%]$" -- SourceHanSansK-VF.otf[Heavy]
3090 end
3091 if not name then
3092 name, subfont = f:match"(.+)%((%d+)%)$" -- Times.ttc(2)
3093 end
3094 name = name or f
3095 subfont = (subfont or 0)+1
3096 instance = instance and instance:lower()
3097 for _,ftype in ipairs{"opentype", "truetype"} do
3098 filename = kpse.find_file(name, ftype.." fonts")
3099 if filename then
3100 kind = ftype; break
3101 end
3102 end
3103 end
3104 if kind ~= "opentype" and kind ~= "truetype" then
3105 f = fid and fid > 0 and tex.fontname(fid) or f
3106 if kpse.find_file(f, "tfm") then
3107 return format("glyph %s of %q", tonumber(c) or format("%q",c), f)
3108 else
3109 filename = kpse.find_file(f, "type1 fonts")
3110 if filename then
3111 kind = "type1" -- there's bug in processing cmr family
3112 else
3113 return mperr"font not found"
3114 end
3115 end
3116 end
3117 local time = lfsattributes(filename,"modification")
3118 % \end{macrocode}
3119 %\begin{verbatim}
3120 % local k = format("shapes_%s(%s)[%s]%s", filename, subfont or "", instance or "",
3121 % luaotfload and luaotfload.version or "")
3122 %\end{verbatim}
3123 % ^^X replace next line with prev one in 2027.
3124 % \begin{macrocode}
3125 local k = format("shapes_%s(%s)[%s]", filename, subfont or "", instance or "")
3126 local h = format(string.rep('%02x', 256/8), string.byte(sha2.digest256(k), 1, -1))
3127 local newname = format("%s/%s.lua", cachedir or outputdir(), h)
3128 local newtime = lfsattributes(newname,"modification") or 0
3129 if time == newtime then
3130 shapedata = require(newname)
3131 end
3132 if not shapedata then
3133 if fonts then
3134 local handler = kind == "type1" and fonts.handlers.afm or fonts.handlers.otf
3135 shapedata = handler.readers.loadshapes(filename,subfont,instance)
3136 end
3137 if not shapedata then return mperr"loadshapes() failed. luaotfload not loaded?" end
3138 table.tofile(newname, shapedata, "return")
3139 lfstouch(newname, time, time)
3140 end
3141 local gid = tonumber(c)
3142 if not gid then
3143 local uni = utf8.codepoint(c)
3144 for i,v in pairs(shapedata.glyphs) do
3145 if c == v.name or uni == v.unicode then
3146 gid = i; break
3147 end
3148 end
3149 end
3150 if not gid then return mperr"cannot get GID (glyph id)" end
3151 local fac = 1000 / (shapedata.units or 1000)
3152 local t = shapedata.glyphs[gid]; t = t and t.segments
3153 if not t then return "image()" end
3154 for i,v in ipairs(t) do
3155 if type(v) == "table" then
3156 for ii,vv in ipairs(v) do
3157 if type(vv) == "number" then
3158 t[i][ii] = format("%.0f", vv * fac)
3159 end
3160 end
3161 end
3162 end
3163 local result, towarn = glyphimage(t, shapedata.format or kind)
3164 if towarn then
3165 warn("mplibglyph %s not working properly. Use glyph instead", f)
3166 end
3167 return result
3168 end
3169 end
3170
3171 % \end{macrocode}
3172 %
3173 % mpliboutlinetext : based on mkiv's font-mps.lua
3174 % \begin{macrocode}
3175 do
3176 local rulefmt = "mpliboutlinepic[%i]:=image(addto currentpicture contour \z
3177 unitsquare shifted - center unitsquare;) xscaled %f yscaled %f shifted (%f,%f);"
3178 local outline_horz, outline_vert
3179 function outline_vert (res, box, curr, xshift, yshift)
3180 local b2u = box.dir == "LTL"
3181 local dy = (b2u and -box.depth or box.height)/factor
3182 local ody = dy
3183 while curr do
3184 if curr.id == node.id"rule" then
3185 local wd, ht, dp = getrulemetric(box, curr, true)
3186 local hd = ht + dp
3187 if hd ~= 0 then
3188 dy = dy + (b2u and dp or -ht)
3189 if wd ~= 0 and curr.subtype == 0 then
3190 res[#res+1] = rulefmt:format(#res+1, wd, hd, xshift+wd/2, yshift+dy+(ht-dp)/2)
3191 end
3192 dy = dy + (b2u and ht or -dp)
3193 end
3194 elseif curr.id == node.id"glue" then
3195 local vwidth = node.effective_glue(curr,box)/factor
3196 if curr.leader then
3197 local curr, kind = curr.leader, curr.subtype
3198 if curr.id == node.id"rule" then
3199 local wd = getrulemetric(box, curr, true)
3200 if wd ~= 0 then
3201 local hd = vwidth
3202 local dy = dy + (b2u and 0 or -hd)
3203 if hd ~= 0 and curr.subtype == 0 then
3204 res[#res+1] = rulefmt:format(#res+1, wd, hd, xshift+wd/2, yshift+dy+hd/2)
3205 end
3206 end
3207 elseif curr.head then
3208 local hd = (curr.height + curr.depth)/factor
3209 if hd <= vwidth then
3210 local dy, n, iy = dy, 0, 0
3211 if kind == 100 or kind == 103 then -- todo: gleaders
3212 local ady = abs(ody - dy)
3213 local ndy = math.ceil(ady / hd) * hd
3214 local diff = ndy - ady
3215 n = math.floor((vwidth-diff) / hd)
3216 dy = dy + (b2u and diff or -diff)
3217 else
3218 n = math.floor(vwidth / hd)
3219 if kind == 101 then
3220 local side = vwidth % hd / 2
3221 dy = dy + (b2u and side or -side)
3222 elseif kind == 102 then
3223 iy = vwidth % hd / (n+1)
3224 dy = dy + (b2u and iy or -iy)
3225 end
3226 end
3227 dy = dy + (b2u and curr.depth or -curr.height)/factor
3228 hd = b2u and hd or -hd
3229 iy = b2u and iy or -iy
3230 local func = curr.id == node.id"hlist" and outline_horz or outline_vert
3231 for i=1,n do
3232 res = func(res, curr, curr.head, xshift+curr.shift/factor, yshift+dy)
3233 dy = dy + hd + iy
3234 end
3235 end
3236 end
3237 end
3238 dy = dy + (b2u and vwidth or -vwidth)
3239 elseif curr.id == node.id"kern" then
3240 dy = dy + curr.kern/factor * (b2u and 1 or -1)
3241 elseif curr.id == node.id"vlist" then
3242 dy = dy + (b2u and curr.depth or -curr.height)/factor
3243 res = outline_vert(res, curr, curr.head, xshift+curr.shift/factor, yshift+dy)
3244 dy = dy + (b2u and curr.height or -curr.depth)/factor
3245 elseif curr.id == node.id"hlist" then
3246 dy = dy + (b2u and curr.depth or -curr.height)/factor
3247 res = outline_horz(res, curr, curr.head, xshift+curr.shift/factor, yshift+dy)
3248 dy = dy + (b2u and curr.height or -curr.depth)/factor
3249 end
3250 curr = node.getnext(curr)
3251 end
3252 return res
3253 end
3254 function outline_horz (res, box, curr, xshift, yshift, discwd)
3255 local r2l = box.dir == "TRT"
3256 local dx = r2l and (discwd or box.width/factor) or 0
3257 local dirs = { { dir = r2l, dx = dx } }
3258 while curr do
3259 if curr.id == node.id"dir" then
3260 local sign, dir = curr.dir:match"(.)(...)"
3261 local level, newdir = curr.level, r2l
3262 if sign == "+" then
3263 newdir = dir == "TRT"
3264 if r2l ~= newdir then
3265 local n = node.getnext(curr)
3266 while n do
3267 if n.id == node.id"dir" and n.level+1 == level then break end
3268 n = node.getnext(n)
3269 end
3270 n = n or node.tail(curr)
3271 dx = dx + node.rangedimensions(box, curr, n)/factor * (newdir and 1 or -1)
3272 end
3273 dirs[level] = { dir = r2l, dx = dx }
3274 else
3275 local level = level + 1
3276 newdir = dirs[level].dir
3277 if r2l ~= newdir then
3278 dx = dirs[level].dx
3279 end
3280 end
3281 r2l = newdir
3282 elseif curr.char and curr.font and curr.font > 0 then
3283 local ft = font.getfont(curr.font) or font.getcopy(curr.font)
3284 local gid = ft.characters[curr.char].index or curr.char
3285 local scale = ft.size / factor / 1000
3286 local slant = (ft.slant or 0)/1000
3287 local extend = (ft.extend or 1000)/1000
3288 local squeeze = (ft.squeeze or 1000)/1000
3289 local expand = 1 + (curr.expansion_factor or 0)/1000000
3290 local xscale, yscale = scale * extend * expand, scale * squeeze
3291 dx = dx - (r2l and curr.width/factor*expand or 0)
3292 local xoff, yoff = (curr.xoffset or 0)/factor, (curr.yoffset or 0)/factor
3293 local xpos, ypos = dx + xshift + xoff, yshift + yoff
3294 local vertical = ""
3295 if ft.shared and (ft.shared.features.vert or ft.shared.features.vrt2) then
3296 if ft.shared.features.vertical then -- luatexko
3297 vertical = "rotated 90"
3298 local data = ft.characters[curr.char] or { }
3299 if ft.hb then
3300 local hoff, voff = (data.luatexko_hoff or 0)/factor, (data.luatexko_voff or 0)/factor
3301 local charraise = (ft.luatexko_charraise or 0)/factor
3302 xpos, ypos = xpos - voff + hoff - charraise, ypos + hoff + voff + charraise
3303 else
3304 local cmds = data.commands or { {0,0}, {0,0} }
3305 local voff, hoff = -cmds[1][2]/factor, cmds[2][2]/factor
3306 xpos, ypos = xpos + hoff, ypos + voff
3307 end
3308 elseif curr ~= box.head then -- luatexja
3309 vertical = "rotated 90"
3310 local en = ft.parameters.quad/factor/2
3311 xpos, ypos = xpos - xoff - yoff + en, ypos - yoff + xoff - en
3312 end
3313 end
3314 local image
3315 if ft.format == "opentype" or ft.format == "truetype" then
3316 image = luamplib.glyph(curr.font, gid)
3317 else
3318 local name, scale = ft.name, 1
3319 local vf = font.read_vf(name, ft.size)
3320 if vf and vf.characters[gid] then
3321 local cmds = vf.characters[gid].commands or {}
3322 for _,v in ipairs(cmds) do
3323 if v[1] == "char" then
3324 gid = v[2]
3325 elseif v[1] == "font" and vf.fonts[v[2]] then
3326 name = vf.fonts[v[2]].name
3327 scale = vf.fonts[v[2]].size / ft.size
3328 end
3329 end
3330 end
3331 image = format("glyph %s of %q scaled %f", gid, name, scale)
3332 end
3333 res[#res+1] = format("mpliboutlinepic[%i]:=%s xscaled %f yscaled %f slanted %f %s shifted (%f,%f);",
3334 #res+1, image, xscale, yscale, slant, vertical, xpos, ypos)
3335 dx = dx + (r2l and 0 or curr.width/factor*expand)
3336 elseif curr.replace then
3337 local width = node.dimensions(curr.replace)/factor
3338 dx = dx - (r2l and width or 0)
3339 res = outline_horz(res, box, curr.replace, xshift+dx, yshift, width)
3340 dx = dx + (r2l and 0 or width)
3341 elseif curr.id == node.id"rule" then
3342 local wd, ht, dp = getrulemetric(box, curr, true)
3343 if wd ~= 0 then
3344 local hd = ht + dp
3345 dx = dx - (r2l and wd or 0)
3346 if hd ~= 0 and curr.subtype == 0 then
3347 res[#res+1] = rulefmt:format(#res+1, wd, hd, xshift+dx+wd/2, yshift+(ht-dp)/2)
3348 end
3349 dx = dx + (r2l and 0 or wd)
3350 end
3351 elseif curr.id == node.id"glue" then
3352 local width = node.effective_glue(curr, box)/factor
3353 dx = dx - (r2l and width or 0)
3354 if curr.leader then
3355 local curr, kind = curr.leader, curr.subtype
3356 if curr.id == node.id"rule" then
3357 local wd, ht, dp = getrulemetric(box, curr, true)
3358 local hd = ht + dp
3359 if hd ~= 0 then
3360 wd = width
3361 if wd ~= 0 and curr.subtype == 0 then
3362 res[#res+1] = rulefmt:format(#res+1, wd, hd, xshift+dx+wd/2, yshift+(ht-dp)/2)
3363 end
3364 end
3365 elseif curr.head then
3366 local wd = curr.width/factor
3367 if wd <= width then
3368 local dx = r2l and dx+width or dx
3369 local n, ix = 0, 0
3370 if kind == 100 or kind == 103 then -- todo: gleaders
3371 local adx = abs(dx-dirs[1].dx)
3372 local ndx = math.ceil(adx / wd) * wd
3373 local diff = ndx - adx
3374 n = math.floor((width-diff) / wd)
3375 dx = dx + (r2l and -diff-wd or diff)
3376 else
3377 n = math.floor(width / wd)
3378 if kind == 101 then
3379 local side = width % wd /2
3380 dx = dx + (r2l and -side-wd or side)
3381 elseif kind == 102 then
3382 ix = width % wd / (n+1)
3383 dx = dx + (r2l and -ix-wd or ix)
3384 end
3385 end
3386 wd = r2l and -wd or wd
3387 ix = r2l and -ix or ix
3388 local func = curr.id == node.id"hlist" and outline_horz or outline_vert
3389 for i=1,n do
3390 res = func(res, curr, curr.head, xshift+dx, yshift-curr.shift/factor)
3391 dx = dx + wd + ix
3392 end
3393 end
3394 end
3395 end
3396 dx = dx + (r2l and 0 or width)
3397 elseif curr.id == node.id"kern" then
3398 dx = dx + curr.kern/factor * (r2l and -1 or 1)
3399 elseif curr.id == node.id"math" then
3400 dx = dx + curr.surround/factor * (r2l and -1 or 1)
3401 elseif curr.id == node.id"vlist" then
3402 dx = dx - (r2l and curr.width/factor or 0)
3403 res = outline_vert(res, curr, curr.head, xshift+dx, yshift-curr.shift/factor)
3404 dx = dx + (r2l and 0 or curr.width/factor)
3405 elseif curr.id == node.id"hlist" then
3406 dx = dx - (r2l and curr.width/factor or 0)
3407 res = outline_horz(res, curr, curr.head, xshift+dx, yshift-curr.shift/factor)
3408 dx = dx + (r2l and 0 or curr.width/factor)
3409 end
3410 curr = node.getnext(curr)
3411 end
3412 return res
3413 end
3414 function luamplib.outlinetext (text)
3415 local fmt = process_tex_text(text)
3416 local id = tonumber(fmt:match"mplibtexboxid=(%d+):")
3417 local box = texgetbox(id)
3418 local res = outline_horz({ }, box, box.head, 0, 0)
3419 if #res == 0 then res = { "mpliboutlinepic[1]:=image();" } end
3420 return tableconcat(res) .. format("mpliboutlinenum:=%i;", #res)
3421 end
3422 end
3423
3424 % \end{macrocode}
3425 %
3426 % lua functions for |mplib(uc)substring ... of ...|
3427 % \begin{macrocode}
3428 function luamplib.getunicodegraphemes (s)
3429 local t = { }
3430 local graphemes = require'lua-uni-graphemes'
3431 for _, _, c in graphemes.graphemes(s) do
3432 table.insert(t, c)
3433 end
3434 return t
3435 end
3436 function luamplib.unicodesubstring (s,b,e,grph)
3437 local tt, t, step = { }
3438 if grph then
3439 t = luamplib.getunicodegraphemes(s)
3440 else
3441 t = { }
3442 for _, c in utf8.codes(s) do
3443 table.insert(t, utf8.char(c))
3444 end
3445 end
3446 if b <= e then
3447 b, step = b+1, 1
3448 else
3449 e, step = e+1, -1
3450 end
3451 for i = b, e, step do
3452 table.insert(tt, t[i])
3453 end
3454 s = table.concat(tt):gsub('"','"&ditto&"')
3455 return string.format('"%s"', s)
3456 end
3457
3458 % \end{macrocode}
3459 %
3460 % \metapost preambles
3461 % \begin{macrocode}
3462 luamplib.preambles = {
3463 preamble = [[
3464 boolean mplib ; mplib := true ;
3465 let dump = endinput ;
3466 let normalfontsize = fontsize;
3467 input %s ;
3468 ]],
3469 mplibcode = [[
3470 texscriptmode := 2;
3471 def rawtextext primary t = runscript("luamplibtext{"&t&"}") enddef;
3472 def mplibcolor primary t = runscript("luamplibcolor{"&t&"}") enddef;
3473 def mplibdimen primary t = runscript("luamplibdimen{"&t&"}") enddef;
3474 def VerbatimTeX primary t = runscript("luamplibverbtex{"&t&"}") enddef;
3475 if known context_mlib:
3476 defaultfont := "cmtt10";
3477 let infont = normalinfont;
3478 let fontsize = normalfontsize;
3479 vardef thelabel@#(expr p,z) =
3480 if string p :
3481 thelabel@#(p infont defaultfont scaled defaultscale,z)
3482 else :
3483 p shifted (z + labeloffset*mfun_laboff@# -
3484 (mfun_labxf@#*lrcorner p + mfun_labyf@#*ulcorner p +
3485 (1-mfun_labxf@#-mfun_labyf@#)*llcorner p))
3486 fi
3487 enddef;
3488 else:
3489 vardef textext@# primary t = rawtextext (t) enddef;
3490 def message expr t =
3491 if string t: runscript("mp.report[=["&t&"]=]") else: errmessage "Not a string" fi
3492 enddef;
3493 def withtransparency (expr a, t) =
3494 withprescript "tr_alternative=" & if numeric a: decimal fi a
3495 withprescript "tr_transparency=" & decimal t
3496 enddef;
3497 vardef ddecimal primary p =
3498 decimal xpart p & " " & decimal ypart p
3499 enddef;
3500 vardef boundingbox primary p =
3501 if (path p) or (picture p) :
3502 llcorner p -- lrcorner p -- urcorner p -- ulcorner p
3503 else :
3504 origin
3505 fi -- cycle
3506 enddef;
3507 fi
3508 def resolvedcolor(expr s) =
3509 runscript("return luamplib.shadecolor('"& s &"')")
3510 enddef;
3511 def colordecimals primary c =
3512 if cmykcolor c:
3513 decimal cyanpart c & ":" & decimal magentapart c & ":" &
3514 decimal yellowpart c & ":" & decimal blackpart c
3515 elseif rgbcolor c:
3516 decimal redpart c & ":" & decimal greenpart c & ":" & decimal bluepart c
3517 elseif string c:
3518 if known graphictextpic: c else: colordecimals resolvedcolor(c) fi
3519 else:
3520 decimal c
3521 fi
3522 enddef;
3523 def externalfigure primary filename =
3524 draw rawtextext("\includegraphics{"& filename &"}")
3525 enddef;
3526 def TEX = textext enddef;
3527 def mplibtexcolor primary c =
3528 runscript("return luamplib.gettexcolor('"& c &"')")
3529 enddef;
3530 def mplibrgbtexcolor primary c =
3531 runscript("return luamplib.gettexcolor('"& c &"','rgb')")
3532 enddef;
3533 def mplibgraphictext primary t =
3534 begingroup;
3535 mplibgraphictext_ (t)
3536 enddef;
3537 def mplibgraphictext_ (expr t) text rest =
3538 save fakebold, scale, fillcolor, drawcolor, withfillcolor, withdrawcolor, strokecolor,
3539 fb, fc, dc, graphictextpic, alsoordoublepath;
3540 picture graphictextpic; graphictextpic := nullpicture;
3541 numeric fb; string fc, dc; fb:=2; fc:="white"; dc:="black";
3542 let scale = scaled;
3543 def fakebold primary c = hide(fb:=c;) enddef;
3544 def fillcolor primary c = hide(fc:=colordecimals c;) enddef;
3545 def drawcolor primary c = hide(dc:=colordecimals c;) enddef;
3546 let withfillcolor = fillcolor; let withdrawcolor = drawcolor; let strokecolor = drawcolor;
3547 def alsoordoublepath expr p = if picture p: also else: doublepath fi p enddef;
3548 addto graphictextpic alsoordoublepath (origin--cycle) rest; graphictextpic:=nullpicture;
3549 def fakebold primary c = enddef;
3550 let fillcolor = fakebold; let drawcolor = fakebold;
3551 let withfillcolor = fillcolor; let withdrawcolor = drawcolor; let strokecolor = drawcolor;
3552 image(draw runscript("return luamplib.graphictext([===["&t&"]===],"
3553 & decimal fb &",'"& fc &"','"& dc &"')") rest;)
3554 endgroup;
3555 enddef;
3556 def mplibglyph expr c of f =
3557 runscript (
3558 "return luamplib.glyph('"
3559 & if numeric f: decimal fi f
3560 & "','"
3561 & if numeric c: decimal fi c
3562 & "')"
3563 )
3564 enddef;
3565 numeric luamplib_tmp_num_; luamplib_tmp_num_ = 0;
3566 def mplibdrawglyph expr g =
3567 luamplib_tmp_num_ := 0;
3568 for item within g:
3569 fill pathpart item
3570 if incr luamplib_tmp_num_ < length g: withpostscript "collect"; fi
3571 endfor
3572 enddef;
3573 let mplibfillglyph = mplibdrawglyph;
3574 def mplibstrokeglyph expr g =
3575 luamplib_tmp_num_ := 0;
3576 for item within g:
3577 draw pathpart item
3578 if incr luamplib_tmp_num_ < length g: withpostscript "collect"; fi
3579 endfor
3580 enddef;
3581 def mplibfillandstrokeglyph expr g =
3582 luamplib_tmp_num_ := 0;
3583 for item within g:
3584 draw pathpart item withpostscript
3585 if incr luamplib_tmp_num_ < length g: "collect"; else: "both" fi
3586 endfor
3587 enddef;
3588 def withmplibcolors (expr f, s) =
3589 runscript("return luamplib.fillandstrokecolor('" &
3590 if not string f: colordecimals fi f & "','" &
3591 if not string s: colordecimals fi s & "')")
3592 enddef;
3593 def withmplibopacities (expr a, f, s) =
3594 withprescript "tr_alternative=" & if numeric a: decimal fi a
3595 withprescript "tr_transparency=" & decimal f & ":" & decimal s
3596 enddef;
3597 def mplib_do_outline_text_set_b (text f) (text d) text r =
3598 def mplib_do_outline_options_f = f enddef;
3599 def mplib_do_outline_options_d = d enddef;
3600 def mplib_do_outline_options_r = r enddef;
3601 enddef;
3602 def mplib_do_outline_text_set_f (text f) text r =
3603 def mplib_do_outline_options_f = f enddef;
3604 def mplib_do_outline_options_r = r enddef;
3605 enddef;
3606 def mplib_do_outline_text_set_u (text f) text r =
3607 def mplib_do_outline_options_f = f enddef;
3608 enddef;
3609 def mplib_do_outline_text_set_d (text d) text r =
3610 def mplib_do_outline_options_d = d enddef;
3611 def mplib_do_outline_options_r = r enddef;
3612 enddef;
3613 def mplib_do_outline_text_set_r (text d) (text f) text r =
3614 def mplib_do_outline_options_d = d enddef;
3615 def mplib_do_outline_options_f = f enddef;
3616 def mplib_do_outline_options_r = r enddef;
3617 enddef;
3618 def mplib_do_outline_text_set_n text r =
3619 def mplib_do_outline_options_r = r enddef;
3620 enddef;
3621 def mplib_do_outline_text_set_p = enddef;
3622 def mplib_fill_outline_text =
3623 for n=1 upto mpliboutlinenum:
3624 i:=0;
3625 for item within mpliboutlinepic[n]:
3626 i:=i+1;
3627 fill pathpart item mplib_do_outline_options_f withpen pencircle scaled 0
3628 if (n<mpliboutlinenum) or (i<length mpliboutlinepic[n]): withpostscript "collect"; fi
3629 endfor
3630 endfor
3631 enddef;
3632 def mplib_draw_outline_text =
3633 for n=1 upto mpliboutlinenum:
3634 for item within mpliboutlinepic[n]:
3635 draw pathpart item mplib_do_outline_options_d;
3636 endfor
3637 endfor
3638 enddef;
3639 def mplib_filldraw_outline_text =
3640 for n=1 upto mpliboutlinenum:
3641 i:=0;
3642 for item within mpliboutlinepic[n]:
3643 i:=i+1;
3644 if (n<mpliboutlinenum) or (i<length mpliboutlinepic[n]):
3645 fill pathpart item mplib_do_outline_options_f withpostscript "collect";
3646 else:
3647 draw pathpart item mplib_do_outline_options_f withpostscript "both";
3648 fi
3649 endfor
3650 endfor
3651 enddef;
3652 vardef mpliboutlinetext@# (expr t) text rest =
3653 save kind; string kind; kind := str @#;
3654 save i; numeric i;
3655 picture mpliboutlinepic[]; numeric mpliboutlinenum;
3656 def mplib_do_outline_options_d = enddef;
3657 def mplib_do_outline_options_f = enddef;
3658 def mplib_do_outline_options_r = enddef;
3659 runscript("return luamplib.outlinetext[===["&t&"]===]");
3660 image ( addto currentpicture also image (
3661 if kind = "f":
3662 mplib_do_outline_text_set_f rest;
3663 mplib_fill_outline_text;
3664 elseif kind = "d":
3665 mplib_do_outline_text_set_d rest;
3666 mplib_draw_outline_text;
3667 elseif kind = "b":
3668 mplib_do_outline_text_set_b rest;
3669 mplib_fill_outline_text;
3670 mplib_draw_outline_text;
3671 elseif kind = "u":
3672 mplib_do_outline_text_set_u rest;
3673 mplib_filldraw_outline_text;
3674 elseif kind = "r":
3675 mplib_do_outline_text_set_r rest;
3676 mplib_draw_outline_text;
3677 mplib_fill_outline_text;
3678 elseif kind = "p":
3679 mplib_do_outline_text_set_p;
3680 mplib_draw_outline_text;
3681 else:
3682 mplib_do_outline_text_set_n rest;
3683 mplib_fill_outline_text;
3684 fi;
3685 ) mplib_do_outline_options_r; )
3686 enddef ;
3687 def withmppattern primary p =
3688 withprescript "mplibpattern=" & if numeric p: decimal fi p
3689 enddef;
3690 primarydef t withpattern p =
3691 image(
3692 if cycle t:
3693 fill
3694 else:
3695 draw
3696 fi
3697 t withprescript "mplibpattern=" & if numeric p: decimal fi p; )
3698 enddef;
3699 vardef mplibtransformmatrix (text e) =
3700 save t; transform t;
3701 t = identity e;
3702 runscript("luamplib.transformmatrix = {"
3703 & decimal xxpart t & ","
3704 & decimal yxpart t & ","
3705 & decimal xypart t & ","
3706 & decimal yypart t & ","
3707 & decimal xpart t & ","
3708 & decimal ypart t & ","
3709 & "}");
3710 enddef;
3711 primarydef p withmaskinggroup s =
3712 if picture p:
3713 image(
3714 draw p;
3715 draw center p withprescript "mplibfadestate=stop";
3716 )
3717 else:
3718 p withprescript "mplibfadestate=stop"
3719 fi
3720 withprescript "mplibfadetype=masking"
3721 withprescript "mplibmaskname=" & s
3722 enddef;
3723 def withmaskingbgcolor expr c =
3724 withprescript "mplibmaskingbgcolor=" & colordecimals c
3725 enddef;
3726 primarydef p withfademethod s =
3727 if picture p:
3728 image(
3729 draw p;
3730 draw center p withprescript "mplibfadestate=stop";
3731 )
3732 else:
3733 p withprescript "mplibfadestate=stop"
3734 fi
3735 withprescript "mplibfadetype=" & s
3736 hide(mplib_shade_step := 1;)
3737 withprescript "sh_color_a=1"
3738 withprescript "sh_color_b=0"
3739 withprescript "mplibfadebbox=" &
3740 decimal (xpart llcorner p -1/4) & ":" &
3741 decimal (ypart llcorner p -1/4) & ":" &
3742 decimal (xpart urcorner p +1/4) & ":" &
3743 decimal (ypart urcorner p +1/4)
3744 enddef;
3745 def withfadevector (expr a,b) =
3746 withprescript "mplibfadevector=" &
3747 decimal xpart a & ":" &
3748 decimal ypart a & ":" &
3749 decimal xpart b & ":" &
3750 decimal ypart b
3751 enddef;
3752 let withfadecenter = withfadevector;
3753 def withfaderadius (expr a,b) =
3754 withprescript "mplibfaderadius=" &
3755 decimal a & ":" &
3756 decimal b
3757 enddef;
3758 def withfadebbox (expr a,b) =
3759 withprescript "mplibfadebbox=" &
3760 decimal xpart a & ":" &
3761 decimal ypart a & ":" &
3762 decimal xpart b & ":" &
3763 decimal ypart b
3764 enddef;
3765 primarydef p asgroup s =
3766 image(
3767 draw center p
3768 withprescript "mplibgroupbbox=" &
3769 decimal (xpart llcorner p -1/4) & ":" &
3770 decimal (ypart llcorner p -1/4) & ":" &
3771 decimal (xpart urcorner p +1/4) & ":" &
3772 decimal (ypart urcorner p +1/4)
3773 withprescript "gr_state=start"
3774 withprescript "gr_type=" & s;
3775 draw p withprescript "sh_in_xobj=yes";
3776 draw center p withprescript "gr_state=stop";
3777 )
3778 enddef;
3779 def withgroupbbox (expr a,b) =
3780 withprescript "mplibgroupbbox=" &
3781 decimal xpart a & ":" &
3782 decimal ypart a & ":" &
3783 decimal xpart b & ":" &
3784 decimal ypart b
3785 enddef;
3786 def withgroupname expr s =
3787 withprescript "mplibgroupname=" & s
3788 enddef;
3789 def usemplibgroup primary s =
3790 draw maketext("\luamplibtagasgroupput{"& s &"}{\csname luamplib.group."& s &"\endcsname}")
3791 shifted runscript("return luamplib.trgroupshifts['" & s & "']")
3792 enddef;
3793 path mplib_shade_path ;
3794 numeric mplib_shade_step ; mplib_shade_step := 0 ;
3795 numeric mplib_shade_fx, mplib_shade_fy ;
3796 numeric mplib_shade_lx, mplib_shade_ly ;
3797 numeric mplib_shade_nx, mplib_shade_ny ;
3798 numeric mplib_shade_dx, mplib_shade_dy ;
3799 numeric mplib_shade_tx, mplib_shade_ty ;
3800 primarydef p withshadingmethod m =
3801 p
3802 if picture p :
3803 withprescript "sh_operand_type=picture"
3804 if textual p or (length p > 1):
3805 withprescript "sh_transform=no"
3806 mplib_with_shade_method (boundingbox p, m)
3807 else:
3808 withprescript "sh_transform=yes"
3809 mplib_with_shade_method (pathpart p, m)
3810 fi
3811 else :
3812 withprescript "sh_transform=yes"
3813 mplib_with_shade_method (p, m)
3814 fi
3815 enddef;
3816 def mplib_with_shade_method (expr p, m) =
3817 hide(mplib_with_shade_method_analyze(p))
3818 withprescript "sh_domain=0 1"
3819 withprescript "sh_color=into"
3820 withprescript "sh_color_a=" & colordecimals white
3821 withprescript "sh_color_b=" & colordecimals black
3822 withprescript "sh_first=" & ddecimal point 0 of p
3823 withprescript "sh_set_x=" & ddecimal (mplib_shade_nx,mplib_shade_lx)
3824 withprescript "sh_set_y=" & ddecimal (mplib_shade_ny,mplib_shade_ly)
3825 if m = "linear" :
3826 withprescript "sh_type=linear"
3827 withprescript "sh_factor=1"
3828 withprescript "sh_center_a=" & ddecimal llcorner p
3829 withprescript "sh_center_b=" & ddecimal urcorner p
3830 else :
3831 withprescript "sh_type=circular"
3832 withprescript "sh_factor=1.2"
3833 withprescript "sh_center_a=" & ddecimal center p
3834 withprescript "sh_center_b=" & ddecimal center p
3835 withprescript "sh_radius_a=" & decimal 0
3836 withprescript "sh_radius_b=" & decimal mplib_max_radius(p)
3837 fi
3838 enddef;
3839 def mplib_with_shade_method_analyze(expr p) =
3840 mplib_shade_path := p ;
3841 mplib_shade_step := 1 ;
3842 mplib_shade_fx := xpart point 0 of p ;
3843 mplib_shade_fy := ypart point 0 of p ;
3844 mplib_shade_lx := mplib_shade_fx ;
3845 mplib_shade_ly := mplib_shade_fy ;
3846 mplib_shade_nx := 0 ;
3847 mplib_shade_ny := 0 ;
3848 mplib_shade_dx := abs(mplib_shade_fx - mplib_shade_lx) ;
3849 mplib_shade_dy := abs(mplib_shade_fy - mplib_shade_ly) ;
3850 for i=1 upto length(p) :
3851 mplib_shade_tx := abs(mplib_shade_fx - xpart point i of p) ;
3852 mplib_shade_ty := abs(mplib_shade_fy - ypart point i of p) ;
3853 if mplib_shade_tx > mplib_shade_dx :
3854 mplib_shade_nx := i + 1 ;
3855 mplib_shade_lx := xpart point i of p ;
3856 mplib_shade_dx := mplib_shade_tx ;
3857 fi ;
3858 if mplib_shade_ty > mplib_shade_dy :
3859 mplib_shade_ny := i + 1 ;
3860 mplib_shade_ly := ypart point i of p ;
3861 mplib_shade_dy := mplib_shade_ty ;
3862 fi ;
3863 endfor ;
3864 enddef;
3865 vardef mplib_max_radius(expr p) =
3866 max (
3867 (xpart center p - xpart llcorner p) ++ (ypart center p - ypart llcorner p),
3868 (xpart center p - xpart ulcorner p) ++ (ypart ulcorner p - ypart center p),
3869 (xpart lrcorner p - xpart center p) ++ (ypart center p - ypart lrcorner p),
3870 (xpart urcorner p - xpart center p) ++ (ypart urcorner p - ypart center p)
3871 )
3872 enddef;
3873 def withshadingstep (text t) =
3874 hide(mplib_shade_step := mplib_shade_step + 1 ;)
3875 withprescript "sh_step=" & decimal mplib_shade_step
3876 t
3877 enddef;
3878 let withfadestep = withshadingstep;
3879 def withshadingradius expr a =
3880 withprescript "sh_radius_a=" & decimal (xpart a)
3881 withprescript "sh_radius_b=" & decimal (ypart a)
3882 enddef;
3883 def withshadingorigin expr a =
3884 withprescript "sh_center_a=" & ddecimal a
3885 withprescript "sh_center_b=" & ddecimal a
3886 enddef;
3887 def withshadingvector expr a =
3888 withprescript "sh_center_a=" & ddecimal (point xpart a of mplib_shade_path)
3889 withprescript "sh_center_b=" & ddecimal (point ypart a of mplib_shade_path)
3890 enddef;
3891 def withshadingdirection expr a =
3892 withprescript "sh_center_a=" & ddecimal (point xpart a of boundingbox(mplib_shade_path))
3893 withprescript "sh_center_b=" & ddecimal (point ypart a of boundingbox(mplib_shade_path))
3894 enddef;
3895 def withshadingtransform expr a =
3896 withprescript "sh_transform=" & a
3897 enddef;
3898 def withshadingcenter expr a =
3899 withprescript "sh_center_a=" & ddecimal (
3900 center mplib_shade_path shifted (
3901 xpart a * xpart (lrcorner mplib_shade_path - llcorner mplib_shade_path)/2,
3902 ypart a * ypart (urcorner mplib_shade_path - lrcorner mplib_shade_path)/2
3903 )
3904 )
3905 enddef;
3906 def withshadingcenters (expr a, b) =
3907 withprescript "sh_center_a=" & ddecimal a
3908 withprescript "sh_center_b=" & ddecimal b
3909 withshadingtransform "no"
3910 withshadingfactor 1
3911 enddef;
3912 let withshadingpoints = withshadingcenters;
3913 def withshadingextend (expr a, b) =
3914 withprescript "sh_extend=" &
3915 if a: "true" else: "false" fi & " " &
3916 if b: "true" else: "false" fi
3917 enddef;
3918 let withfadeextend = withshadingextend;
3919 def withshadingdomain expr d =
3920 withprescript "sh_domain=" & ddecimal d
3921 enddef;
3922 def withshadingfactor expr f =
3923 withprescript "sh_factor=" & decimal f
3924 enddef;
3925 def withshadingfraction expr a =
3926 if mplib_shade_step > 0 :
3927 withprescript "sh_fraction_" & decimal mplib_shade_step & "=" & decimal a
3928 fi
3929 enddef;
3930 let withfadefraction = withshadingfraction;
3931 def withshadingcolors (expr a, b) =
3932 if mplib_shade_step > 0 :
3933 withprescript "sh_color=into"
3934 withprescript "sh_color_a_" & decimal mplib_shade_step & "=" & colordecimals a
3935 withprescript "sh_color_b_" & decimal mplib_shade_step & "=" & colordecimals b
3936 else :
3937 withprescript "sh_color=into"
3938 withprescript "sh_color_a=" & colordecimals a
3939 withprescript "sh_color_b=" & colordecimals b
3940 fi
3941 enddef;
3942 let withfadeopacity = withshadingcolors;
3943 def withshadingstroke expr a =
3944 withprescript "sh_stroking=" & a
3945 enddef;
3946 def withshadingmatrix expr s =
3947 withprescript "sh_matrix=" & s
3948 enddef;
3949 let withfadematrix = withshadingmatrix;
3950 def mpliblength primary t =
3951 runscript("return utf8.len[===[" & t & "]===]")
3952 enddef;
3953 def mplibsubstring expr p of t =
3954 runscript("return luamplib.unicodesubstring([===[" & t & "]===],"
3955 & decimal xpart p & ","
3956 & decimal ypart p & ")")
3957 enddef;
3958 def mplibuclength primary t =
3959 runscript("return #luamplib.getunicodegraphemes[===[" & t & "]===]")
3960 enddef;
3961 def mplibucsubstring expr p of t =
3962 runscript("return luamplib.unicodesubstring([===[" & t & "]===],"
3963 & decimal xpart p & ","
3964 & decimal ypart p & ",true)")
3965 enddef;
3966 ]],
3967 legacyverbatimtex = [[
3968 def specialVerbatimTeX (text t) = runscript("luamplibprefig{"&t&"}") enddef;
3969 def normalVerbatimTeX (text t) = runscript("luamplibinfig{"&t&"}") enddef;
3970 let VerbatimTeX = specialVerbatimTeX;
3971 extra_beginfig := extra_beginfig & " let VerbatimTeX = normalVerbatimTeX;"&
3972 "runscript(" &ditto& "luamplib.in_the_fig=true" &ditto& ");";
3973 extra_endfig := extra_endfig & " let VerbatimTeX = specialVerbatimTeX;"&
3974 "runscript(" &ditto&
3975 "if luamplib.in_the_fig then luamplib.figid=luamplib.figid+1 end "&
3976 "luamplib.in_the_fig=false" &ditto& ");";
3977 ]],
3978 textextlabel = [[
3979 let luampliboriginalinfont = infont;
3980 primarydef s infont f =
3981 if (s < char 32)
3982 or (s = char 35) % #
3983 or (s = char 36) % $
3984 or (s = char 37) % %
3985 or (s = char 38) % &
3986 or (s = char 92) % \
3987 or (s = char 94) % ^
3988 or (s = char 95) % _
3989 or (s = char 123) % {
3990 or (s = char 125) % }
3991 or (s = char 126) % ~
3992 or (s = char 127) :
3993 s luampliboriginalinfont f
3994 else :
3995 rawtextext(s)
3996 fi
3997 enddef;
3998 def fontsize expr f =
3999 begingroup
4000 save size; numeric size;
4001 size := mplibdimen("1em");
4002 if size = 0: 10pt else: size fi
4003 endgroup
4004 enddef;
4005 ]],
4006 }
4007
4008 % \end{macrocode}
4009 %
4010 % |process_mplibcode|
4011 %
4012 % When \cs{mplibverbatim} is enabled, do not expand |mplibcode| data.
4013 % \begin{macrocode}
4014 luamplib.verbatiminput = false
4015 luamplib.everymplib = setmetatable({ [""] = "" },{ __index = function(t) return t[""] end })
4016 luamplib.everyendmplib = setmetatable({ [""] = "" },{ __index = function(t) return t[""] end })
4017 function luamplib.process_mplibcode (data, instancename)
4018 texboxes.localid = 4096
4019 % \end{macrocode}
4020 % This is needed for legacy behavior
4021 % \begin{macrocode}
4022 if luamplib.legacyverbatimtex then
4023 luamplib.figid, tex_code_pre_mplib = 1, {}
4024 end
4025 local everymplib = luamplib.everymplib[instancename]
4026 local everyendmplib = luamplib.everyendmplib[instancename]
4027 data = format("\n%s\n%s\n%s\n",everymplib, data, everyendmplib)
4028 :gsub("\r","\n")
4029 % \end{macrocode}
4030 % These five lines are needed for |mplibverbatim| mode.
4031 % \begin{macrocode}
4032 if luamplib.verbatiminput then
4033 data = data:gsub("\\mpcolor%s+(.-%b{})","mplibcolor(\"%1\")")
4034 :gsub("\\mpdim%s+(%b{})", "mplibdimen(\"%1\")")
4035 :gsub("\\mpdim%s+(\\%a+)","mplibdimen(\"%1\")")
4036 :gsub(btex_etex, "btex %1 etex ")
4037 :gsub(verbatimtex_etex, "verbatimtex %1 etex;")
4038 else
4039 % \end{macrocode}
4040 % If not |mplibverbatim|, expand |mplibcode| data,
4041 % so that users can use \TeX\ codes in it.
4042 % It has turned out that no comment sign is allowed.
4043 % However, we do not expand |btex| |...| |etex|, |verbatimtex| |...| |etex|, and
4044 % string expressions.
4045 % \begin{macrocode}
4046 local t = { } -- to store btex, verbatimtex, string
4047 data = data:gsub(btex_etex, function(str)
4048 t[#t+1] = str
4049 return format("btex \\unexpanded{!l!u!a!%s!m!p!l!} etex ", #t) -- space
4050 end)
4051 :gsub(verbatimtex_etex, function(str)
4052 t[#t+1] = str
4053 return format("verbatimtex \\unexpanded{!l!u!a!%s!m!p!l!} etex;", #t) -- semicolon
4054 end)
4055 :gsub('"(.-)"', function(str)
4056 t[#t+1] = str
4057 return format('"\\unexpanded{!l!u!a!%s!m!p!l!}"', #t)
4058 end)
4059 :gsub("\\%%", "\0PerCent\0")
4060 :gsub("%%.-\n","\n")
4061 :gsub("%zPerCent%z", "\\%%")
4062 run_tex_code(format("\\mplibtmptoks\\expandafter{\\expanded{%s}}",data))
4063 data = texgettoks"mplibtmptoks"
4064 % \end{macrocode}
4065 % Next line to address issue \#55
4066 % \begin{macrocode}
4067 :gsub("##", "#")
4068 :gsub("!l!u!a!(%d+)!m!p!l!", function(str) return t[tonumber(str)] or str end)
4069 end
4070 process(data, instancename)
4071 end
4072
4073 % \end{macrocode}
4074 %
4075 % pdfliterals will be stored in |figcontents| table, and written to pdf in one go
4076 % at the end of the flushing figure.
4077 % Subtable |post| is for the legacy behavior.
4078 % \begin{macrocode}
4079 local figcontents = { post = { } }
4080 local function put2output(a,...)
4081 figcontents[#figcontents+1] = type(a) == "string" and format(a,...) or a
4082 end
4083 local function pdf_startfigure(n,llx,lly,urx,ury)
4084 put2output("\\mplibstarttoPDF{%f}{%f}{%f}{%f}",llx,lly,urx,ury)
4085 end
4086 local function pdf_stopfigure()
4087 put2output("\\mplibstoptoPDF")
4088 end
4089 % \end{macrocode}
4090 % |tex.sprint| with catcode regime -2, as sometimes |#| gets doubled
4091 % in the argument of pdfliteral.
4092 % \begin{macrocode}
4093 local function pdf_literalcode (...)
4094 put2output{ -2, (format(...) :gsub(decimals,rmzeros)) }
4095 end
4096 local start_pdf_code = pdfmode
4097 and function() pdf_literalcode"q" end
4098 or function() put2output"\\special{pdf:bcontent}" end
4099 local stop_pdf_code = pdfmode
4100 and function() pdf_literalcode"Q" end
4101 or function() put2output"\\special{pdf:econtent}" end
4102
4103 % \end{macrocode}
4104 %
4105 % Now we process hboxes created from |btex| |...| |etex| or
4106 % |textext(...)| or |TEX(...)| etc.
4107 % \begin{macrocode}
4108 local function put_tex_boxes (object,prescript)
4109 local box = prescript.mplibtexboxid:explode":"
4110 local n,tw,th = box[1],tonumber(box[2]),tonumber(box[3])
4111 if n and tw and th then
4112 local op = object.path
4113 local first, second, fourth = op[1], op[2], op[4]
4114 local tx, ty = first.x_coord, first.y_coord
4115 local sx, rx, ry, sy = 1, 0, 0, 1
4116 if tw ~= 0 then
4117 sx = (second.x_coord - tx)/tw
4118 rx = (second.y_coord - ty)/tw
4119 if sx == 0 then sx = 0.00001 end
4120 end
4121 if th ~= 0 then
4122 sy = (fourth.y_coord - ty)/th
4123 ry = (fourth.x_coord - tx)/th
4124 if sy == 0 then sy = 0.00001 end
4125 end
4126
4127 % \end{macrocode}
4128 % Attempt to address \#189, the displacement issue of pdf link boxes.
4129 % \begin{macrocode}
4130 local matrix = format("%f %f %f %f", sx, rx, ry, sy) :gsub(decimals,rmzeros)
4131 put2output("\\mplibputtextbox{%i}{%f}{%f}{%s}", n, tx, ty, matrix)
4132 end
4133 end
4134
4135 % \end{macrocode}
4136 %
4137 % Colors
4138 % \begin{macrocode}
4139 local do_preobj_CR
4140 do
4141 local prev_override_color
4142 function do_preobj_CR(object,prescript)
4143 if object.postscript == "collect" then return end
4144 local override = prescript and prescript.mpliboverridecolor
4145 if override then
4146 if pdfmode then
4147 pdf_literalcode(override)
4148 override = nil
4149 else
4150 put2output("\\special{%s}",override)
4151 prev_override_color = override
4152 end
4153 else
4154 local cs = object.color
4155 if cs and #cs > 0 then
4156 pdf_literalcode(luamplib.colorconverter(cs))
4157 prev_override_color = nil
4158 elseif not pdfmode then
4159 override = prev_override_color
4160 if override then
4161 put2output("\\special{%s}",override)
4162 end
4163 end
4164 end
4165 return override
4166 end
4167 end
4168
4169 % \end{macrocode}
4170 %
4171 % For transparency, shading, fading, and pattern
4172 % \begin{macrocode}
4173 local pdfmanagement = is_defined'pdfmanagement_add:nnn'
4174 local pdfobjs, pdfetcs = {}, {}
4175 pdfetcs.pgfextgs = "pgf@sys@addpdfresource@extgs@plain"
4176 pdfetcs.pgfpattern = "pgf@sys@addpdfresource@patterns@plain"
4177 pdfetcs.pgfcolorspace = "pgf@sys@addpdfresource@colorspaces@plain"
4178 local function update_pdfobjs (os, stream)
4179 local key = os
4180 if stream then key = key..stream end
4181 local on = key and pdfobjs[key]
4182 if on then
4183 return on,false
4184 end
4185 if pdfmode then
4186 if stream then
4187 on = pdf.immediateobj("stream",stream,os)
4188 elseif os then
4189 on = pdf.immediateobj(os)
4190 else
4191 on = pdf.reserveobj()
4192 end
4193 else
4194 on = pdfetcs.cnt or 1
4195 if stream then
4196 texsprint(format("\\special{pdf:stream @mplibpdfobj%s (%s) <<%s>>}",on,stream,os))
4197 elseif os then
4198 texsprint(format("\\special{pdf:obj @mplibpdfobj%s %s}",on,os))
4199 else
4200 texsprint(format("\\special{pdf:obj @mplibpdfobj%s <<>>}",on))
4201 end
4202 pdfetcs.cnt = on + 1
4203 end
4204 if key then
4205 pdfobjs[key] = on
4206 end
4207 return on,true
4208 end
4209 pdfetcs.resfmt = pdfmode and "%s 0 R" or "@mplibpdfobj%s"
4210 if pdfmode then
4211 pdfetcs.getpageres = pdf.getpageresources or function() return pdf.pageresources end
4212 local getpageres = pdfetcs.getpageres
4213 local setpageres = pdf.setpageresources or function(s) pdf.pageresources = s end
4214 local initialize_resources = function (name)
4215 local tabname = format("%s_res",name)
4216 pdfetcs[tabname] = { }
4217 if luatexbase.callbacktypes.finish_pdffile then -- ltluatex
4218 local obj = pdf.reserveobj()
4219 setpageres(format("%s/%s %i 0 R", getpageres() or "", name, obj))
4220 luatexbase.add_to_callback("finish_pdffile", function()
4221 pdf.immediateobj(obj, format("<<%s>>", tableconcat(pdfetcs[tabname])))
4222 end,
4223 format("luamplib.%s.finish_pdffile",name))
4224 end
4225 end
4226 pdfetcs.fallback_update_resources = function (name, res)
4227 local tabname = format("%s_res",name)
4228 if not pdfetcs[tabname] then
4229 initialize_resources(name)
4230 end
4231 if luatexbase.callbacktypes.finish_pdffile then
4232 local t = pdfetcs[tabname]
4233 t[#t+1] = res
4234 else
4235 local tpr, n = getpageres() or "", 0
4236 tpr, n = tpr:gsub(format("/%s<<",name), "%1"..res)
4237 if n == 0 then
4238 tpr = format("%s/%s<<%s>>", tpr, name, res)
4239 end
4240 setpageres(tpr)
4241 end
4242 end
4243 else
4244 texsprint {
4245 "\\luamplibatfirstshipout{",
4246 "\\special{pdf:obj @MPlibTr<<>>}",
4247 "\\special{pdf:obj @MPlibSh<<>>}",
4248 "\\special{pdf:obj @MPlibCS<<>>}",
4249 "\\special{pdf:obj @MPlibPt<<>>}}",
4250 }
4251 pdfetcs.fallback_update_resources = function (name,res,obj)
4252 texsprint{"\\special{pdf:put ", obj, " <<", res, ">>}"}
4253 local tabname = format("%s_res",name)
4254 if not pdfetcs[tabname] then
4255 texsprint{"\\luamplibateveryshipout{\\special{pdf:put @resources <</", name, " ", obj, ">>}}"}
4256 pdfetcs[tabname] = { }
4257 end
4258 tableinsert(pdfetcs[tabname], res)
4259 end
4260 end
4261
4262 % \end{macrocode}
4263 %
4264 % Transparency
4265 % \begin{macrocode}
4266 local function add_extgs_resources (on, new)
4267 local key = format("MPlibTr%s", on)
4268 if new then
4269 local val = format(pdfetcs.resfmt, on)
4270 if pdfmanagement then
4271 texsprint {
4272 "\\csname pdfmanagement_add:nnn\\endcsname{Page/Resources/ExtGState}{", key, "}{", val, "}"
4273 }
4274 else
4275 local tr = format("/%s %s", key, val)
4276 if is_defined(pdfetcs.pgfextgs) then
4277 texsprint { "\\csname ", pdfetcs.pgfextgs, "\\endcsname{", tr, "}" }
4278 elseif is_defined"TRP@list" then
4279 texsprint(catat11,{
4280 [[\if@filesw\immediate\write\@auxout{]],
4281 [[\string\g@addto@macro\string\TRP@list{]],
4282 tr,
4283 [[}}\fi]],
4284 })
4285 if not get_macro"TRP@list":find(tr) then
4286 texsprint(catat11,[[\global\TRP@reruntrue]])
4287 end
4288 else
4289 pdfetcs.fallback_update_resources("ExtGState",tr,"@MPlibTr")
4290 end
4291 end
4292 end
4293 return key
4294 end
4295
4296 local do_preobj_TR
4297 do
4298 local transparancy_modes = {
4299 [0] = "Normal",
4300 "Normal", "Multiply", "Screen", "Overlay",
4301 "SoftLight", "HardLight", "ColorDodge", "ColorBurn",
4302 "Darken", "Lighten", "Difference", "Exclusion",
4303 "Hue", "Saturation", "Color", "Luminosity",
4304 "Compatible",
4305 normal = "Normal", multiply = "Multiply", screen = "Screen",
4306 overlay = "Overlay", softlight = "SoftLight", hardlight = "HardLight",
4307 colordodge = "ColorDodge", colorburn = "ColorBurn", darken = "Darken",
4308 lighten = "Lighten", difference = "Difference", exclusion = "Exclusion",
4309 hue = "Hue", saturation = "Saturation", color = "Color",
4310 luminosity = "Luminosity", compatible = "Compatible",
4311 }
4312 function do_preobj_TR(object,prescript)
4313 if object.postscript == "collect" then return end
4314 local opaq = prescript and prescript.tr_transparency
4315 if not opaq then return end
4316
4317 local key, on, os, new
4318 local mode = prescript.tr_alternative or 1
4319 mode = transparancy_modes[tonumber(mode) or mode:lower()]
4320 if not mode then
4321 mode = prescript.tr_alternative
4322 warn("unsupported blend mode: '%s'", mode)
4323 end
4324 opaq = opaq:explode":"
4325 for i,v in ipairs(opaq) do
4326 opaq[i] = format("%.3f", v) :gsub(decimals,rmzeros)
4327 end
4328 for i,v in ipairs{ {mode,opaq[1],opaq[2] or opaq[1]},{"Normal",1,1} } do
4329 os = format("<</BM/%s/ca %s/CA %s/AIS false>>",v[1],v[2],v[3])
4330 on, new = update_pdfobjs(os)
4331 key = add_extgs_resources(on,new)
4332 if i == 1 then
4333 pdf_literalcode("/%s gs",key)
4334 else
4335 return format("/%s gs",key)
4336 end
4337 end
4338 end
4339 end
4340
4341 % \end{macrocode}
4342 %
4343 % Shading with \emph{metafun} format.
4344 % \begin{macrocode}
4345 local function sh_pdfpageresources(shtype,domain,colorspace,ca,cb,coordinates,steps,fractions,extend)
4346 for _,v in ipairs{ca,cb} do
4347 for i,vv in ipairs(v) do
4348 for ii,vvv in ipairs(vv) do
4349 v[i][ii] = tonumber(vvv) and format("%.3f",vvv) or vvv
4350 end
4351 end
4352 end
4353 local fun2fmt,os = "<</FunctionType 2/Domain[%s]/C0[%s]/C1[%s]/N 1>>"
4354 if steps > 1 then
4355 local list,bounds,encode = { },{ },{ }
4356 for i=1,steps do
4357 if i < steps then
4358 bounds[i] = format("%.3f", fractions[i] or 1)
4359 end
4360 encode[2*i-1] = 0
4361 encode[2*i] = 1
4362 os = fun2fmt:format(domain,tableconcat(ca[i],' '),tableconcat(cb[i],' '))
4363 :gsub(decimals,rmzeros)
4364 list[i] = format(pdfetcs.resfmt, update_pdfobjs(os))
4365 end
4366 os = tableconcat {
4367 "<</FunctionType 3",
4368 format("/Bounds[%s]", tableconcat(bounds,' ')),
4369 format("/Encode[%s]", tableconcat(encode,' ')),
4370 format("/Functions[%s]", tableconcat(list, ' ')),
4371 format("/Domain[%s]>>", domain),
4372 } :gsub(decimals,rmzeros)
4373 else
4374 os = fun2fmt:format(domain,tableconcat(ca[1],' '),tableconcat(cb[1],' '))
4375 :gsub(decimals,rmzeros)
4376 end
4377 local objref = format(pdfetcs.resfmt, update_pdfobjs(os))
4378 os = tableconcat {
4379 format("<</ShadingType %i", shtype),
4380 format("/ColorSpace %s", colorspace),
4381 format("/Function %s", objref),
4382 format("/Coords[%s]", coordinates),
4383 format("/Extend[%s]/AntiAlias true>>", extend or "true true")
4384 } :gsub(decimals,rmzeros)
4385 local on, new = update_pdfobjs(os)
4386 if new then
4387 local key, val = format("MPlibSh%s", on), format(pdfetcs.resfmt, on)
4388 if pdfmanagement then
4389 texsprint {
4390 "\\csname pdfmanagement_add:nnn\\endcsname{Page/Resources/Shading}{", key, "}{", val, "}"
4391 }
4392 else
4393 local res = format("/%s %s", key, val)
4394 pdfetcs.fallback_update_resources("Shading",res,"@MPlibSh")
4395 end
4396 end
4397 return on
4398 end
4399
4400 local do_preobj_SH
4401 do
4402 pdfetcs.clrspcs = setmetatable({ }, { __index = function(t,names)
4403 run_tex_code({
4404 [[\color_model_new:nnn]],
4405 format("{mplibcolorspace_%s}", names:gsub(",","_")),
4406 format("{DeviceN}{names={%s}}", names),
4407 [[\edef\mplib_@tempa{\pdf_object_ref_last:}]],
4408 }, ccexplat)
4409 local colorspace = get_macro'mplib_@tempa'
4410 t[names] = colorspace
4411 return colorspace
4412 end })
4413 local function color_normalize(ca,cb)
4414 if #cb == 1 then
4415 if #ca == 4 then
4416 cb[1], cb[2], cb[3], cb[4] = 0, 0, 0, 1-cb[1]
4417 else -- #ca = 3
4418 cb[1], cb[2], cb[3] = cb[1], cb[1], cb[1]
4419 end
4420 elseif #cb == 3 then -- #ca == 4
4421 cb[1], cb[2], cb[3], cb[4] = 1-cb[1], 1-cb[2], 1-cb[3], 0
4422 end
4423 end
4424 function do_preobj_SH(object, prescript)
4425 local shade_no
4426 local sh_type = prescript and prescript.sh_type
4427 if not sh_type then return end
4428
4429 local domain = prescript.sh_domain or "0 1"
4430 local centera = (prescript.sh_center_a or "0 0"):explode()
4431 local centerb = (prescript.sh_center_b or "0 0"):explode()
4432 local transform = prescript.sh_transform == "yes"
4433 local sx,sy,sr,dx,dy = 1,1,1,0,0
4434 if transform then
4435 local first = (prescript.sh_first or "0 0"):explode()
4436 local setx = (prescript.sh_set_x or "0 0"):explode()
4437 local sety = (prescript.sh_set_y or "0 0"):explode()
4438 local x,y = tonumber(setx[1]) or 0, tonumber(sety[1]) or 0
4439 if x ~= 0 and y ~= 0 then
4440 local path = object.path
4441 local path1x = path[1].x_coord
4442 local path1y = path[1].y_coord
4443 local path2x = path[x].x_coord
4444 local path2y = path[y].y_coord
4445 local dxa = path2x - path1x
4446 local dya = path2y - path1y
4447 local dxb = setx[2] - first[1]
4448 local dyb = sety[2] - first[2]
4449 if dxa ~= 0 and dya ~= 0 and dxb ~= 0 and dyb ~= 0 then
4450 sx = dxa / dxb ; if sx < 0 then sx = - sx end
4451 sy = dya / dyb ; if sy < 0 then sy = - sy end
4452 sr = math.sqrt(sx^2 + sy^2)
4453 dx = path1x - sx*first[1]
4454 dy = path1y - sy*first[2]
4455 end
4456 end
4457 end
4458 local ca, cb, colorspace, steps, fractions
4459 ca = { (prescript.sh_color_a_1 or prescript.sh_color_a or "0"):explode":" }
4460 cb = { (prescript.sh_color_b_1 or prescript.sh_color_b or "1"):explode":" }
4461 steps = tonumber(prescript.sh_step) or 1
4462 if steps > 1 then
4463 fractions = { prescript.sh_fraction_1 or 0 }
4464 for i=2,steps do
4465 fractions[i] = prescript[format("sh_fraction_%i",i)] or (i/steps)
4466 ca[i] = (prescript[format("sh_color_a_%i",i)] or "0"):explode":"
4467 cb[i] = (prescript[format("sh_color_b_%i",i)] or "1"):explode":"
4468 end
4469 end
4470 if prescript.mplib_spotcolor then
4471 ca, cb = { }, { }
4472 local names, pos, objref = { }, -1, ""
4473 local script = object.prescript:explode"\13+"
4474 for i=#script,1,-1 do
4475 if script[i]:find"mplib_spotcolor" then
4476 local t, name, value = script[i]:explode"="[2]:explode":"
4477 value, objref, name = t[1], t[2], t[3]
4478 if not names[name] then
4479 pos = pos+1
4480 names[name] = pos
4481 names[#names+1] = name
4482 end
4483 t = { }
4484 for j=1,names[name] do t[#t+1] = 0 end
4485 t[#t+1] = value
4486 tableinsert(#ca == #cb and ca or cb, t)
4487 end
4488 end
4489 for _,t in ipairs{ca,cb} do
4490 for _,tt in ipairs(t) do
4491 for i=1,#names-#tt do tt[#tt+1] = 0 end
4492 end
4493 end
4494 if #names == 1 then
4495 colorspace = objref
4496 else
4497 colorspace = pdfetcs.clrspcs[ tableconcat(names,",") ]
4498 end
4499 else
4500 local model = 0
4501 for _,t in ipairs{ca,cb} do
4502 for _,tt in ipairs(t) do
4503 model = model > #tt and model or #tt
4504 end
4505 end
4506 for _,t in ipairs{ca,cb} do
4507 for _,tt in ipairs(t) do
4508 if #tt < model then
4509 color_normalize(model == 4 and {1,1,1,1} or {1,1,1},tt)
4510 end
4511 end
4512 end
4513 colorspace = model == 4 and "/DeviceCMYK"
4514 or model == 3 and "/DeviceRGB"
4515 or model == 1 and "/DeviceGray"
4516 or err"unknown color model"
4517 end
4518 local extend = prescript.sh_extend
4519 if sh_type == "linear" then
4520 local coordinates = format("%f %f %f %f",
4521 dx + sx*centera[1], dy + sy*centera[2],
4522 dx + sx*centerb[1], dy + sy*centerb[2])
4523 shade_no = sh_pdfpageresources(2,domain,colorspace,ca,cb,coordinates,steps,fractions,extend)
4524 elseif sh_type == "circular" then
4525 local factor = prescript.sh_factor or 1
4526 local radiusa = factor * prescript.sh_radius_a
4527 local radiusb = factor * prescript.sh_radius_b
4528 local coordinates = format("%f %f %f %f %f %f",
4529 dx + sx*centera[1], dy + sy*centera[2], sr*radiusa,
4530 dx + sx*centerb[1], dy + sy*centerb[2], sr*radiusb)
4531 shade_no = sh_pdfpageresources(3,domain,colorspace,ca,cb,coordinates,steps,fractions,extend)
4532 else
4533 err"unknown shading type"
4534 end
4535 return shade_no, prescript.sh_stroking == "yes"
4536 end
4537 end
4538
4539 % \end{macrocode}
4540 %
4541 % Shading Patterns:
4542 % we can apply shading to textual pictures as well as paths.
4543 % \begin{macrocode}
4544 local function add_pattern_resources (key, val)
4545 if pdfmanagement then
4546 texsprint {
4547 "\\csname pdfmanagement_add:nnn\\endcsname{Page/Resources/Pattern}{", key, "}{", val, "}"
4548 }
4549 else
4550 local res = format("/%s %s", key, val)
4551 if is_defined(pdfetcs.pgfpattern) then
4552 texsprint { "\\csname ", pdfetcs.pgfpattern, "\\endcsname{", res, "}" }
4553 else
4554 pdfetcs.fallback_update_resources("Pattern",res,"@MPlibPt")
4555 end
4556 end
4557 end
4558 if pdfmode then
4559 function luamplib.dolatelua (on, os, matrix)
4560 local h, v = pdf.getpos()
4561 local t = matrix and matrix:explode() or {1,0,0,1,0,0}
4562 matrix = format("%f %f %f %f %f %f", t[1], t[2], t[3], t[4], t[5]+h/factor, t[6]+v/factor)
4563 :gsub(decimals,rmzeros)
4564 pdf.obj(on, format("<<%s/Matrix[%s]>>", os, matrix))
4565 pdf.refobj(on)
4566 end
4567 else
4568 pdfetcs.shadingpatterns = { }
4569 pdfetcs.shadingpatterninit_r, pdfetcs.shadingpatterninit_w = true, true
4570 function luamplib.dolatelua (on, kind, xobj)
4571 local h, v
4572 local t = pdfetcs.shadingpatterns[on] or { }
4573 local shift = kind == "group" and pdfetcs.tr_group.shifts[xobj]
4574 or kind == "pattern" and pdfetcs.patterns[xobj].shifts
4575 if shift then
4576 h, v = -shift[1], -shift[2] -- engine bug in dvi mode?
4577 else
4578 h, v = pdf.getpos()
4579 h = format("%f", h/factor) :gsub(decimals,rmzeros)
4580 v = format("%f", v/factor) :gsub(decimals,rmzeros)
4581 end
4582 if tonumber(h) ~= tonumber(t[1]) or tonumber(v) ~= tonumber(t[2]) then
4583 warn"Rerun to get correct shading pattern"
4584 end
4585 local name = format("%s/%s_shadingpatterns.aux", cachedir or outputdir(), tex.jobname)
4586 local init = pdfetcs.shadingpatterninit_w
4587 if init then pdfetcs.shadingpatterninit_w = nil end
4588 local f = ioopen(name, init and "w" or "a")
4589 if f then
4590 f:write(("%s %s %s\n"):format(on, h, v))
4591 f:close()
4592 else
4593 err"cannot write a file. check the cache dir path"
4594 end
4595 end
4596 end
4597 local function do_preobj_shading (object, prescript)
4598 if not prescript or not prescript.sh_operand_type then return end
4599 local on = do_preobj_SH(object, prescript)
4600 local os = format("/PatternType 2/Shading %s", format(pdfetcs.resfmt, on))
4601 local matrix = prescript.sh_matrix or "1 0 0 1 0 0"
4602 if matrix:find"%a" then
4603 local data = format("mplibtransformmatrix(%s);",matrix)
4604 process(data,"@mplibtransformmatrix")
4605 local t = luamplib.transformmatrix
4606 matrix = format("%f %f %f %f %f %f", t[1], t[2], t[3], t[4], t[5], t[6]):gsub(decimals,rmzeros)
4607 end
4608 if prescript.sh_in_xobj == "yes" then
4609 on = update_pdfobjs(("<<%s/Matrix[%s]>>"):format(os, matrix))
4610 goto skip_latelua
4611 end
4612 on = update_pdfobjs()
4613 if pdfmode then
4614 put2output(tableconcat{"\\latelua{luamplib.dolatelua(",on,",[[",os,"]],[[",matrix,"]])}"})
4615 else
4616 local xobj = is_defined"mplibgroupname" and {"group", get_macro"mplibgroupname"}
4617 or is_defined"mplibpatternname" and {"pattern", get_macro"mplibpatternname"}
4618 local init = pdfetcs.shadingpatterninit_r
4619 if init then
4620 pdfetcs.shadingpatterninit_r = nil
4621 local name = format("%s/%s_shadingpatterns.aux", cachedir or outputdir(), tex.jobname)
4622 local f = ioopen(name)
4623 if f then
4624 for line in f:lines() do
4625 local t = line:explode()
4626 pdfetcs.shadingpatterns[ tonumber(t[1]) ] = { t[2], t[3] }
4627 end
4628 f:close()
4629 end
4630 end
4631 % \end{macrocode}
4632 % This seems to be needed for proper functioning:
4633 %\begin{verbatim}
4634 % \pagewidth=\paperwidth
4635 % \pageheight=\paperheight
4636 % \special{papersize=\the\paperwidth,\the\paperheight}
4637 %\end{verbatim}
4638 % \begin{macrocode}
4639 local t = pdfetcs.shadingpatterns[on] or { 0, 0 }
4640 local mt = matrix:explode()
4641 matrix = format("%s %s %s %s %s %s", mt[1], mt[2], mt[3], mt[4], mt[5]+t[1], mt[6]+t[2])
4642 texsprint{ "\\special{pdf:put ", format(pdfetcs.resfmt, on),
4643 format(" <<%s/Matrix[%s]>>}", os, matrix) }
4644 put2output("\\latelua{ luamplib.dolatelua(%s,%s) }", on,
4645 xobj and ("'%s',[[%s]]"):format(xobj[1], xobj[2]))
4646 end
4647 ::skip_latelua::
4648 local key, val = format("MPlibPt%s", on), format(pdfetcs.resfmt, on)
4649 add_pattern_resources(key,val)
4650 pdf_literalcode("/Pattern cs/%s scn", key)
4651 % \end{macrocode}
4652 % To avoid possible double execution, once by Pattern gs, once by Sh operator.
4653 % \begin{macrocode}
4654 prescript.sh_type = nil
4655 end
4656
4657 % \end{macrocode}
4658 %
4659 % Tiling Patterns
4660 % \begin{macrocode}
4661 pdfetcs.patterns = { }
4662 local function gather_resources (optres, ispattern)
4663 local t = { }
4664 if pdfmanagement then
4665 for _,v in ipairs {"ExtGState","ColorSpace","Pattern","Shading"} do
4666 local mytoks
4667 run_tex_code ({
4668 "\\mplibtmptoks\\expanded{{",
4669 "\\pdfdict_if_empty:nF{g__pdf_Core/Page/Resources/",v,"}",
4670 "{\\pdfdict_use:n{g__pdf_Core/Page/Resources/",v,"}}", "}}",
4671 },ccexplat)
4672 mytoks = texgettoks"mplibtmptoks"
4673 if not pdfmode then
4674 mytoks = mytoks:gsub("\\str_convert_pdfname:n%s*{(.-)}","%1") -- why not expanded?
4675 end
4676 mytoks = mytoks and mytoks:gsub("^%s*(.-)%s*$", "%1")
4677 if mytoks and mytoks ~= "" then
4678 t[#t+1] = ("/%s<<%s>>"):format(v, mytoks)
4679 end
4680 end
4681 elseif is_defined(pdfetcs.pgfextgs) then
4682 run_tex_code"\\relax" -- flush tex.sprint queue
4683 if pdfmode then
4684 for k,v in pairs { ExtGState = "pgf@sys@pgf@resource@list@extgs",
4685 ColorSpace = "pgf@sys@pgf@resource@list@colorspaces",
4686 Pattern = "pgf@sys@pgf@resource@list@patterns", } do
4687 local res = (get_macro(v) or ""):gsub("^%s*(.-)%s*$","%1")
4688 if res ~= "" then
4689 t[#t+1] = ("/%s<<%s>>"):format(k, res )
4690 end
4691 end
4692 else
4693 local abc = get_macro"pgfutil@abc" or ""
4694 for k,v in pairs { ExtGState = "@pgfextgs",
4695 ColorSpace = "@pgfcolorspaces",
4696 Pattern = "@pgfpatterns", } do
4697 local tt = { }
4698 for vv in abc:gmatch( v .. "%s*(%b<>)" ) do
4699 tt[#tt+1] = vv:match("^<<%s*(.-)%s*>>$")
4700 end
4701 if #tt > 0 then
4702 t[#t+1] = ("/%s<<%s>>"):format(k, tableconcat(tt) )
4703 end
4704 end
4705 end
4706 % \end{macrocode}
4707 % We still have to deal with Shading resources.
4708 % \begin{macrocode}
4709 if luatexbase.callbacktypes.finish_pdffile then
4710 if pdfetcs.Shading_res then
4711 t[#t+1] = ("/Shading<<%s>>"):format( tableconcat(pdfetcs.Shading_res) )
4712 end
4713 else
4714 local res = pdfetcs.getpageres()
4715 res = res and res:match"/Shading%s*%b<>"
4716 if res then
4717 t[#t+1] = res
4718 end
4719 end
4720 else
4721 if ispattern and is_defined"TRP@list" then
4722 % \end{macrocode}
4723 % We do not gather \pkg{transparent} package's \cs{TRP@list}
4724 % as Acrobat glitches on tiling pattern plus masking group,
4725 % so warn users and recommend \cs{DocumentMetadata}
4726 % \begin{macrocode}
4727 warn"transparent package is not fully functional without pdfmanagement code."
4728 end
4729 if luatexbase.callbacktypes.finish_pdffile then
4730 for _,v in ipairs {"ExtGState","ColorSpace","Pattern","Shading"} do
4731 local tt = pdfetcs[v.."_res"]
4732 if tt then
4733 t[#t+1] = ("/%s<<%s>>"):format(v, tableconcat(tt))
4734 end
4735 end
4736 else
4737 local res = pdfetcs.getpageres()
4738 if res then
4739 t[#t+1] = res
4740 end
4741 end
4742 end
4743 local result = tableconcat(t)
4744 if optres ~= "" then
4745 for _,v in ipairs {"ExtGState","ColorSpace","Pattern","Shading"} do
4746 local res = optres:match("/"..v.."%s*%b<>")
4747 if res then
4748 if result:find("/"..v) then
4749 res = res:match("<<(.+)>>$")
4750 result = result:gsub("/"..v.."%s*<<", "%1"..res, 1)
4751 else
4752 result = result .. res
4753 end
4754 end
4755 end
4756 end
4757 return result
4758 end
4759 function luamplib.registerpattern ( boxid, name, opts )
4760 local box = texgetbox(boxid)
4761 local wd = format("%.3f",box.width/factor)
4762 local hd = format("%.3f",(box.height+box.depth)/factor)
4763 info("w/h/d of pattern '%s': %s 0", name, format("%s %s",wd, hd):gsub(decimals,rmzeros))
4764 if opts.xstep == 0 then opts.xstep = nil end
4765 if opts.ystep == 0 then opts.ystep = nil end
4766 if opts.colored == nil then
4767 opts.colored = opts.coloured
4768 if opts.colored == nil then
4769 opts.colored = true
4770 end
4771 end
4772 if type(opts.matrix) == "table" then opts.matrix = tableconcat(opts.matrix," ") end
4773 if type(opts.bbox) == "table" then opts.bbox = tableconcat(opts.bbox," ") end
4774 if opts.matrix and opts.matrix:find"%a" then
4775 local data = format("mplibtransformmatrix(%s);",opts.matrix)
4776 process(data,"@mplibtransformmatrix")
4777 local t = luamplib.transformmatrix
4778 opts.matrix = format("%f %f %f %f", t[1], t[2], t[3], t[4])
4779 opts.xshift = opts.xshift or format("%f",t[5])
4780 opts.yshift = opts.yshift or format("%f",t[6])
4781 end
4782 local attr = {
4783 "/Type/Pattern",
4784 "/PatternType 1",
4785 format("/PaintType %i", opts.colored and 1 or 2),
4786 "/TilingType 2",
4787 format("/XStep %s", opts.xstep or wd),
4788 format("/YStep %s", opts.ystep or hd),
4789 format("/Matrix[%s %s %s]", opts.matrix or "1 0 0 1", opts.xshift or 0, opts.yshift or 0),
4790 }
4791 local optres = opts.resources or ""
4792 optres = gather_resources(optres, true) -- tiling pattern plus masking glitches with acrobat
4793 local patterns = pdfetcs.patterns
4794 if pdfmode then
4795 if opts.bbox then
4796 attr[#attr+1] = format("/BBox[%s]", opts.bbox)
4797 end
4798 attr = tableconcat(attr) :gsub(decimals,rmzeros)
4799 local index = tex.saveboxresource(boxid, attr, optres, true, opts.bbox and 4 or 1)
4800 patterns[name] = { id = index, colored = opts.colored }
4801 else
4802 local cnt = #patterns + 1
4803 local objname = "@mplibpattern" .. cnt
4804 local metric = format("bbox %s", opts.bbox or format("0 0 %s %s",wd,hd))
4805 texsprint {
4806 "\\expandafter\\newbox\\csname luamplib.patternbox.", cnt, "\\endcsname",
4807 "\\global\\setbox\\csname luamplib.patternbox.", cnt, "\\endcsname",
4808 "\\hbox{\\unhbox ", boxid, "}\\luamplibatnextshipout{",
4809 "\\special{pdf:bcontent}",
4810 "\\special{pdf:bxobj ", objname, " ", metric, "}",
4811 "\\raise\\dp\\csname luamplib.patternbox.", cnt, "\\endcsname",
4812 "\\box\\csname luamplib.patternbox.", cnt, "\\endcsname",
4813 "\\special{pdf:put @resources <<", optres, ">>}",
4814 "\\special{pdf:exobj <<", tableconcat(attr), ">>}",
4815 "\\special{pdf:econtent}}",
4816 }
4817 patterns[cnt] = objname
4818 patterns[name] = { id = cnt, colored = opts.colored }
4819 patterns[name].shifts = { get_macro"MPllx", get_macro"MPlly" } -- for shading patterns above
4820 end
4821 end
4822
4823 local do_preobj_PAT
4824 do
4825 local function pattern_colorspace (cs)
4826 local on, new = update_pdfobjs(format("[/Pattern %s]", cs))
4827 if new then
4828 local key, val = format("MPlibCS%i",on), format(pdfetcs.resfmt,on)
4829 if pdfmanagement then
4830 texsprint {
4831 "\\csname pdfmanagement_add:nnn\\endcsname{Page/Resources/ColorSpace}{", key, "}{", val, "}"
4832 }
4833 else
4834 local res = format("/%s %s", key, val)
4835 if is_defined(pdfetcs.pgfcolorspace) then
4836 texsprint { "\\csname ", pdfetcs.pgfcolorspace, "\\endcsname{", res, "}" }
4837 else
4838 pdfetcs.fallback_update_resources("ColorSpace",res,"@MPlibCS")
4839 end
4840 end
4841 end
4842 return on
4843 end
4844 function do_preobj_PAT(object, prescript)
4845 local name = prescript and prescript.mplibpattern
4846 if not name then return end
4847 local patterns = pdfetcs.patterns
4848 local patt = patterns[name]
4849 local index = patt and patt.id or err("cannot get pattern object '%s'", name)
4850 local key = format("MPlibPt%s",index)
4851 if patt.colored then
4852 pdf_literalcode("/Pattern cs /%s scn", key)
4853 else
4854 local color = prescript.mpliboverridecolor
4855 if not color then
4856 local t = object.color
4857 color = t and #t>0 and luamplib.colorconverter(t)
4858 end
4859 if not color then return end
4860 local cs
4861 if color:find" cs " or color:find"@pdf.obj" then
4862 local t = color:explode()
4863 if pdfmode then
4864 cs = format("%s 0 R", ltx.pdf.object_id( t[1]:sub(2,-1) ))
4865 color = t[3]
4866 else
4867 cs = t[2]
4868 color = t[3]:match"%[(.+)%]"
4869 end
4870 else
4871 local t = colorsplit(color)
4872 cs = #t == 4 and "/DeviceCMYK" or #t == 3 and "/DeviceRGB" or "/DeviceGray"
4873 color = tableconcat(t," ")
4874 end
4875 pdf_literalcode("/MPlibCS%i cs %s /%s scn", pattern_colorspace(cs), color, key)
4876 end
4877 if not patt.done then
4878 local val = pdfmode and format("%s 0 R",index) or patterns[index]
4879 add_pattern_resources(key,val)
4880 end
4881 patt.done = true
4882 end
4883 end
4884
4885 % \end{macrocode}
4886 %
4887 % Fading
4888 % \begin{macrocode}
4889 pdfetcs.fading = { }
4890 local function do_preobj_FADE (object, prescript)
4891 local fd_type = prescript and prescript.mplibfadetype
4892 local fd_stop = prescript and prescript.mplibfadestate
4893 if not fd_type then
4894 return fd_stop -- returns "stop" (if picture) or nil
4895 end
4896 local on, os, new
4897 if fd_type == "masking" then
4898 local mac = get_macro("luamplib.group."..prescript.mplibmaskname)
4899 on = mac:match(pdfmode and "%d+" or "{pdf:uxobj (.-)}")
4900 local bc = prescript.mplibmaskingbgcolor
4901 bc = bc and bc:gsub(":"," ")
4902 bc = bc and ("/BC[%s]"):format(bc):gsub(decimals,rmzeros) or ""
4903 os = format("<</SMask<</S/Luminosity/G %s%s>>>>",
4904 pdfmode and format(pdfetcs.resfmt, on) or on, bc)
4905 else
4906 local bbox = prescript.mplibfadebbox:explode":"
4907 local dx, dy = -bbox[1], -bbox[2]
4908 local vec = prescript.mplibfadevector; vec = vec and vec:explode":"
4909 if not vec then
4910 if fd_type == "linear" then
4911 vec = {bbox[1], bbox[2], bbox[3], bbox[2]} -- left to right
4912 else
4913 local centerx, centery = (bbox[1]+bbox[3])/2, (bbox[2]+bbox[4])/2
4914 vec = {centerx, centery, centerx, centery} -- center for both circles
4915 end
4916 end
4917 local coords = { vec[1], vec[2], vec[3], vec[4] }
4918 if fd_type == "linear" then
4919 coords = format("%f %f %f %f", tableunpack(coords))
4920 elseif fd_type == "circular" then
4921 local width, height = bbox[3]-bbox[1], bbox[4]-bbox[2]
4922 local radius = (prescript.mplibfaderadius or "0:"..math.sqrt(width^2+height^2)/2):explode":"
4923 tableinsert(coords, 3, radius[1])
4924 tableinsert(coords, radius[2])
4925 coords = format("%f %f %f %f %f %f", tableunpack(coords))
4926 else
4927 err("unknown fading method '%s'", fd_type)
4928 end
4929 fd_type = fd_type == "linear" and 2 or 3
4930 local extend, steps, fractions = prescript.sh_extend, tonumber(prescript.sh_step) or 1
4931 local ca = { (prescript.sh_color_a_1 or prescript.sh_color_a or "1"):explode":" }
4932 local cb = { (prescript.sh_color_b_1 or prescript.sh_color_b or "0"):explode":" }
4933 if steps > 1 then
4934 fractions = { prescript.sh_fraction_1 or 0 }
4935 for i=2,steps do
4936 fractions[i] = prescript[format("sh_fraction_%i",i)] or (i/steps)
4937 ca[i] = (prescript[format("sh_color_a_%i",i)] or "1"):explode":"
4938 cb[i] = (prescript[format("sh_color_b_%i",i)] or "0"):explode":"
4939 end
4940 end
4941 local matrix = prescript.sh_matrix or "1 0 0 1 0 0"
4942 if matrix:find"%a" then
4943 local data = format("mplibtransformmatrix(%s);",matrix)
4944 process(data,"@mplibtransformmatrix")
4945 matrix = luamplib.transformmatrix
4946 else
4947 matrix = matrix:explode()
4948 end
4949 matrix[5] = matrix[5] + dx
4950 matrix[6] = matrix[6] + dy
4951 matrix = format("%f %f %f %f %f %f", tableunpack(matrix)) :gsub(decimals,rmzeros)
4952 on = sh_pdfpageresources(fd_type,"0 1","/DeviceGray",ca,cb,coords,steps,fractions,extend)
4953 os = format("<</PatternType 2/Shading %s/Matrix[%s]>>", format(pdfetcs.resfmt, on), matrix)
4954 on = update_pdfobjs(os)
4955 bbox = format("0 0 %f %f", bbox[3]+dx, bbox[4]+dy)
4956 local streamtext = format("q /Pattern cs/MPlibFd%s scn %s re f Q", on, bbox)
4957 :gsub(decimals,rmzeros)
4958 os = format("<</Pattern<</MPlibFd%s %s>>>>", on, format(pdfetcs.resfmt, on))
4959 on = update_pdfobjs(os)
4960 local resources = format(pdfetcs.resfmt, on)
4961 on = update_pdfobjs"<</S/Transparency/CS/DeviceGray>>"
4962 local attr = tableconcat{
4963 "/Subtype/Form",
4964 "/BBox[", bbox, "]",
4965 "/Matrix[1 0 0 1 ", format("%f %f", -dx,-dy), "]",
4966 "/Resources ", resources,
4967 "/Group ", format(pdfetcs.resfmt, on),
4968 } :gsub(decimals,rmzeros)
4969 on = update_pdfobjs(attr, streamtext)
4970 os = format("<</SMask<</S/Luminosity/G %s>>>>", format(pdfetcs.resfmt, on))
4971 end
4972 on, new = update_pdfobjs(os)
4973 local key = add_extgs_resources(on,new)
4974 start_pdf_code()
4975 pdf_literalcode("/%s gs", key)
4976 if fd_stop then return "standalone" end
4977 return "start"
4978 end
4979
4980 % \end{macrocode}
4981 %
4982 % Transparency Group
4983 % \begin{macrocode}
4984 pdfetcs.tr_group = { shifts = { } }
4985 luamplib.trgroupshifts = pdfetcs.tr_group.shifts
4986 local function do_preobj_GRP (object, prescript)
4987 local grstate = prescript and prescript.gr_state
4988 if not grstate then return end
4989 local trgroup = pdfetcs.tr_group
4990 if grstate == "start" then
4991 trgroup.name = prescript.mplibgroupname or "lastmplibgroup"
4992 trgroup.isolated, trgroup.knockout, trgroup.off = false, false, false
4993 trgroup.wrapped = false
4994 for _,v in ipairs(prescript.gr_type:gsub("%s",""):explode",+") do
4995 trgroup[v] = true
4996 end
4997 trgroup.bbox = prescript.mplibgroupbbox:explode":"
4998 put2output[[\begingroup\setbox\mplibscratchbox\hbox\bgroup\luamplibtagasgroupset]]
4999 elseif grstate == "stop" then
5000 local llx,lly,urx,ury = tableunpack(trgroup.bbox)
5001 put2output(tableconcat{
5002 "\\egroup",
5003 format("\\wd\\mplibscratchbox %fbp", urx-llx),
5004 format("\\ht\\mplibscratchbox %fbp", ury-lly),
5005 "\\dp\\mplibscratchbox 0pt",
5006 })
5007 local grattr
5008 if trgroup.off then
5009 grattr = ""
5010 else
5011 local on = update_pdfobjs(format("<</S/Transparency/I %s/K %s>>",
5012 trgroup.isolated, trgroup.knockout))
5013 grattr = format("/Group %s", pdfetcs.resfmt:format(on))
5014 end
5015 local res = gather_resources("")
5016 local bbox = format("%f %f %f %f", llx,lly,urx,ury) :gsub(decimals,rmzeros)
5017 if pdfmode then
5018 if trgroup.wrapped then
5019 put2output(tableconcat{
5020 "\\saveboxresource type 2 attr{/Type/XObject/Subtype/Form/FormType 1",
5021 "/BBox[", bbox, "]} resources{", res, "}\\mplibscratchbox",
5022 "\\setbox\\mplibscratchbox\\hbox{\\useboxresource\\lastsavedboxresourceindex}",
5023 })
5024 end
5025 put2output(tableconcat{
5026 "\\saveboxresource type 2 attr{/Type/XObject/Subtype/Form/FormType 1",
5027 "/BBox[", bbox, "]", grattr, "} resources{", res, "}\\mplibscratchbox",
5028 "\\luamplibtagasgroupput{",trgroup.name,"}{",
5029 [[\setbox\mplibscratchbox\hbox{\useboxresource\lastsavedboxresourceindex}]],
5030 [[\wd\mplibscratchbox 0pt\ht\mplibscratchbox 0pt\dp\mplibscratchbox 0pt]],
5031 [[\box\mplibscratchbox]],
5032 "}\\endgroup",
5033 "\\expandafter\\xdef\\csname luamplib.group.", trgroup.name, "\\endcsname{",
5034 "\\setbox\\mplibscratchbox\\hbox{\\hskip",-llx,"bp\\raise",-lly,"bp\\hbox{",
5035 "\\useboxresource \\the\\lastsavedboxresourceindex",
5036 "}}\\wd\\mplibscratchbox",urx-llx,"bp\\ht\\mplibscratchbox",ury-lly,"bp",
5037 "\\box\\mplibscratchbox}",
5038 })
5039 else
5040 if trgroup.wrapped then
5041 trgroup.cnt = (trgroup.cnt or 0) + 1
5042 local objname = format("@mplibtrgr%s", trgroup.cnt)
5043 put2output(tableconcat{
5044 "\\special{pdf:bxobj ", objname, " bbox ", bbox, "}",
5045 "\\unhbox\\mplibscratchbox",
5046 "\\special{pdf:put @resources <<", res, ">>}",
5047 "\\special{pdf:exobj}",
5048 "\\setbox\\mplibscratchbox\\hbox{\\special{pdf:uxobj ", objname, "}}",
5049 })
5050 end
5051 trgroup.cnt = (trgroup.cnt or 0) + 1
5052 local objname = format("@mplibtrgr%s", trgroup.cnt)
5053 put2output(tableconcat{
5054 "\\special{pdf:bxobj ", objname, " bbox ", bbox, "}",
5055 "\\unhbox\\mplibscratchbox",
5056 "\\special{pdf:put @resources <<", res, ">>}",
5057 "\\special{pdf:exobj <<", grattr, ">>}",
5058 "\\luamplibtagasgroupput{",trgroup.name,"}{",
5059 "\\special{pdf:uxobj ", objname, "}",
5060 "}\\endgroup",
5061 })
5062 token.set_macro("luamplib.group."..trgroup.name, tableconcat{
5063 "\\setbox\\mplibscratchbox\\hbox{\\hskip",-llx,"bp\\raise",-lly,"bp\\hbox{",
5064 "\\special{pdf:uxobj ", objname, "}",
5065 "}}\\wd\\mplibscratchbox",urx-llx,"bp\\ht\\mplibscratchbox",ury-lly,"bp",
5066 "\\box\\mplibscratchbox",
5067 }, "global")
5068 end
5069 trgroup.shifts[trgroup.name] = { llx, lly }
5070 end
5071 return grstate
5072 end
5073 function luamplib.registergroup (boxid, name, opts)
5074 if opts.asgroup and opts.asgroup:find"wrapped" then
5075 luamplib.registergroup(boxid, name, {bbox=opts.bbox, resources=opts.resources})
5076 run_tex_code{"\\setbox", boxid, "\\hbox bdir0{\\csname luamplib.group.", name, "\\endcsname}"}
5077 opts.asgroup = opts.asgroup:gsub("wrapped","")
5078 end
5079 local box = texgetbox(boxid)
5080 local wd, ht, dp = node.getwhd(box)
5081 local is_mask = opts.asgroup and opts.asgroup:find"masking"
5082 local res = opts.resources or ""
5083 res = gather_resources(res)
5084 local attr = { "/Type/XObject/Subtype/Form/FormType 1" }
5085 if type(opts.matrix) == "table" then opts.matrix = tableconcat(opts.matrix," ") end
5086 if type(opts.bbox) == "table" then opts.bbox = tableconcat(opts.bbox," ") end
5087 if opts.matrix and opts.matrix:find"%a" then
5088 local data = format("mplibtransformmatrix(%s);",opts.matrix)
5089 process(data,"@mplibtransformmatrix")
5090 opts.matrix = format("%f %f %f %f %f %f",tableunpack(luamplib.transformmatrix))
5091 end
5092 local grtype = 3
5093 if opts.bbox then
5094 attr[#attr+1] = format("/BBox[%s]", opts.bbox)
5095 grtype = 2
5096 end
5097 local mpllx, mplly = get_macro'MPllx', get_macro'MPlly'
5098 if is_mask then
5099 local t = opts.matrix and opts.matrix:explode() or {1, 0, 0, 1, 0, 0}
5100 t[5], t[6] = t[5]+mpllx, t[6]+mplly
5101 opts.matrix = format("%f %f %f %f %f %f",tableunpack(t))
5102 mpllx, mplly = 0, 0
5103 end
5104 if opts.matrix then
5105 attr[#attr+1] = format("/Matrix[%s]", opts.matrix)
5106 grtype = opts.bbox and 4 or 1
5107 end
5108 if opts.asgroup and not opts.asgroup:find"off" then
5109 local t = { isolated = false, knockout = false, masking = false }
5110 for _,v in ipairs(opts.asgroup:gsub("%s",""):explode",+") do t[v] = true end
5111 local on
5112 if t.masking then
5113 on = update_pdfobjs(format("<</S/Transparency/CS%s>>", opts.colorspace or "/DeviceGray"))
5114 else
5115 local cs = opts.colorspace and ("/CS%s"):format(opts.colorspace) or ""
5116 on = update_pdfobjs(format("<</S/Transparency%s/I %s/K %s>>", cs, t.isolated, t.knockout))
5117 end
5118 attr[#attr+1] = format("/Group %s", pdfetcs.resfmt:format(on))
5119 end
5120 local trgroup = pdfetcs.tr_group
5121 trgroup.shifts[name] = { mpllx, mplly }
5122 local whd
5123 if pdfmode then
5124 attr = tableconcat(attr) :gsub(decimals,rmzeros)
5125 local index = tex.saveboxresource(boxid, attr, res, true, grtype)
5126 token.set_macro("luamplib.group."..name, tableconcat{
5127 "\\useboxresource ", index,
5128 }, "global")
5129 whd = format("%.3f %.3f 0", wd/factor, (ht+dp)/factor) :gsub(decimals,rmzeros)
5130 else
5131 trgroup.cnt = (trgroup.cnt or 0) + 1
5132 local objname = format("@mplibtrgr%s", trgroup.cnt)
5133 texsprint {
5134 "\\expandafter\\newbox\\csname luamplib.groupbox.", trgroup.cnt, "\\endcsname",
5135 "\\global\\setbox\\csname luamplib.groupbox.", trgroup.cnt, "\\endcsname",
5136 "\\hbox{\\unhbox ", boxid, "}\\luamplibatnextshipout{",
5137 "\\special{pdf:bcontent}",
5138 "\\special{pdf:bxobj ", objname, " width ", wd, "sp height ", ht, "sp depth ", dp, "sp}",
5139 "\\unhbox\\csname luamplib.groupbox.", trgroup.cnt, "\\endcsname",
5140 "\\special{pdf:put @resources <<", res, ">>}",
5141 "\\special{pdf:exobj <<", tableconcat(attr), ">>}",
5142 "\\special{pdf:econtent}}",
5143 }
5144 token.set_macro("luamplib.group."..name, tableconcat{
5145 "\\setbox\\mplibscratchbox\\hbox{\\special{pdf:uxobj ", objname, "}}",
5146 "\\wd\\mplibscratchbox ", wd, "sp",
5147 "\\ht\\mplibscratchbox ", ht, "sp",
5148 "\\dp\\mplibscratchbox ", dp, "sp",
5149 "\\box\\mplibscratchbox",
5150 }, "global")
5151 whd = format("%.3f %.3f %.3f", wd/factor, ht/factor, dp/factor) :gsub(decimals,rmzeros)
5152 end
5153 info("w/h/d of group '%s': %s", name, whd)
5154 end
5155
5156 % \end{macrocode}
5157 %
5158 % |luamplib.convert|: flushing figures
5159 % \begin{macrocode}
5160 do
5161 local function stop_special_effects(fade,opaq,over)
5162 if fade then -- fading
5163 stop_pdf_code()
5164 end
5165 if opaq then -- opacity
5166 pdf_literalcode(opaq)
5167 end
5168 if over then -- color
5169 if over:find"pdf:bc" then
5170 put2output"\\special{pdf:ec}"
5171 else
5172 put2output"\\special{color pop}"
5173 end
5174 end
5175 end
5176
5177 % \end{macrocode}
5178 % For parsing |prescript| materials.
5179 % \begin{macrocode}
5180 local function script2table(s)
5181 local t = {}
5182 for _,i in ipairs(s:explode("\13+")) do
5183 local k,v = i:match("(.-)=(.*)") -- v may contain = or empty.
5184 if k and v and k ~= "" and not t[k] then
5185 t[k] = v
5186 end
5187 end
5188 return t
5189 end
5190
5191 % \end{macrocode}
5192 % Codes below to insert PDF lieterals are mostly from \ConTeXt general,
5193 % with small changes when needed.
5194 % \begin{macrocode}
5195 local function pdf_textfigure(font,size,text,width,height,depth)
5196 text = text:gsub(".",function(c)
5197 return format("\\hbox{\\char%i}",string.byte(c)) -- kerning happens in metapost : false
5198 end)
5199 put2output("\\mplibtextext{%s}{%f}{%s}{%s}{%s}",font,size,text,0,0)
5200 end
5201
5202 local bend_tolerance = 131/65536
5203
5204 local rx, sx, sy, ry, tx, ty, divider = 1, 0, 0, 1, 0, 0, 1
5205
5206 local function pen_characteristics(object)
5207 local t = mplib.pen_info(object)
5208 rx, ry, sx, sy, tx, ty = t.rx, t.ry, t.sx, t.sy, t.tx, t.ty
5209 divider = sx*sy - rx*ry
5210 return not (sx==1 and rx==0 and ry==0 and sy==1 and tx==0 and ty==0), t.width
5211 end
5212
5213 local function concat(px, py) -- no tx, ty here
5214 return (sy*px-ry*py)/divider,(sx*py-rx*px)/divider
5215 end
5216
5217 local function curved(ith,pth)
5218 local d = pth.left_x - ith.right_x
5219 if abs(ith.right_x - ith.x_coord - d) <= bend_tolerance and
5220 abs(pth.x_coord - pth.left_x - d) <= bend_tolerance then
5221 d = pth.left_y - ith.right_y
5222 if abs(ith.right_y - ith.y_coord - d) <= bend_tolerance and
5223 abs(pth.y_coord - pth.left_y - d) <= bend_tolerance then
5224 return false
5225 end
5226 end
5227 return true
5228 end
5229
5230 local function flushnormalpath(path,open)
5231 local pth, ith
5232 for i=1,#path do
5233 pth = path[i]
5234 if not ith then
5235 pdf_literalcode("%f %f m",pth.x_coord,pth.y_coord)
5236 elseif curved(ith,pth) then
5237 pdf_literalcode("%f %f %f %f %f %f c",
5238 ith.right_x,ith.right_y,pth.left_x,pth.left_y,pth.x_coord,pth.y_coord)
5239 else
5240 pdf_literalcode("%f %f l",pth.x_coord,pth.y_coord)
5241 end
5242 ith = pth
5243 end
5244 if not open then
5245 local one = path[1]
5246 if curved(pth,one) then
5247 pdf_literalcode("%f %f %f %f %f %f c",
5248 pth.right_x,pth.right_y,one.left_x,one.left_y,one.x_coord,one.y_coord )
5249 else
5250 pdf_literalcode("%f %f l",one.x_coord,one.y_coord)
5251 end
5252 elseif #path == 1 then -- special case .. draw point
5253 local one = path[1]
5254 pdf_literalcode("%f %f l",one.x_coord,one.y_coord)
5255 end
5256 end
5257
5258 local function flushconcatpath(path,open)
5259 pdf_literalcode("%f %f %f %f %f %f cm", sx, rx, ry, sy, tx ,ty)
5260 local pth, ith
5261 for i=1,#path do
5262 pth = path[i]
5263 if not ith then
5264 pdf_literalcode("%f %f m",concat(pth.x_coord,pth.y_coord))
5265 elseif curved(ith,pth) then
5266 local a, b = concat(ith.right_x,ith.right_y)
5267 local c, d = concat(pth.left_x,pth.left_y)
5268 pdf_literalcode("%f %f %f %f %f %f c",a,b,c,d,concat(pth.x_coord, pth.y_coord))
5269 else
5270 pdf_literalcode("%f %f l",concat(pth.x_coord, pth.y_coord))
5271 end
5272 ith = pth
5273 end
5274 if not open then
5275 local one = path[1]
5276 if curved(pth,one) then
5277 local a, b = concat(pth.right_x,pth.right_y)
5278 local c, d = concat(one.left_x,one.left_y)
5279 pdf_literalcode("%f %f %f %f %f %f c",a,b,c,d,concat(one.x_coord, one.y_coord))
5280 else
5281 pdf_literalcode("%f %f l",concat(one.x_coord,one.y_coord))
5282 end
5283 elseif #path == 1 then -- special case .. draw point
5284 local one = path[1]
5285 pdf_literalcode("%f %f l",concat(one.x_coord,one.y_coord))
5286 end
5287 end
5288
5289 % \end{macrocode}
5290 % Finally, flush figures by inserting PDF literals.
5291 % \begin{macrocode}
5292 local function flush (result,flusher)
5293 if result then
5294 local figures = result.fig
5295 if figures then
5296 for f=1, #figures do
5297 info("flushing figure %s",f)
5298 local figure = figures[f]
5299 local objects = figure:objects()
5300 local fignum = tonumber(figure:filename():match("([%d]+)$") or figure:charcode() or 0)
5301 local miterlimit, linecap, linejoin, dashed = -1, -1, -1, false
5302 local bbox = figure:boundingbox()
5303 local llx, lly, urx, ury = bbox[1], bbox[2], bbox[3], bbox[4] -- faster than unpack
5304 if urx < llx then
5305 % \end{macrocode}
5306 % luamplib silently ignores this invalid figure for those
5307 % that do not contain |beginfig ... endfig|. (issue \#70)
5308 % Original code of \ConTeXt general was:
5309 %\begin{verbatim}
5310 % -- invalid
5311 % pdf_startfigure(fignum,0,0,0,0)
5312 % pdf_stopfigure()
5313 %\end{verbatim}
5314 % \begin{macrocode}
5315 else
5316 % \end{macrocode}
5317 % For legacy behavior, insert `pre-fig' \TeX\ code here.
5318 % \begin{macrocode}
5319 if tex_code_pre_mplib[f] then
5320 put2output(tex_code_pre_mplib[f])
5321 end
5322 pdf_startfigure(fignum,llx,lly,urx,ury)
5323 start_pdf_code()
5324 if objects then
5325 local savedpath = nil
5326 local savedhtap = nil
5327 for o=1,#objects do
5328 local object = objects[o]
5329 local objecttype = object.type
5330 % \end{macrocode}
5331 % The following 10 lines are part of |btex...etex| patch.
5332 % Again, colors are processed at this stage.
5333 % \begin{macrocode}
5334 local prescript = object.prescript
5335 prescript = prescript and script2table(prescript) -- prescript is now a table
5336 local cr_over = do_preobj_CR(object,prescript) -- color
5337 local tr_opaq = do_preobj_TR(object,prescript) -- opacity
5338 local fading_ = do_preobj_FADE(object,prescript) -- fading
5339 local pattern_ = do_preobj_PAT(object,prescript) -- tiling pattern
5340 local shading_ = do_preobj_shading(object,prescript) -- shading pattern
5341 local trgroup = do_preobj_GRP(object,prescript) -- transparency group
5342 if prescript and prescript.mplibtexboxid then
5343 put_tex_boxes(object,prescript)
5344 elseif objecttype == "start_bounds" or objecttype == "stop_bounds" then --skip
5345 elseif objecttype == "start_clip" then
5346 local evenodd = not object.istext and object.postscript == "evenodd"
5347 start_pdf_code()
5348 flushnormalpath(object.path,false)
5349 pdf_literalcode(evenodd and "W* n" or "W n")
5350 elseif objecttype == "stop_clip" then
5351 stop_pdf_code()
5352 miterlimit, linecap, linejoin, dashed = -1, -1, -1, false
5353 elseif objecttype == "special" then
5354 % \end{macrocode}
5355 % Collect \TeX\ codes that will be executed after flushing.
5356 % Legacy behavior.
5357 % \begin{macrocode}
5358 if prescript and prescript.postmplibverbtex then
5359 figcontents.post[#figcontents.post+1] = prescript.postmplibverbtex
5360 end
5361 elseif objecttype == "text" then
5362 local ot = object.transform -- 3,4,5,6,1,2
5363 start_pdf_code()
5364 pdf_literalcode("%f %f %f %f %f %f cm",ot[3],ot[4],ot[5],ot[6],ot[1],ot[2])
5365 pdf_textfigure(object.font,object.dsize,object.text,object.width,object.height,object.depth)
5366 stop_pdf_code()
5367 elseif not trgroup and fading_ ~= "stop" then
5368 local evenodd, collect, both = false, false, false
5369 local postscript = object.postscript
5370 if not object.istext then
5371 if postscript == "evenodd" then
5372 evenodd = true
5373 elseif postscript == "collect" then
5374 collect = true
5375 elseif postscript == "both" then
5376 both = true
5377 elseif postscript == "eoboth" then
5378 evenodd = true
5379 both = true
5380 end
5381 end
5382 if collect then
5383 if not savedpath then
5384 savedpath = { object.path or false }
5385 savedhtap = { object.htap or false }
5386 else
5387 savedpath[#savedpath+1] = object.path or false
5388 savedhtap[#savedhtap+1] = object.htap or false
5389 end
5390 else
5391 % \end{macrocode}
5392 % Removed from \ConTeXt general: color stuff.
5393 % \begin{macrocode}
5394 local ml = object.miterlimit
5395 if ml and ml ~= miterlimit then
5396 miterlimit = ml
5397 pdf_literalcode("%f M",ml)
5398 end
5399 local lj = object.linejoin
5400 if lj and lj ~= linejoin then
5401 linejoin = lj
5402 pdf_literalcode("%i j",lj)
5403 end
5404 local lc = object.linecap
5405 if lc and lc ~= linecap then
5406 linecap = lc
5407 pdf_literalcode("%i J",lc)
5408 end
5409 local dl = object.dash
5410 if dl then
5411 local d = format("[%s] %f d",tableconcat(dl.dashes or {}," "),dl.offset)
5412 if d ~= dashed then
5413 dashed = d
5414 pdf_literalcode(dashed)
5415 end
5416 elseif dashed then
5417 pdf_literalcode("[] 0 d")
5418 dashed = false
5419 end
5420 local path = object.path
5421 local transformed, penwidth = false, 1
5422 local open = path and path[1].left_type and path[#path].right_type
5423 local pen = object.pen
5424 if pen then
5425 if pen.type == 'elliptical' then
5426 transformed, penwidth = pen_characteristics(object) -- boolean, value
5427 pdf_literalcode("%f w",penwidth)
5428 if objecttype == 'fill' then
5429 objecttype = 'both'
5430 end
5431 else -- calculated by mplib itself
5432 objecttype = 'fill'
5433 end
5434 end
5435 % \end{macrocode}
5436 % Added : shading
5437 % \begin{macrocode}
5438 local shade_no, shade_stroking = do_preobj_SH(object,prescript) -- shading
5439 if shade_no then
5440 pdf_literalcode"q /Pattern cs"
5441 objecttype = false
5442 end
5443 if transformed then
5444 start_pdf_code()
5445 end
5446 if path then
5447 if savedpath then
5448 for i=1,#savedpath do
5449 local path = savedpath[i]
5450 if transformed then
5451 flushconcatpath(path,open)
5452 else
5453 flushnormalpath(path,open)
5454 end
5455 end
5456 savedpath = nil
5457 end
5458 if transformed then
5459 flushconcatpath(path,open)
5460 else
5461 flushnormalpath(path,open)
5462 end
5463 if objecttype == "fill" then
5464 pdf_literalcode(evenodd and "h f*" or "h f")
5465 elseif objecttype == "outline" then
5466 if both then
5467 pdf_literalcode(evenodd and "h B*" or "h B")
5468 else
5469 pdf_literalcode(open and "S" or "h S")
5470 end
5471 elseif objecttype == "both" then
5472 pdf_literalcode(evenodd and "h B*" or "h B")
5473 end
5474 end
5475 if transformed then
5476 stop_pdf_code()
5477 end
5478 local path = object.htap
5479 % \end{macrocode}
5480 % How can we generate an |htap| object? Please let us know if you have succeeded.
5481 % \begin{macrocode}
5482 if path then
5483 if transformed then
5484 start_pdf_code()
5485 end
5486 if savedhtap then
5487 for i=1,#savedhtap do
5488 local path = savedhtap[i]
5489 if transformed then
5490 flushconcatpath(path,open)
5491 else
5492 flushnormalpath(path,open)
5493 end
5494 end
5495 savedhtap = nil
5496 evenodd = true
5497 end
5498 if transformed then
5499 flushconcatpath(path,open)
5500 else
5501 flushnormalpath(path,open)
5502 end
5503 if objecttype == "fill" then
5504 pdf_literalcode(evenodd and "h f*" or "h f")
5505 elseif objecttype == "outline" then
5506 pdf_literalcode(open and "S" or "h S")
5507 elseif objecttype == "both" then
5508 pdf_literalcode(evenodd and "h B*" or "h B")
5509 end
5510 if transformed then
5511 stop_pdf_code()
5512 end
5513 end
5514 % \end{macrocode}
5515 % Added to \ConTeXt general: post-object colors and shading stuff.
5516 % Beware |q ... Q| scope.
5517 % \begin{macrocode}
5518 if shade_no then -- shading
5519 pdf_literalcode("W%s %s /MPlibSh%s sh Q",
5520 evenodd and "*" or "", shade_stroking and "s" or "n", shade_no)
5521 end
5522 end
5523 end
5524 if fading_ == "start" then
5525 pdfetcs.fading.specialeffects = {fading_, tr_opaq, cr_over}
5526 elseif trgroup == "start" then
5527 pdfetcs.tr_group.specialeffects = {fading_, tr_opaq, cr_over}
5528 elseif fading_ == "stop" then
5529 local se = pdfetcs.fading.specialeffects
5530 if se then stop_special_effects(se[1], se[2], se[3]) end
5531 elseif trgroup == "stop" then
5532 local se = pdfetcs.tr_group.specialeffects
5533 if se then stop_special_effects(se[1], se[2], se[3]) end
5534 else
5535 stop_special_effects(fading_, tr_opaq, cr_over)
5536 end
5537 if fading_ or trgroup then -- extgs resetted
5538 miterlimit, linecap, linejoin, dashed = -1, -1, -1, false
5539 end
5540 end
5541 end
5542 stop_pdf_code()
5543 pdf_stopfigure()
5544 % \end{macrocode}
5545 % output collected materials to PDF, plus legacy |verbatimtex| code.
5546 % \begin{macrocode}
5547 for _,v in ipairs(figcontents) do
5548 if type(v) == "table" then
5549 texsprint"\\mplibtoPDF{"; texsprint(v[1], v[2]); texsprint"}"
5550 else
5551 texsprint(v)
5552 end
5553 end
5554 if #figcontents.post > 0 then texsprint(figcontents.post) end
5555 figcontents = { post = { } }
5556 end
5557 end
5558 end
5559 end
5560 end
5561
5562 function luamplib.convert (result, flusher)
5563 flush(result, flusher)
5564 return true -- done
5565 end
5566 end
5567
5568 function luamplib.colorconverter (cr)
5569 local n = #cr
5570 if n == 4 then
5571 local c, m, y, k = cr[1], cr[2], cr[3], cr[4]
5572 return format("%.3f %.3f %.3f %.3f k %.3f %.3f %.3f %.3f K",c,m,y,k,c,m,y,k), "0 g 0 G"
5573 elseif n == 3 then
5574 local r, g, b = cr[1], cr[2], cr[3]
5575 return format("%.3f %.3f %.3f rg %.3f %.3f %.3f RG",r,g,b,r,g,b), "0 g 0 G"
5576 else
5577 local s = cr[1]
5578 return format("%.3f g %.3f G",s,s), "0 g 0 G"
5579 end
5580 end
5581 % \end{macrocode}
5582 %
5583 % \iffalse
5584 %</lua>
5585 % \fi
5586 %
5587 % \subsection{\texorpdfstring{\TeX}{TeX} package}
5588 %
5589 %
5590 % \iffalse
5591 %<*package>
5592 % \fi
5593 %
5594 % First we need to load some packages.
5595 %
5596 % \begin{macrocode}
5597 \ifcsname ProvidesPackage\endcsname
5598 % \end{macrocode}
5599 % We need \LaTeX\ 2024-06-01 as we use |ltx.pdf.object_id| when pdfmanagement is loaded.
5600 % But as \pkg{fp} package does not accept an option, we do not append the date option.
5601 % \begin{macrocode}
5602 \NeedsTeXFormat{LaTeX2e}
5603 \ProvidesPackage{luamplib}
5604 [2026/05/26 v2.41.3 mplib package for LuaTeX]
5605 \fi
5606 \ifdefined\newluafunction\else
5607 \input ltluatex
5608 \fi
5609 % \end{macrocode}
5610 %
5611 % In DVI mode, a new XObject (mppattern, mplibgroup) must be encapsulated in an \cs{hbox}.
5612 % But this should not affect typesetting. So we use Hook mechanism provided by \LaTeX\ kernel.
5613 % In Plain, \pkg{atbegshi.sty} is loaded.
5614 % \begin{macrocode}
5615 \ifnum\outputmode=0
5616 \ifdefined\AddToHookNext
5617 \def\luamplibatnextshipout{\AddToHookNext{shipout/background}}
5618 \def\luamplibatfirstshipout{\AddToHook{shipout/firstpage}}
5619 \def\luamplibateveryshipout{\AddToHook{shipout/background}}
5620 \else
5621 \input atbegshi.sty
5622 \def\luamplibatnextshipout#1{\AtBeginShipoutNext{\AtBeginShipoutAddToBox{#1}}}
5623 \let\luamplibatfirstshipout\AtBeginShipoutFirst
5624 \def\luamplibateveryshipout#1{\AtBeginShipout{\AtBeginShipoutAddToBox{#1}}}
5625 \fi
5626 \fi
5627 % \end{macrocode}
5628 %
5629 % Loading of lua code.
5630 % \begin{macrocode}
5631 \directlua{require("luamplib")}
5632 % \end{macrocode}
5633 %
5634 % legacy commands. Seems we don't need it, but no harm.
5635 % \begin{macrocode}
5636 \ifx\pdfoutput\undefined
5637 \let\pdfoutput\outputmode
5638 \fi
5639 \ifx\pdfliteral\undefined
5640 \protected\def\pdfliteral{\pdfextension literal}
5641 \fi
5642 % \end{macrocode}
5643 %
5644 % Set the format for \metapost.
5645 % \begin{macrocode}
5646 \def\mplibsetformat#1{\directlua{luamplib.setformat("#1")}}
5647 % \end{macrocode}
5648 %
5649 % luamplib works in both PDF and DVI mode,
5650 % but only DVIPDFMx is supported currently among a number of DVI tools.
5651 % So we output a info.
5652 % \begin{macrocode}
5653 \ifnum\pdfoutput>0
5654 \let\mplibtoPDF\pdfliteral
5655 \else
5656 \def\mplibtoPDF#1{\special{pdf:literal direct #1}}
5657 \ifcsname PackageInfo\endcsname
5658 \PackageInfo{luamplib}{only dvipdfmx is supported currently}
5659 \else
5660 \immediate\write-1{luamplib Info: only dvipdfmx is supported currently}
5661 \fi
5662 \fi
5663 % \end{macrocode}
5664 %
5665 % To make |mplibcode| typeset always in horizontal mode.
5666 % \begin{macrocode}
5667 \def\mplibforcehmode{\let\prependtomplibbox\leavevmode}
5668 \def\mplibnoforcehmode{\let\prependtomplibbox\relax}
5669 \mplibnoforcehmode
5670 % \end{macrocode}
5671 %
5672 % Catcode. We want to allow comment sign in |mplibcode|.
5673 % \begin{macrocode}
5674 \def\mplibsetupcatcodes{%
5675 %catcode`\{=12 %catcode`\}=12
5676 \catcode`\#=12 \catcode`\^=12 \catcode`\~=12 \catcode`\_=12
5677 \catcode`\&=12 \catcode`\$=12 \catcode`\%=12 \catcode`\^^M=12
5678 }
5679 % \end{macrocode}
5680 %
5681 % Make |btex...etex| box zero-metric. Plus address the issue \#189.
5682 % |bdir 0| seems to be redundant, but no harm.
5683 % \begin{macrocode}
5684 \ifnum\outputmode>0 %
5685 \def\mplibputtextbox#1#2#3#4{%
5686 \pdfextension save\relax
5687 \vbox to 0pt{\vss
5688 \hbox bdir0 to 0pt{\kern#2bp\pdfextension setmatrix{#4}\raise\dp#1\copy#1\hss}%
5689 \kern#3bp}%
5690 \pdfextension restore\relax}
5691 \else
5692 \def\mplibputtextbox#1#2#3#4{%
5693 \special{pdf:btrans matrix #4 #2 #3}%
5694 \vbox to 0pt{\vss\hbox bdir0 to 0pt{\raise\dp#1\copy#1\hss}}%
5695 \special{pdf:etrans}}
5696 \fi
5697 % \end{macrocode}
5698 %
5699 % use Transparency Group
5700 % \begin{macrocode}
5701 \protected\def\usemplibgroup#1#{\usemplibgroupmain}
5702 \def\usemplibgroupmain#1{%
5703 \prependtomplibbox\hbox dir TLT\bgroup
5704 \csname luamplib.group.#1\endcsname
5705 \egroup
5706 }
5707 \protected\def\mplibgroup#1{%
5708 \begingroup
5709 \def\MPllx{0}\def\MPlly{0}%
5710 \def\mplibgroupname{#1}%
5711 \mplibgroupgetnexttok
5712 }
5713 \def\mplibgroupgetnexttok{\futurelet\nexttok\mplibgroupbranch}
5714 \def\mplibgroupskipspace{\afterassignment\mplibgroupgetnexttok\let\nexttok= }
5715 \def\mplibgroupbranch{%
5716 \ifx [\nexttok
5717 \expandafter\mplibgroupopts
5718 \else
5719 \ifx\mplibsptoken\nexttok
5720 \expandafter\expandafter\expandafter\mplibgroupskipspace
5721 \else
5722 \let\mplibgroupoptions\empty
5723 \expandafter\expandafter\expandafter\mplibgroupmain
5724 \fi
5725 \fi
5726 }
5727 \def\mplibgroupopts[#1]{\def\mplibgroupoptions{#1}\mplibgroupmain}
5728 \def\mplibgroupmain{\setbox\mplibscratchbox\hbox\bgroup\ignorespaces}
5729 \protected\def\endmplibgroup{\egroup
5730 \directlua{ luamplib.registergroup(
5731 \the\mplibscratchbox, '\mplibgroupname', {\mplibgroupoptions}
5732 )}%
5733 \endgroup
5734 }
5735 % \end{macrocode}
5736 %
5737 % Patterns
5738 % \begin{macrocode}
5739 {\def\:{\global\let\mplibsptoken= } \: }
5740 \protected\def\mppattern#1{%
5741 \begingroup
5742 \def\MPllx{0}\def\MPlly{0}%
5743 \def\mplibpatternname{#1}%
5744 \mplibpatterngetnexttok
5745 }
5746 \def\mplibpatterngetnexttok{\futurelet\nexttok\mplibpatternbranch}
5747 \def\mplibpatternskipspace{\afterassignment\mplibpatterngetnexttok\let\nexttok= }
5748 \def\mplibpatternbranch{%
5749 \ifx [\nexttok
5750 \expandafter\mplibpatternopts
5751 \else
5752 \ifx\mplibsptoken\nexttok
5753 \expandafter\expandafter\expandafter\mplibpatternskipspace
5754 \else
5755 \let\mplibpatternoptions\empty
5756 \expandafter\expandafter\expandafter\mplibpatternmain
5757 \fi
5758 \fi
5759 }
5760 \def\mplibpatternopts[#1]{%
5761 \def\mplibpatternoptions{#1}%
5762 \mplibpatternmain
5763 }
5764 \def\mplibpatternmain{%
5765 \setbox\mplibscratchbox\hbox\bgroup\ignorespaces
5766 }
5767 \protected\def\endmppattern{%
5768 \egroup
5769 \directlua{ luamplib.registerpattern(
5770 \the\mplibscratchbox, '\mplibpatternname', {\mplibpatternoptions}
5771 )}%
5772 \endgroup
5773 }
5774 % \end{macrocode}
5775 %
5776 % simple way to use \mplib:
5777 % |\mpfig draw fullcircle scaled 10; \endmpfig|
5778 % \begin{macrocode}
5779 \def\mpfiginstancename{@mpfig}
5780 \protected\def\mpfig{%
5781 \begingroup
5782 \futurelet\nexttok\mplibmpfigbranch
5783 }
5784 \def\mplibmpfigbranch{%
5785 \ifx *\nexttok
5786 \expandafter\mplibprempfig
5787 \else
5788 \ifx [\nexttok
5789 \expandafter\expandafter\expandafter\mplibgobbleoptsmpfig
5790 \else
5791 \expandafter\expandafter\expandafter\mplibmainmpfig
5792 \fi
5793 \fi
5794 }
5795 \def\mplibgobbleoptsmpfig[#1]{\mplibmainmpfig}
5796 \def\mplibmainmpfig{%
5797 \begingroup
5798 \mplibsetupcatcodes
5799 \mplibdomainmpfig
5800 }
5801 \long\def\mplibdomainmpfig#1\endmpfig{%
5802 \endgroup
5803 \directlua{
5804 local legacy = luamplib.legacyverbatimtex
5805 local everympfig = luamplib.everymplib["\mpfiginstancename"] or ""
5806 local everyendmpfig = luamplib.everyendmplib["\mpfiginstancename"] or ""
5807 luamplib.legacyverbatimtex = false
5808 luamplib.everymplib["\mpfiginstancename"] = ""
5809 luamplib.everyendmplib["\mpfiginstancename"] = ""
5810 luamplib.process_mplibcode(
5811 "beginfig(0) "..everympfig.." "..[===[\unexpanded{#1}]===].." "..everyendmpfig.." endfig;",
5812 "\mpfiginstancename")
5813 luamplib.legacyverbatimtex = legacy
5814 luamplib.everymplib["\mpfiginstancename"] = everympfig
5815 luamplib.everyendmplib["\mpfiginstancename"] = everyendmpfig
5816 }%
5817 \endgroup
5818 }
5819 \def\mplibprempfig#1{%
5820 \begingroup
5821 \mplibsetupcatcodes
5822 \mplibdoprempfig
5823 }
5824 \long\def\mplibdoprempfig#1\endmpfig{%
5825 \endgroup
5826 \directlua{
5827 local legacy = luamplib.legacyverbatimtex
5828 local everympfig = luamplib.everymplib["\mpfiginstancename"]
5829 local everyendmpfig = luamplib.everyendmplib["\mpfiginstancename"]
5830 luamplib.legacyverbatimtex = false
5831 luamplib.everymplib["\mpfiginstancename"] = ""
5832 luamplib.everyendmplib["\mpfiginstancename"] = ""
5833 luamplib.process_mplibcode([===[\unexpanded{#1}]===],"\mpfiginstancename")
5834 luamplib.legacyverbatimtex = legacy
5835 luamplib.everymplib["\mpfiginstancename"] = everympfig
5836 luamplib.everyendmplib["\mpfiginstancename"] = everyendmpfig
5837 }%
5838 \endgroup
5839 }
5840 \protected\def\endmpfig{endmpfig}
5841 % \end{macrocode}
5842 %
5843 % The Plain-specific stuff.
5844 % \begin{macrocode}
5845 \unless\ifcsname [email protected]\endcsname
5846 \def\mplibcodegetinstancename[#1]{\xdef\currentmpinstancename{#1}\mplibcodeindeed}
5847 \protected\def\mplibcode{%
5848 \begingroup
5849 \futurelet\nexttok\mplibcodebranch
5850 }
5851 \def\mplibcodebranch{%
5852 \ifx [\nexttok
5853 \expandafter\mplibcodegetinstancename
5854 \else
5855 \global\let\currentmpinstancename\empty
5856 \expandafter\mplibcodeindeed
5857 \fi
5858 }
5859 \def\mplibcodeindeed{%
5860 \begingroup
5861 \mplibsetupcatcodes
5862 \mplibdocode
5863 }
5864 \long\def\mplibdocode#1\endmplibcode{%
5865 \endgroup
5866 \directlua{luamplib.process_mplibcode([===[\unexpanded{#1}]===],"\currentmpinstancename")}%
5867 \endgroup
5868 }
5869 \protected\def\endmplibcode{endmplibcode}
5870 \else
5871 % \end{macrocode}
5872 %
5873 % The \LaTeX-specific part: a new environment.
5874 % \begin{macrocode}
5875 \newenvironment{mplibcode}[1][]{%
5876 \xdef\currentmpinstancename{#1}%
5877 \mplibtmptoks{}\ltxdomplibcode
5878 }{}
5879 \def\ltxdomplibcode{%
5880 \begingroup
5881 \mplibsetupcatcodes
5882 \ltxdomplibcodeindeed
5883 }
5884 \def\mplib@mplibcode{mplibcode}
5885 \long\def\ltxdomplibcodeindeed#1\end#2{%
5886 \endgroup
5887 \mplibtmptoks\expandafter{\the\mplibtmptoks#1}%
5888 \def\mplibtemp@a{#2}%
5889 \ifx\mplib@mplibcode\mplibtemp@a
5890 \directlua{luamplib.process_mplibcode([===[\the\mplibtmptoks]===],"\currentmpinstancename")}%
5891 \end{mplibcode}%
5892 \else
5893 \mplibtmptoks\expandafter{\the\mplibtmptoks\end{#2}}%
5894 \expandafter\ltxdomplibcode
5895 \fi
5896 }
5897 \fi
5898 % \end{macrocode}
5899 %
5900 % User settings.
5901 % \begin{macrocode}
5902 \def\mplibshowlog#1{\directlua{
5903 local s = string.lower("#1")
5904 if s == "enable" or s == "true" or s == "yes" then
5905 luamplib.showlog = true
5906 else
5907 luamplib.showlog = false
5908 end
5909 }}
5910 \def\mpliblegacybehavior#1{\directlua{
5911 local s = string.lower("#1")
5912 if s == "enable" or s == "true" or s == "yes" then
5913 luamplib.legacyverbatimtex = true
5914 else
5915 luamplib.legacyverbatimtex = false
5916 end
5917 }}
5918 \def\mplibverbatim#1{\directlua{
5919 local s = string.lower("#1")
5920 if s == "enable" or s == "true" or s == "yes" then
5921 luamplib.verbatiminput = true
5922 else
5923 luamplib.verbatiminput = false
5924 end
5925 }}
5926 \newtoks\mplibtmptoks
5927 % \end{macrocode}
5928 %
5929 % \cs{everymplib} \& \cs{everyendmplib}: macros resetting
5930 % |luamplib.every(end)mplib| tables
5931 %
5932 % \begin{macrocode}
5933 \ifcsname [email protected]\endcsname
5934 \protected\def\everymplib{%
5935 \begingroup
5936 \mplibsetupcatcodes
5937 \mplibdoeverymplib
5938 }
5939 \protected\def\everyendmplib{%
5940 \begingroup
5941 \mplibsetupcatcodes
5942 \mplibdoeveryendmplib
5943 }
5944 \newcommand\mplibdoeverymplib[2][]{%
5945 \endgroup
5946 \directlua{
5947 luamplib.everymplib["#1"] = [===[\unexpanded{#2}]===]
5948 }%
5949 }
5950 \newcommand\mplibdoeveryendmplib[2][]{%
5951 \endgroup
5952 \directlua{
5953 luamplib.everyendmplib["#1"] = [===[\unexpanded{#2}]===]
5954 }%
5955 }
5956 \else
5957 \def\mplibgetinstancename[#1]{\def\currentmpinstancename{#1}}
5958 \protected\def\everymplib#1#{%
5959 \ifx\empty#1\empty \mplibgetinstancename[]\else \mplibgetinstancename#1\fi
5960 \begingroup
5961 \mplibsetupcatcodes
5962 \mplibdoeverymplib
5963 }
5964 \long\def\mplibdoeverymplib#1{%
5965 \endgroup
5966 \directlua{
5967 luamplib.everymplib["\currentmpinstancename"] = [===[\unexpanded{#1}]===]
5968 }%
5969 }
5970 \protected\def\everyendmplib#1#{%
5971 \ifx\empty#1\empty \mplibgetinstancename[]\else \mplibgetinstancename#1\fi
5972 \begingroup
5973 \mplibsetupcatcodes
5974 \mplibdoeveryendmplib
5975 }
5976 \long\def\mplibdoeveryendmplib#1{%
5977 \endgroup
5978 \directlua{
5979 luamplib.everyendmplib["\currentmpinstancename"] = [===[\unexpanded{#1}]===]
5980 }%
5981 }
5982 \fi
5983 % \end{macrocode}
5984 %
5985 % \TeX\ macros for dimen/color
5986 % \begin{macrocode}
5987 \def\mpdim#1{ runscript("luamplibdimen{#1}") }
5988 \def\mpcolor#1#{\domplibcolor{#1}}
5989 \def\domplibcolor#1#2{ runscript("luamplibcolor{#1{#2}}") }
5990 % \end{macrocode}
5991 %
5992 % \mplib's number system. Now |binary| has gone away.
5993 % \begin{macrocode}
5994 \def\mplibnumbersystem#1{\directlua{
5995 local t = "#1"
5996 if t == "binary" then t = "decimal" end
5997 luamplib.numbersystem = t
5998 }}
5999 % \end{macrocode}
6000 %
6001 % Settings for |.mp| cache files.
6002 % \begin{macrocode}
6003 \def\mplibmakenocache#1{\mplibdomakenocache #1,\stop,}
6004 \def\mplibdomakenocache#1,{%
6005 \ifx\empty#1\empty
6006 \expandafter\mplibdomakenocache
6007 \else
6008 \ifx\stop#1\else
6009 \directlua{luamplib.noneedtoreplace["#1.mp"]=true}%
6010 \expandafter\expandafter\expandafter\mplibdomakenocache
6011 \fi
6012 \fi
6013 }
6014 \def\mplibcancelnocache#1{\mplibdocancelnocache #1,\stop,}
6015 \def\mplibdocancelnocache#1,{%
6016 \ifx\empty#1\empty
6017 \expandafter\mplibdocancelnocache
6018 \else
6019 \ifx\stop#1\else
6020 \directlua{luamplib.noneedtoreplace["#1.mp"]=false}%
6021 \expandafter\expandafter\expandafter\mplibdocancelnocache
6022 \fi
6023 \fi
6024 }
6025 \def\mplibcachedir#1{\directlua{luamplib.getcachedir("\unexpanded{#1}")}}
6026 % \end{macrocode}
6027 %
6028 % More user settings.
6029 % \begin{macrocode}
6030 \def\mplibtextextlabel#1{\directlua{
6031 local s = string.lower("#1")
6032 if s == "enable" or s == "true" or s == "yes" then
6033 luamplib.textextlabel = true
6034 else
6035 luamplib.textextlabel = false
6036 end
6037 }}
6038 \def\mplibcodeinherit#1{\directlua{
6039 local s = string.lower("#1")
6040 if s == "enable" or s == "true" or s == "yes" then
6041 luamplib.codeinherit = true
6042 else
6043 luamplib.codeinherit = false
6044 end
6045 }}
6046 \def\mplibglobaltextext#1{\directlua{
6047 local s = string.lower("#1")
6048 if s == "enable" or s == "true" or s == "yes" then
6049 luamplib.globaltextext = true
6050 else
6051 luamplib.globaltextext = false
6052 end
6053 }}
6054 % \end{macrocode}
6055 %
6056 % The followings are from \ConTeXt general, mostly.
6057 %
6058 % We use a dedicated scratchbox.
6059 % \begin{macrocode}
6060 \ifx\mplibscratchbox\undefined \newbox\mplibscratchbox \fi
6061 % \end{macrocode}
6062 %
6063 % We encapsulate the literals.
6064 % \begin{macrocode}
6065 \def\mplibstarttoPDF#1#2#3#4{%
6066 \prependtomplibbox
6067 \hbox dir TLT\bgroup
6068 \xdef\MPllx{#1}\xdef\MPlly{#2}%
6069 \xdef\MPurx{#3}\xdef\MPury{#4}%
6070 \xdef\MPwidth{\the\dimexpr#3bp-#1bp\relax}%
6071 \xdef\MPheight{\the\dimexpr#4bp-#2bp\relax}%
6072 \parskip0pt%
6073 \leftskip0pt%
6074 \parindent0pt%
6075 \everypar{}%
6076 \setbox\mplibscratchbox\vbox\bgroup
6077 \noindent
6078 }
6079 \def\mplibstoptoPDF{%
6080 \par
6081 \egroup %
6082 \setbox\mplibscratchbox\hbox %
6083 {\hskip-\MPllx bp%
6084 \raise-\MPlly bp%
6085 \box\mplibscratchbox}%
6086 \setbox\mplibscratchbox\vbox to \MPheight
6087 {\vfill
6088 \hsize\MPwidth
6089 \wd\mplibscratchbox0pt%
6090 \ht\mplibscratchbox0pt%
6091 \dp\mplibscratchbox0pt%
6092 \box\mplibscratchbox}%
6093 \wd\mplibscratchbox\MPwidth
6094 \ht\mplibscratchbox\MPheight
6095 \box\mplibscratchbox
6096 \egroup
6097 }
6098 % \end{macrocode}
6099 %
6100 % Text items have a special handler.
6101 % \begin{macrocode}
6102 \def\mplibtextext#1#2#3#4#5{%
6103 \begingroup
6104 \setbox\mplibscratchbox\hbox
6105 {\font\temp=#1 at #2bp%
6106 \temp
6107 #3}%
6108 \setbox\mplibscratchbox\hbox
6109 {\hskip#4 bp%
6110 \raise#5 bp%
6111 \box\mplibscratchbox}%
6112 \wd\mplibscratchbox0pt%
6113 \ht\mplibscratchbox0pt%
6114 \dp\mplibscratchbox0pt%
6115 \box\mplibscratchbox
6116 \endgroup
6117 }
6118 % \end{macrocode}
6119 %
6120 % Input |luamplib.cfg| when it exists.
6121 % \begin{macrocode}
6122 \openin0=luamplib.cfg
6123 \ifeof0 \else
6124 \closein0
6125 \input luamplib.cfg
6126 \fi
6127 % \end{macrocode}
6128 %
6129 % Code for \pkg{tagpdf}
6130 % \begin{macrocode}
6131 \def\luamplibtagtextboxset#1#2{#2}
6132 \let\luamplibnotagtextboxset\luamplibtagtextboxset
6133 \let\luamplibtagasgroupset\relax
6134 \let\luamplibtagasgroupput\luamplibtagtextboxset
6135 \ifcsname SuspendTagging\endcsname\else\endinput\fi
6136 \ifcsname [email protected]\endcsname \else
6137 \ExplSyntaxOn
6138 \keys_define:nn{luamplib/tagging}
6139 {
6140 ,alt .code:n = { }
6141 ,actualtext .code:n = { }
6142 ,artifact .code:n = { }
6143 ,text .code:n = { }
6144 ,off .code:n = { }
6145 ,tag .code:n = { }
6146 ,adjust-BBox .code:n = { }
6147 ,tagging-setup .code:n = { }
6148 ,instance .code:n = { \tl_gset:Nn \currentmpinstancename {#1} }
6149 ,instancename .meta:n = { instance = {#1} }
6150 ,unknown .code:n = { \tl_gset:NV \currentmpinstancename \l_keys_key_str }
6151 }
6152 \RenewDocumentCommand\mplibcode{O{}}
6153 {
6154 \tl_gclear:N \currentmpinstancename
6155 \keys_set:ne{luamplib/tagging}{#1}
6156 \mplibtmptoks{}\ltxdomplibcode
6157 }
6158 \cs_set_eq:NN \mplibalttext \use_none:n
6159 \cs_set_eq:NN \mplibactualtext \use_none:n
6160 % \end{macrocode}
6161 % 2025/12/05:
6162 % |\begin{center}\mpfig ...\endmpfig\end{center}| raises an Error!
6163 % as we issue |\everypar{}| before flushing literals out.
6164 % It is related to \cs{partokencontext=2} recently introduced by \LaTeX.
6165 % Why we used |vbox| initially? where |hbox| seems to be sufficient. Anyway,
6166 % among various solutions including |\partokencontext\z@|, |\let\par\@@par|, and \cs{endgraf},
6167 % we here attempt to address the issue by adding the following line,
6168 % which \LaTeX's \cs{everypar} should have done.
6169 % \begin{macrocode}
6170 \tl_put_left:Nn \mplibstoptoPDF \@newlistfalse
6171 \ExplSyntaxOff
6172 \endinput\fi
6173 \ExplSyntaxOn
6174 \tl_new:N \l__luamplib_tag_envname_tl
6175 \tl_new:N \l__luamplib_tag_alt_tl
6176 \tl_new:N \l__luamplib_tag_alt_dflt_tl
6177 \tl_new:N \l__luamplib_tag_actual_tl
6178 \tl_new:N \l__luamplib_tag_struct_tl
6179 \tl_set:Nn\l__luamplib_tag_struct_tl {Figure}
6180 \bool_new:N \l__luamplib_tag_usetext_bool
6181 \bool_new:N \l__luamplib_tag_bboxcorr_bool
6182 \seq_new:N \l__luamplib_tag_bboxcorr_seq
6183 \tl_new:N \l__luamplib_tag_bbox_draw_tl
6184 \tl_new:N \l__luamplib_BBox_llx_tl
6185 \tl_new:N \l__luamplib_BBox_lly_tl
6186 \tl_new:N \l__luamplib_BBox_urx_tl
6187 \tl_new:N \l__luamplib_BBox_ury_tl
6188 \msg_new:nnn {luamplib}{figure-text-reuse}
6189 {
6190 tex-text~box~#1~probably~is~incorrectly~tagged.~
6191 Reusing~a~box~in~text~mode~is~strongly~discouraged.~
6192 Check~the~resulting~PDF.
6193 }
6194 \msg_new:nnn {luamplib}{mplibgroup-text-mode}
6195 {
6196 mplibgroup~'#1'~probably~is~incorrectly~tagged.~
6197 Using~mplibgroup~with~text~mode~is~not~recommended.~
6198 Check~the~resulting~PDF.
6199 }
6200 \msg_new:nnn{luamplib}{alt-text-missing}
6201 {
6202 Alternate~text~for~#1~is~missing.~
6203 Using~the~default~value~'#2'~instead.
6204 }
6205 % \end{macrocode}
6206 % Sockets for tex-text boxes.
6207 % \begin{macrocode}
6208 \socket_new:nn{tagsupport/luamplib/textext/set}{2}
6209 \socket_new:nn{tagsupport/luamplib/textext/put}{2}
6210 \socket_new_plug:nnn{tagsupport/luamplib/textext/set}{default}
6211 {
6212 % \end{macrocode}
6213 % TODO: we check |text| mode here.
6214 % If we tag text boxes for all modes, we will get a lot of structure-has-no-parent warning;
6215 % no good-looking, though it seems to be no harm.
6216 % \begin{macrocode}
6217 \bool_if:NTF \l__luamplib_tag_usetext_bool
6218 {
6219 \tag_mc_end_push:
6220 \tag_struct_begin:n{tag=NonStruct, stash, parent-tag=text}
6221 \cs_gset_nopar:cpe {luamplib.taggedbox.#1} {\tag_get:n{struct_num}}
6222 % \end{macrocode}
6223 % TODO: We force an MC. Otherwise |a| and |b| in |btex a $x$ b etex| are not tagged.
6224 % \begin{macrocode}
6225 \tag_mc_begin:n{tag=text}
6226 #2
6227 \tag_mc_end:
6228 \tag_struct_end:
6229 \tag_mc_begin_pop:n{}
6230 }
6231 {
6232 \tag_suspend:n{\luamplibtagtextboxset}
6233 #2
6234 \tag_resume:n{\luamplibtagtextboxset}
6235 }
6236 }
6237 \socket_new_plug:nnn{tagsupport/luamplib/textext/put}{default}
6238 {
6239 \bool_lazy_and:nnTF
6240 { \l__luamplib_tag_usetext_bool }
6241 { \cs_if_free_p:c {luamplib.notaggedbox.#1} }
6242 {
6243 \tag_resume:n{\mplibputtextbox}
6244 \tag_mc_end:
6245 \cs_if_exist:cTF {luamplib.taggedbox.#1}
6246 {
6247 \exp_args:Nc \tag_struct_use_num:n {luamplib.taggedbox.#1}
6248 #2
6249 \cs_undefine:c {luamplib.taggedbox.#1}
6250 }
6251 {
6252 \msg_warning:nnn{luamplib}{figure-text-reuse}{#1}
6253 \tag_mc_begin:n{}
6254 \int_set:Nn \l_tmpa_int {#1}
6255 \tag_mc_reset_box:N \l_tmpa_int
6256 #2
6257 \tag_mc_end:
6258 }
6259 \tag_mc_begin:n{artifact}
6260 }
6261 {
6262 \int_set:Nn \l_tmpa_int {#1}
6263 \tag_mc_reset_box:N \l_tmpa_int
6264 #2
6265 }
6266 }
6267 \socket_assign_plug:nn{tagsupport/luamplib/textext/set}{default}
6268 \socket_assign_plug:nn{tagsupport/luamplib/textext/put}{default}
6269 \cs_set_nopar:Npn \luamplibtagtextboxset
6270 {
6271 \tag_socket_use:nnn{luamplib/textext/set}
6272 }
6273 % \end{macrocode}
6274 % For tex-text boxes starting with |[taggingoff]|, which we will not tag at all.
6275 % They will be just in the artifact MC-chunks.
6276 % \begin{macrocode}
6277 \cs_set_nopar:Npn \luamplibnotagtextboxset #1 #2
6278 {
6279 \bool_set_eq:NN \l_tmpa_bool \l__luamplib_tag_usetext_bool
6280 \bool_set_false:N \l__luamplib_tag_usetext_bool
6281 \tag_socket_use:nnn{luamplib/textext/set}{#1}{#2}
6282 \cs_gset_nopar:cpn {luamplib.notaggedbox.#1}{#1}
6283 \bool_set_eq:NN \l__luamplib_tag_usetext_bool \l_tmpa_bool
6284 }
6285 \sys_if_output_pdf:TF
6286 {
6287 \cs_set_nopar:Npn \mplibputtextbox #1 #2 #3 #4
6288 {
6289 \pdfextension save\relax
6290 \vbox to 0pt{\vss
6291 \hbox bdir0 to 0pt{\kern #2bp \pdfextension setmatrix {#4}
6292 \socket_use:nnn{tagsupport/luamplib/textext/put}{#1}{\raise\dp#1\copy#1}\hss}
6293 \kern #3bp}
6294 \pdfextension restore\relax
6295 }
6296 }
6297 {
6298 \cs_set_nopar:Npn \mplibputtextbox #1 #2 #3 #4
6299 {
6300 \special{pdf:btrans~matrix~#4~#2~#3}
6301 \vbox to 0pt{\vss\hbox bdir0 to 0pt{
6302 \socket_use:nnn{tagsupport/luamplib/textext/put}{#1}{\raise\dp#1\copy#1}\hss}}
6303 \special{pdf:etrans}
6304 }
6305 }
6306 % \end{macrocode}
6307 % TODO: Not sure whether asgroup/mplibgroup with |text| mode will be tagged correctly.
6308 % Probably not. At least, this will raise a warning.
6309 % \begin{macrocode}
6310 \cs_set_nopar:Npn \luamplibtagasgroupset
6311 {
6312 \bool_set_false:N \l__luamplib_tag_usetext_bool
6313 }
6314 \cs_set_nopar:Npn \luamplibtagasgroupput
6315 {
6316 \bool_if:NT \l__luamplib_tag_usetext_bool { \tag_resume:n{\luamplibtagasgroupput} }
6317 \tag_socket_use:nnn{luamplib/mplibgroup/put}
6318 }
6319 % \end{macrocode}
6320 % A socket for mplibgroup. Again, we issue a warning upon |text| mode.
6321 % \begin{macrocode}
6322 \socket_new:nn{tagsupport/luamplib/mplibgroup/put}{2}
6323 \socket_new_plug:nnn{tagsupport/luamplib/mplibgroup/put}{default}
6324 {
6325 \cs_if_free:cT {luamplib.mplibgroup.text.#1}
6326 {
6327 \msg_warning:nnn {luamplib} {mplibgroup-text-mode} {#1}
6328 \cs_gset_nopar:cpn {luamplib.mplibgroup.text.#1} {#1}
6329 }
6330 \tag_mc_end:
6331 \tag_mc_begin:n{tag=text}
6332 #2
6333 \tag_mc_end:
6334 \tag_mc_begin:n{artifact}
6335 }
6336 \socket_assign_plug:nn{tagsupport/luamplib/mplibgroup/put}{default}
6337 % \end{macrocode}
6338 % A macro for BBox attribute
6339 % \begin{macrocode}
6340 \cs_set_nopar:Npn \__luamplib_tag_bbox_attribute:n #1
6341 {
6342 \tl_set:Ne \l_tmpa_tl {luamplib.BBox.\tag_get:n{struct_num}}
6343 \tex_savepos:D
6344 \property_record:ee{\l_tmpa_tl}{xpos,ypos}
6345 \tl_set:Ne \l__luamplib_BBox_llx_tl
6346 { \dim_to_decimal_in_bp:n { \property_ref:een {\l_tmpa_tl}{xpos}{0}sp } }
6347 \tl_set:Ne \l__luamplib_BBox_lly_tl
6348 { \dim_to_decimal_in_bp:n { \property_ref:een {\l_tmpa_tl}{ypos}{0}sp - \dp#1 } }
6349 \tl_set:Ne \l__luamplib_BBox_urx_tl
6350 { \dim_to_decimal_in_bp:n { \l__luamplib_BBox_llx_tl bp + \wd#1 } }
6351 \tl_set:Ne \l__luamplib_BBox_ury_tl
6352 { \dim_to_decimal_in_bp:n { \l__luamplib_BBox_lly_tl bp + \ht#1 + \dp#1 } }
6353 \bool_if:NT \l__luamplib_tag_bboxcorr_bool
6354 {
6355 \int_zero:N \l_tmpa_int
6356 \tl_map_inline:nn
6357 {
6358 \l__luamplib_BBox_llx_tl
6359 \l__luamplib_BBox_lly_tl
6360 \l__luamplib_BBox_urx_tl
6361 \l__luamplib_BBox_ury_tl
6362 }
6363 {
6364 \int_incr:N \l_tmpa_int
6365 \tl_set:Ne ##1
6366 {
6367 \fp_eval:n
6368 {
6369 ##1
6370 +
6371 \dim_to_decimal_in_bp:n { \seq_item:NV \l__luamplib_tag_bboxcorr_seq \l_tmpa_int }
6372 }
6373 }
6374 }
6375 }
6376 \tag_struct_gput:ene {\tag_get:n{struct_num}} {attribute}
6377 {
6378 /O /Layout /BBox [
6379 \l__luamplib_BBox_llx_tl\c_space_tl
6380 \l__luamplib_BBox_lly_tl\c_space_tl
6381 \l__luamplib_BBox_urx_tl\c_space_tl
6382 \l__luamplib_BBox_ury_tl
6383 ]
6384 }
6385 \bool_if:NT \l__tag_graphic_debug_bool
6386 {
6387 \iow_log:e
6388 {
6389 luamplib/tagging~debug:~BBox~of~structure~\tag_get:n{struct_num}~is~
6390 \l__luamplib_BBox_llx_tl\c_space_tl
6391 \l__luamplib_BBox_lly_tl\c_space_tl
6392 \l__luamplib_BBox_urx_tl\c_space_tl
6393 \l__luamplib_BBox_ury_tl
6394 }
6395 \sys_if_output_pdf:TF
6396 {
6397 \tl_set:Ne \l__luamplib_tag_bbox_draw_tl
6398 {
6399 \pdfextension save\relax
6400 \opacity_select:n{0.5} \color_select:n{red}
6401 \pdfextension literal~text
6402 {
6403 \l__luamplib_BBox_llx_tl\c_space_tl
6404 \l__luamplib_BBox_lly_tl\c_space_tl
6405 \fp_eval:n { \l__luamplib_BBox_urx_tl - \l__luamplib_BBox_llx_tl }~
6406 \fp_eval:n { \l__luamplib_BBox_ury_tl - \l__luamplib_BBox_lly_tl }~
6407 re~f
6408 }
6409 \pdfextension restore\relax
6410 }
6411 }
6412 {
6413 \tl_set:Ne \l__luamplib_tag_bbox_draw_tl
6414 {
6415 \special{pdf:bcontent}
6416 \opacity_select:n{0.5} \color_select:n{red}
6417 \special{pdf:code~
6418 1~0~0~1~
6419 -\dim_to_decimal_in_bp:n { \property_ref:een{\l_tmpa_tl}{xpos}{0}sp + \wd#1 }~
6420 -\dim_to_decimal_in_bp:n { \property_ref:een{\l_tmpa_tl}{ypos}{0}sp }~
6421 cm
6422 }
6423 \special{pdf:code~
6424 \l__luamplib_BBox_llx_tl\c_space_tl
6425 \l__luamplib_BBox_lly_tl\c_space_tl
6426 \fp_eval:n { \l__luamplib_BBox_urx_tl - \l__luamplib_BBox_llx_tl }~
6427 \fp_eval:n { \l__luamplib_BBox_ury_tl - \l__luamplib_BBox_lly_tl }~
6428 re~f
6429 }
6430 \special{pdf:econtent}
6431 }
6432 }
6433 }
6434 }
6435 % \end{macrocode}
6436 % Sockets for main process
6437 % \begin{macrocode}
6438 \socket_new:nn{tagsupport/luamplib/figure/begin}{1}
6439 \socket_new:nn{tagsupport/luamplib/figure/end}{2}
6440 \socket_new_plug:nnn{tagsupport/luamplib/figure/end}{transparent}{#2}
6441 \socket_new_plug:nnn{tagsupport/luamplib/figure/begin}{alt}
6442 {
6443 \tag_mc_end_push:
6444 \tl_if_empty:NT\l__luamplib_tag_alt_tl
6445 {
6446 \tl_if_empty:eTF{#1}
6447 { \tl_set:Nn \l__luamplib_tag_alt_tl {metapost~figure} }
6448 { \tl_set:Ne \l__luamplib_tag_alt_tl {metapost~figure~\text_purify:n{#1}} }
6449 \msg_warning:nnVV{luamplib}{alt-text-missing}
6450 \l__luamplib_tag_envname_tl \l__luamplib_tag_alt_tl
6451 }
6452 \tag_struct_begin:n
6453 {
6454 tag=\l__luamplib_tag_struct_tl,
6455 alt=\l__luamplib_tag_alt_tl,
6456 }
6457 \tag_mc_begin:n{}
6458 }
6459 \socket_new_plug:nnn{tagsupport/luamplib/figure/end}{alt}
6460 {
6461 \__luamplib_tag_bbox_attribute:n {#1}
6462 #2
6463 \tl_use:N \l__luamplib_tag_bbox_draw_tl
6464 \tag_mc_end:
6465 \tag_struct_end:
6466 \tag_mc_begin_pop:n{}
6467 }
6468 \socket_new_plug:nnn{tagsupport/luamplib/figure/begin}{actualtext}
6469 {
6470 \tag_mc_end_push:
6471 \tag_struct_begin:n
6472 {
6473 tag=Span,
6474 actualtext=\l__luamplib_tag_actual_tl,
6475 }
6476 \tag_mc_begin:n{}
6477 }
6478 \socket_new_plug:nnn{tagsupport/luamplib/figure/end}{actualtext}
6479 {
6480 #2
6481 \tag_mc_end:
6482 \tag_struct_end:
6483 \tag_mc_begin_pop:n{}
6484 }
6485 \socket_new_plug:nnn{tagsupport/luamplib/figure/begin}{artifact}
6486 {
6487 \tag_mc_end_push:
6488 \tag_mc_begin:n{artifact}
6489 }
6490 \socket_new_plug:nnn{tagsupport/luamplib/figure/end}{artifact}
6491 {
6492 #2
6493 \tag_mc_end:
6494 \tag_mc_begin_pop:n{}
6495 }
6496 % \end{macrocode}
6497 % A socket for tagging init, so that we can declare
6498 % |\SetKeys[luamplib/tagging]{...}| anywhere in the document.
6499 % \begin{macrocode}
6500 \socket_new:nn{tagsupport/luamplib/figure/init}{0}
6501 \socket_new_plug:nnn{tagsupport/luamplib/figure/init}{alt}
6502 {
6503 \socket_assign_plug:nn{tagsupport/luamplib/figure/begin}{alt}
6504 \socket_assign_plug:nn{tagsupport/luamplib/figure/end}{alt}
6505 }
6506 \socket_new_plug:nnn{tagsupport/luamplib/figure/init}{actualtext}
6507 {
6508 \socket_assign_plug:nn{tagsupport/luamplib/figure/begin}{actualtext}
6509 \socket_assign_plug:nn{tagsupport/luamplib/figure/end}{actualtext}
6510 % \end{macrocode}
6511 % In vmode, hmode will be forced by \cs{noindent} upon |actualtext| and |text| modes.
6512 % \begin{macrocode}
6513 \prependtomplibbox \mplibnoforcehmode
6514 \mode_if_vertical:T { \noindent \aftergroup\par }
6515 }
6516 \socket_new_plug:nnn{tagsupport/luamplib/figure/init}{artifact}
6517 {
6518 \socket_assign_plug:nn{tagsupport/luamplib/figure/begin}{artifact}
6519 \socket_assign_plug:nn{tagsupport/luamplib/figure/end}{artifact}
6520 }
6521 \socket_new_plug:nnn{tagsupport/luamplib/figure/init}{text}
6522 {
6523 \bool_set_true:N \l__luamplib_tag_usetext_bool
6524 \socket_assign_plug:nn{tagsupport/luamplib/figure/begin}{artifact}
6525 \socket_assign_plug:nn{tagsupport/luamplib/figure/end}{artifact}
6526 \prependtomplibbox \mplibnoforcehmode
6527 \mode_if_vertical:T { \noindent \aftergroup\par }
6528 }
6529 \socket_new_plug:nnn{tagsupport/luamplib/figure/init}{off}
6530 {
6531 \socket_assign_plug:nn{tagsupport/luamplib/figure/begin}{noop}
6532 \socket_assign_plug:nn{tagsupport/luamplib/figure/end}{transparent}
6533 }
6534 \socket_assign_plug:nn{tagsupport/luamplib/figure/init}{alt}
6535 % \end{macrocode}
6536 % Key-value options
6537 % \begin{macrocode}
6538 \keys_define:nn{luamplib/tagging}
6539 {
6540 ,alt .code:n =
6541 {
6542 \tl_set:Ne\l__luamplib_tag_alt_tl{\text_purify:n{#1}}
6543 \socket_assign_plug:nn{tagsupport/luamplib/figure/init}{alt}
6544 }
6545 ,actualtext .code:n =
6546 {
6547 \tl_set:Ne\l__luamplib_tag_actual_tl{\text_purify:n{#1}}
6548 \socket_assign_plug:nn{tagsupport/luamplib/figure/init}{actualtext}
6549 }
6550 ,artifact .code:n = { \socket_assign_plug:nn{tagsupport/luamplib/figure/init}{artifact} }
6551 ,text .code:n = { \socket_assign_plug:nn{tagsupport/luamplib/figure/init}{text} }
6552 ,off .code:n = { \socket_assign_plug:nn{tagsupport/luamplib/figure/init}{off} }
6553 ,tag .code:n =
6554 {
6555 \str_case:nnF {#1}
6556 {
6557 {false} { \keys_set:nn {luamplib/tagging} {off} }
6558 {artifact} { \keys_set:nn {luamplib/tagging} {artifact} }
6559 }
6560 {
6561 \tl_set:Nn\l__luamplib_tag_struct_tl{#1}
6562 \socket_assign_plug:nn{tagsupport/luamplib/figure/init}{alt}
6563 }
6564 }
6565 ,adjust-BBox .code:n =
6566 {
6567 \bool_set_true:N \l__luamplib_tag_bboxcorr_bool
6568 \seq_set_split:Nnn \l__luamplib_tag_bboxcorr_seq{~}{#1~0pt~0pt~0pt~0pt}
6569 }
6570 ,tagging-setup .code:n = { \keys_set_known:nn {luamplib/tagging} {#1} }
6571 }
6572 \keys_define:nn {luamplib/instance}
6573 {
6574 ,instance .code:n = { \tl_gset:Nn \currentmpinstancename {#1} }
6575 ,instancename .meta:n = { instance = {#1} }
6576 ,unknown .code:n = { \tl_gset:NV \currentmpinstancename \l_keys_key_str }
6577 }
6578 % \end{macrocode}
6579 % Redefine our macros
6580 % \begin{macrocode}
6581 \cs_set_nopar:Npn \mplibstarttoPDF #1 #2 #3 #4
6582 {
6583 \prependtomplibbox
6584 \hbox dir~TLT\bgroup
6585 \tag_socket_use:nn{luamplib/figure/begin}\l__luamplib_tag_alt_dflt_tl
6586 \xdef\MPllx{#1}\xdef\MPlly{#2}%
6587 \xdef\MPurx{#3}\xdef\MPury{#4}%
6588 \xdef\MPwidth{\the\dimexpr#3bp-#1bp\relax}%
6589 \xdef\MPheight{\the\dimexpr#4bp-#2bp\relax}%
6590 \parskip0pt
6591 \leftskip0pt
6592 \parindent0pt
6593 \everypar{}%
6594 \setbox\mplibscratchbox\vbox\bgroup
6595 \tag_suspend:n{\mplibstarttoPDF}
6596 \noindent
6597 }
6598 \cs_set_nopar:Npn \mplibstoptoPDF
6599 {
6600 \par
6601 \egroup
6602 \setbox\mplibscratchbox\hbox
6603 {\hskip-\MPllx bp
6604 \raise-\MPlly bp
6605 \box\mplibscratchbox}%
6606 \setbox\mplibscratchbox\vbox to \MPheight
6607 {\vfill
6608 \hsize\MPwidth
6609 \wd\mplibscratchbox0pt
6610 \ht\mplibscratchbox0pt
6611 \dp\mplibscratchbox0pt
6612 \box\mplibscratchbox}%
6613 \wd\mplibscratchbox\MPwidth
6614 \ht\mplibscratchbox\MPheight
6615 \tag_socket_use:nnn{luamplib/figure/end}{\mplibscratchbox}{\box\mplibscratchbox}
6616 \egroup
6617 }
6618 \RenewDocumentCommand\mplibcode{O{}}
6619 {
6620 \tl_set:Nn \l__luamplib_tag_envname_tl {mplibcode}
6621 \tl_gclear:N \currentmpinstancename
6622 \keys_set_known:neN {luamplib/tagging} {#1} \l_tmpa_tl
6623 \keys_set:nV {luamplib/instance} \l_tmpa_tl
6624 \tl_set_eq:NN \l__luamplib_tag_alt_dflt_tl \currentmpinstancename
6625 \tag_socket_use:n{luamplib/figure/init}
6626 \mplibtmptoks{}\ltxdomplibcode
6627 }
6628 \RenewDocumentCommand\mpfig{s O{}}
6629 {
6630 \begingroup
6631 \tl_set:Nn \l__luamplib_tag_envname_tl {mpfig}
6632 \keys_set_known:ne {luamplib/tagging} {#2}
6633 \tl_set_eq:NN \l__luamplib_tag_alt_dflt_tl \mpfiginstancename
6634 \tag_socket_use:n{luamplib/figure/init}
6635 \IfBooleanTF{#1} { \mplibprempfig * }
6636 { \mplibmainmpfig }
6637 }
6638 \RenewDocumentCommand\usemplibgroup{O{} m}
6639 {
6640 \begingroup
6641 \tl_set:Nn \l__luamplib_tag_envname_tl {usemplibgroup}
6642 \keys_set_known:ne {luamplib/tagging} {#1}
6643 \tag_socket_use:n{luamplib/figure/init}
6644 \prependtomplibbox\hbox dir~TLT\bgroup
6645 \tag_socket_use:nn{luamplib/figure/begin}{#2}
6646 \setbox\mplibscratchbox\hbox\bgroup
6647 \bool_if:NF \l__luamplib_tag_usetext_bool { \tag_suspend:n{\usemplibgroup} }
6648 \tag_socket_use:nnn{luamplib/mplibgroup/put}{#2}{\csname luamplib.group.#2\endcsname}
6649 \egroup
6650 \tag_socket_use:nnn{luamplib/figure/end}{\mplibscratchbox}{\unhbox\mplibscratchbox}
6651 \egroup
6652 \endgroup
6653 }
6654 % \end{macrocode}
6655 % Allow setting alt/actual text within \metapost code.
6656 % Of course we can use them in \TeX\ code as well.
6657 % \begin{macrocode}
6658 \cs_new_nopar:Npn \mplibalttext #1
6659 {
6660 \tl_set:Ne \l__luamplib_tag_alt_tl {\text_purify:n{#1}}
6661 }
6662 \cs_new_nopar:Npn \mplibactualtext #1
6663 {
6664 \tl_set:Ne \l__luamplib_tag_actual_tl {\text_purify:n{#1}}
6665 }
6666 \ExplSyntaxOff
6667 % \end{macrocode}
6668 %
6669 % That's all folks!
6670 %
6671 % \iffalse
6672 %</package>
6673 % \fi
6674 %
6675 % \clearpage
6676 % \section{The GNU GPL License v2}
6677 %
6678 % The GPL requires the complete license text to be distributed along
6679 % with the code. I recommend the canonical source, instead:
6680 % \url{http://www.gnu.org/licenses/old-licenses/gpl-2.0.html}.
6681 % But if you insist on an included copy, here it is.
6682 % You might want to zoom in.
6683 %
6684 % \newsavebox{\gpl}
6685 % \begin{lrbox}{\gpl}
6686 % \begin{minipage}{3\textwidth}
6687 % \columnsep=3\columnsep
6688 % \begin{multicols}{3}
6689 % \begin{center}
6690 % {\Large GNU GENERAL PUBLIC LICENSE\par}
6691 % \bigskip
6692 % {Version 2, June 1991}
6693 % \end{center}
6694 %
6695 % \begin{center}
6696 % {\parindent 0in
6697 %
6698 % Copyright \textcopyright\ 1989, 1991 Free Software Foundation, Inc.
6699 %
6700 % \bigskip
6701 %
6702 % 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
6703 %
6704 % \bigskip
6705 %
6706 % Everyone is permitted to copy and distribute verbatim copies
6707 % of this license document, but changing it is not allowed.
6708 % }
6709 % \end{center}
6710 %
6711 % \begin{center}
6712 % {\bf\large Preamble}
6713 % \end{center}
6714 %
6715 %
6716 % The licenses for most software are designed to take away your freedom to
6717 % share and change it. By contrast, the GNU General Public License is
6718 % intended to guarantee your freedom to share and change free software---to
6719 % make sure the software is free for all its users. This General Public
6720 % License applies to most of the Free Software Foundation's software and to
6721 % any other program whose authors commit to using it. (Some other Free
6722 % Software Foundation software is covered by the GNU Library General Public
6723 % License instead.) You can apply it to your programs, too.
6724 %
6725 % When we speak of free software, we are referring to freedom, not price.
6726 % Our General Public Licenses are designed to make sure that you have the
6727 % freedom to distribute copies of free software (and charge for this service
6728 % if you wish), that you receive source code or can get it if you want it,
6729 % that you can change the software or use pieces of it in new free programs;
6730 % and that you know you can do these things.
6731 %
6732 % To protect your rights, we need to make restrictions that forbid anyone to
6733 % deny you these rights or to ask you to surrender the rights. These
6734 % restrictions translate to certain responsibilities for you if you
6735 % distribute copies of the software, or if you modify it.
6736 %
6737 % For example, if you distribute copies of such a program, whether gratis or
6738 % for a fee, you must give the recipients all the rights that you have. You
6739 % must make sure that they, too, receive or can get the source code. And
6740 % you must show them these terms so they know their rights.
6741 %
6742 % We protect your rights with two steps: (1) copyright the software, and (2)
6743 % offer you this license which gives you legal permission to copy,
6744 % distribute and/or modify the software.
6745 %
6746 % Also, for each author's protection and ours, we want to make certain that
6747 % everyone understands that there is no warranty for this free software. If
6748 % the software is modified by someone else and passed on, we want its
6749 % recipients to know that what they have is not the original, so that any
6750 % problems introduced by others will not reflect on the original authors'
6751 % reputations.
6752 %
6753 % Finally, any free program is threatened constantly by software patents.
6754 % We wish to avoid the danger that redistributors of a free program will
6755 % individually obtain patent licenses, in effect making the program
6756 % proprietary. To prevent this, we have made it clear that any patent must
6757 % be licensed for everyone's free use or not licensed at all.
6758 %
6759 % The precise terms and conditions for copying, distribution and
6760 % modification follow.
6761 %
6762 % \begin{center}
6763 % {\Large \sc Terms and Conditions For Copying, Distribution and
6764 % Modification}
6765 % \end{center}
6766 %
6767 % \begin{enumerate}
6768 % \item
6769 % This License applies to any program or other work which contains a notice
6770 % placed by the copyright holder saying it may be distributed under the
6771 % terms of this General Public License. The ``Program'', below, refers to
6772 % any such program or work, and a ``work based on the Program'' means either
6773 % the Program or any derivative work under copyright law: that is to say, a
6774 % work containing the Program or a portion of it, either verbatim or with
6775 % modifications and/or translated into another language. (Hereinafter,
6776 % translation is included without limitation in the term ``modification''.)
6777 % Each licensee is addressed as ``you''.
6778 %
6779 % Activities other than copying, distribution and modification are not
6780 % covered by this License; they are outside its scope. The act of
6781 % running the Program is not restricted, and the output from the Program
6782 % is covered only if its contents constitute a work based on the
6783 % Program (independent of having been made by running the Program).
6784 % Whether that is true depends on what the Program does.
6785 %
6786 % \item You may copy and distribute verbatim copies of the Program's source
6787 % code as you receive it, in any medium, provided that you conspicuously
6788 % and appropriately publish on each copy an appropriate copyright notice
6789 % and disclaimer of warranty; keep intact all the notices that refer to
6790 % this License and to the absence of any warranty; and give any other
6791 % recipients of the Program a copy of this License along with the Program.
6792 %
6793 % You may charge a fee for the physical act of transferring a copy, and you
6794 % may at your option offer warranty protection in exchange for a fee.
6795 %
6796 % \item
6797 % You may modify your copy or copies of the Program or any portion
6798 % of it, thus forming a work based on the Program, and copy and
6799 % distribute such modifications or work under the terms of Section 1
6800 % above, provided that you also meet all of these conditions:
6801 %
6802 % \begin{enumerate}
6803 %
6804 % \item
6805 % You must cause the modified files to carry prominent notices stating that
6806 % you changed the files and the date of any change.
6807 %
6808 % \item
6809 % You must cause any work that you distribute or publish, that in
6810 % whole or in part contains or is derived from the Program or any
6811 % part thereof, to be licensed as a whole at no charge to all third
6812 % parties under the terms of this License.
6813 %
6814 % \item
6815 % If the modified program normally reads commands interactively
6816 % when run, you must cause it, when started running for such
6817 % interactive use in the most ordinary way, to print or display an
6818 % announcement including an appropriate copyright notice and a
6819 % notice that there is no warranty (or else, saying that you provide
6820 % a warranty) and that users may redistribute the program under
6821 % these conditions, and telling the user how to view a copy of this
6822 % License. (Exception: if the Program itself is interactive but
6823 % does not normally print such an announcement, your work based on
6824 % the Program is not required to print an announcement.)
6825 %
6826 % \end{enumerate}
6827 %
6828 %
6829 % These requirements apply to the modified work as a whole. If
6830 % identifiable sections of that work are not derived from the Program,
6831 % and can be reasonably considered independent and separate works in
6832 % themselves, then this License, and its terms, do not apply to those
6833 % sections when you distribute them as separate works. But when you
6834 % distribute the same sections as part of a whole which is a work based
6835 % on the Program, the distribution of the whole must be on the terms of
6836 % this License, whose permissions for other licensees extend to the
6837 % entire whole, and thus to each and every part regardless of who wrote it.
6838 %
6839 % Thus, it is not the intent of this section to claim rights or contest
6840 % your rights to work written entirely by you; rather, the intent is to
6841 % exercise the right to control the distribution of derivative or
6842 % collective works based on the Program.
6843 %
6844 % In addition, mere aggregation of another work not based on the Program
6845 % with the Program (or with a work based on the Program) on a volume of
6846 % a storage or distribution medium does not bring the other work under
6847 % the scope of this License.
6848 %
6849 % \item
6850 % You may copy and distribute the Program (or a work based on it,
6851 % under Section 2) in object code or executable form under the terms of
6852 % Sections 1 and 2 above provided that you also do one of the following:
6853 %
6854 % \begin{enumerate}
6855 %
6856 % \item
6857 %
6858 % Accompany it with the complete corresponding machine-readable
6859 % source code, which must be distributed under the terms of Sections
6860 % 1 and 2 above on a medium customarily used for software interchange; or,
6861 %
6862 % \item
6863 %
6864 % Accompany it with a written offer, valid for at least three
6865 % years, to give any third party, for a charge no more than your
6866 % cost of physically performing source distribution, a complete
6867 % machine-readable copy of the corresponding source code, to be
6868 % distributed under the terms of Sections 1 and 2 above on a medium
6869 % customarily used for software interchange; or,
6870 %
6871 % \item
6872 %
6873 % Accompany it with the information you received as to the offer
6874 % to distribute corresponding source code. (This alternative is
6875 % allowed only for noncommercial distribution and only if you
6876 % received the program in object code or executable form with such
6877 % an offer, in accord with Subsection b above.)
6878 %
6879 % \end{enumerate}
6880 %
6881 %
6882 % The source code for a work means the preferred form of the work for
6883 % making modifications to it. For an executable work, complete source
6884 % code means all the source code for all modules it contains, plus any
6885 % associated interface definition files, plus the scripts used to
6886 % control compilation and installation of the executable. However, as a
6887 % special exception, the source code distributed need not include
6888 % anything that is normally distributed (in either source or binary
6889 % form) with the major components (compiler, kernel, and so on) of the
6890 % operating system on which the executable runs, unless that component
6891 % itself accompanies the executable.
6892 %
6893 % If distribution of executable or object code is made by offering
6894 % access to copy from a designated place, then offering equivalent
6895 % access to copy the source code from the same place counts as
6896 % distribution of the source code, even though third parties are not
6897 % compelled to copy the source along with the object code.
6898 %
6899 % \item
6900 % You may not copy, modify, sublicense, or distribute the Program
6901 % except as expressly provided under this License. Any attempt
6902 % otherwise to copy, modify, sublicense or distribute the Program is
6903 % void, and will automatically terminate your rights under this License.
6904 % However, parties who have received copies, or rights, from you under
6905 % this License will not have their licenses terminated so long as such
6906 % parties remain in full compliance.
6907 %
6908 % \item
6909 % You are not required to accept this License, since you have not
6910 % signed it. However, nothing else grants you permission to modify or
6911 % distribute the Program or its derivative works. These actions are
6912 % prohibited by law if you do not accept this License. Therefore, by
6913 % modifying or distributing the Program (or any work based on the
6914 % Program), you indicate your acceptance of this License to do so, and
6915 % all its terms and conditions for copying, distributing or modifying
6916 % the Program or works based on it.
6917 %
6918 % \item
6919 % Each time you redistribute the Program (or any work based on the
6920 % Program), the recipient automatically receives a license from the
6921 % original licensor to copy, distribute or modify the Program subject to
6922 % these terms and conditions. You may not impose any further
6923 % restrictions on the recipients' exercise of the rights granted herein.
6924 % You are not responsible for enforcing compliance by third parties to
6925 % this License.
6926 %
6927 % \item
6928 % If, as a consequence of a court judgment or allegation of patent
6929 % infringement or for any other reason (not limited to patent issues),
6930 % conditions are imposed on you (whether by court order, agreement or
6931 % otherwise) that contradict the conditions of this License, they do not
6932 % excuse you from the conditions of this License. If you cannot
6933 % distribute so as to satisfy simultaneously your obligations under this
6934 % License and any other pertinent obligations, then as a consequence you
6935 % may not distribute the Program at all. For example, if a patent
6936 % license would not permit royalty-free redistribution of the Program by
6937 % all those who receive copies directly or indirectly through you, then
6938 % the only way you could satisfy both it and this License would be to
6939 % refrain entirely from distribution of the Program.
6940 %
6941 % If any portion of this section is held invalid or unenforceable under
6942 % any particular circumstance, the balance of the section is intended to
6943 % apply and the section as a whole is intended to apply in other
6944 % circumstances.
6945 %
6946 % It is not the purpose of this section to induce you to infringe any
6947 % patents or other property right claims or to contest validity of any
6948 % such claims; this section has the sole purpose of protecting the
6949 % integrity of the free software distribution system, which is
6950 % implemented by public license practices. Many people have made
6951 % generous contributions to the wide range of software distributed
6952 % through that system in reliance on consistent application of that
6953 % system; it is up to the author/donor to decide if he or she is willing
6954 % to distribute software through any other system and a licensee cannot
6955 % impose that choice.
6956 %
6957 % This section is intended to make thoroughly clear what is believed to
6958 % be a consequence of the rest of this License.
6959 %
6960 % \item
6961 % If the distribution and/or use of the Program is restricted in
6962 % certain countries either by patents or by copyrighted interfaces, the
6963 % original copyright holder who places the Program under this License
6964 % may add an explicit geographical distribution limitation excluding
6965 % those countries, so that distribution is permitted only in or among
6966 % countries not thus excluded. In such case, this License incorporates
6967 % the limitation as if written in the body of this License.
6968 %
6969 % \item
6970 % The Free Software Foundation may publish revised and/or new versions
6971 % of the General Public License from time to time. Such new versions will
6972 % be similar in spirit to the present version, but may differ in detail to
6973 % address new problems or concerns.
6974 %
6975 % Each version is given a distinguishing version number. If the Program
6976 % specifies a version number of this License which applies to it and ``any
6977 % later version'', you have the option of following the terms and conditions
6978 % either of that version or of any later version published by the Free
6979 % Software Foundation. If the Program does not specify a version number of
6980 % this License, you may choose any version ever published by the Free Software
6981 % Foundation.
6982 %
6983 % \item
6984 % If you wish to incorporate parts of the Program into other free
6985 % programs whose distribution conditions are different, write to the author
6986 % to ask for permission. For software which is copyrighted by the Free
6987 % Software Foundation, write to the Free Software Foundation; we sometimes
6988 % make exceptions for this. Our decision will be guided by the two goals
6989 % of preserving the free status of all derivatives of our free software and
6990 % of promoting the sharing and reuse of software generally.
6991 %
6992 % \begin{center}
6993 % {\Large\sc
6994 % No Warranty
6995 % }
6996 % \end{center}
6997 %
6998 % \item
6999 % {\sc Because the program is licensed free of charge, there is no warranty
7000 % for the program, to the extent permitted by applicable law. Except when
7001 % otherwise stated in writing the copyright holders and/or other parties
7002 % provide the program ``as is'' without warranty of any kind, either expressed
7003 % or implied, including, but not limited to, the implied warranties of
7004 % merchantability and fitness for a particular purpose. The entire risk as
7005 % to the quality and performance of the program is with you. Should the
7006 % program prove defective, you assume the cost of all necessary servicing,
7007 % repair or correction.}
7008 %
7009 % \item
7010 % {\sc In no event unless required by applicable law or agreed to in writing
7011 % will any copyright holder, or any other party who may modify and/or
7012 % redistribute the program as permitted above, be liable to you for damages,
7013 % including any general, special, incidental or consequential damages arising
7014 % out of the use or inability to use the program (including but not limited
7015 % to loss of data or data being rendered inaccurate or losses sustained by
7016 % you or third parties or a failure of the program to operate with any other
7017 % programs), even if such holder or other party has been advised of the
7018 % possibility of such damages.}
7019 %
7020 % \end{enumerate}
7021 %
7022 %
7023 % \begin{center}
7024 % {\Large\sc End of Terms and Conditions}
7025 % \end{center}
7026 %
7027 %
7028 % \pagebreak[2]
7029 %
7030 % \section*{Appendix: How to Apply These Terms to Your New Programs}
7031 %
7032 % If you develop a new program, and you want it to be of the greatest
7033 % possible use to the public, the best way to achieve this is to make it
7034 % free software which everyone can redistribute and change under these
7035 % terms.
7036 %
7037 % To do so, attach the following notices to the program. It is safest to
7038 % attach them to the start of each source file to most effectively convey
7039 % the exclusion of warranty; and each file should have at least the
7040 % ``copyright'' line and a pointer to where the full notice is found.
7041 %
7042 % \begin{quote}
7043 % one line to give the program's name and a brief idea of what it does. \\
7044 % Copyright (C) yyyy name of author \\
7045 %
7046 % This program is free software; you can redistribute it and/or modify
7047 % it under the terms of the GNU General Public License as published by
7048 % the Free Software Foundation; either version 2 of the License, or
7049 % (at your option) any later version.
7050 %
7051 % This program is distributed in the hope that it will be useful,
7052 % but WITHOUT ANY WARRANTY; without even the implied warranty of
7053 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7054 % GNU General Public License for more details.
7055 %
7056 % You should have received a copy of the GNU General Public License
7057 % along with this program; if not, write to the Free Software
7058 % Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
7059 % \end{quote}
7060 %
7061 % Also add information on how to contact you by electronic and paper mail.
7062 %
7063 % If the program is interactive, make it output a short notice like this
7064 % when it starts in an interactive mode:
7065 %
7066 % \begin{quote}
7067 % Gnomovision version 69, Copyright (C) yyyy name of author \\
7068 % Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. \\
7069 % This is free software, and you are welcome to redistribute it
7070 % under certain conditions; type `show c' for details.
7071 % \end{quote}
7072 %
7073 %
7074 % The hypothetical commands {\tt show w} and {\tt show c} should show the
7075 % appropriate parts of the General Public License. Of course, the commands
7076 % you use may be called something other than {\tt show w} and {\tt show c};
7077 % they could even be mouse-clicks or menu items---whatever suits your
7078 % program.
7079 %
7080 % You should also get your employer (if you work as a programmer) or your
7081 % school, if any, to sign a ``copyright disclaimer'' for the program, if
7082 % necessary. Here is a sample; alter the names:
7083 %
7084 % \begin{quote}
7085 % Yoyodyne, Inc., hereby disclaims all copyright interest in the program \\
7086 % `Gnomovision' (which makes passes at compilers) written by James Hacker. \\
7087 %
7088 % signature of Ty Coon, 1 April 1989 \\
7089 % Ty Coon, President of Vice
7090 % \end{quote}
7091 %
7092 %
7093 % This General Public License does not permit incorporating your program
7094 % into proprietary programs. If your program is a subroutine library, you
7095 % may consider it more useful to permit linking proprietary applications
7096 % with the library. If this is what you want to do, use the GNU Library
7097 % General Public License instead of this License.
7098 %
7099 % \end{multicols}
7100 % \end{minipage}
7101 % \end{lrbox}
7102 %
7103 % \begin{center}
7104 % \scalebox{0.33}{\usebox{\gpl}}
7105 % \end{center}
7106 %
7107 % \Finale
7108 \endinput