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 % functtion of |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 % \subsection{Minimum Lua\TeX{} version}
367 % Lua\TeX{} has changed a lot over time. In the kernel support for ancient
368 % versions is not provided: trying to build a format with a very old binary
369 % therefore gives some information in the log and loading stops. The cut-off
370 % selected here relates to the tree-searching behaviour of |require()|:
371 % from version~0.60, Lua\TeX{} will correctly find Lua files in the |texmf|
372 % tree without `help'.
374 %<latexrelease>\IncludeInRelease{2015/10/01}
375 %<latexrelease> {\newluafunction}{LuaTeX}%
376 \ifnum\luatexversion<60 %
377 \wlog{***************************************************}
378 \wlog{* LuaTeX version too old for ltluatex support *}
379 \wlog{***************************************************}
380 \expandafter\endinput
384 % \subsection{Older \LaTeX{}/Plain \TeX\ setup}
390 % Older \LaTeX{} formats don't have the primitives with `native' names:
391 % sort that out. If they already exist this will still be safe.
393 \directlua{tex.enableprimitives("",tex.extraprimitives("luatex"))}
397 \ifx\e@alloc\@undefined
400 % In pre-2014 \LaTeX{}, or plain \TeX{}, load |etex.{sty,src}|.
402 \ifx\documentclass\@undefined
403 \ifx\loccount\@undefined
407 \outer\expandafter\def\csname newfam\endcsname
408 {\alloc@8\fam\chardef\et@xmaxfam}
410 \RequirePackage{etex}
411 \expandafter\def\csname newfam\endcsname
412 {\alloc@8\fam\chardef\et@xmaxfam}
413 \expandafter\let\expandafter\new@mathgroup\csname newfam\endcsname
417 % \subsubsection{Fixes to \texttt{etex.src}/\texttt{etex.sty}}
419 % These could and probably should be made directly in an
420 % update to etex.src which already has some luatex-specific
421 % code, but does not define the correct range for luatex.
424 % 2015-07-13 higher range in luatex
425 \edef \et@xmaxregs {\ifx\directlua\@undefined 32768\else 65536\fi}
426 % luatex/xetex also allow more math fam
427 \edef \et@xmaxfam {\ifx\Umathchar\@undefined\sixt@@n\else\@cclvi\fi}
431 \count 270=\et@xmaxregs % locally allocates \count registers
432 \count 271=\et@xmaxregs % ditto for \dimen registers
433 \count 272=\et@xmaxregs % ditto for \skip registers
434 \count 273=\et@xmaxregs % ditto for \muskip registers
435 \count 274=\et@xmaxregs % ditto for \box registers
436 \count 275=\et@xmaxregs % ditto for \toks registers
437 \count 276=\et@xmaxregs % ditto for \marks classes
440 % and 256 or 16 fam. (Done above due to plain/\LaTeX\ differences in
441 % \textsf{ltluatex}.)
443 % \outer\def\newfam{\alloc@8\fam\chardef\et@xmaxfam}
446 % End of proposed changes to \texttt{etex.src}
448 % \subsubsection{luatex specific settings}
450 % Switch to global cf |luatex.sty| to leave room for inserts
451 % not really needed for luatex but possibly most compatible
454 \expandafter\let\csname newcount\expandafter\expandafter\endcsname
455 \csname globcount\endcsname
456 \expandafter\let\csname newdimen\expandafter\expandafter\endcsname
457 \csname globdimen\endcsname
458 \expandafter\let\csname newskip\expandafter\expandafter\endcsname
459 \csname globskip\endcsname
460 \expandafter\let\csname newbox\expandafter\expandafter\endcsname
461 \csname globbox\endcsname
464 % Define|\e@alloc| as in latex (the existing macros in |etex.src|
465 % hard to extend to further register types as they assume specific
466 % 26x and 27x count range. For compatibility the existing register
467 % allocation is not changed.
470 \chardef\e@alloc@top=65535
471 \let\e@alloc@chardef\chardef
475 \def\e@alloc#1#2#3#4#5#6{%
476 \global\advance#3\@ne
477 \e@ch@ck{#3}{#4}{#5}#1%
478 \allocationnumber#3\relax
479 \global#2#6\allocationnumber
480 \wlog{\string#6=\string#1\the\allocationnumber}}%
484 \gdef\e@ch@ck#1#2#3#4{%
488 \ifx\count#4\advance#1 10 \fi
492 \errmessage{No room for a new \string#4}%
497 % Two simple \LaTeX\ macros used in |ltlatex.sty|.
499 \long\def\@gobble#1{}
500 \long\def\@firstofone#1{#1}
504 % Fix up allocations not to clash with |etex.src|.
508 \expandafter\csname newcount\endcsname\e@alloc@attribute@count
509 \expandafter\csname newcount\endcsname\e@alloc@ccodetable@count
510 \expandafter\csname newcount\endcsname\e@alloc@luafunction@count
511 \expandafter\csname newcount\endcsname\e@alloc@whatsit@count
512 \expandafter\csname newcount\endcsname\e@alloc@bytecode@count
513 \expandafter\csname newcount\endcsname\e@alloc@luachunk@count
516 % End of conditional setup for plain \TeX\ / old \LaTeX.
523 % \subsection{Attributes}
525 % \begin{macro}{\newattribute}
526 % \changes{v1.0a}{2015/09/24}{Macro added}
527 % As is generally the case for the Lua\TeX{} registers we start here
528 % from~$1$. Notably, some code assumes that |\attribute0| is never used so
529 % this is important in this case.
531 \ifx\e@alloc@attribute@count\@undefined
532 \countdef\e@alloc@attribute@count=258
534 \def\newattribute#1{%
535 \e@alloc\attribute\attributedef
536 \e@alloc@attribute@count\m@ne\e@alloc@top#1%
538 \e@alloc@attribute@count=\z@
542 % \begin{macro}{\setattribute}
543 % \begin{macro}{\unsetattribute}
546 \def\setattribute#1#2{#1=\numexpr#2\relax}
547 \def\unsetattribute#1{#1=-"7FFFFFFF\relax}
552 % \subsection{Category code tables}
554 % \begin{macro}{\newcatcodetable}
555 % \changes{v1.0a}{2015/09/24}{Macro added}
556 % Category code tables are allocated with a limit half of that used by Lua\TeX{}
557 % for everything else. At the end of allocation there needs to be an
558 % initialisation step. Table~$0$ is already taken (it's the global one for
559 % current use) so the allocation starts at~$1$.
561 \ifx\e@alloc@ccodetable@count\@undefined
562 \countdef\e@alloc@ccodetable@count=259
564 \def\newcatcodetable#1{%
565 \e@alloc\catcodetable\chardef
566 \e@alloc@ccodetable@count\m@ne{"8000}#1%
567 \initcatcodetable\allocationnumber
569 \e@alloc@ccodetable@count=\z@
573 % \begin{macro}{\catcodetable@initex}
574 % \changes{v1.0a}{2015/09/24}{Macro added}
575 % \begin{macro}{\catcodetable@string}
576 % \changes{v1.0a}{2015/09/24}{Macro added}
577 % \begin{macro}{\catcodetable@latex}
578 % \changes{v1.0a}{2015/09/24}{Macro added}
579 % \begin{macro}{\catcodetable@atletter}
580 % \changes{v1.0a}{2015/09/24}{Macro added}
581 % Save a small set of standard tables. The Unicode data is read
582 % here in a group avoiding any global definitions: that needs a bit
583 % of effort so that in package/plain mode there is no effect on any
584 % settings already in force.
586 \newcatcodetable\catcodetable@initex
587 \newcatcodetable\catcodetable@string
589 \def\setrangecatcode#1#2#3{%
593 \expandafter\@firstofone
597 \expandafter\setrangecatcode\expandafter
598 {\number\numexpr#1 + 1\relax}{#2}{#3}
602 \catcodetable\catcodetable@initex
606 \setrangecatcode{65}{90}{12}%
607 \setrangecatcode{97}{122}{12}%
610 \savecatcodetable\catcodetable@string
613 \newcatcodetable\catcodetable@latex
614 \newcatcodetable\catcodetable@atletter
616 \let\ENDGROUP\endgroup
617 \let\begingroup\relax
621 \input{unicode-letters.def}%
622 \let\endgroup\ENDGROUP
625 \savecatcodetable\catcodetable@latex
627 \savecatcodetable\catcodetable@atletter
636 % \subsection{Named Lua functions}
638 % \begin{macro}{\newluafunction}
639 % \changes{v1.0a}{2015/09/24}{Macro added}
640 % Much the same story for allocating Lua\TeX{} functions except here they are
641 % just numbers so are allocated in the same way as boxes. Lua index from~$1$
642 % so once again slot~$0$ is skipped.
644 \ifx\e@alloc@luafunction@count\@undefined
645 \countdef\e@alloc@luafunction@count=260
647 \def\newluafunction{%
648 \e@alloc\luafunction\e@alloc@chardef
649 \e@alloc@luafunction@count\m@ne\e@alloc@top
651 \e@alloc@luafunction@count=\z@
655 % \subsection{Custom whatsits}
657 % \begin{macro}{\newwhatsit}
658 % \changes{v1.0a}{2015/09/24}{Macro added}
659 % These are only settable from Lua but for consistency are definable
662 \ifx\e@alloc@whatsit@count\@undefined
663 \countdef\e@alloc@whatsit@count=261
666 \e@alloc\whatsit\e@alloc@chardef
667 \e@alloc@whatsit@count\m@ne\e@alloc@top#1%
669 \e@alloc@whatsit@count=\z@
673 % \subsection{Lua bytecode registers}
675 % \begin{macro}{\newluabytecode}
676 % \changes{v1.0a}{2015/09/24}{Macro added}
677 % These are only settable from Lua but for consistency are definable
680 \ifx\e@alloc@bytecode@count\@undefined
681 \countdef\e@alloc@bytecode@count=262
683 \def\newluabytecode#1{%
684 \e@alloc\luabytecode\e@alloc@chardef
685 \e@alloc@bytecode@count\m@ne\e@alloc@top#1%
687 \e@alloc@bytecode@count=\z@
691 % \subsection{Lua chunk registers}
693 % \begin{macro}{\newluachunkname}
694 % \changes{v1.0a}{2015/09/24}{Macro added}
695 % As for bytecode registers, but in addition we need to add a string
696 % to the \verb|lua.name| table to use in stack tracing. We use the
697 % name of the command passed to the allocator, with no backslash.
699 \ifx\e@alloc@luachunk@count\@undefined
700 \countdef\e@alloc@luachunk@count=263
702 \def\newluachunkname#1{%
703 \e@alloc\luachunk\e@alloc@chardef
704 \e@alloc@luachunk@count\m@ne\e@alloc@top#1%
706 \directlua{lua.name[\the\allocationnumber]="\string#1"}}%
708 \e@alloc@luachunk@count=\z@
712 % \subsection{Lua loader}
714 % Load the Lua code at the start of every job.
715 % For the conversion of \TeX{} into numbers at the Lua side we need some
716 % known registers: for convenience we use a set of systematic names, which
717 % means using a group around the Lua loader.
719 %<2ekernel>\everyjob\expandafter{%
720 %<2ekernel> \the\everyjob
722 \attributedef\attributezero=0 %
723 \chardef \charzero =0 %
725 % Note name change required on older luatex, for hash table access.
727 \countdef \CountZero =0 %
728 \dimendef \dimenzero =0 %
729 \mathchardef \mathcharzero =0 %
730 \muskipdef \muskipzero =0 %
731 \skipdef \skipzero =0 %
732 \toksdef \tokszero =0 %
733 \directlua{require("ltluatex")}
736 %<latexrelease>\EndIncludeInRelease
740 % \changes{v1.0b}{2015/10/02}{Fix backing out of \TeX{} code}
741 % \changes{v1.0c}{2015/10/02}{Allow backing out of Lua code}
742 %<latexrelease>\IncludeInRelease{0000/00/00}
743 %<latexrelease> {\newluafunction}{LuaTeX}%
744 %<latexrelease>\let\e@alloc@attribute@count\@undefined
745 %<latexrelease>\let\newattribute\@undefined
746 %<latexrelease>\let\setattribute\@undefined
747 %<latexrelease>\let\unsetattribute\@undefined
748 %<latexrelease>\let\e@alloc@ccodetable@count\@undefined
749 %<latexrelease>\let\newcatcodetable\@undefined
750 %<latexrelease>\let\catcodetable@initex\@undefined
751 %<latexrelease>\let\catcodetable@string\@undefined
752 %<latexrelease>\let\catcodetable@latex\@undefined
753 %<latexrelease>\let\catcodetable@atletter\@undefined
754 %<latexrelease>\let\e@alloc@luafunction@count\@undefined
755 %<latexrelease>\let\newluafunction\@undefined
756 %<latexrelease>\let\e@alloc@luafunction@count\@undefined
757 %<latexrelease>\let\newwhatsit\@undefined
758 %<latexrelease>\let\e@alloc@whatsit@count\@undefined
759 %<latexrelease>\let\newluabytecode\@undefined
760 %<latexrelease>\let\e@alloc@bytecode@count\@undefined
761 %<latexrelease>\let\newluachunkname\@undefined
762 %<latexrelease>\let\e@alloc@luachunk@count\@undefined
763 %<latexrelease>\directlua{luatexbase.uninstall()}
764 %<latexrelease>\EndIncludeInRelease
768 %<2ekernel|latexrelease>\fi
769 %</2ekernel|tex|latexrelease>
772 % \subsection{Lua module preliminaries}
776 % \begingroup\lccode`~=`_
777 % \lowercase{\endgroup\let~}_
784 % Some set up for the Lua module which is needed for all of the Lua
785 % functionality added here.
787 % \begin{macro}{luatexbase}
788 % \changes{v1.0a}{2015/09/24}{Table added}
789 % Set up the table for the returned functions. This is used to expose
790 % all of the public functions.
792 luatexbase = luatexbase or { }
793 local luatexbase = luatexbase
797 % Some Lua best practice: use local versions of functions where possible.
799 local string_gsub = string.gsub
800 local tex_count = tex.count
801 local tex_setattribute = tex.setattribute
802 local tex_setcount = tex.setcount
803 local texio_write_nl = texio.write_nl
806 % \subsection{Lua module utilities}
808 % \subsubsection{Module tracking}
810 % \begin{macro}{modules}
811 % \changes{v1.0a}{2015/09/24}{Function modified}
812 % To allow tracking of module usage, a structure is provided to store
813 % information and to return it.
815 local modules = modules or { }
819 % \begin{macro}{provides_module}
820 % \changes{v1.0a}{2015/09/24}{Function added}
821 % \changes{v1.0f}{2015/10/03}{use luatexbase\_log}
822 % Local function to write to the log.
824 local function luatexbase_log(text)
825 texio_write_nl("log", text)
829 % Modelled on |\ProvidesPackage|, we store much the same information but
830 % with a little more structure.
832 local function provides_module(info)
833 if not (info and info.name) then
834 luatexbase_error("Missing module name for provides_modules")
837 local function spaced(text)
838 return text and (" " .. text) or ""
841 "Lua module: " .. info.name
843 .. spaced(info.version)
844 .. spaced(info.description)
846 modules[info.name] = info
848 luatexbase.provides_module = provides_module
852 % \subsubsection{Module messages}
854 % There are various warnings and errors that need to be given. For warnings
855 % we can get exactly the same formatting as from \TeX{}. For errors we have to
856 % make some changes. Here we give the text of the error in the \LaTeX{} format
857 % then force an error from Lua to halt the run. Splitting the message text is
858 % done using |\n| which takes the place of |\MessageBreak|.
860 % First an auxiliary for the formatting: this measures up the message
861 % leader so we always get the correct indent.
863 local function msg_format(mod, msg_type, text)
866 if mod == "LaTeX" then
867 cont = string_gsub(leader, ".", " ")
868 leader = leader .. "LaTeX: "
870 first_head = leader .. "Module " .. msg_type
871 cont = "(" .. mod .. ")"
872 .. string_gsub(first_head, ".", " ")
873 first_head = leader .. "Module " .. mod .. " " .. msg_type .. ":"
875 if msg_type == "Error" then
876 first_head = "\n" .. first_head
878 if string.sub(text,-1) ~= "\n" then
881 return first_head .. " "
885 .. tex.inputlineno, "\n", "\n" .. cont .. " "
891 % \begin{macro}{module_info}
892 % \changes{v1.0a}{2015/09/24}{Function added}
893 % \begin{macro}{module_warning}
894 % \changes{v1.0a}{2015/09/24}{Function added}
895 % \begin{macro}{module_error}
896 % \changes{v1.0a}{2015/09/24}{Function added}
899 local function module_info(mod, text)
900 texio_write_nl("log", msg_format(mod, "Info", text))
902 luatexbase.module_info = module_info
903 local function module_warning(mod, text)
904 texio_write_nl("term and log",msg_format(mod, "Warning", text))
906 luatexbase.module_warning = module_warning
907 local function module_error(mod, text)
908 error(msg_format(mod, "Error", text))
910 luatexbase.module_error = module_error
916 % Dedicated versions for the rest of the code here.
918 local function luatexbase_warning(text)
919 module_warning("luatexbase", text)
921 local function luatexbase_error(text)
922 module_error("luatexbase", text)
927 % \subsection{Accessing register numbers from Lua}
929 % Collect up the data from the \TeX{} level into a Lua table: from
930 % version~0.80, Lua\TeX{} makes that easy.
932 local luaregisterbasetable = { }
933 local registermap = {
934 attributezero = "assign_attr" ,
935 charzero = "char_given" ,
936 CountZero = "assign_int" ,
937 dimenzero = "assign_dimen" ,
938 mathcharzero = "math_given" ,
939 muskipzero = "assign_mu_skip" ,
940 skipzero = "assign_skip" ,
941 tokszero = "assign_toks" ,
945 if tex.luatexversion >79 then
946 createtoken = newtoken.create
948 local hashtokens = tex.hashtokens
949 local luatexversion = tex.luatexversion
950 for i,j in pairs (registermap) do
951 if luatexversion < 80 then
952 luaregisterbasetable[hashtokens()[i][1]] =
955 luaregisterbasetable[j] = createtoken(i).mode
960 % \begin{macro}{registernumber}
961 % Working out the correct return value can be done in two ways. For older
962 % Lua\TeX{} releases it has to be extracted from the |hashtokens|. On the
963 % other hand, newer Lua\TeX{}'s have |newtoken|, and whilst |.mode| isn't
964 % currently documented, Hans Hagen pointed to this approach so we should be
968 if luatexversion < 80 then
969 function registernumber(name)
970 local nt = hashtokens()[name]
971 if(nt and luaregisterbasetable[nt[1]]) then
972 return nt[2] - luaregisterbasetable[nt[1]]
978 function registernumber(name)
979 local nt = createtoken(name)
980 if(luaregisterbasetable[nt.cmdname]) then
981 return nt.mode - luaregisterbasetable[nt.cmdname]
987 luatexbase.registernumber = registernumber
991 % \subsection{Attribute allocation}
993 % \begin{macro}{new_attribute}
994 % \changes{v1.0a}{2015/09/24}{Function added}
995 % As attributes are used for Lua manipulations its useful to be able
996 % to assign from this end.
998 local attributes=setmetatable(
1001 __index = function(t,key)
1002 return registernumber(key) or nil
1005 luatexbase.attributes=attributes
1009 local function new_attribute(name)
1010 tex_setcount("global", "e@alloc@attribute@count",
1011 tex_count["e@alloc@attribute@count"] + 1)
1012 if tex_count["e@alloc@attribute@count"] > 65534 then
1013 luatexbase_error("No room for a new \\attribute")
1016 attributes[name]= tex_count["e@alloc@attribute@count"]
1017 luatexbase_log("Lua-only attribute " .. name .. " = " ..
1018 tex_count["e@alloc@attribute@count"])
1019 return tex_count["e@alloc@attribute@count"]
1021 luatexbase.new_attribute = new_attribute
1025 % \subsection{Custom whatsit allocation}
1027 % \begin{macro}{new_whatsit}
1028 % Much the same as for attribute allocation in Lua
1030 local function new_whatsit(name)
1031 tex_setcount("global", "e@alloc@whatsit@count",
1032 tex_count["e@alloc@whatsit@count"] + 1)
1033 if tex_count["e@alloc@whatsit@count"] > 65534 then
1034 luatexbase_error("No room for a new custom whatsit")
1037 luatexbase_log("Custom whatsit " .. (name or "") .. " = " ..
1038 tex_count["e@alloc@whatsit@count"])
1039 return tex_count["e@alloc@whatsit@count"]
1041 luatexbase.new_whatsit = new_whatsit
1045 % \subsection{Bytecode register allocation}
1047 % \begin{macro}{new_bytecode}
1048 % Much the same as for attribute allocation in Lua.
1049 % The optional \meta{name} argument is used in the log if given.
1051 local function new_bytecode(name)
1052 tex_setcount("global", "e@alloc@bytecode@count",
1053 tex_count["e@alloc@bytecode@count"] + 1)
1054 if tex_count["e@alloc@bytecode@count"] > 65534 then
1055 luatexbase_error("No room for a new bytecode register")
1058 luatexbase_log("Lua bytecode " .. (name or "") .. " = " ..
1059 tex_count["e@alloc@bytecode@count"])
1060 return tex_count["e@alloc@bytecode@count"]
1062 luatexbase.new_bytecode = new_bytecode
1066 % \subsection{Lua chunk name allocation}
1068 % \begin{macro}{new_chunkname}
1069 % As for bytecode registers but also store the name in the
1072 local function new_chunkname(name)
1073 tex_setcount("global", "e@alloc@luachunk@count",
1074 tex_count["e@alloc@luachunk@count"] + 1)
1075 local chunkname_count = tex_count["e@alloc@luachunk@count"]
1076 chunkname_count = chunkname_count + 1
1077 if chunkname_count > 65534 then
1078 luatexbase_error("No room for a new chunkname")
1081 lua.name[chunkname_count]=name
1082 luatexbase_log("Lua chunkname " .. (name or "") .. " = " ..
1083 chunkname_count .. "\n")
1084 return chunkname_count
1086 luatexbase.new_chunkname = new_chunkname
1090 % \subsection{Lua callback management}
1092 % The native mechanism for callbacks in Lua allows only one per function.
1093 % That is extremely restrictive and so a mechanism is needed to add and
1094 % remove callbacks from the appropriate hooks.
1096 % \subsubsection{Housekeeping}
1098 % The main table: keys are callback names, and values are the associated lists
1099 % of functions. More precisely, the entries in the list are tables holding the
1100 % actual function as |func| and the identifying description as |description|.
1101 % Only callbacks with a non-empty list of functions have an entry in this
1104 local callbacklist = callbacklist or { }
1107 % Numerical codes for callback types, and name-to-value association (the
1108 % table keys are strings, the values are numbers).
1110 local list, data, exclusive, simple = 1, 2, 3, 4
1114 exclusive = exclusive,
1119 % Now, list all predefined callbacks with their current type, based on the
1120 % Lua\TeX{} manual version~0.80. A full list of the currently-available
1121 % callbacks can be obtained using
1124 % for i,_ in pairs(callback.list()) do
1125 % texio.write_nl("- " .. i)
1130 % in plain Lua\TeX{}. (Some undocumented callbacks are omitted as they are
1133 local callbacktypes = callbacktypes or {
1135 % Section 4.1.1: file discovery callbacks.
1137 find_read_file = exclusive,
1138 find_write_file = exclusive,
1139 find_font_file = data,
1140 find_output_file = data,
1141 find_format_file = data,
1142 find_vf_file = data,
1143 find_map_file = data,
1144 find_enc_file = data,
1145 find_sfd_file = data,
1146 find_pk_file = data,
1147 find_data_file = data,
1148 find_opentype_file = data,
1149 find_truetype_file = data,
1150 find_type1_file = data,
1151 find_image_file = data,
1153 % Section 4.1.2: file reading callbacks.
1155 open_read_file = exclusive,
1156 read_font_file = exclusive,
1157 read_vf_file = exclusive,
1158 read_map_file = exclusive,
1159 read_enc_file = exclusive,
1160 read_sfd_file = exclusive,
1161 read_pk_file = exclusive,
1162 read_data_file = exclusive,
1163 read_truetype_file = exclusive,
1164 read_type1_file = exclusive,
1165 read_opentype_file = exclusive,
1167 % Section 4.1.3: data processing callbacks.
1169 process_input_buffer = data,
1170 process_output_buffer = data,
1171 process_jobname = data,
1172 token_filter = exclusive,
1174 % Section 4.1.4: node list processing callbacks.
1176 buildpage_filter = simple,
1177 pre_linebreak_filter = list,
1178 linebreak_filter = list,
1179 post_linebreak_filter = list,
1180 hpack_filter = list,
1181 vpack_filter = list,
1182 pre_output_filter = list,
1184 ligaturing = simple,
1186 mlist_to_hlist = list,
1188 % Section 4.1.5: information reporting callbacks.
1193 start_page_number = simple,
1194 stop_page_number = simple,
1195 show_error_hook = simple,
1196 show_error_message = simple,
1197 show_lua_error_hook = simple,
1198 start_file = simple,
1201 % Section 4.1.6: PDF-related callbacks.
1203 finish_pdffile = data,
1204 finish_pdfpage = data,
1206 % Section 4.1.7: font-related callbacks.
1208 define_font = exclusive,
1210 % Undocumented callbacks which are likely to get documented.
1212 find_cidmap_file = data,
1213 pdf_stream_filter_callback = data,
1215 luatexbase.callbacktypes=callbacktypes
1218 % \begin{macro}{callback.register}
1219 % \changes{v1.0a}{2015/09/24}{Function modified}
1220 % Save the original function for registering callbacks and prevent the
1221 % original being used. The original is saved in a place that remains
1222 % available so other more sophisticated code can override the approach
1223 % taken by the kernel if desired.
1225 local callback_register = callback_register or callback.register
1226 function callback.register()
1227 luatexbase_error("Attempt to use callback.register() directly\n")
1232 % \subsubsection{Handlers}
1234 % The handler function is registered into the callback when the
1235 % first function is added to this callback's list. Then, when the callback
1236 % is called, then handler takes care of running all functions in the list.
1237 % When the last function is removed from the callback's list, the handler
1240 % More precisely, the functions below are used to generate a specialized
1241 % function (closure) for a given callback, which is the actual handler.
1243 % Handler for |data| callbacks.
1245 local function data_handler(name)
1246 return function(data, ...)
1248 for _,i in ipairs(callbacklist[name]) do
1249 data = i.func(data,...)
1255 % Handler for |exclusive| callbacks. We can assume |callbacklist[name]| is not
1256 % empty: otherwise, the function wouldn't be registered in the callback any
1259 local function exclusive_handler(name)
1260 return function(...)
1261 return callbacklist[name][1].func(...)
1265 % Handler for |list| callbacks.
1267 local function list_handler(name)
1268 return function(head, ...)
1270 local alltrue = true
1272 for _,i in ipairs(callbacklist[name]) do
1273 ret = i.func(head, ...)
1274 if ret == false then
1276 "Function `i.description' returned false\n"
1277 .. "in callback `name'"
1286 return alltrue and true or head
1290 % Handler for |simple| callbacks.
1292 local function simple_handler(name)
1293 return function(...)
1295 for _,i in ipairs(callbacklist[name]) do
1302 % Keep a handlers table for indexed access.
1305 [data] = data_handler,
1306 [exclusive] = exclusive_handler,
1307 [list] = list_handler,
1308 [simple] = simple_handler,
1312 % \subsubsection{Public functions for callback management}
1314 % Defining user callbacks perhaps should be in package code,
1315 % but impacts on |add_to_callback|.
1316 % If a default function is not required, may may be declared as |false|.
1317 % First we need a list of user callbacks.
1319 local user_callbacks_defaults = { }
1322 % \begin{macro}{create_callback}
1323 % \changes{v1.0a}{2015/09/24}{Function added}
1324 % The allocator itself.
1326 local function create_callback(name, ctype, default)
1329 callbacktypes[name] or
1330 not(default == false or type(default) == "function")
1332 luatexbase_error("Unable to create callback " .. name)
1334 user_callbacks_defaults[name] = default
1335 callbacktypes[name] = types[ctype]
1337 luatexbase.create_callback = create_callback
1341 % \begin{macro}{call_callback}
1342 % \changes{v1.0a}{2015/09/24}{Function added}
1343 % Call a user defined callback. First check arguments.
1345 local function call_callback(name,...)
1348 user_callbacks_defaults[name] == nil
1350 luatexbase_error("Unable to call callback " .. name)
1352 local l = callbacklist[name]
1355 f = user_callbacks_defaults[name]
1360 f = handlers[callbacktypes[name]](name)
1364 luatexbase.call_callback=call_callback
1368 % \begin{macro}{add_to_callback}
1369 % \changes{v1.0a}{2015/09/24}{Function added}
1370 % Add a function to a callback. First check arguments.
1372 local function add_to_callback(name, func, description)
1376 not callbacktypes[name] or
1377 type(func) ~= "function" or
1379 description == "" then
1381 "Unable to register callback.\n\n"
1382 .. "Correct usage:\n"
1383 .. "add_to_callback(<callback>, <function>, <description>)"
1388 % Then test if this callback is already in use. If not, initialise its list
1389 % and register the proper handler.
1391 local l = callbacklist[name]
1394 callbacklist[name] = l
1396 % If it is not a user defined callback use the primitive callback register.
1398 if user_callbacks_defaults[name] == nil then
1399 callback_register(name, handlers[callbacktypes[name]](name))
1403 % Actually register the function and give an error if more than one
1404 % |exclusive| one is registered.
1408 description = description,
1410 local priority = #l + 1
1411 if callbacktypes[name] == exclusive then
1414 "Cannot add second callback to exclusive function\n`" ..
1418 table.insert(l, priority, f)
1420 % Keep user informed.
1423 "Inserting `" .. description .. "' at position "
1424 .. priority .. " in `" .. name .. "'."
1427 luatexbase.add_to_callback = add_to_callback
1431 % \begin{macro}{remove_from_callback}
1432 % \changes{v1.0a}{2015/09/24}{Function added}
1433 % Remove a function from a callback. First check arguments.
1435 local function remove_from_callback(name, description)
1439 not callbacktypes[name] or
1441 description == "" then
1443 "Unable to remove function from callback.\n\n"
1444 .. "Correct usage:\n"
1445 .. "remove_from_callback(<callback>, <description>)"
1449 local l = callbacklist[name]
1452 "No callback list for `" .. name .. "'\n")
1455 % Loop over the callback's function list until we find a matching entry.
1456 % Remove it and check if the list is empty: if so, unregister the
1462 for i,j in ipairs(l) do
1463 if j.description == description then
1470 "No callback `" .. description .. "' registered for `" ..
1475 table.remove(l, index)
1477 "Removing `" .. description .. "' from `" .. name .. "'."
1480 callbacklist[name] = nil
1481 callback_register(name, nil)
1483 return cb.func,cb.description
1485 luatexbase.remove_from_callback = remove_from_callback
1489 % \begin{macro}{in_callback}
1490 % \changes{v1.0a}{2015/09/24}{Function added}
1491 % Look for a function description in a callback.
1493 local function in_callback(name, description)
1496 or not callbacktypes[name]
1497 or not description then
1501 for _, i in pairs(callbacklist[name]) do
1502 if i.description == description then
1508 luatexbase.in_callback = in_callback
1512 % \begin{macro}{disable_callback}
1513 % \changes{v1.0a}{2015/09/24}{Function added}
1514 % As we subvert the engine interface we need to provide a way to access
1515 % this functionality.
1517 local function disable_callback(name)
1518 if(callbacklist[name] == nil) then
1519 callback_register(name, false)
1521 luatexbase_error("Callback list for " .. name .. " not empty")
1524 luatexbase.disable_callback = disable_callback
1528 % \begin{macro}{callback_descriptions}
1529 % \changes{v1.0a}{2015/09/24}{Function added}
1530 % List the descriptions of functions registered for the given callback.
1532 local function callback_descriptions (name)
1536 or not callbacktypes[name]
1541 for k, i in pairs(callbacklist[name] or {}) do
1547 luatexbase.callback_descriptions =callback_descriptions
1551 % \begin{macro}{uninstall}
1552 % \changes{v1.0e}{2015/10/02}{Function added}
1553 % Unlike at the \TeX{} level, we have to provide a back-out mechanism here
1554 % at the same time as the rest of the code. This is not meant for use by
1555 % anything other than \textsf{latexrelease}: as such this is
1556 % \emph{deliberately} not documented for users!
1558 local function uninstall()
1561 "Uninstalling kernel luatexbase code"
1563 callback.register = callback_register
1566 luatexbase.uninstall = uninstall
1575 % Reset the catcode of |@|.
1577 %<tex>\catcode`\@=\etatcatcode\relax