Changes

Jump to navigation Jump to search
2,080 bytes added ,  07:15, 13 July 2023
m
→‎Undefined Commands in Lua Comments: Fix a broken link. And add enough information to be able to re-fix it easily. (I guess this last part could go in a footnote reference, but I am not sure how to do that properly…)
{{note | This is a wikified version of [https://www.tug.org/members/TUGboat/tb30-2/tb95mahajan-luatex.pdf this TugBoat article ]. Feel free to modify it. }}= Calling Lua from TeX =
In this article, I explain how to use lua to write macros in [[LuaTeX]]. I give some examples The interweaving of ConTeXt and Lua consists of macros two elements: first you tell TeX that are complicated in [[PdfTeX]]you're starting some Lua code; then, but can be defined easily using lua in luaTeX. These examples include macros that do arithmetic on their argumentsonce inside Lua, you need to use loops, and parse their argumentsthe appropriate functions to put things into the TeX stream.
There are two main ways to execute Lua code in a ConTeXt document: The command {{cmd|ctxlua}}, and the environment {{cmd|startluacode}}…{{cmd|stopluacode}}. Both are wrappers around the LuaTeX primitive {{cmd|directlua}}, which you should never need to use. In general, you will define a function inside a {{cmd|startluacode}} block, and then define a TeX command that calls the function using {{cmd|ctxlua</code>, especially because {{cmd|ctxlua}} has a few idiosyncracies. <blockquote>The main thing about Lua code in a TeX document is this: the code is expanded by TeX ''before'' Lua gets to it. '''This means that all the Lua code, even the comments, must be valid TeX!''' A string like {{cmd|undefined}} will cause an immediate failure.</blockquote> = Introduction =Calling a bit of Lua inline: {{cmd|ctxlua}} == The command {{cmd|ctxlua}} is for short inline snippets of Lua, suchas
As its name suggests, [[LuaTeX]] adds lua, a programming language, to TeX, the typesetter. This allows us to program TeX in a high-level programming language. For example, consider a TeX macro that divides two numbers. Such a macro is provided by the <tt>fp</tt> package and also by <tt>pgfmath</tt> library of the <tt>TikZ</tt> package. The following comment is from the <tt>fp</tt> package
<texcode>
\def\FP@div#1#$2.#3.#4+ 5 \relax#5.#6.#7neq \relaxctxlua{% % [...] algorithmic idea context(for x>03+5)}$, y>0) % - %determine but is equal to \FP@shift such that % y*10^\FP@shift < 100000000 % <=y*10^ctxlua{context(\FP@shift2+15)}. % - %determine This is \FP@shift' such that % x*10^\FP@shift'< 100000000 % <=x*10^ctxlua{context(string.upper(\FP@shift+1"absolutely")) % - x=x*\FP@shift' % - y=y*\FP@shift % - \FP@shift=\FP@shift-\FP@shift' % - res=0 % - while y>0 %fixed-point representation! % - \FP@times=0 % - while x>y % - \FP@times=\FP@times+1 % - x=x-y % - end % - y=y/10 % - res=10*res+\FP@times/1000000000 % - end % - %shift the result according to \FP@shift} true.
</texcode>
The <tt>pgfmath</tt> library implements {{cmd|ctxlua}} operates under the macro in a similar way, but limits the number of shifts that it doesnormal TeX catcodes (category codes). These macros highlight This means the state of affairs in writing TeX macros. Even simple following two things like multiplying two numbers are hard; you either have to work extremely hard to circumvent for the programming limitations of Lua code inside:* all newlines get treated as spaces* special TeXcharacters like &, #, $, or{, more frequently}, hope that someone else has done the hard work for youetc., need to be escaped.  In luaTeXaddition, such a function can be written using the <warning above still holds. All the Lua code>/</, even the comments, must be valid TeX. Some code> operator (I will explain to illustrate the details later)newline problem:
<texcode>
\def\DIVIDE#1#2ctxlua {-- A Lua comment tex.print("This is not printed")}\directluactxlua {% A Tex comment tex.print(#1/#2"This is printed")}}
</texcode>
ThusThe problem with special TeX characters. (<code>#t</code> is Lua for 'the length of array <code>t</code>.)<texcode>% This doesn't work:%\ctxlua% {local t = {1,2,3,4}% tex.print("length " .. #t)}\ctxlua {local t = {1,2,3, 4} tex.print("length " .. \string#t)}</texcode>  == Calling a lua function with luaTeX ordinary users {{cmd|cldcontext}} and get the return == One can write simple macros; execute a Lua code from within TeX andget back the result in TeX by using {{cmd|cldcontext}}. Thus, if {{code|myfunction}} is a function of a variable {{code|x}} defined in Lua, perhaps more importantly{{cmd|cldcontext|{myfunction(5)}}} returns the value {{code|myfunction(5)}} in TeX. This is equivalent to {{cmd|ctxlua|{context(myfunction(5))}}}.  == A larger Lua block: {{cmd|startluacode}}…{{cmd|stopluacode}} == Inside the {{cmd|startluacode}}…{{cmd|stopluacode}} environment, can read newlines and understand macros written by special characters behave normally. This solves the catcode problem that {{cmd|ctxlua}} suffers from. Apart from these special characters, the main warning remains in force: all the Lua code, even the comments, must be valid TeX wizards<texcode>\startluacode -- The unknown command \undefined will cause this entire block to fail.  -- Print a countdown '10, 8, …, 0!' -- `..` is Lua for string concatenation for i = 10, 2, -2 do context(i .. ", ") end context("0!")
Since the luaTeX project started it has been actively supported by ConTeXt. <ref>Not surprising, as two of luaTeX's main developers -- \Dash Taco Hoekwater and Hans Hagen\Dash are also par is equivalent to a blank line in the main ConTeXt developers.</ref> These days, input -- (Notice the various <em>How do I write such a macro</em> questions on escaped backslash: TeX won't mind the ConTeXt mailing list are answered by a solution that uses lua. I present a few such examples in this article. I have deliberately avoided examples about [[Fonts in LuaTeX | fonts]] and non-Latin languages. There is already quite a bit of documentation about themabove comment. In this article, I highlight how to use luaTeX to write macros that require some <em>flow control</em>: randomized outputs, loops, and parsing) context.par()
= Interaction between TeX -- Look! we can use # and lua =$ with impunity! context("Unless we print them, then we must \\#\\$\\& print the escape characters, too.")\stopluacode</texcode>
To a first approximation, the interaction between TeX and lua is straightforward. When TeX (i.e., the luaTeX engine) starts, it loads the input file in memory and processes it token by token. When TeX encounters <== Putting Lua code>\directlua</code>, it stops reading the file in memory, <em>fully expands the argument of <code>\directlua</code></em>, and passes the control to a lua instance. The lua instance, which runs with a few preloaded libraries, processes the expanded arguments of <code>\directlua</code>. This lua instance has a special output stream which can be accessed using <code>tex.print(...)</code>. The function <code>tex.print(...)</code> is just like the lua function <code>print(...)</code> except that <code>tex.print(...)</code> prints to a <em>TeX stream</em> rather than to the standard output. When the lua instance finishes processing its input, it passes the contents of the <em>TeX stream</em> back to TeX.<ref>The output of <code>tex.print(...)</code> is buffered and not passed to TeX until the lua instance has stopped.</ref> TeX then inserts the contents of the <em>TeX stream</em> at the current location of the an external file that it was reading; expands the contents of the <em>TeX stream</em>; and continues. If TeX encounters another <code>\directlua</code>, the above process is repeated. ==
As You can put your lua code in an exercise, imagine what happens when external file (with the following input is processed by luaTeX. <refcode>In this example, I used two different kinds of quotations to avoid escaping quotes. Escaping quotes inside <code>\directlualua</code> is tricky. The above was a contrived example; if you ever need to escape quotes, you can use extension) and include it with the <code>\startluacode ... \stopluacoderequire</code> syntax explained later.</ref>command:
<texcode>
\directlua%startluacode {tex-- include the file my-lua-lib.printluarequire("Depth 1 my-lua-lib") \stopluacode</texcode> == Namespaces == It is a good habit to put your custom-defined functions in their own namespace. The traditional namespace for this is <code>userdata</code>:<texcode>\directluastartluacode -- if userdata doesn't exist yet, create it userdata = userdata or {tex} -- define a shorter synonym u = userdata  -- create my custom function inside the userdata namespace function u.printmyfunction('Depth 2')}")} -- do stuff end\stopluacode
</texcode>
On top The full list of these luaTeX primitivescanonical namespaces, ConTeXt provides a higher level interfacetaken from [https://distribution. There are two ways to call lua from ConTeXtcontextgarden.net/current/context/latest/tex/context/base/mkxl/luat-ini.lmt luat-ini. The first is a macro lmt]: <code>\ctxlua</codepre> userdata = userdata or { } -- for users (read as ConTeXt luae.g. functions etc), which is similar to thirddata = thirddata or { } -- only for third party modulesmoduledata = moduledata or { } -- only for development teamdocumentdata = documentdata or { } -- for users (e.g. raw data)parametersets = parametersets or { } -- experimental for team<code/pre>\directlua</code>. (Aside: It  If your module, environment, or document is possible going to run the lua instance under different name spacesbe used by other people, you should create your own subnamespaces within these tables.  <code>\ctxlua</codepre> is the default name space; other name spaces are explained latermoduledata['mymodule'] = { }mm = moduledata.mymodulefunction mm.mainfunction() -- do stuffend<code/pre>\ctxlua</code> is good for calling small snippets of lua. The argument of < == Undefined Commands in Lua Comments == Lua code>\ctxlua</code> is parsed under normal invoked inside TeX doesn’t allow TeX catcodes (category codes), so the end of line character has the same catcode as a space. This can lead to surprises. For example, if you try to use a lua comment, everything after the comment gets ignoredundefined commands ''even inside comments''
<texcode>
\starttext\startluacode--\undefinedcommandfromme\stopluacodeHello\ctxlua {-- A lua comment\undefinedcommandfromme} tex.print("This is not printed")}\stoptext
</texcode>
This can be avoided by using a TeX comment instead of a lua comment. However, To get the sample above working under normal TeX catcodes poses a bigger problem(as [https: special TeX characters like \letterampersand, \letterhash, \letterdollar, \{, \}, etc//www.mail-archive., need to be escapedcom/ntg-context@ntg. For example, \letterhash\ has to be escaped with <code>\string<nl/code> to be used msg103892.html explained by Hans in <code>\ctxlua</code>a NTG-context thread from jan.2023 entitled “Minor bug in Lua or ConTeXt”]), you would need a fallback definition: 
<texcode>
\ctxlua {local t = {1,2,3,4} tex.print("length " .. ifdefined\string#t)}undefinedcommandfromme \else \let\undefinedcommandfromme\relax \fi
</texcode>
As the argument of <code>\ctxlua</code> {{cmd|undefinedcommandfromme}} gets only defined (as {{cmd|relax}}, to do nothing), if and only if it is fully expanded, escaping characters can sometimes be trickyundefined. To circumvent this problem = Calling TeX from Lua = Being a topic on itself, pages are dedicated:* '''[[CLD|ConTeXt defines a environment called <code>\startluacode Lua Documents]]''', or CLD, are way to access TeX from inside Lua scripts.A page give clues about [[CLD_passing_variables|passing variables]] within CLD (2018).. \stopluacode<* [[Lua|Wiki page dedicated to Lua]]** [[Extensions to the Lua I/code>O library]]** [[String manipulation]]** [[Table manipulation]] = Putting stuff in your TeX document from Lua = == Simple printing: context(), tex. This sets the catcodes to what one would expect in luaprint(), and tex. Basically only sprint() ==Use <code>\context(…)</code> has its usual TeX meaning, the catcode of everything else for most things. It is set equivalent to other. So, for all practical purposes, we can forget about catcodes inside <code>\startluacode tex.print(string.. \stopluacodeformat(…))</code>. The above two examples can be written as, so 
<texcode>
\startluacode
-- A lua comment tex.print(name = "This is printed.Jane") local t date = {1,2,3,4}"today" tex.printcontext("length Hello %s, how are you %s?" .. #t, name, date)-- Becomes 'Hello Jane, how are you today?'
\stopluacode
</texcode>
This environment is meant for moderately sized More primitively, you have <code>tex.print()</code> and <code snippets>tex. For longer lua sprint()</code>. Either one can take as an argument either a number of strings, it or an array of strings, and will then insert the strings into the TeX stream. The only difference is more convenient to write the that <code>tex.print()</code in > treats each string as a separate lua file and then load it using lua's input line, while <code>dofiletex.sprint()</code> doesn't.So the following lines <texcode>\ctxlua{tex.print("a", "b")}\ctxlua{tex.print({"a", "b"})}</texcode> are both interpreted by TeX as <texcode>ab</codetexcode> function.
ConTeXt also provides a lua function to conveniently write to the TeX stream. The function is called <code>context(...)</code> and it is equivalent to but when we use <code>tex.print(string.format(...))sprint</code>. instead, either of the following
Using the above, it is easy to define TeX macros that pass control to lua, do some processing in lua, and then pass the result back to TeX. For example, a macro to convert a decimal number to hexadecimal can be written simply, by asking lua to do the conversion.
<texcode>
\def\TOHEX#1{\ctxlua{contexttex.sprint("\%Xa",#1"b")}}\TOHEXctxlua{35tex.sprint({"a", "b"})}
</texcode>
The percent sign had to will be escaped because read by TeX as <codetexcode>\ctxluaab</codetexcode> assumes TeX catcodes without any space in between. Sometimes == Context commands == Most commands that you would type with a backslash in plain ConTeXt, escaping arguments you can be difficult; instead, it can be easier to define a lua function inside access from Lua with <code>\startluacode context... \stopluacode</codeem> and call it using command<code/em>\ctxlua</code>. For example, a macro that takes a comma separated list of Unadorned strings and prints a random item can be written end up in TeX as arguments in curly braces; Lua tables end up in TeX as paramater blocks in square brackets. The following two pieces of code are equivalent: 
<texcode>
\startluacode
userdata = userdata or context.chapter({first}, "Some title") math context.randomseedstartcolumns( os{n = 3, rule = "on"}) context("Hello one") context.timecolumn() context("Hello two") function userdata context.randomcolumn(...) context("Hello three") context(arg[math.randomstopcolumns(1, #arg)]) end
\stopluacode
\def\CHOOSERANDOM#1% {\ctxlua{userdata.random(#1)}}</texcode>
<texcode> \CHOOSERANDOMchapter[first]{"Some title} \startcolumns[n=3, rule=on] Hello one", " \column Hello two", " \column Hello three"} \stopcolumns
</texcode>
I could have written For a wrapper so that fuller account of the function takes a list of words and chooses a random word among themcontext. For an example of such a conversioncommands, see the <em>sorting a list of tokens</em> page on the [http://luatexwww.bluwikipragma-ade.comnl/gogeneral/Sort_a_token_list luaTeX wikimanuals/cld-mkiv.pdf ConTeXt Lua document]manual. It is old, but most of it still applies.
In One final note: arguments can also be specified in the form of nested functions. Because LuaTeX evaluates the abovedeepest-nested argument first, I created a name space called <code>userdata</code> and defined this may cause the function <code>randomcontext()</code> calls to be evaluated in that name spacethe wrong order. Using a name space avoids clashes with For more on this, see the lua functions defined in luaTeX article on [[CLD|ConTeXt Lua documents]], and ConTeXtalso, again, the [http://www.pragma-ade.nl/general/manuals/cld-mkiv.pdf CLD manual].
In order to avoid name clashes, = Passing arguments and buffers: ConTeXt also defines independent name spaces of lua instances. They are commands that hook into Lua =
== Making \command{| |- | user arg1}{arg2} hook into Lua == | First, define a private user instance |- | third | third party module instance |- | module | ConTeXt module instance |- | isolated | an isolated instance |}Lua function:
Thus, for example, instead of <code>\ctxlua</code> and <code>\startluacode ... \stopluacode</code>, the <code>user</code> instance can be accessed via the macros <code>\usercode</code> and <code>\startusercode ... \stopusercode</code>. In instances other than <code>isolated</code>, all the lua functions defined by ConTeXt (but not the inbuilt lua functions) are stored in a <code>global</code> name space. In the <code>isolated</code> instance, all lua functions defined by ConTeXt are hidden and cannot be accessed. Using these instances, we could write the above <code>\CHOOSERANDOM</code> macro as follows
<texcode>
\startusercodestartluacode math -- remember, using the userdata namespace prevents conflicts userdata = userdata or {}  function userdata.randomseedsurroundwithdashes(str) context( global"--" .os.timestr .. "--") end\stopluacode</texcode> Then define the TeX command that expands to a {{cmd|ctxlua}} call: <texcode>\def\surroundwd#1% {\ctxlua{userdata.surroundwithdashes([==[#1]==]) )}}</texcode> ''NB'': quoting with <code>[==[#1]==]</code> function random([http://www.lua.org/manual/5.2/manual.html#3.1 long strings]) globalworks just like <code>"#1"</code> in most cases, but in addition it is robust against <code>#1</code> containing the quotation mark<code>"</code> which would terminate the Lua string prematurely.Inside {{cmd|protect}}…{{cmd|unprotect}} the macros {{cmd|!!bs}}and {{cmd|!!es} are at your disposition.They are equivalent to <code>[===[</code> and <code>]===]</code> and --being single tokens to TeX -- parsed faster.context(argSee [mathhttp://repo.or.cz/w/context.git/blob/refs/heads/origin:/tex/context/base/luat-ini.random(1, mkiv#arg)l174 <code>luat-ini.mkiv</code>].) end== Making {{cmd|startenv}}…{{cmd|stopenv}} hook into Lua ==The first job is, as ever, to have the Lua function at the ready<texcode>\stopusercodestartluacode userdata = userdata or {}
function userdata.verynarrow(buffer) -- equivalent to \def\CHOOSERANDOM#1%startnarrower[10em] context.startnarrower({\usercode{random"10em"}) context(buffer) context.stopnarrower(#1)}} end\stopluacode
</texcode>
Since I defined the function <code>random</code> in the <code>user</code> instance of lua, I did not bother to use a separate name space for the function. The lua functions <code>os.time</code>, which is defined by a luaTeX library, and <code>context</code>, which is defined by ConTeXt, needed to be accessed through a <code>global</code> name space. On the other handNext, we define the <code>math.randomseed</code> function, which is part start command of lua, could be accessed as is. our custom buffer:
A separate lua instance also makes debugging slightly easier. With <code>\ctxlua</code> the error message starts with
<texcode>
! LuaTeX error &lt;main ctx instance&gt;\def\startverynarrow% {\dostartbuffer [verynarrow] % buffer name [startverynarrow] % command where buffer starts [stopverynarrow]} % command where buffer ends % also:command invoked when buffer stops 
</texcode>
With Lastly, we define the {{cmd|stopverynarrow}} command such that it passes the recently-complated buffer to our <code>\usercodeverynarrow</code> the error message starts withLua function: 
<texcode>
! LuaTeX error &lt;private user instance&gt;:\def\stopverynarrow {\ctxlua {userdata.verynarrow(buffers.getcontent('verynarrow'))}}
</texcode>
This makes And that's it easier to narrow down the source ! The rest of errorthis article will consist of examples.
Normally, it is best to define your lua functions in the <code>user</code> name space. If you are writing a module, then define your lua functions in the <code>third</code> instance and in a name space which is the name of your module. In this article, I will simply use the default lua instance, but take care to define all my lua functions in a <code>userdata</code> name space.= Examples =
Now that we have some idea of how to work with luaTeX, let's look at some examples.== Arithmetic without using an abacus ==
= Arithmetic without using a abacus =''This example demonstrates writing simple commands that invoke \ctxlua.''
Doing simple arithmetic in TeX can be extremely difficult, as illustrated by the division macro in the introduction. With luaLua, simple arithmetic becomes trivial. For example, if you want a macro to find the cosine of an angle (in degrees), you can write
<texcode>
\def\COSINE#1%
$\pi = \ctxlua{context(math.pi)}$
</texcode>
or , if you want less precision (notice the percent sign is escaped):
<texcode>
$\pi = \ctxlua{context("\%letterpercent.6f", math.pi)}$
</texcode>
Notice that the percent sign is escaped with letterpercent.
= Loops without worrying about expansion == mathexpr with LMTX ===
In LMTX there is a new way to use calculated expressions with mathexpr through ([https://github.com/contextgarden/context-mirror/blob/7fd782dace8f90e7e032ca8f449f8ca4eada450b/doc/context/sources/general/manuals/math/math-fun.tex math-fun]). Some examples are: <texcode>$ \pi = \mathexpr[.40N]{pi} $$ \pi = \mathexpr[.80N]{sqrt(11)} $$ \pi = \decimalexpr[.80N]{sqrt(11)} $$ \pi = \decimalexpr{sqrt(11)} $$ c = \complexexpr{123 + new(456,789)} $</texcode> == Loops without worrying about expansion == ''This example demonstrates using Lua to write a quasi-repetitive piece of ConTeXt code.'' Loops in TeX are tricky , because macro assignments and macro expansion interact in strange ways. For example, suppose we want to typeset a table showing the sum of the roll of two dice and want the output to look like this:
<context source="yes">
\setupcolors[state=start]
</context>
The tedious (but faster!) way to achieve this This is to simply type easy in LuaTeX. Once a Lua instance starts, TeX does not see anything until the whole table by handLua instance exits.  It is however natural to want to So, we can write this table as a the loopin Lua, and compute simply print the valuesthat we would have typed to the TeX stream. When the control is passed to TeX, TeX sees the input as if we had typed it by hand. A first ConTeXt implementation using This is the Lua code for the recursion level might beabove table:
<texcode>
\bTABLE \bTR \bTD $(+)$ \eTD \dorecurse{6} {\bTD \recurselevel \eTD} setupcolors[state=start] \eTR \dorecursesetupTABLE[each][each][width=2em,height=2em,align={6middle,middle} ] {\bTR setupTABLE[r][1][background=color,backgroundcolor=gray] \bTD \recurselevel \eTD \edef\firstrecurselevel{\recurselevel} \dorecurse{6} {\bTD \the\numexpr\firstrecurselevel+\recurselevel \eTD}% \eTR} \eTABLE</texcode>setupTABLE[c][1][background=color,backgroundcolor=gray]
However, this does not work as expected, yielding all zeros.
 
A natural table stores the contents of all the cells, before typesetting it. But it does not expand the contents of its cell before storing them. So, at the time the table is actually typeset, TeX has already finished the <code>\dorecurse</code> and <code>\recurselevel</code> is set to 0.
 
The solution is to place <code>\expandafter</code> at the correct location(s) to coax TeX into expanding the <code>\recurselevel</code> macro before the natural table stores the cell contents. The difficult part is figuring out the exact location of <code>\expandafter</code>s. Here is a solution that works:
 
<texcode>
\bTABLE
\bTR
\bTD $(+)$ \eTD
\dorecurse{6}
{\expandafter \bTD \recurselevel \eTD}
\eTR
\dorecurse{6}
{\bTR
\edef\firstrecurselevel{\recurselevel}
\expandafter\bTD \recurselevel \eTD
\dorecurse{6}
{\expandafter\bTD
\the\numexpr\firstrecurselevel+\recurselevel
\relax
\eTD}
\eTR}
\eTABLE
</texcode>
 
We only needed to add three <code>\expandafter</code>s to make the naive loop work. Nevertheless, finding the right location of <code>\expandafter</code> can be frustrating, especially for a non-expert.
 
By contrast, in luaTeX writing loops is easy. Once a lua instance starts, TeX does not see anything until the lua instance exits. So, we can write the loop in lua, and simply print the values that we would have typed to the TeX stream. When the control is passed to TeX, TeX sees the input as if we had typed it by hand. Consequently, macro expansion is no longer an issue. For example, we can get the above table by:
<texcode>
\startluacode
context.bTABLE()
</texcode>
The lua functions such as <code>context.bTABLE()</code> and <code>context.bTR()</code> are just abbreviations for running <code>context ("\\bTABLE")</code>, <code>context("\\bTR")</code>, etc. See the [http://www.pragma-ade.com/general/manuals/cld-mkiv.pdf ConTeXt lua document] manual for more details about such functions. The rest of the code is a simple nested for-loop that computes the sum of two dice. We do not need to worry about macro expansion at all!== Parsing input without exploding your head ==
= Parsing input without exploding your head =''This example demonstrates parsing simple ASCII notation with Lua's lpeg parser.''
In order to get around the weird rules of macro expansionAs an example, writing a parser let's consider typesetting chemical molecules in TeX involves . Normally, molecules should be typeset in text mode rather than math mode. If we want :H<sub>3</sub>SO<sub>4</sub><sup>+</sup>,we must type :<code>H{{cmd|low|{3}}}SO{{cmd|lohi|{4}}}{{{cmd|textplus}}}</code>,but we'd much rather type:{{cmd|molecule|{H_3SO_4^+}}}. So, we need a lot of macro jugglery function that can take a string like that, parse it, and catcode trickeryturn it into the appropriate TeX code. It is LuaTeX includes a black artgeneral parser based on PEG (parsing expression grammar) called [http://www.inf.puc-rio.br/~roberto/lpeg/lpeg.html lpeg], one and it makes writing little parsers positively joyful. (Once you've got the knack of it, at least.) For example, the biggest mysteries of TeX for ordinary usersabove {{cmd|molecule}} macro can be written as follows.
As an example, let's consider typesetting chemical molecules in TeX. Normally, molecules should be typeset in text mode rather than math mode. For example, <context>H\low{2}SO\lohi{4}{--}</context>, can be input as <code>H\low{2}SO\lohi{4}{--}</code>. Typing so much markup can be cumbersome. Ideally, we want a macro such that we type <code>\molecule{H_2SO_4^-}</code> and the macro translates this into <code>H\low{2}SO\lohi{4}{--}</code>. Such a macro can be written in TeX as follows.
<texcode>
\newbox\chemlowbox \def\chemlow#1% {\setbox\chemlowbox \hbox{{\switchtobodyfont[small]#1}}} startluacode
\def\chemhigh#1% -- we will put our molecule function in the userdata namespace. userdata = userdata or {\ifvoid\chemlowbox \high{{\switchtobodyfont[small]#1}}% \else \lohi{\box\chemlowbox} {{\switchtobodyfont[small]#1}} \fi}
\def\finishchem%-- The formatting functions into which the captured {\ifvoid\chemlowbox\else -- superscript/subscript blocks will be fed \lowlocal formatters = {\box\chemlowbox} \fi}
\unexpanded\def\molecule% {\bgroup \catcode`\_=\active \uccode`\~=`\_ \uppercase{\let~\chemlow}% \catcode`\^=\active \uccode`\~=`\^ \uppercase{\let~\chemhigh}% \dostepwiserecurse {65}{90}{1} {\catcode \recurselevel = \active function formatters.low(one) return string.format("\uccode`\~=\recurselevel \uppercaselow{\edef~{\noexpand\finishchem \rawcharacter{\recurselevel}}}}% \catcode`\-=\active \uccode`\~=`\- \uppercase{\def~{--}s}% ", one) \domolecule }% end
function formatters.high(one) return string.format("\\high{%s}", one)end function formatters.lowhigh(one, two) return string.format("\\lohi{%s}{%s}", one, two)end function formatters.highlow(one, two,three) return string.format("\\lohi{%s}{%s}", one,two)end -- These are the characters we may encounter-- The `/` means we want to expand + and - to \textplus c.q. \textminus;-- this substition is not instant, but will take place inside the first -- surrounding lpeg.Cs() call.local plus = lpeg.P("+") / "\\textplus "local minus = lpeg.P("-") / "\\textminus "local character = lpeg.R("az", "AZ", "09") -- R is for 'range'local subscript = lpeg.P("_") -- P is simply for 'pattern'local superscript = lpeg.P("^")local leftbrace = lpeg.P("{")local rightbrace = lpeg.P("}") -- a ^ or _ affects either a single character, or a brace-delimited-- block. Whichever it is, call it `content`.local single = character + plus + minuslocal multiple = leftbrace * single^1 * rightbracelocal content = single + multiple -- These are our top-level elements: non-special text, of course, and-- blocks of superscript/subscript/both.-- lpeg.Cs(content) does two things:-- (1) not all matches go into the `/ function` construction; only-- *captures* go in. The C in Cs stands for Capture. This way, -- the superscript/subscript mark gets discarded.-- (2) it expands plus/minus before they go into the formatter. The-- s in Cs stands for 'substitute in the replacement values, if any'local text = single^1local low = subscript * lpeg.Cs(content) / formatters.lowlocal high = superscript * lpeg.Cs(content) / formatters.highlocal lowhigh = subscript * lpeg.Cs(content) * superscript * lpeg.Cs(content) / formatters.lowhighlocal highlow = superscript * lpeg.Cs(content) * subscript * lpeg.Cs(content) / formatters.highlow -- Finally, the root element: 'moleculepattern'local moleculepattern = lpeg.Cs((lowhigh + highlow + low + high + text)^0) function thirddata.molecule(string) -- * `:match` returns the matched string. Our pattern -- `moleculepattern` should match the entire input string. Any -- *performed* substitutions are retained. (`.Cs()` performs a -- previously defined substitution.) -- * `context()` inserts the resulting string into the stream, ready for -- TeX to evaluate. context(moleculepattern:match(string))end \stopluacode \def\domoleculemolecule#1{\ctxlua{thirddata.molecule("#1")}} \finishchemstarttext \egroupmolecule{Hg^+}, \molecule{SO_4^{2-}}\stoptext
</texcode>
This monstrosity is a typical TeX Quite terse and readable by parser. Appropriate characters need to be made active; occasionallystandards, <code>\lccode</code> and <code>\uccode</code> need to be set; signaling tricks are needed (for instance, checking if <code>\chemlowbox</code> is void); and then magic happens (or so isn't it seems to a flabbergasted user). More sophisticated parsers involve creating finite state automata, which look even more monstrous.?
With luaTeX== Manipulating verbatim text == ''This example demonstrates defining a custom {{cmd|start}}…{{cmd|stop}} buffer that gets processed through Lua in its entirety.'' Suppose we want to write an environment {{cmd|startdedentedtyping}} … {{cmd|stopdedentedtyping}} that removes the indentation of the first line from every line. Thus, things are differentthe output of … <texcode>\startdedentedtyping #include &lt;stdio. luaTeX includes a general parser based on PEG h&gt; void main() { print(parsing expression grammar"Hello world \n") called [http:; }\stopdedentedtyping<//wwwtexcode>… should be the same as the output of … <texcode>\starttyping#include &lt;stdio.inf.puc-rio.brh&gt;void main(){ print("Hello world \n") ;}\stoptyping</roberto/lpeg/lpeg.html lpeg]texcode>… even though the leading whitespace is different. This makes writing parsers  Defining an environment in TeX much more comprehensiblethat removes the leading spaces but leavesother spaces untouched is complicated. For exampleOn the other hand, once we capture thecontents of the environment, removing the leading indent or ''dedenting'' the above <code>\molecule</code> macro can be written ascontent in Lua is easy. Here is a Lua function that uses simple stringsubstitutions.
<texcode>
\startluacode
-- Initialize a userdata name space to keep our own functions in. -- That way, we won't interfere with anything ConTeXt keeps in -- the global name space. userdata = userdata or {}
local lowercase = lpegfunction userdata.Rdedentedtyping("az"content) local uppercase lines = lpegstring.Rsplitlines("AZ"content) local backslash indent = lpegstring.Pmatch("\\"lines[1], '^ +')or '' local csname pattern = backslash * lpeg'^' .P(1) . indent * ( for i=1-backslash)^0,#lines dolocal plus lines[i] = lpegstring.Pgsub(lines[i],pattern,"+") / "\\textplus "local minus end  content = lpegtable.Pconcat("-"lines,'\n') /   tex.sprint("\\textminus starttyping\n"local digit = lpeg.R(. content .. "09\\stoptyping\n")local sign = plus + minuslocal cardinal = digit^1 -- The typing environment looks for an explicit \type{\stoptyping}. So,local integer = sign^0 * cardinallocal leftbrace = lpeg-- context.Pstarttyping("{")local rightbrace = lpegcontext(content) context.Pstoptyping("}")local nobrace = 1 - (leftbrace + rightbrace)local nested = lpeg- does not work.P {leftbrace But * (csname + sign + nobrace + lpeg -- context.Vstarttyping(1)context(content)^0 * rightbrace}local any = lpegtex.Psprint(1"\\stoptyping") -- does. end\stopluacode</texcode>
local subscript = lpeg.P("_")local superscript = lpeg.P("^")local somescript = subscript + superscriptHere is the code for defining the {{cmd|startdedentedtyping}} … {{cmd|stopdedentedtyping}} pair:
local content <texcode>% Create an environment that stores everything % between \startdedentedtyping and \stopdedentedtyping % in a buffer named 'dedentedtyping'.\def\startdedentedtyping {\dostartbuffer = lpeg[dedentedtyping] [startdedentedtyping] [stopdedentedtyping]} % On closing the dedentedtyping environment, call the LuaTeX% function dedentedtyping(), and pass it the contents of % the buffer called 'dedentedtyping'\def\stopdedentedtyping {\ctxlua {userdata.dedentedtyping(buffers.Csgetcontent(csname + nested 'dedentedtyping'))}} + sign + any)</texcode>
local lowhigh = lpeg.Cc("\\lohi{%s}{%s}") * subscript * content * superscript * content / string.formatlocal highlow = lpeg.Cc("\\hilo{%s}{%s}") * superscript * content * subscript * content / string.formatlocal low = lpeg.Cc("\\low{%s}") * subscript * content / string.formatlocal high = lpeg.Cc("\\high{%That's}") * superscript * content / stringall.formatlocal justtext = (1 - somescript)^1local parser = lpegFinally, we will go into a little more detail on how TeX and Lua communicate with each other.Cs((csname + lowhigh + highlow + low + high + sign + any)^0)
userdata.moleculeparser = parser = Other examples ==
function userdata.molecule* [[Calculations_in_Lua|Calculations in Lua]] (strwarning date 2012) return * [[LPeg|Writing a parser:matchwith LPeg]] (strLua Parsing Expression Grammars)end* [[Random|Random numbers]] in ConTeXt and MetaPost\stopluacode* [[SQL|An example with SQL database]]* [[Pascal's Triangle]]
\def\molecule#1% {\ctxlua{userdata.molecule("#1")}}</texcode> = In detail: the interaction between TeX and Lua =
This To a first approximation, the interaction between TeX and Lua is more verbose than straightforward. When TeX (i.e., the LuaTeX engine) starts, it loads the input file in memory and processes it token by token. When TeX solutionencounters {{cmd|directlua}}, it stops reading the file in memory, but is easier <em>fully expands the argument of {{cmd|directlua}}</em>, and passes the control to read and writea Lua instance. With The Lua instance, which runs with a proper parserfew preloaded libraries, I do not have to use tricks to check if either one or both processes the expanded arguments of {{cmd|directlua}}. This Lua instance has a special output stream which can be accessed using <code>tex.print(…)</code>. The function <code>_tex.print(…)</code> and is just like the Lua function <code>^print(…)</code> are presentexcept that <code>tex. More importantly, anyone print(once they know …)</code> prints to a <em>TeX stream</em> rather than to the lpeg syntax) can read standard output. When the parser and easily understand what Lua instance finishes processing its input, it doespasses the contents of the <em>TeX stream</em> back to TeX. This <ref>The output of <code>tex.print(…)</code> is in contrast buffered and not passed to TeX until the implementation based on Lua instance has stopped.</ref> TeX macro jugglery which require you to implement a then inserts the contents of the <em>TeX stream</em> at the current location of the file that it was reading; expands the contents of the <em>TeX stream</em>; and continues. If TeX interpreter in your head to understandencounters another {{cmd|directlua{{cmd|, the above process is repeated.
= Conclusion =As an exercise, imagine what happens when the following input is processed by LuaTeX. The answer is in the footnotes. <ref>In this example, two different kinds of quotations are used to avoid escaping quotes. Escaping quotes inside {{cmd|directlua}} is tricky. The above was a contrived example; if you ever need to escape quotes, you can use the {{cmd|startluacode}}…{{cmd|\stopluacode{{cmd| syntax.</ref>
luaTeX is removing many TeX barriers: using system fonts, reading and writing Unicode files, typesetting non-Latin languages, among others<texcode>\directlua% {tex. However, the biggest feature of luaTeX is the ability to use a high-level programming language to program TeX. This can potentially lower the learning curve for programming TeXprint("Depth 1 \\directlua{tex.print('Depth 2')}")}</texcode>
In For more on this article, I have mentioned only one aspect of programming TeXsee the [http: macros that manipulate their input and output some text to the main TeX stream//wiki.luatex. Many other kinds of manipulations are possible: luaTeX provides access to TeX boxes, token lists, dimensions, glues, catcodes, direction parameters, math parameters, etcorg/index. The details can be found in php/Writing_Lua_in_TeX] article on the [http://wwwwiki.luatex.org/documentationindex.html luaTeX manualphp/Main_Page LuaTeX wiki].
= Notes =
<references />
 
{{note | This article is originally based on [https://www.tug.org/members/TUGboat/tb30-2/tb95mahajan-luatex.pdf this TugBoat article ]. Feel free to modify it.}}
 
[[Category:Programming and Databases]]
2

edits

Navigation menu