Debian Codegraph @

texmf-dist/doc/lualatex/yamlvars/yamlvars.tex

raw
1 % Kale Ewasiuk ([email protected])
2 % 2025-02-11
3 % Copyright (C) 2021-2025 Kale Ewasiuk
4 %
5 % Permission is hereby granted, free of charge, to any person obtaining a copy
6 % of this software and associated documentation files (the "Software"), to deal
7 % in the Software without restriction, including without limitation the rights
8 % to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 % copies of the Software, and to permit persons to whom the Software is
10 % furnished to do so, subject to the following conditions:
11 %
12 % The above copyright notice and this permission notice shall be included in
13 % all copies or substantial portions of the Software.
14 %
15 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
16 % ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
17 % TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
18 % PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
19 % SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
20 % ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
21 % ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 % OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
23 % OR OTHER DEALINGS IN THE SOFTWARE.
24
25
26 \documentclass[11pt,parskip=half]{scrartcl}
27 \setlength{\parindent}{0ex}
28 \newcommand{\llcmd}[1]{\leavevmode\llap{\texttt{\detokenize{#1}\ }}}
29 \newcommand{\cmd}[1]{\texttt{\detokenize{#1}}}
30 \newcommand{\qcmd}[1]{``\cmd{#1}''}
31 \usepackage{url}
32 \usepackage{xcolor}
33 \usepackage{showexpl}
34 \lstset{explpreset={justification=\raggedright,pos=r,wide=true}}
35 \setlength\ResultBoxRule{0mm}
36 \lstset{
37 language=[LaTeX]TeX,
38 basicstyle=\ttfamily\small,
39 commentstyle=\ttfamily\small\color{gray},
40 frame=none,
41 numbers=left,
42 numberstyle=\ttfamily\small\color{gray},
43 prebreak=\raisebox{0ex}[0ex][0ex]{\color{gray}\ensuremath{\hookleftarrow}},
44 extendedchars=true,
45 breaklines=true,
46 tabsize=4,
47 }
48 \addtokomafont{title}{\raggedright}
49 \addtokomafont{author}{\raggedright}
50 \addtokomafont{date}{\raggedright}
51 \author{Kale Ewasiuk (\url{[email protected]})}
52 \usepackage[yyyymmdd]{datetime}\renewcommand{\dateseparator}{--}
53 \date{\today}
54
55
56 \usepackage[overwritedefs]{yamlvars}
57 \yamlvarsdebugon
58 \subtitle{a YAML variable parser for LuaLaTeX}
59 \usepackage{geometry}
60 \begin{declareYAMLvars}
61 title:
62 prc: setdocvar
63 geometry:
64 prc: keyvals
65 writePDFmetadatakv:
66 prc: keyvals
67 \end{declareYAMLvars}
68
69 \begin{parseYAMLvars}
70 title: YAMLvars
71 geometry:
72 left: 2in
73 right: 3in
74 writePDFmetadatakv:
75 title: yamlvars
76 \end{parseYAMLvars}
77
78
79 \begin{document}
80
81
82 \maketitle
83
84
85
86 %todo need way better error tracing for this pkg}
87
88
89 %%%%%%%%%%%
90
91
92 YAMLvars is a LuaLaTeX-based package to help make definitions or produce LaTeX code using a YAML file.
93 This package might be useful for you if you want to batch create documents
94 by pushing various sets YAML data to a fixed LaTeX template,
95 or just find it easier to read document metadata from a YAML file compared to the
96 standard title, author, etc. commands.
97
98 \section{Package Options}
99
100 \leavevmode\llap{\texttt{parseCLI}\ \ \ }If this option is enabled, any arguments passed to your lualatex compile
101 command that end in ``.yaml'' will be used, separated by a space.
102 If two yaml files are passed, the first one will be the declaration file,
103 and the second will be the parsing file.
104 They will be used at the beginning of the document.
105 If one yaml file is passed, it will be treated as a parsing file, so you should
106 declare the variables somewhere in the preamble.
107 This option is offered to help with automation scripts.
108 An example is showin in Section \ref{example}.
109
110 \hspace*{3ex}\llcmd{allowundeclared}%
111 It might be helpful to define something in your YAML parsing doc without declaring it.
112 If you want this flexibility, use this setting. Note that existing definitions will not be overwritten and an error
113 will br thrown if the name exists. Alternatively, you can use the commands \cmd{\AllowUndeclaredYV} or \cmd{\ForbidUndeclaredYV} to toggle this behavior.
114
115 \llcmd{overwritedefs}Danger! This will allow you to \cmd{gdef} commands with YAML. Caution should be taken to not set definitions like \cmd{begin}, \cmd{section}, etc.
116
117 \leavevmode\llap{\texttt{useyv}\ \ \ }By default, when you specify a YAML variable, it will be defined using \texttt{gdef}
118 (only if it wasn't defined previously).
119 If you use this setting, unless otherwise specified, YAML variables will be accessible under
120 the \texttt{\textbackslash yv\{<var>\}} command.
121 Note that internally, the variables are stored in the command sequence
122 \cmd{\yv<var>}.
123
124 \section{Dependencies}
125 \llcmd{Note:}This package requires the \cmd{tinyyaml} package, available on CTAN.
126
127 The distribution: \url{https://github.com/api7/lua-tinyyaml}\\
128 \ \ \ \ \url{https://ctan.org/pkg/lua-tinyyaml}\\
129 The YAML specification: \url{https://yaml.org/spec/}\\
130
131 Many of the ``transform'' and ``processing'' functions built-in to this package rely on other packages,
132 like
133 \texttt{hyperref}, or \texttt{xspace} for example, but they are not loaded, and this package will only load
134 \cmd{penlightplus},
135 \cmd{luacode}, \cmd{luakeys}, and
136 \cmd{etoolbox}.
137
138 \section{Settings}
139 \cmd{\setdefYAMLvars{kv}} changes the default settings of key-vals.\\
140 \cmd{\setYAMLvars*{kv}} changes the current settings from key-vals. Use \cmd{*} if you want to first restore to defaults.
141
142 The \cmd{YAMLvars.setts} lua table contains the settings, which are:\\
143 \cmd{parseopts} table passed to YAML parser options (default is \cmd{{timestamps=false}}) \\
144 \cmd{decstr} in the declaration YAML text, if a value is a string, how should it be treated (\cmd{xfm, dft, or prc}) \\
145 \cmd{undeclared} boolean for allowing parsing of undeclared vars \\
146 \cmd{overwrite} boolean for allowing overwriting of previous definitions \\
147 \cmd{lowercase} boolean for auto-changing vars to lowercase \\
148 \cmd{prcstring} a string with types (default 'number') for auto-converting final value before processing (sometimes) numbers can have odd effects. You might also include 'table' \\
149 %\cmd{tabmidrule} type of rule for tabu \\
150 \cmd{xfm} default xfm function(s) if none passed to declared key, separated by space \\
151 \cmd{prc} default prc function if none passed to declared key \\
152 \cmd{dft} default dft function if none passed to declared key \\
153
154
155 \section{Declaring variables}
156 A declaration file can either be parsed with the command \texttt{declareYAMLvarsFile} command,
157 or, if you want to do it \LaTeX, you can put the YAML code in the \texttt{declareYAMLvars} environment.
158 It is a declaring YAML document is (like all YAML) key-value dictionary:
159 The top level key is the name of the variable to be defined/used.
160 If the value of the top level is a string: it's interpreted as a single transform function to be applied.
161 Otherwise, it must
162 be a table that contains at least one of the following keys:\\
163 \texttt{xfm} (transform, may be a string or list of strings),\\
164 \texttt{prc} (processing, must be a single string), or \\
165 \texttt{dft} (default value, if being defined. Must be a string).
166
167 If you want to change the way a variable is initialized, you can change the function
168 \cmd{YAMLvars.dec.PRC = function (var) ... end } where \cmd{PRC} is how the variable will be processed (\cmd{gdef}, \cmd{yvdef}, \cmd{length}, or something of your choosing).
169
170 The default value for variables is the Lua \texttt{nil}.
171 YAMLvars will first check if the definition exists, if so, an error will be thrown
172 so that we avoid overwriting.
173 If the token is available, it is set to a package error, so that if the variable no defined later on, an error will
174 tell the user they forgot to set it.
175 This will be overwritten when you parse the variables and assign a value to it.
176
177 \paragraph{If you want a case-insensitive variable} In the declaration YAML document,
178 add a \cmd{lowcasevar: true} under the variable name.
179 This will make the variable name lowercase before any transforms or processing is done.
180 For example, if you have \cmd{title} as a YAML variable to set
181 the \cmd{prc} function \cmd{setdocvar}, a user could write
182 \cmd{Title} in the parsing file and still have it work.
183 You can toggle this behaviour globally with
184 the commands \cmd{\lowercasevarYVon} and \cmd{\lowercasevarYVoff}
185 See the last example below.
186
187 You can change the default \texttt{xfm}, \texttt{prc}, or \texttt{dft} by changing
188 the value (in Lua): \texttt{YAMLvars.xfmDefault = ''} etc.
189
190 Here is an example of a declaration document.
191 \begin{verbatim}
192 \begin{declareYAMLvars}
193 Location: addxspace # sets xfm=addxspace
194 People: [arrsortlastnameAZ, list2nl] # BAD! don't do.
195 People:
196 xfm: [arrsortlastnameAZ, list2nl] # Correct way
197 Company:
198 dft: Amazon # Change default only
199 Revisions:
200 dft: '1 & \today & initial version \\'
201 xfm: [sortZA, list2tab]
202 Rhead:
203 prc: setRightHead
204
205
206 author:
207 xfm: list2and # (joins a list with \and (or lets a single string be passed)
208 prc: setdocvar # calls \author{val}
209 lowcasevar: true # allows user to use Title: or TITLE:
210
211 title:
212 xfm: lb2nl # (make line-breaks \\)
213 prc: setdocvar # calls \title{val}
214 lowcasevar: true # allows user to use Title: or TITLE:
215 \end{declareYAMLvars}
216 \end{verbatim}
217
218
219 To change how a variable is declared (initialize), you can modify or add functions in
220 \texttt{YAMLvars.dec} table, where the index is the same as the \texttt{prc} name.
221 This function accepts two variables, the var name, and the default value set by dft.
222 For lengths and toggles (from etoolbox), these functions are used to initialize lengths
223 with newlength and newtoggle.
224
225
226 \section{Parsing variables}
227 A YAML file to be parsed will contain the variables as the top level keys, similar to declaring.
228 The value can be anything you want; as long as you have applied appropriate transform and declaring
229 functions to it so that it can be useful. For example, a value specified as a YAML list will first be
230 interpreted as a Lua table (with numeric indexes/keys). You could declare a series of transforms functions
231 to sort this table, map functions, and convert it to a series of \LaTeX \texttt{\textbackslash item}s.
232
233 Here is an example of a parsing document.
234
235
236 \begin{verbatim}
237 \begin{parseYAMLvars}
238 Location: Planet Earth
239 People: # a YAML list
240 - Some One # turns into Lua table
241 - No Body
242 # company assumed Amazon if not set here
243 Rhead: \today
244 \end{parseYAMLvars}
245 \end{verbatim}
246
247 Note: all whitespace is stripped from the variable name when parsing.
248
249 \section{xfm -- Transform Functions}
250 These functions accept two arguments: \texttt{(var, val)} where \texttt{var} is the variable (or key) and val is the value.
251 The transforms are specified as a list and are iteratively applied to the val.
252 Usually, the final \texttt{xfm} function should produce a string so it can be defined.
253
254 Hint: if for some reason, your \texttt{xfm} and \texttt{prc} depends on other variables,
255 you can access them within the function
256 with \texttt{YAMLvars.varsvals}
257
258 \subsection{Defining your own transform functions}
259 After the package is loaded, you may add your function (somewhere in Lua)
260 by adding it to the \texttt{YAMLvars.xfm} table.
261 For example, if you wanted to wrap a variable's value with ``xxx'', here's how you could do that.
262 \begin{verbatim}
263 function myfunction(var, val)
264 return 'xxx'..val..'xxx'
265 end
266 YAMLvars.xfm['addmyfunction'] = myfunction
267 \end{verbatim}
268
269 If you want to run some Lua code and write in your YAML file (weird idea, but maybe useful for one-off functions),
270 you can do so by specifying a transform function with an \texttt{=} in it to make a lambda function.
271 For example, a \texttt{xfm} equal to
272 ``\texttt{= '---'..x..'---'}''
273 would surround your YAML variable's value with em-dashes.
274 You can access the variable name with this lambda function with \texttt{v}.
275 If you want to just execute code (instead of settings \texttt{x = }, use \texttt{/}).
276
277 \section{prc -- Processing Functions}
278 Like the transform functions, the processing function must accept \texttt{(var, val)}.
279 Only one processing function is applied to the final (var, val) after the transforms are done.
280
281 This package includes \texttt{gdef} to set a definition, \texttt{yvdef} to define a variable under the \texttt{yv} command.
282 \texttt{title, author, date} to set \texttt{\textbackslash @title, \textbackslash @author, \textbackslash @date},
283 respectively
284
285 \pagebreak
286
287 \section{Some Examples}
288
289 \begin{LTXexample}
290 %! language = yaml
291 \begin{declareYAMLvars}
292 address:
293 xfm:
294 - list2nl
295 - = x..'!!!'
296 name: null
297
298 title:
299 xfm:
300 - lb2nl
301 # - / YAMLvars.prvcmd(titletext, YAMLvars.varsvals['atitle']:gsub('\n', ' ')..'\\xspace{}')
302 \end{declareYAMLvars}
303
304 %! language = yaml
305 \begin{parseYAMLvars}
306 title: |-
307 A Multiline
308 Monumental Title!
309
310 name: Joe Smith
311 address:
312 - 1234 Fake St.
313 - City
314 \end{parseYAMLvars}
315
316 \title
317
318 %\titletext!
319
320 \name
321
322 \address
323
324 \end{LTXexample}
325
326 \pagebreak
327 \section{Automation Example}\label{example}
328
329 Suppose you had a number of bills of sales in yaml format and wanted to produce some nice pdfs.
330 The following code shows how this could be done.
331
332 \pagebreak
333 \vspace*{-5em}
334 \subsection{The main tex template}
335 \begin{verbatim}
336 %% main.tex
337 \documentclass{article}
338 \usepackage[paperheight=4in,paperwidth=3in,margin=0.25in]{geometry}
339 \usepackage[pl,func,extras]{penlight}
340 \usepackage[useyv,parseCLI]{YAMLvars} % using command line option to make files
341 \usepackage{hyperref}
342 \usepackage{xspace}
343 \usepackage{luacode}
344
345 \setlength{\parindent}{0ex}
346 \setlength{\parskip}{0.75em}
347
348 \begin{luacode*} -- adding a custom function, put hfill between k-v pairs
349 function YAMLvars.xfm.kv2hfill(var, val)
350 local t = {}
351 for k, v in pairs(val) do
352 t[#t+1] = k..'\\hfill '..tostring(v)
353 end
354 return t
355 end
356 \end{luacode*}
357
358
359 %! language = yaml
360 \begin{declareYAMLvars}
361 Customer: addxspace
362 Date: addxspace
363 Items:
364 xfm: [kv2hfill, arr2itemize]
365 \end{declareYAMLvars}
366
367 \begin{document}
368 Bill of sale for: \hfill \yv{Customer}\\
369 Purchased: \hfill \yv{Date}\\
370 \begin{itemize}
371 \item[] ITEM \hfill PRICE
372 \yv{Items} % the yaml variable
373 \begin{luacode*}
374 totalcost = pl.tablex.reduce('+',
375 pl.tablex.values(YAMLvars.varsvals['Items']), 0)
376 tex.print('\\item[] TOTAL:\\hfill'..tostring(totalcost))
377 \end{luacode*}
378 \end{itemize}
379 \end{document}
380 \end{verbatim}
381
382 \subsection{The lua automation script}
383 \begin{verbatim}
384 --automate.lua
385 for f in io.popen('dir .'):lines() do -- get all files and info in cwd
386 local i, j = f:find('%S*%.yaml') -- find fnames
387 if i ~= nil then
388 f = f:sub(i,j) -- extract .yaml file name (no space in fname allowed)
389 os.execute('lualatex -output-format=pdf main.tex '.. f)
390 -- compile w/ yaml file as arg
391 local fnew = f:gsub('yaml', 'pdf') -- file name for output pdf
392 os.remove(fnew) -- delete if it exists already
393 os.rename('main.pdf', fnew) -- change main.pdf to same as yaml file name
394 end
395 end
396 \end{verbatim}
397
398 \subsection{The yaml data files}
399 \begin{verbatim}
400 # sale1.yaml
401 Customer: Someone Cold
402 Date: January 2, 2021
403 Items:
404 Toque: 12
405 Mitts: 5.6
406 Boots: 80
407
408 # sale2.yaml
409 Customer: Someone Warm
410 Date: July 1, 2021
411 Items:
412 Beer (24 pk): 24
413 Sunscreen: 5
414 Hat: 12
415 \end{verbatim}
416
417
418
419 \clearpage
420 \section{xfm, dec, prc functions (from yamlvars.lua)}
421
422 \lstinputlisting[linerange=103-319]{yamlvars.lua}
423
424 \end{document}
425