1 % \iffalse meta-comment
4 % The LaTeX3 Project and any individual authors listed elsewhere
7 % It may be distributed and/or modified under the conditions of
8 % the LaTeX Project Public License (LPPL), either version 1.3c of
9 % this license or (at your option) any later version. The latest
10 % version of this license is in the file:
12 % http://www.latex-project.org/lppl.txt
16 %<2ekernel>%%% From File: ltluatex.dtx
17 %<plain>\ifx\newluafunction\undefined\else\expandafter\endinput\fi
19 %<tex> \ProvidesFile\undefined\begingroup\def\ProvidesFile
20 %<tex> #1#2[#3]{\endgroup\immediate\write-1{File: #1 #3}}
22 %<plain>\ProvidesFile{ltluatex.tex}
24 \ProvidesFile{ltluatex.dtx}
29 %<plain> LuaTeX support for plain TeX (core)
32 \edef\etatcatcode{\the\catcode`\@}
36 \documentclass{ltxdoc}
37 \GetFileInfo{ltluatex.dtx}
39 \title{\filename\\(Lua\TeX{}-specific support)}
40 \author{David Carlisle and Joseph Wright\footnote{Significant portions
41 of the code here are adapted/simplified from the packages \textsf{luatex} and
42 \textsf{luatexbase} written by Heiko Oberdiek, \'{E}lie Roux,
43 Manuel P\'{e}gouri\'{e}-Gonnar and Philipp Gesang.}}
46 \setcounter{tocdepth}{2}
56 % Lua\TeX{} adds a number of engine-specific functions to \TeX{}. Several of
57 % these require set up that is best done in the kernel or need related support
58 % functions. This file provides \emph{basic} support for Lua\TeX{} at the
59 % \LaTeXe{} kernel level plus as a loadable file which can be used with
60 % plain \TeX{} and \LaTeX{}.
62 % This file contains code for both \TeX{} (to be stored as part of the format)
63 % and Lua (to be loaded at the start of each job). In the Lua code, the kernel
64 % uses the namespace |luatexbase|.
66 % The following |\count| registers are used here for register allocation:
68 % \item[\texttt{\string\e@alloc@attribute@count}] Attributes (default~258)
69 % \item[\texttt{\string\e@alloc@ccodetable@count}] Category code tables
71 % \item[\texttt{\string\e@alloc@luafunction@count}] Lua functions
73 % \item[\texttt{\string\e@alloc@whatsit@count}] User whatsits (default~261)
74 % \item[\texttt{\string\e@alloc@bytecode@count}] Lua bytecodes (default~262)
75 % \item[\texttt{\string\e@alloc@luachunk@count}] Lua chunks (default~263)
77 % (|\count 256| is used for |\newmarks| allocation and |\count 257|
78 % is used for\linebreak
79 % |\newXeTeXintercharclass| with Xe\TeX{}, with code defined in
80 % \texttt{ltfinal.dtx}).
81 % With any \LaTeXe{} kernel from 2015 onward these registers are part of
82 % the block in the extended area reserved by the kernel (prior to 2015 the
83 % \LaTeXe{} kernel did not provide any functionality for the extended
86 % \section{Core \TeX{} functionality}
88 % The commands defined here are defined for
89 % possible inclusion in a future \LaTeX{} format, however also extracted
90 % to the file |ltluatex.tex| which may be used with older \LaTeX\
91 % formats, and with plain \TeX.
94 % \DescribeMacro{\newattribute}
95 % |\newattribute{|\meta{attribute}|}|\\
96 % Defines a named \cs{attribute}, indexed from~$1$
97 % (\emph{i.e.}~|\attribute0| is never defined). Attributes initially
98 % have the marker value |-"7FFFFFFF| (`unset') set by the engine.
101 % \DescribeMacro{\newcatcodetable}
102 % |\newcatcodetable{|\meta{catcodetable}|}|\\
103 % Defines a named \cs{catcodetable}, indexed from~$1$
104 % (|\catcodetable0| is never assigned). A new catcode table will be
105 % populated with exactly those values assigned by Ini\TeX{} (as described
106 % in the Lua\TeX{} manual).
109 % \DescribeMacro{\newluafunction}
110 % |\newluafunction{|\meta{function}|}|\\
111 % Defines a named \cs{luafunction}, indexed from~$1$. (Lua indexes
112 % tables from $1$ so |\luafunction0| is not available).
115 % \DescribeMacro{\newwhatsit}
116 % |\newwhatsit{|\meta{whatsit}|}|\\
117 % Defines a custom \cs{whatsit}, indexed from~$1$.
120 % \DescribeMacro{\newluabytecode}
121 % |\newluabytecode{|\meta{bytecode}|}|\\
122 % Allocates a number for Lua bytecode register, indexed from~$1$.
125 % \DescribeMacro{\newluachunkname}
126 % |newluachunkname{|\meta{chunkname}|}|\\
127 % Allocates a number for Lua chunk register, indexed from~$1$.
128 % Also enters the name of the regiser (without backslash) into the
129 % \verb|lua.name| table to be used in stack traces.
132 % \DescribeMacro{\catcodetable@initex}
133 % \DescribeMacro{\catcodetable@string}
134 % \DescribeMacro{\catcodetable@latex}
135 % \DescribeMacro{\catcodetable@atletter}
136 % Predefined category code tables with the obvious assignments. Note
137 % that the |latex| and |atletter| tables set the full Unicode range
138 % to the codes predefined by the kernel.
141 % \DescribeMacro{\setattribute}
142 % \DescribeMacro{\unsetattribute}
143 % |\setattribute{|\meta{attribute}|}{|\meta{value}|}|\\
144 % |\unsetattribute{|\meta{attribute}|}|\\
145 % Set and unset attributes in a manner analogous to |\setlength|. Note that
146 % attributes take a marker value when unset so this operation is distinct
147 % from setting the value to zero.
149 % \section{Plain \TeX\ interface}
151 % The \textsf{ltluatex} interface may be used with plain \TeX\ using
152 % |\input{ltluatex}|. This inputs |ltluatex.tex| which inputs
153 % |etex.src| (or |etex.sty| if used with \LaTeX)
154 % if it is not already input, and then defines some internal commands to
155 % allow the \textsf{ltluatex} interface to be defined.
157 % The \textsf{luatexbase} package interface may also be used in plain \TeX,
158 % as before, by inputting the package |\input luatexbase.sty|. The new
159 % version of \textsf{luatexbase} is based on this \textsf{ltluatex}
160 % code but implements a compatibility layer providing the interface
161 % of the original package.
163 % \section{Lua functionality}
167 % \begingroup\lccode`~=`_
168 % \lowercase{\endgroup\let~}_
171 % \subsection{Allocators in Lua}
173 % \DescribeMacro{new_attribute}
174 % |luatexbase.new_attribute(|\meta{attribute}|)|\\
175 % Returns an allocation number for the \meta{attribute}, indexed from~$1$.
176 % The attribute will be initialised with the marker value |-"7FFFFFFF|
177 % (`unset'). The attribute allocation sequence is shared with the \TeX{}
178 % code but this function does \emph{not} define a token using
180 % The attribute name is recorded in the |attributes| table. A
181 % metatable is provided so that the table syntax can be used
182 % consistently for attributes declared in \TeX\ or Lua.
185 % \DescribeMacro{new_whatsit}
186 % |luatexbase.new_whatsit(|\meta{whatsit}|)|\\
187 % Returns an allocation number for the custom \meta{whatsit}, indexed from~$1$.
190 % \DescribeMacro{new_bytecode}
191 % |luatexbase.new_bytecode(|\meta{bytecode}|)|\\
192 % Returns an allocation number for a bytecode register, indexed from~$1$.
193 % The optional \meta{name} argument is just used for logging.
196 % \DescribeMacro{new_chunkname}
197 % |luatexbase.new_chunkname(|\meta{chunkname}|)|\\
198 % Returns an allocation number for a Lua chunk name for use with
199 % |\directlua| and |\latelua|, indexed from~$1$.
200 % The number is returned and also \meta{name} argument is added to the
201 % |lua.name| array at that index.
204 % \subsection{Lua access to \TeX{} register numbers}
206 % \DescribeMacro{registernumber}
207 % |luatexbase.registernumer(|\meta{name}|)|\\
208 % Sometimes (notably in the case of Lua attributes) it is necessary to
209 % access a register \emph{by number} that has been allocated by \TeX{}.
210 % This package provides a function to look up the relevant number
211 % using Lua\TeX{}'s internal tables. After for example
212 % |\newattribute\myattrib|, |\myattrib| would be defined by (say)
213 % |\myattrib=\attribute15|. |luatexbase.registernumer("myattrib")|
214 % would then return the register number, $15$ in this case. If the string passed
215 % as argument does not correspond to a token defined by |\attributedef|,
216 % |\countdef| or similar commands, the Lua value |false| is returned.
218 % As an example, consider the input:
220 % \newcommand\test[1]{%
221 % \typeout{#1: \expandafter\meaning\csname#1\endcsname^^J
222 % \space\space\space\space
223 % \directlua{tex.write(luatexbase.registernumber("#1") or "bad input")}%
226 % \test{undefinedrubbish}
241 % \attrbutedef\myattr=12
247 % If the demonstration code is processed with Lua\LaTeX{} then the following
248 % would be produced in the log and terminal output.
250 % undefinedrubbish: \relax
256 % @MM: \mathchar"4E20
258 % @tempdima: \dimen14
260 % @tempdimb: \dimen15
266 % myattr: \attribute12
270 % Notice how undefined commands, or commands unrelated to registers
271 % do not produce an error, just return |false| and so print
272 % |bad input| here. Note also that commands defined by |\newbox| work and
273 % return the number of the box register even though the actual command
274 % holding this number is a |\chardef| defined token (there is no
277 % \subsection{Module utilities}
279 % \DescribeMacro{provides_module}
280 % |luatexbase.provides_module(|\meta{info}|)|\\
281 % This function is used by modules to identify themselves; the |info| should be
282 % a table containing information about the module. The required field
283 % |name| must contain the name of the module. It is recommended to provide a
284 % field |date| in the usual \LaTeX{} format |yyyy/mm/dd|. Optional fields
285 % |version| (a string) and |description| may be used if present. This
286 % information will be recorded in the log. Other fields are ignored.
289 % \DescribeMacro{module_info}
290 % \DescribeMacro{module_warning}
291 % \DescribeMacro{module_error}
292 % |luatexbase.module_info(|\meta{module}, \meta{text}|)|\\
293 % |luatexbase.module_warning(|\meta{module}, \meta{text}|)|\\
294 % |luatexbase.module_error(|\meta{module}, \meta{text}|)|\\
295 % These functions are similar to \LaTeX{}'s |\PackageError|, |\PackageWarning|
296 % and |\PackageInfo| in the way they format the output. No automatic line
297 % breaking is done, you may still use |\n| as usual for that, and the name of
298 % the package will be prepended to each output line.
300 % Note that |luatexbase.module_error| raises an actual Lua error with |error()|,
301 % which currently means a call stack will be dumped. While this may not
302 % look pretty, at least it provides useful information for tracking the
305 % \subsection{Callback management}
308 % \DescribeMacro{add_to_callback}
309 % |luatexbase.add_to_callback(|^^A
310 % \meta{callback}, \meta{function}, \meta{description}|)|
311 % Registers the \meta{function} into the \meta{callback} with a textual
312 % \meta{description} of the function. Functions are inserted into the callback
313 % in the order loaded.
316 % \DescribeMacro{remove_from_callback}
317 % |luatexbase.remove_from_callback(|\meta{callback}, \meta{description}|)|
318 % Removes the callback function with \meta{description} from the \meta{callback}.
319 % The removed function and its description
320 % are returned as the results of this function.
323 % \DescribeMacro{in_callback}
324 % |luatexbase.in_callback(|\meta{callback}, \meta{description}|)|
325 % Checks if the \meta{description} matches one of the functions added
326 % to the list for the \meta{callback}, returning a boolean value.
329 % \DescribeMacro{disable_callback}
330 % |luatexbase.disable_callback(|\meta{callback}|)|
331 % Sets the \meta{callback} to \texttt{false} as described in the Lua\TeX{}
332 % manual for the underlying \texttt{callback.register} built-in. Callbacks
333 % will only be set to false (and thus be skipped entirely) if there are
334 % no functions registered using the callback.
337 % \DescribeMacro{callback_descriptions}
338 % A list of the descriptions of functions registered to the specified
339 % callback is returned. |{}| is returned if there are no functions registered.
342 % \DescribeMacro{create_callback}
343 % |luatexbase.create_callback(|\meta{name},meta{type},\meta{default}|)|
344 % Defines a user defined callback. The last argument is a default
345 % function or |false|.
348 % \DescribeMacro{call_callback}
349 % |luatexbase.call_callback(|\meta{name},\ldots|)|
350 % Calls a user defined callback with the supplied arguments.
357 % \section{Implementation}
360 %<*2ekernel|tex|latexrelease>
361 %<2ekernel|latexrelease>\ifx\directlua\@undefined\else
365 % \changes{v1.0j}{2015/12/02}{Remove nonlocal iteration variables (PHG)}
366 % \changes{v1.0j}{2015/12/02}{Assorted typos fixed (PHG)}
367 % \changes{v1.0j}{2015/12/02}{Remove unreachable code after calls to error() (PHG)}
368 % \subsection{Minimum Lua\TeX{} version}
370 % Lua\TeX{} has changed a lot over time. In the kernel support for ancient
371 % versions is not provided: trying to build a format with a very old binary
372 % therefore gives some information in the log and loading stops. The cut-off
373 % selected here relates to the tree-searching behaviour of |require()|:
374 % from version~0.60, Lua\TeX{} will correctly find Lua files in the |texmf|
375 % tree without `help'.
377 %<latexrelease>\IncludeInRelease{2015/10/01}
378 %<latexrelease> {\newluafunction}{LuaTeX}%
379 \ifnum\luatexversion<60 %
380 \wlog{***************************************************}
381 \wlog{* LuaTeX version too old for ltluatex support *}
382 \wlog{***************************************************}
383 \expandafter\endinput
387 % \subsection{Older \LaTeX{}/Plain \TeX\ setup}
393 % Older \LaTeX{} formats don't have the primitives with `native' names:
394 % sort that out. If they already exist this will still be safe.
396 \directlua{tex.enableprimitives("",tex.extraprimitives("luatex"))}
400 \ifx\e@alloc\@undefined
403 % In pre-2014 \LaTeX{}, or plain \TeX{}, load |etex.{sty,src}|.
405 \ifx\documentclass\@undefined
406 \ifx\loccount\@undefined
410 \outer\expandafter\def\csname newfam\endcsname
411 {\alloc@8\fam\chardef\et@xmaxfam}
413 \RequirePackage{etex}
414 \expandafter\def\csname newfam\endcsname
415 {\alloc@8\fam\chardef\et@xmaxfam}
416 \expandafter\let\expandafter\new@mathgroup\csname newfam\endcsname
420 % \subsubsection{Fixes to \texttt{etex.src}/\texttt{etex.sty}}
422 % These could and probably should be made directly in an
423 % update to |etex.src| which already has some Lua\TeX-specific
424 % code, but does not define the correct range for Lua\TeX.
427 % 2015-07-13 higher range in luatex
428 \edef \et@xmaxregs {\ifx\directlua\@undefined 32768\else 65536\fi}
429 % luatex/xetex also allow more math fam
430 \edef \et@xmaxfam {\ifx\Umathchar\@undefined\sixt@@n\else\@cclvi\fi}
434 \count 270=\et@xmaxregs % locally allocates \count registers
435 \count 271=\et@xmaxregs % ditto for \dimen registers
436 \count 272=\et@xmaxregs % ditto for \skip registers
437 \count 273=\et@xmaxregs % ditto for \muskip registers
438 \count 274=\et@xmaxregs % ditto for \box registers
439 \count 275=\et@xmaxregs % ditto for \toks registers
440 \count 276=\et@xmaxregs % ditto for \marks classes
443 % and 256 or 16 fam. (Done above due to plain/\LaTeX\ differences in
444 % \textsf{ltluatex}.)
446 % \outer\def\newfam{\alloc@8\fam\chardef\et@xmaxfam}
449 % End of proposed changes to \texttt{etex.src}
451 % \subsubsection{luatex specific settings}
453 % Switch to global cf |luatex.sty| to leave room for inserts
454 % not really needed for luatex but possibly most compatible
457 \expandafter\let\csname newcount\expandafter\expandafter\endcsname
458 \csname globcount\endcsname
459 \expandafter\let\csname newdimen\expandafter\expandafter\endcsname
460 \csname globdimen\endcsname
461 \expandafter\let\csname newskip\expandafter\expandafter\endcsname
462 \csname globskip\endcsname
463 \expandafter\let\csname newbox\expandafter\expandafter\endcsname
464 \csname globbox\endcsname
467 % Define|\e@alloc| as in latex (the existing macros in |etex.src|
468 % hard to extend to further register types as they assume specific
469 % 26x and 27x count range. For compatibility the existing register
470 % allocation is not changed.
473 \chardef\e@alloc@top=65535
474 \let\e@alloc@chardef\chardef
478 \def\e@alloc#1#2#3#4#5#6{%
479 \global\advance#3\@ne
480 \e@ch@ck{#3}{#4}{#5}#1%
481 \allocationnumber#3\relax
482 \global#2#6\allocationnumber
483 \wlog{\string#6=\string#1\the\allocationnumber}}%
487 \gdef\e@ch@ck#1#2#3#4{%
491 \ifx\count#4\advance#1 10 \fi
495 \errmessage{No room for a new \string#4}%
500 % Two simple \LaTeX\ macros used in |ltlatex.sty|.
502 \long\def\@gobble#1{}
503 \long\def\@firstofone#1{#1}
507 % Fix up allocations not to clash with |etex.src|.
511 \expandafter\csname newcount\endcsname\e@alloc@attribute@count
512 \expandafter\csname newcount\endcsname\e@alloc@ccodetable@count
513 \expandafter\csname newcount\endcsname\e@alloc@luafunction@count
514 \expandafter\csname newcount\endcsname\e@alloc@whatsit@count
515 \expandafter\csname newcount\endcsname\e@alloc@bytecode@count
516 \expandafter\csname newcount\endcsname\e@alloc@luachunk@count
519 % End of conditional setup for plain \TeX\ / old \LaTeX.
526 % \subsection{Attributes}
528 % \begin{macro}{\newattribute}
529 % \changes{v1.0a}{2015/09/24}{Macro added}
530 % As is generally the case for the Lua\TeX{} registers we start here
531 % from~$1$. Notably, some code assumes that |\attribute0| is never used so
532 % this is important in this case.
534 \ifx\e@alloc@attribute@count\@undefined
535 \countdef\e@alloc@attribute@count=258
537 \def\newattribute#1{%
538 \e@alloc\attribute\attributedef
539 \e@alloc@attribute@count\m@ne\e@alloc@top#1%
541 \e@alloc@attribute@count=\z@
545 % \begin{macro}{\setattribute}
546 % \begin{macro}{\unsetattribute}
549 \def\setattribute#1#2{#1=\numexpr#2\relax}
550 \def\unsetattribute#1{#1=-"7FFFFFFF\relax}
555 % \subsection{Category code tables}
557 % \begin{macro}{\newcatcodetable}
558 % \changes{v1.0a}{2015/09/24}{Macro added}
559 % Category code tables are allocated with a limit half of that used by Lua\TeX{}
560 % for everything else. At the end of allocation there needs to be an
561 % initialisation step. Table~$0$ is already taken (it's the global one for
562 % current use) so the allocation starts at~$1$.
564 \ifx\e@alloc@ccodetable@count\@undefined
565 \countdef\e@alloc@ccodetable@count=259
567 \def\newcatcodetable#1{%
568 \e@alloc\catcodetable\chardef
569 \e@alloc@ccodetable@count\m@ne{"8000}#1%
570 \initcatcodetable\allocationnumber
572 \e@alloc@ccodetable@count=\z@
576 % \changes{v1.0l}{2015/12/18}{Load Unicode data from source}
577 % \begin{macro}{\catcodetable@initex}
578 % \changes{v1.0a}{2015/09/24}{Macro added}
579 % \begin{macro}{\catcodetable@string}
580 % \changes{v1.0a}{2015/09/24}{Macro added}
581 % \begin{macro}{\catcodetable@latex}
582 % \changes{v1.0a}{2015/09/24}{Macro added}
583 % \begin{macro}{\catcodetable@atletter}
584 % \changes{v1.0a}{2015/09/24}{Macro added}
585 % Save a small set of standard tables. The Unicode data is read
586 % here in using a parser simplified from that in |load-unicode-data|:
587 % only the nature of letters needs to be detected.
589 \newcatcodetable\catcodetable@initex
590 \newcatcodetable\catcodetable@string
592 \def\setrangecatcode#1#2#3{%
596 \expandafter\@firstofone
600 \expandafter\setrangecatcode\expandafter
601 {\number\numexpr#1 + 1\relax}{#2}{#3}
605 \catcodetable\catcodetable@initex
609 \setrangecatcode{65}{90}{12}%
610 \setrangecatcode{97}{122}{12}%
613 \savecatcodetable\catcodetable@string
616 \newcatcodetable\catcodetable@latex
617 \newcatcodetable\catcodetable@atletter
619 \def\parseunicodedataI#1;#2;#3;#4\relax{%
620 \parseunicodedataII#1;#3;#2 First>\relax
622 \def\parseunicodedataII#1;#2;#3 First>#4\relax{%
624 \expandafter\parseunicodedataIII
626 \expandafter\parseunicodedataIV
630 \def\parseunicodedataIII#1#2#3\relax{%
638 \def\parseunicodedataIV#1#2#3\relax{%
639 \read\unicoderead to \unicodedataline
642 \expandafter\parseunicodedataV\unicodedataline\relax
645 \def\parseunicodedataV#1;#2\relax{%
647 \unless\ifnum\count0>"#1 %
649 \advance\count0 by 1 %
652 \def\storedpar{\par}%
653 \chardef\unicoderead=\numexpr\count16 + 1\relax
654 \openin\unicoderead=UnicodeData.txt %
655 \loop\unless\ifeof\unicoderead %
656 \read\unicoderead to \unicodedataline
657 \unless\ifx\unicodedataline\storedpar
658 \expandafter\parseunicodedataI\unicodedataline\relax
664 \savecatcodetable\catcodetable@latex
666 \savecatcodetable\catcodetable@atletter
675 % \subsection{Named Lua functions}
677 % \begin{macro}{\newluafunction}
678 % \changes{v1.0a}{2015/09/24}{Macro added}
679 % Much the same story for allocating Lua\TeX{} functions except here they are
680 % just numbers so they are allocated in the same way as boxes.
681 % Lua indexes from~$1$ so once again slot~$0$ is skipped.
683 \ifx\e@alloc@luafunction@count\@undefined
684 \countdef\e@alloc@luafunction@count=260
686 \def\newluafunction{%
687 \e@alloc\luafunction\e@alloc@chardef
688 \e@alloc@luafunction@count\m@ne\e@alloc@top
690 \e@alloc@luafunction@count=\z@
694 % \subsection{Custom whatsits}
696 % \begin{macro}{\newwhatsit}
697 % \changes{v1.0a}{2015/09/24}{Macro added}
698 % These are only settable from Lua but for consistency are definable
701 \ifx\e@alloc@whatsit@count\@undefined
702 \countdef\e@alloc@whatsit@count=261
705 \e@alloc\whatsit\e@alloc@chardef
706 \e@alloc@whatsit@count\m@ne\e@alloc@top#1%
708 \e@alloc@whatsit@count=\z@
712 % \subsection{Lua bytecode registers}
714 % \begin{macro}{\newluabytecode}
715 % \changes{v1.0a}{2015/09/24}{Macro added}
716 % These are only settable from Lua but for consistency are definable
719 \ifx\e@alloc@bytecode@count\@undefined
720 \countdef\e@alloc@bytecode@count=262
722 \def\newluabytecode#1{%
723 \e@alloc\luabytecode\e@alloc@chardef
724 \e@alloc@bytecode@count\m@ne\e@alloc@top#1%
726 \e@alloc@bytecode@count=\z@
730 % \subsection{Lua chunk registers}
732 % \begin{macro}{\newluachunkname}
733 % \changes{v1.0a}{2015/09/24}{Macro added}
734 % As for bytecode registers, but in addition we need to add a string
735 % to the \verb|lua.name| table to use in stack tracing. We use the
736 % name of the command passed to the allocator, with no backslash.
738 \ifx\e@alloc@luachunk@count\@undefined
739 \countdef\e@alloc@luachunk@count=263
741 \def\newluachunkname#1{%
742 \e@alloc\luachunk\e@alloc@chardef
743 \e@alloc@luachunk@count\m@ne\e@alloc@top#1%
745 \directlua{lua.name[\the\allocationnumber]="\string#1"}}%
747 \e@alloc@luachunk@count=\z@
751 % \subsection{Lua loader}
753 % Load the Lua code at the start of every job.
754 % For the conversion of \TeX{} into numbers at the Lua side we need some
755 % known registers: for convenience we use a set of systematic names, which
756 % means using a group around the Lua loader.
758 %<2ekernel>\everyjob\expandafter{%
759 %<2ekernel> \the\everyjob
761 \attributedef\attributezero=0 %
762 \chardef \charzero =0 %
764 % Note name change required on older luatex, for hash table access.
766 \countdef \CountZero =0 %
767 \dimendef \dimenzero =0 %
768 \mathchardef \mathcharzero =0 %
769 \muskipdef \muskipzero =0 %
770 \skipdef \skipzero =0 %
771 \toksdef \tokszero =0 %
772 \directlua{require("ltluatex")}
775 %<latexrelease>\EndIncludeInRelease
779 % \changes{v1.0b}{2015/10/02}{Fix backing out of \TeX{} code}
780 % \changes{v1.0c}{2015/10/02}{Allow backing out of Lua code}
781 %<latexrelease>\IncludeInRelease{0000/00/00}
782 %<latexrelease> {\newluafunction}{LuaTeX}%
783 %<latexrelease>\let\e@alloc@attribute@count\@undefined
784 %<latexrelease>\let\newattribute\@undefined
785 %<latexrelease>\let\setattribute\@undefined
786 %<latexrelease>\let\unsetattribute\@undefined
787 %<latexrelease>\let\e@alloc@ccodetable@count\@undefined
788 %<latexrelease>\let\newcatcodetable\@undefined
789 %<latexrelease>\let\catcodetable@initex\@undefined
790 %<latexrelease>\let\catcodetable@string\@undefined
791 %<latexrelease>\let\catcodetable@latex\@undefined
792 %<latexrelease>\let\catcodetable@atletter\@undefined
793 %<latexrelease>\let\e@alloc@luafunction@count\@undefined
794 %<latexrelease>\let\newluafunction\@undefined
795 %<latexrelease>\let\e@alloc@luafunction@count\@undefined
796 %<latexrelease>\let\newwhatsit\@undefined
797 %<latexrelease>\let\e@alloc@whatsit@count\@undefined
798 %<latexrelease>\let\newluabytecode\@undefined
799 %<latexrelease>\let\e@alloc@bytecode@count\@undefined
800 %<latexrelease>\let\newluachunkname\@undefined
801 %<latexrelease>\let\e@alloc@luachunk@count\@undefined
802 %<latexrelease>\directlua{luatexbase.uninstall()}
803 %<latexrelease>\EndIncludeInRelease
807 %<2ekernel|latexrelease>\fi
808 %</2ekernel|tex|latexrelease>
811 % \subsection{Lua module preliminaries}
815 % \begingroup\lccode`~=`_
816 % \lowercase{\endgroup\let~}_
823 % Some set up for the Lua module which is needed for all of the Lua
824 % functionality added here.
826 % \begin{macro}{luatexbase}
827 % \changes{v1.0a}{2015/09/24}{Table added}
828 % Set up the table for the returned functions. This is used to expose
829 % all of the public functions.
831 luatexbase = luatexbase or { }
832 local luatexbase = luatexbase
836 % Some Lua best practice: use local versions of functions where possible.
838 local string_gsub = string.gsub
839 local tex_count = tex.count
840 local tex_setattribute = tex.setattribute
841 local tex_setcount = tex.setcount
842 local texio_write_nl = texio.write_nl
844 % \changes{v1.0i}{2015/11/29}{Declare this as local before used in the module error definitions (PHG)}
846 local luatexbase_warning
847 local luatexbase_error
850 % \subsection{Lua module utilities}
852 % \subsubsection{Module tracking}
854 % \begin{macro}{modules}
855 % \changes{v1.0a}{2015/09/24}{Function modified}
856 % To allow tracking of module usage, a structure is provided to store
857 % information and to return it.
859 local modules = modules or { }
863 % \begin{macro}{provides_module}
864 % \changes{v1.0a}{2015/09/24}{Function added}
865 % \changes{v1.0f}{2015/10/03}{use luatexbase\_log}
866 % Local function to write to the log.
868 local function luatexbase_log(text)
869 texio_write_nl("log", text)
873 % Modelled on |\ProvidesPackage|, we store much the same information but
874 % with a little more structure.
876 local function provides_module(info)
877 if not (info and info.name) then
878 luatexbase_error("Missing module name for provides_module")
880 local function spaced(text)
881 return text and (" " .. text) or ""
884 "Lua module: " .. info.name
886 .. spaced(info.version)
887 .. spaced(info.description)
889 modules[info.name] = info
891 luatexbase.provides_module = provides_module
895 % \subsubsection{Module messages}
897 % There are various warnings and errors that need to be given. For warnings
898 % we can get exactly the same formatting as from \TeX{}. For errors we have to
899 % make some changes. Here we give the text of the error in the \LaTeX{} format
900 % then force an error from Lua to halt the run. Splitting the message text is
901 % done using |\n| which takes the place of |\MessageBreak|.
903 % First an auxiliary for the formatting: this measures up the message
904 % leader so we always get the correct indent.
905 % \changes{v1.0j}{2015/12/02}{Declaration/use of first\_head fixed (PHG)}
907 local function msg_format(mod, msg_type, text)
911 if mod == "LaTeX" then
912 cont = string_gsub(leader, ".", " ")
913 first_head = leader .. "LaTeX: "
915 first_head = leader .. "Module " .. msg_type
916 cont = "(" .. mod .. ")"
917 .. string_gsub(first_head, ".", " ")
918 first_head = leader .. "Module " .. mod .. " " .. msg_type .. ":"
920 if msg_type == "Error" then
921 first_head = "\n" .. first_head
923 if string.sub(text,-1) ~= "\n" then
926 return first_head .. " "
930 .. tex.inputlineno, "\n", "\n" .. cont .. " "
936 % \begin{macro}{module_info}
937 % \changes{v1.0a}{2015/09/24}{Function added}
938 % \begin{macro}{module_warning}
939 % \changes{v1.0a}{2015/09/24}{Function added}
940 % \begin{macro}{module_error}
941 % \changes{v1.0a}{2015/09/24}{Function added}
944 local function module_info(mod, text)
945 texio_write_nl("log", msg_format(mod, "Info", text))
947 luatexbase.module_info = module_info
948 local function module_warning(mod, text)
949 texio_write_nl("term and log",msg_format(mod, "Warning", text))
951 luatexbase.module_warning = module_warning
952 local function module_error(mod, text)
953 error(msg_format(mod, "Error", text))
955 luatexbase.module_error = module_error
961 % Dedicated versions for the rest of the code here.
963 function luatexbase_warning(text)
964 module_warning("luatexbase", text)
966 function luatexbase_error(text)
967 module_error("luatexbase", text)
972 % \subsection{Accessing register numbers from Lua}
974 % \changes{v1.0g}{2015/11/14}{Track Lua\TeX{} changes for
975 % \texttt{(new)token.create}}
976 % Collect up the data from the \TeX{} level into a Lua table: from
977 % version~0.80, Lua\TeX{} makes that easy.
978 % \changes{v1.0j}{2015/12/02}{Adjust hashtokens to store the result of tex.hashtokens()), not the function (PHG)}
980 local luaregisterbasetable = { }
981 local registermap = {
982 attributezero = "assign_attr" ,
983 charzero = "char_given" ,
984 CountZero = "assign_int" ,
985 dimenzero = "assign_dimen" ,
986 mathcharzero = "math_given" ,
987 muskipzero = "assign_mu_skip" ,
988 skipzero = "assign_skip" ,
989 tokszero = "assign_toks" ,
992 if tex.luatexversion > 81 then
993 createtoken = token.create
994 elseif tex.luatexversion > 79 then
995 createtoken = newtoken.create
997 local hashtokens = tex.hashtokens()
998 local luatexversion = tex.luatexversion
999 for i,j in pairs (registermap) do
1000 if luatexversion < 80 then
1001 luaregisterbasetable[hashtokens[i][1]] =
1004 luaregisterbasetable[j] = createtoken(i).mode
1009 % \begin{macro}{registernumber}
1010 % Working out the correct return value can be done in two ways. For older
1011 % Lua\TeX{} releases it has to be extracted from the |hashtokens|. On the
1012 % other hand, newer Lua\TeX{}'s have |newtoken|, and whilst |.mode| isn't
1013 % currently documented, Hans Hagen pointed to this approach so we should be
1016 local registernumber
1017 if luatexversion < 80 then
1018 function registernumber(name)
1019 local nt = hashtokens[name]
1020 if(nt and luaregisterbasetable[nt[1]]) then
1021 return nt[2] - luaregisterbasetable[nt[1]]
1027 function registernumber(name)
1028 local nt = createtoken(name)
1029 if(luaregisterbasetable[nt.cmdname]) then
1030 return nt.mode - luaregisterbasetable[nt.cmdname]
1036 luatexbase.registernumber = registernumber
1040 % \subsection{Attribute allocation}
1042 % \begin{macro}{new_attribute}
1043 % \changes{v1.0a}{2015/09/24}{Function added}
1044 % As attributes are used for Lua manipulations its useful to be able
1045 % to assign from this end.
1047 local attributes=setmetatable(
1050 __index = function(t,key)
1051 return registernumber(key) or nil
1054 luatexbase.attributes=attributes
1058 local function new_attribute(name)
1059 tex_setcount("global", "e@alloc@attribute@count",
1060 tex_count["e@alloc@attribute@count"] + 1)
1061 if tex_count["e@alloc@attribute@count"] > 65534 then
1062 luatexbase_error("No room for a new \\attribute")
1064 attributes[name]= tex_count["e@alloc@attribute@count"]
1065 luatexbase_log("Lua-only attribute " .. name .. " = " ..
1066 tex_count["e@alloc@attribute@count"])
1067 return tex_count["e@alloc@attribute@count"]
1069 luatexbase.new_attribute = new_attribute
1073 % \subsection{Custom whatsit allocation}
1075 % \begin{macro}{new_whatsit}
1076 % Much the same as for attribute allocation in Lua.
1078 local function new_whatsit(name)
1079 tex_setcount("global", "e@alloc@whatsit@count",
1080 tex_count["e@alloc@whatsit@count"] + 1)
1081 if tex_count["e@alloc@whatsit@count"] > 65534 then
1082 luatexbase_error("No room for a new custom whatsit")
1084 luatexbase_log("Custom whatsit " .. (name or "") .. " = " ..
1085 tex_count["e@alloc@whatsit@count"])
1086 return tex_count["e@alloc@whatsit@count"]
1088 luatexbase.new_whatsit = new_whatsit
1092 % \subsection{Bytecode register allocation}
1094 % \begin{macro}{new_bytecode}
1095 % Much the same as for attribute allocation in Lua.
1096 % The optional \meta{name} argument is used in the log if given.
1098 local function new_bytecode(name)
1099 tex_setcount("global", "e@alloc@bytecode@count",
1100 tex_count["e@alloc@bytecode@count"] + 1)
1101 if tex_count["e@alloc@bytecode@count"] > 65534 then
1102 luatexbase_error("No room for a new bytecode register")
1104 luatexbase_log("Lua bytecode " .. (name or "") .. " = " ..
1105 tex_count["e@alloc@bytecode@count"])
1106 return tex_count["e@alloc@bytecode@count"]
1108 luatexbase.new_bytecode = new_bytecode
1112 % \subsection{Lua chunk name allocation}
1114 % \begin{macro}{new_chunkname}
1115 % As for bytecode registers but also store the name in the
1118 local function new_chunkname(name)
1119 tex_setcount("global", "e@alloc@luachunk@count",
1120 tex_count["e@alloc@luachunk@count"] + 1)
1121 local chunkname_count = tex_count["e@alloc@luachunk@count"]
1122 chunkname_count = chunkname_count + 1
1123 if chunkname_count > 65534 then
1124 luatexbase_error("No room for a new chunkname")
1126 lua.name[chunkname_count]=name
1127 luatexbase_log("Lua chunkname " .. (name or "") .. " = " ..
1128 chunkname_count .. "\n")
1129 return chunkname_count
1131 luatexbase.new_chunkname = new_chunkname
1135 % \subsection{Lua callback management}
1137 % The native mechanism for callbacks in Lua\TeX\ allows only one per function.
1138 % That is extremely restrictive and so a mechanism is needed to add and
1139 % remove callbacks from the appropriate hooks.
1141 % \subsubsection{Housekeeping}
1143 % The main table: keys are callback names, and values are the associated lists
1144 % of functions. More precisely, the entries in the list are tables holding the
1145 % actual function as |func| and the identifying description as |description|.
1146 % Only callbacks with a non-empty list of functions have an entry in this
1149 local callbacklist = callbacklist or { }
1152 % Numerical codes for callback types, and name-to-value association (the
1153 % table keys are strings, the values are numbers).
1155 local list, data, exclusive, simple = 1, 2, 3, 4
1159 exclusive = exclusive,
1164 % Now, list all predefined callbacks with their current type, based on the
1165 % Lua\TeX{} manual version~0.80. A full list of the currently-available
1166 % callbacks can be obtained using
1169 % for i,_ in pairs(callback.list()) do
1170 % texio.write_nl("- " .. i)
1175 % in plain Lua\TeX{}. (Some undocumented callbacks are omitted as they are
1178 local callbacktypes = callbacktypes or {
1180 % Section 4.1.1: file discovery callbacks.
1182 find_read_file = exclusive,
1183 find_write_file = exclusive,
1184 find_font_file = data,
1185 find_output_file = data,
1186 find_format_file = data,
1187 find_vf_file = data,
1188 find_map_file = data,
1189 find_enc_file = data,
1190 find_sfd_file = data,
1191 find_pk_file = data,
1192 find_data_file = data,
1193 find_opentype_file = data,
1194 find_truetype_file = data,
1195 find_type1_file = data,
1196 find_image_file = data,
1198 % Section 4.1.2: file reading callbacks.
1200 open_read_file = exclusive,
1201 read_font_file = exclusive,
1202 read_vf_file = exclusive,
1203 read_map_file = exclusive,
1204 read_enc_file = exclusive,
1205 read_sfd_file = exclusive,
1206 read_pk_file = exclusive,
1207 read_data_file = exclusive,
1208 read_truetype_file = exclusive,
1209 read_type1_file = exclusive,
1210 read_opentype_file = exclusive,
1212 % Section 4.1.3: data processing callbacks.
1214 process_input_buffer = data,
1215 process_output_buffer = data,
1216 process_jobname = data,
1217 token_filter = exclusive,
1219 % Section 4.1.4: node list processing callbacks.
1221 buildpage_filter = simple,
1222 pre_linebreak_filter = list,
1223 linebreak_filter = list,
1224 post_linebreak_filter = list,
1225 hpack_filter = list,
1226 vpack_filter = list,
1227 pre_output_filter = list,
1229 ligaturing = simple,
1231 mlist_to_hlist = list,
1233 % Section 4.1.5: information reporting callbacks.
1238 start_page_number = simple,
1239 stop_page_number = simple,
1240 show_error_hook = simple,
1241 show_error_message = simple,
1242 show_lua_error_hook = simple,
1243 start_file = simple,
1246 % Section 4.1.6: PDF-related callbacks.
1248 finish_pdffile = data,
1249 finish_pdfpage = data,
1251 % Section 4.1.7: font-related callbacks.
1253 define_font = exclusive,
1255 % Undocumented callbacks which are likely to get documented.
1257 find_cidmap_file = data,
1258 pdf_stream_filter_callback = data,
1260 luatexbase.callbacktypes=callbacktypes
1263 % \begin{macro}{callback.register}
1264 % \changes{v1.0a}{2015/09/24}{Function modified}
1265 % Save the original function for registering callbacks and prevent the
1266 % original being used. The original is saved in a place that remains
1267 % available so other more sophisticated code can override the approach
1268 % taken by the kernel if desired.
1270 local callback_register = callback_register or callback.register
1271 function callback.register()
1272 luatexbase_error("Attempt to use callback.register() directly\n")
1277 % \subsubsection{Handlers}
1279 % The handler function is registered into the callback when the
1280 % first function is added to this callback's list. Then, when the callback
1281 % is called, the handler takes care of running all functions in the list.
1282 % When the last function is removed from the callback's list, the handler
1285 % More precisely, the functions below are used to generate a specialized
1286 % function (closure) for a given callback, which is the actual handler.
1288 % Handler for |data| callbacks.
1290 local function data_handler(name)
1291 return function(data, ...)
1292 for _,i in ipairs(callbacklist[name]) do
1293 data = i.func(data,...)
1299 % Handler for |exclusive| callbacks. We can assume |callbacklist[name]| is not
1300 % empty: otherwise, the function wouldn't be registered in the callback any
1303 local function exclusive_handler(name)
1304 return function(...)
1305 return callbacklist[name][1].func(...)
1309 % Handler for |list| callbacks.
1310 % \changes{v1.0k}{2015/12/02}{resolve name and i.description (PHG)}
1312 local function list_handler(name)
1313 return function(head, ...)
1315 local alltrue = true
1316 for _,i in ipairs(callbacklist[name]) do
1317 ret = i.func(head, ...)
1318 if ret == false then
1320 "Function `" .. i.description .. "' returned false\n"
1321 .. "in callback `" .. name .."'"
1330 return alltrue and true or head
1334 % Handler for |simple| callbacks.
1336 local function simple_handler(name)
1337 return function(...)
1338 for _,i in ipairs(callbacklist[name]) do
1345 % Keep a handlers table for indexed access.
1348 [data] = data_handler,
1349 [exclusive] = exclusive_handler,
1350 [list] = list_handler,
1351 [simple] = simple_handler,
1355 % \subsubsection{Public functions for callback management}
1357 % Defining user callbacks perhaps should be in package code,
1358 % but impacts on |add_to_callback|.
1359 % If a default function is not required, it may be declared as |false|.
1360 % First we need a list of user callbacks.
1362 local user_callbacks_defaults = { }
1365 % \begin{macro}{create_callback}
1366 % \changes{v1.0a}{2015/09/24}{Function added}
1367 % \changes{v1.0i}{2015/11/29}{Check name is not nil in error message (PHG)}
1368 % \changes{v1.0k}{2015/12/02}{Give more specific error messages (PHG)}
1369 % The allocator itself.
1371 local function create_callback(name, ctype, default)
1372 if not name or name == ""
1373 or not ctype or ctype == ""
1375 luatexbase_error("Unable to create callback:\n" ..
1376 "valid callback name and type required")
1378 if callbacktypes[name] then
1379 luatexbase_error("Unable to create callback `" .. name ..
1380 "':\ncallback type disallowed as name")
1382 if default ~= false and type (default) ~= "function" then
1383 luatexbase_error("Unable to create callback `" .. name ..
1384 ":\ndefault is not a function")
1386 user_callbacks_defaults[name] = default
1387 callbacktypes[name] = types[ctype]
1389 luatexbase.create_callback = create_callback
1393 % \begin{macro}{call_callback}
1394 % \changes{v1.0a}{2015/09/24}{Function added}
1395 % \changes{v1.0i}{2015/11/29}{Check name is not nil in error message (PHG)}
1396 % \changes{v1.0k}{2015/12/02}{Give more specific error messages (PHG)}
1397 % Call a user defined callback. First check arguments.
1399 local function call_callback(name,...)
1400 if not name or name == "" then
1401 luatexbase_error("Unable to create callback:\n" ..
1402 "valid callback name required")
1404 if user_callbacks_defaults[name] == nil then
1405 luatexbase_error("Unable to call callback `" .. name
1406 .. "':\nunknown or empty")
1408 local l = callbacklist[name]
1411 f = user_callbacks_defaults[name]
1416 f = handlers[callbacktypes[name]](name)
1420 luatexbase.call_callback=call_callback
1424 % \begin{macro}{add_to_callback}
1425 % \changes{v1.0a}{2015/09/24}{Function added}
1426 % Add a function to a callback. First check arguments.
1427 % \changes{v1.0k}{2015/12/02}{Give more specific error messages (PHG)}
1429 local function add_to_callback(name, func, description)
1430 if not name or name == "" then
1431 luatexbase_error("Unable to register callback:\n" ..
1432 "valid callback name required")
1434 if not callbacktypes[name] or
1435 type(func) ~= "function" or
1437 description == "" then
1439 "Unable to register callback.\n\n"
1440 .. "Correct usage:\n"
1441 .. "add_to_callback(<callback>, <function>, <description>)"
1445 % Then test if this callback is already in use. If not, initialise its list
1446 % and register the proper handler.
1448 local l = callbacklist[name]
1451 callbacklist[name] = l
1453 % If it is not a user defined callback use the primitive callback register.
1455 if user_callbacks_defaults[name] == nil then
1456 callback_register(name, handlers[callbacktypes[name]](name))
1460 % Actually register the function and give an error if more than one
1461 % |exclusive| one is registered.
1465 description = description,
1467 local priority = #l + 1
1468 if callbacktypes[name] == exclusive then
1471 "Cannot add second callback to exclusive function\n`" ..
1475 table.insert(l, priority, f)
1477 % Keep user informed.
1480 "Inserting `" .. description .. "' at position "
1481 .. priority .. " in `" .. name .. "'."
1484 luatexbase.add_to_callback = add_to_callback
1488 % \begin{macro}{remove_from_callback}
1489 % \changes{v1.0a}{2015/09/24}{Function added}
1490 % \changes{v1.0k}{2015/12/02}{adjust initialisation of cb local (PHG)}
1491 % \changes{v1.0k}{2015/12/02}{Give more specific error messages (PHG)}
1492 % Remove a function from a callback. First check arguments.
1494 local function remove_from_callback(name, description)
1495 if not name or name == "" then
1496 luatexbase_error("Unable to remove function from callback:\n" ..
1497 "valid callback name required")
1499 if not callbacktypes[name] or
1501 description == "" then
1503 "Unable to remove function from callback.\n\n"
1504 .. "Correct usage:\n"
1505 .. "remove_from_callback(<callback>, <description>)"
1508 local l = callbacklist[name]
1511 "No callback list for `" .. name .. "'\n")
1514 % Loop over the callback's function list until we find a matching entry.
1515 % Remove it and check if the list is empty: if so, unregister the
1519 for i,j in ipairs(l) do
1520 if j.description == description then
1527 "No callback `" .. description .. "' registered for `" ..
1531 table.remove(l, index)
1533 "Removing `" .. description .. "' from `" .. name .. "'."
1536 callbacklist[name] = nil
1537 callback_register(name, nil)
1539 return cb.func,cb.description
1541 luatexbase.remove_from_callback = remove_from_callback
1545 % \begin{macro}{in_callback}
1546 % \changes{v1.0a}{2015/09/24}{Function added}
1547 % \changes{v1.0h}{2015/11/27}{Guard against undefined list latex/4445}
1548 % Look for a function description in a callback.
1550 local function in_callback(name, description)
1553 or not callbacklist[name]
1554 or not callbacktypes[name]
1555 or not description then
1558 for _, i in pairs(callbacklist[name]) do
1559 if i.description == description then
1565 luatexbase.in_callback = in_callback
1569 % \begin{macro}{disable_callback}
1570 % \changes{v1.0a}{2015/09/24}{Function added}
1571 % As we subvert the engine interface we need to provide a way to access
1572 % this functionality.
1574 local function disable_callback(name)
1575 if(callbacklist[name] == nil) then
1576 callback_register(name, false)
1578 luatexbase_error("Callback list for " .. name .. " not empty")
1581 luatexbase.disable_callback = disable_callback
1585 % \begin{macro}{callback_descriptions}
1586 % \changes{v1.0a}{2015/09/24}{Function added}
1587 % \changes{v1.0h}{2015/11/27}{Match test in in-callback latex/4445}
1588 % List the descriptions of functions registered for the given callback.
1590 local function callback_descriptions (name)
1594 or not callbacklist[name]
1595 or not callbacktypes[name]
1599 for k, i in pairs(callbacklist[name]) do
1605 luatexbase.callback_descriptions =callback_descriptions
1609 % \begin{macro}{uninstall}
1610 % \changes{v1.0e}{2015/10/02}{Function added}
1611 % Unlike at the \TeX{} level, we have to provide a back-out mechanism here
1612 % at the same time as the rest of the code. This is not meant for use by
1613 % anything other than \textsf{latexrelease}: as such this is
1614 % \emph{deliberately} not documented for users!
1616 local function uninstall()
1619 "Uninstalling kernel luatexbase code"
1621 callback.register = callback_register
1624 luatexbase.uninstall = uninstall
1633 % Reset the catcode of |@|.
1635 %<tex>\catcode`\@=\etatcatcode\relax