Debian Codegraph @

texmf-dist/tex/luatex/penlightplus/penlightplus.lua

raw
1 --% Kale Ewasiuk ([email protected])
2 --% 2025-02-14
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, subjected 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
27 -- https://lunarmodules.github.io/Penlight/
28
29 __PL_PLUS__ = true
30 __PL_SKIP_TEX__ = __PL_SKIP_TEX__ or false --if declared true before here, it will use regular print functions
31 -- (for troubleshooting with texlua instead of actual use in lua latex)
32 __PL_GLOBALS__ = __PL_GLOBALS__ or false
33 __PL_NO_HYPERREF__ = __PL_NO_HYPERREF__ or false
34
35 penlight.luakeys = require'luakeys'()
36
37 penlight.debug_available = false -- check if penlight debug package is available
38 if debug ~= nil then
39 if type(debug.getinfo) == 'function' then
40 penlight.debug_available = true
41 end
42 end
43
44
45
46
47 -- http://lua-users.org/wiki/SplitJoin -- todo read me!!
48
49 penlight.tex = {} -- adding a sub-module for tex related stuff
50
51 local bind = bind or penlight.func.bind
52
53
54 function penlight.hasval(x) -- if something has value
55 if (type(x) == 'function') or (type(x) == 'CFunction') or (type(x) == 'userdata') then
56 return true
57 elseif (x == nil) or (x == false) or (x == 0) or (x == '') or (x == {}) then
58 return false
59 elseif (type(x) ~= 'boolean') and (type(x) ~= 'number') and (type(x) ~= 'string') then -- something else? maybe ths not needed
60 if #x == 0 then -- one more check, probably no needed though, I was trying to cover other classes but they all tables
61 return false
62 else
63 return true
64 end
65 end
66 return true
67 end
68
69
70
71 function penlight._Gdot(s)
72 -- return a global with nots
73 o = _G
74 for _, a in ipairs(s:split('.')) do
75 o = o[a]
76 end
77 return o
78 end
79
80
81 -- Some simple and helpful LaTeX functions -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
82
83 -- xparse defaults
84
85 penlight.tex.xTrue = '\\BooleanTrue '
86 penlight.tex.xFalse = '\\BooleanFalse '
87 penlight.tex.xNoValue = '-NoValue-'
88
89 penlight.tex._xTrue = '\\BooleanTrue '
90 penlight.tex._xFalse = '\\BooleanFalse '
91 penlight.tex._xNoValue = '-NoValue-'
92
93
94 --Generic LuaLaTeX utilities for print commands or environments
95
96 if not __PL_SKIP_TEX__ then
97 local function check_special_chars(s) -- todo extend to toher special chars?
98 if type(s) == 'string' then
99 if string.find(s, '[\n\r\t\0]') then
100 penlight.tex.pkgwarn('penlight', 'printing string with special (eg. newline) char, possible unexpected behaviour on string: '..s)
101 end
102 end
103 end
104
105 -- NOTE: usage is a bit different than default. If number is first arg, you CANT change catcode.
106 -- We don't need that under normal use, use tex.print or tex.sprint if you need
107 function penlight.tex.prt(s, ...) -- print something, no new line after
108 check_special_chars(s)
109 if type(s) == 'number' then s = tostring(s) end
110 tex.sprint(s, ...) --can print lists as well, but will NOT put new line between them or anything printed
111 end
112
113 function penlight.tex.prtn(s, ...) -- print with new line after, can print lists or nums. C-function not in Lua, apparantly
114 s = s or ''
115 check_special_chars(s)
116 if type(s) == 'number' then s = tostring(s) end
117 tex.print(s, ...)
118 end
119
120 penlight.tex.wrt = texio.write
121 penlight.tex.wrtn = texio.write_nl
122 else
123 penlight.tex.prt = io.write
124 penlight.tex.prtn = print --print with new line
125 penlight.tex.wrt = io.write
126 penlight.tex.wrtn = io.write_nl
127 end
128
129 function penlight.tex.prtl(str) -- prints a literal/lines string in latex, adds new line between them
130 for line in str:gmatch"[^\n]*" do -- gets all characters up to a new line
131 penlight.tex.prtn(line)
132 end
133 end
134
135 -- todo option to specify between character? one for first table, on for recursives?
136 function penlight.tex.prtt(tab, d1, d2) -- prints a table with new line between each item
137 d1 = d1 or ''
138 d2 = d2 or '\\leavevmode\\\\'
139 for _, t in pairs(tab) do --
140 if type(t) ~= 'table' then
141 if d1 == '' then
142 penlight.tex.prtn(t)
143 else
144 penlight.tex.prt(t, d1)
145 end
146 else
147 penlight.tex.prtn(d2)
148 penlight.tex.prtt(t,d1,d2)
149 end
150 end
151 end
152
153 function penlight.tex.wrth(s1, s2) -- helpful printing, makes it easy to debug, s1 is object, s2 is note
154 local wrt2 = wrt or texio.write_nl or print
155 s2 = s2 or ''
156 wrt2('\nvvvvv '..s2..'\n')
157 if type(s1) == 'table' then
158 wrt2(penlight.pretty.write(s1))
159 else
160 wrt2(tostring(s1))
161 end
162 wrt2('\n^^^^^\n')
163 end
164 penlight.wrth = penlight.tex.wrth
165 penlight.tex.help_wrt = penlight.tex.wrth
166 penlight.help_wrt = penlight.tex.wrth
167
168 function penlight.tex.prt_array2d(t)
169 for _, r in ipairs(t) do
170 local s = ''
171 for _, v in ipairs(r) do
172 s = s.. tostring(v)..', '
173 end
174 penlight.tex.prt(s)
175 penlight.tex.prt('\n')
176 end
177 end
178
179 -- -- -- -- --
180
181 function penlight.tex.pkgwarn(pkg, msg1, msg2)
182 pkg = pkg or ''
183 msg1 = msg1 or ''
184 msg2 = msg2 or ''
185 tex.sprint('\\PackageWarning{'..pkg..'}{'..msg1..'}{'..msg2..'}')
186 end
187
188 function penlight.tex.pkgerror(pkg, msg1, msg2, stop)
189 pkg = pkg or ''
190 msg1 = msg1 or ''
191 msg2 = msg2 or ''
192 stop = penlight.hasval(stop)
193 tex.sprint('\\PackageError{'..pkg..'}{'..msg1..'}{'..msg2..'}')
194 if stop then tex.sprint('\\stop') end -- stop on the spot (say that 10 times)
195 end
196
197
198 if not penlight.debug_available then
199 penlight.tex.pkgwarn('penlightplus', 'lua debug library is not available, recommend re-compiling with the --luadebug option')
200 end
201
202
203 function penlight.tex.errorif(exp, pkg, msg1, msg2, stop)
204 if penlight.hasval(exp) then
205 penlight.tex.pkgerror(pkg, msg1, msg2, stop)
206 end
207 end
208
209
210 --definition helpers -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
211
212 function penlight.tex.defmacro(cs, val, g) -- , will not work if val contains undefined tokens (so pre-define them if using..)
213 val = val or '' -- however this works for arbitrary command names (\@hello-123 etc allowed)
214 g = g or 'global'
215 token.set_macro(cs, val, g)
216 end
217
218
219 function penlight.tex.defcmd(cs, val) -- fixes above issue, but only chars allowed in cs (and no @)
220 val = val or ''
221 tex.sprint('\\gdef\\'..cs..'{'..val..'}')
222 end
223
224 function penlight.tex.defcmdAT(cs, val) -- allows @ in cs,
225 --however should only be used in preamble. I avoid \makeatother because I've ran into issues with cls and sty files using it.
226 val = val or ''
227 tex.sprint('\\makeatletter\\gdef\\'..cs..'{'..val..'}')
228 end
229
230
231
232 function penlight.tex.prvcmd(cs, val) -- provide command via lua
233 if token.is_defined(cs) then
234 -- do nothing if token is defined already --pkgwarn('penlight', 'Definition '..cs..' is being overwritten')
235 else
236 penlight.tex.defcmd(cs, val)
237 end
238 end
239
240 function penlight.tex.newcmd(cs, val) -- provide command via lua
241 if token.is_defined(cs) then
242 penlight.tex.pkgerror('penlight: newcmd',cs..' already defined')
243 else
244 penlight.tex.defcmd(cs, val)
245 end
246 end
247
248 function penlight.tex.renewcmd(cs, val) -- provide command via lua
249 if token.is_defined(cs) then
250 penlight.tex.defcmd(cs, val)
251 else
252 penlight.tex.pkgerror('penlight: renewcmd',cs..' not defined')
253 end
254 end
255
256 function penlight.tex.deccmd(cs, def, overwrite) -- declare a definition, placeholder throws an error if it used but not set!
257 overwrite = penlight.hasval(overwrite)
258 local decfun
259 if overwrite then decfun = penlight.tex.defcmd else decfun = penlight.tex.newcmd end
260 if def == nil then
261 decfun(cs, pkgerror('penlight', cs..' was declared and used in document, but never set'))
262 else
263 decfun(cs, def)
264 end
265 end
266
267
268 --
269 -- -- todo add and improve this, options for args?
270 --local function defcmd_nest(cs) -- for option if you'd like your commands under a parent ex. \csparent{var}
271 -- tex.print('\\gdef\\'..cs..'#1{\\csname '..var..'--#1--\\endcsname}')
272 --end
273 --
274 --
275 --local function defcmd(cs, val, nargs)
276 -- if (nargs == nil) or (args == 0) then
277 -- token.set_macro(cs, tostring(val), 'global')
278 -- else
279 -- local args = '#1'
280 -- tex.print('\\gdef\\'..cs..args..'{'..val..'}')
281 -- -- todo https://tex.stackexchange.com/questions/57551/create-a-capitalized-macro-token-using-csname
282 -- -- \expandafter\gdef\csname Two\endcsname#1#2{1:#1, two:#2} --todo do it like this
283 -- end
284 --end
285
286 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
287
288
289
290 -- when nesting commands, this makes it helpful to not worry about brackets
291 penlight.tex._NumBkts = 0
292 penlight.tex._EndEnvs = {}
293
294 --prt(opencmd('textbf')..opencmd('texttt')..'bold typwriter'..close_bkt_cnt())
295
296 function penlight.tex.opencmd(cmd)
297 return '\\'..cmd..add_bkt_cnt()
298 end
299
300 function penlight.tex.reset_bkt_cnt(n)
301 n = n or 0
302 _NumBkts = n
303 end
304
305 function penlight.tex.add_bkt_cnt(n)
306 -- add open bracket n times, returns brackets
307 n = n or 1
308 _NumBkts = _NumBkts + n
309 return ('{'):rep(n)
310 end
311
312 function penlight.tex.close_bkt_cnt(n)
313 n = n or _NumBkts
314 local s = ('}'):rep(n)
315 _NumBkts = _NumBkts - n
316 return s
317 end
318
319
320
321
322
323 function penlight.tex.openenv(env, opt)
324 if opt == nil then opt = '' else opt = '['..opt..']' end
325 tex.sprint('\\begin{' .. env .. '}'..opt)
326 table.insert(penlight.tex._EndEnvs, 1, '\\end{'..env..'}')
327 end
328
329 function penlight.tex.closeenv(num)
330 num = num or #penlight.tex._EndEnvs
331 for i=1, num do
332 tex.sprint(penlight.tex._EndEnvs[1])
333 table.remove(penlight.tex._EndEnvs, 1)
334 end
335 end
336
337
338
339 function penlight.tex.aliasluastring(s, d)
340 s = s:delspace():upper():tolist()
341 d = d:delspace():upper():tolist()
342 for i, S in penlight.seq.enum(d:slice_assign(1,#s,s)) do
343 if (S == 'F') then S = '' end -- F is fully expanded
344 penlight.tex.prtn('\\let\\plluastring'..penlight.Char(i)..'\\luastring'..S)
345 end
346 end
347
348
349
350
351
352 function penlight.tex.get_ref_info(l)
353 local n = 5
354 if __PL_NO_HYPERREF__ then
355 local n = 2
356 end
357 local r = token.get_macro('r@'..l)
358 local t = {}
359 if r == nil then
360 t = penlight.tablex.new(n, 0) -- make all 0s
361 r = '-not found-'
362 else
363 t = {r:match(("(%b{})"):rep(n))}
364 t = penlight.tablex.map(string.trimfl, t)
365 end
366 t[#t+1] = r -- add the og return of label
367 --penlight.help_wrt(t, 'ref info')
368 return t
369 end
370
371 -- todo add regex pattern for cref info
372 --function penlight.tex.get_ref_info_all_cref(l)
373 -- local r = token.get_macro('r@'..l..'@cref')
374 -- if r == nil then
375 -- return r, 0, 0
376 -- end
377 -- local sec, page = r:match("{([^}]*)}{([^}]*)}")
378 -- return r, sec, page
379 --end
380
381
382 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
383 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
384
385
386
387
388
389
390 -- -- -- -- math stuff
391 function math.mod(a, b) -- math modulo, return remainder only
392 return a - (math.floor(a/b)*b)
393 end
394
395 function math.mod2(a) -- math modulo 2
396 return math.mod(a,2)
397 end
398
399
400
401 -- -- -- -- string stuff
402 local lpeg = require"lpeg"
403 local P, R, S, V = lpeg.P, lpeg.R, lpeg.S, lpeg.V
404
405 local number = P{"number",
406 number = (V"int" * V"frac"^-1 * V"exp"^-1) / tonumber,
407 int = V"sign"^-1 * (R"19" * V"digits" + V"digit"),
408 digits = V"digit" * V"digits" + V"digit",
409 digit = R"09",
410 sign = S"+-",
411 frac = P"." * V"digits",
412 exp = S"eE" * V"sign"^-1 * V"digits",
413 }
414
415
416
417
418 function penlight.char(num)
419 return string.char(string.byte("a")+tonumber(num)-1)
420 end
421
422 function penlight.Char(num)
423 return string.char(string.byte("A")+tonumber(num)-1)
424 end
425
426
427 local str_mt = getmetatable("") -- register functions with str
428
429 function str_mt.__index.gnum(s)
430 return number:match(s)
431 end
432
433 function str_mt.__index.gextract(s, pat) --extract a pattern from string, returns both
434 local s_extr = ''
435 local s_rem = s
436 for e in s:gmatch(pat) do
437 s_extr = s_extr..e
438 s_rem = s_rem:gsub(e,'')
439 end
440 return s_extr, s_rem
441 end
442
443 function str_mt.__index.gxtrct(s, pat, num, join) --extract a pattern from string, returns both
444 -- todo a variant where you can specify the number of extractions, and either list of concatenate them would be helpful
445 local l_extr = penlight.List{}
446 local s_rem = s
447 local n = 1
448 num = num or 99999
449 for e in s:gmatch(pat) do
450 l_extr = l_extr:append(e)
451 s_rem = s_rem:gsub(e,'',1)
452 if n == num then break end
453 n = n +1
454 end
455 if join then
456 l_extr = l_extr:join(join)
457 end
458 return l_extr, s_rem
459 end
460
461
462 function str_mt.__index.gfirst(s, t) -- get the first pattern found from a table of pattern
463 for _, pat in pairs(t) do
464 if string.find(s, pat) then
465 return pat
466 end
467 end
468 end
469
470 function str_mt.__index.appif(S, W, B, O) --append W ord to S tring if B oolean true, otherwise O ther
471 --append Word to String
472 if B then --if b is true
473 S = S .. W
474 else --consider Other word
475 O = O or ''
476 S = S .. O
477 end
478 return S
479 end
480
481
482 function str_mt.__index.containsany(s, exp)
483 if type(exp) ~= 'table' then exp = {exp} end
484 for _, e in ipairs(exp) do
485 if s:find(e) then return true end
486 end
487 return false
488 end
489
490 function str_mt.__index.containsanycase(s, exp)
491 if type(exp) ~= 'table' then exp = {exp} end
492 for _, e in ipairs(exp) do
493 if s:lower():find(e:lower()) then return true end
494 end
495 return false
496 end
497
498 function str_mt.__index.totable(str)
499 local t = {}
500 for i = 1, #str do
501 t[i] = str:sub(i, i)
502 end
503 return t
504 end
505
506 function str_mt.__index.tolist(str)
507 return penlight.List(str)
508 end
509
510
511 function str_mt.__index.upfirst(str)
512 return str:gsub('%a', function(x) return x:upper() end, 1)
513 end
514
515 function str_mt.__index.delspace(str)
516 return str:gsub('%s','')
517 end
518
519 function str_mt.__index.trimfl(str)
520 return str:sub(2,-2)
521 end
522
523 function str_mt.__index.istexdim(str)
524 for _, u in pairs{'pt', 'mm', 'cm', 'in', 'ex', 'em', 'mu', 'sp'} do
525 if penlight.hasval(str:delspace():find('^%-?%d*%.?%d+'..u..'$')) then
526 return true
527 end
528 end
529 return false
530 end
531
532
533
534 function str_mt.__index.subpar(s, r)
535 r = r or ' '
536 return (s:gsub('\\par', r))
537 end
538
539
540 function str_mt.__index.fmt(s, t, fmt) -- format a $1 and $k string with an array or table and formats
541 -- formats can be a luakeys string, or a table and are applied to table before string is formatted
542 if type(t) ~= 'table' then t = {t} end
543 t = penlight.tablex.strinds(t)
544 t = penlight.tablex.fmt(t, fmt, true)
545 return s % t
546 end
547
548 function str_mt.__index.parsekv(s, t) -- parsekv string
549 if type(t) ~= 'table' then t = penlight.luakeys.parse(t) end
550 return penlight.luakeys.parse(s, t)
551 end
552
553 function str_mt.__index.splitstrip(s, sep, stri) --
554 sep = sep or ','
555 return penlight.List(s:split(sep)):map(function(x) return penlight.stringx.strip(x, stri) end)
556 end
557
558
559 function str_mt.__index.split2(s, sep1, sep2, stri) --
560 sep1 = sep1 or ','
561 sep2 = sep2 or '='
562 if stri == nil then stri = true end
563 stri = penlight.hasval(strip)
564 local splitfunc = string.split
565 if stri then
566 splitfunc = string.splitstrip
567 end
568 return penlight.List(splitfunc(s,sep1)):map(function(x) return splitfunc(x, sep2) end)
569 end
570
571
572
573
574 function str_mt.__index.hasnonum(s)
575 -- string only contains letters and symbols
576 --assert_string(1,s) -- todo
577 return string.find(s,'^[%D]+$') == 1
578 end
579
580 function str_mt.__index.hasnoalpha(s)
581 -- string only contains numbers and symbols
582 --assert_string(1,s) -- todo
583 return string.find(s,'^[%A]+$') == 1
584 end
585
586 function str_mt.__index.isvarlike(s)
587 -- string is like a variable, does not start with a number, then followd by letter, number, or underscore
588 --assert_string(1,s) -- todo
589 return string.find(s,'^[%a_][%w%d_]*$') == 1
590 end
591
592
593
594
595 -- -- -- -- function stuff
596
597 function penlight.clone_function(fn)
598 local dumped = string.dump(fn)
599 local cloned = loadstring(dumped)
600 local i = 1
601 while true do
602 local name = debug.getupvalue(fn, i)
603 if not name then
604 break
605 end
606 debug.upvaluejoin(cloned, i, fn, i)
607 i = i + 1
608 end
609 return cloned
610 end
611
612
613
614
615
616
617
618
619
620
621
622 -- -- -- -- -- -- -- -- -- -- -- -- functions below extend the seq module
623
624
625 function penlight.seq.check_neg_index(i, len, fallback)
626 i = tostring(i):delspace()
627 if i == '' then return fallback end
628 i = tonumber(i)
629 if i == nil then
630 local _ = 1*'"Attempted to use seqstr indexing with negative number, but length of list not provided"'
631 return fallback -- fallback is the number to fall back on if i isn't provided
632 end
633 len = tonumber(len)
634 if i < 0 then
635 if len == nil then
636 local _ = 1*'"Attempted to use seqstr indexing with negative number, but length of list not provided"'
637 return penlight.utils.raise("Attempted to use seqstr indexing with negative number, but length of list not provided")
638 end
639 i = len + 1 + i -- negative index
640 end
641 return i
642 end
643
644 penlight.seq.train_element_sep = ','
645 penlight.seq.train_range_sep = ':'
646
647
648 function penlight.seq.train(s, len)
649 -- parse a range given a string indexer
650 -- syntax is: s = 'i1, i2, r1:r2' where i1 and i2 are individual indexes.
651 -- r1:r2 is a range (inclusive).
652 -- a 'stride' can be given to ranges, eg. ::2 is 1,3,5,..., or 2::3 is 2,5,8,...
653 -- negative numbers can be used to index relative to the length of the table, eg, -1 -> len
654 -- if length is not given, negative indeing cannot be used
655 -- returns a penlight list of numbers
656
657 local t = penlight.List() -- list of indexes
658 local check_neg = penlight.seq.check_neg_index
659 local steps = s:split(penlight.seq.train_element_sep)
660 --penlight.wrth(steps,'abc')
661 for _, r in ipairs(steps) do
662 --penlight.wrth(r,'seq.train = '..s)
663 r = penlight.stringx.strip(r)
664 if r == '*' then -- if the string has no numbers and no :, it is a key
665 t:append(r)
666 elseif string.isvarlike(r) then -- if the string has no numbers and no :, it is a key
667 t:append(r)
668 elseif r:find(penlight.seq.train_range_sep) then
669 r = r:split(penlight.seq.train_range_sep) -- if it's a range
670 t:extend(penlight.List.range(check_neg(r[1], len, 1),
671 check_neg(r[2], len, len),
672 tonumber(r[3])))
673 else
674 t:append(check_neg(r, len))
675 end
676 end
677 return t
678 end
679
680 function penlight.seq.itrain(s, len)
681 -- iterator version of sequence-string
682 local t = penlight.seq.train(s, len)
683 local i = 0
684 return function ()
685 i = i + 1
686 if i <= #t then return t[i] end
687 end
688 end
689
690
691
692 function penlight.seq.tbltrain(tbl, s) -- iterate over a table using the train syntax
693 local inds = penlight.seq.train(s, #tbl) -- indexes to use
694 local star = inds:index('*')
695 if star ~= nil then
696 inds:pop(star)
697 inds:inject(penlight.tablex.kkeys(tbl), star)
698 end
699 local i = 0
700 return function ()
701 i = i + 1 -- i of indexes
702 if i <= #inds then
703 local v = tbl[inds[i]]
704 --penlight.wrth(v)
705 --if v == nil then penlight.test.asserteq(v, true) end -- todo make a generic lua error message function
706 return inds[i], v
707 end
708 end
709 end
710
711
712
713
714
715 function penlight.seq.prod(t1, t2)
716 -- cartesian prduct of two tables (uses ipairs)
717 local t_new = {}
718 for _, v1 in ipairs(t1) do
719 for _, v2 in ipairs(t2) do
720 t_new[#t_new + 1] = {v1, v2}
721 end
722 end
723 local i = 0
724 return function ()
725 i = i + 1
726 if i <= #t_new then return t_new[i][1], t_new[i][2] end
727 end
728 end
729
730
731
732
733
734
735
736 -- -- -- -- -- -- -- -- -- -- -- -- functions below extend the operator module
737
738 function penlight.operator.strgt(a,b) return tostring(a) > tostring(b) end
739 function penlight.operator.strlt(a,b) return tostring(a) < tostring(b) end
740
741
742
743 -- -- -- -- functions below are helpers for arrays and 2d
744
745 local function compare_elements(a, b, op, ele)
746 op = op or penlight.oper.gt
747 ele = ele or 1
748 return op(a[ele], b[ele])
749 end
750
751 local function comp_2ele_func(op, ele) -- make a 2 element comparison function,
752 --sort with function on element nnum
753 return bind(compare_elements, _1, _2, op, ele)
754 end
755
756
757
758 -- table stuff below
759
760
761 function penlight.tablex.concatenate(t1,t2)
762 -- todo is this needed
763 for i=1,#t2 do
764 t1[#t1+1] = t2[i]
765 end
766 return t1
767 end
768
769
770 function penlight.tablex.strinds(t) -- convert indices that are numbers to string indices
771 local t_new = {}
772 for i, v in pairs(t) do -- ensure all indexes are strings
773 if type(i) == 'number' then
774 t_new[tostring(i)] = v
775 else
776 t_new[i] = v
777 end
778 end
779 return t_new
780 end
781
782
783
784 function penlight.tablex.listcontains(t, v)
785 return penlight.tablex.find(t, v) ~= nil
786 end
787
788
789 -- format contents of a table
790 function penlight.tablex.fmt(t, fmt, strinds)
791 if fmt == nil then
792 return t
793 end
794 strinds = strinds or false -- if your fmt table should use string indexes
795 if type(fmt) == 'string' then
796 if not fmt:find('=') then -- if no = assume format all same
797 for k, v in pairs(t) do -- apply same format to all
798 if tonumber(v) ~= nil then -- only apply to numeric values
799 t[k] = string.format("%"..fmt, v)
800 end
801 end
802 return t
803 else
804 fmt = fmt:parsekv('naked_as_value') -- make fmt a table from keyval str
805 end
806 end
807 if strinds then fmt = penlight.tablex.strinds(fmt) end -- convert int inds to str inds
808 for k, f in pairs(fmt) do -- apply formatting to table
809 t[k] = string.format("%"..f, tostring(t[k]))
810 end
811 return t
812 end
813
814
815 function penlight.tablex.list2comma(t)
816 t = penlight.List(t)
817 local s = ''
818 if #t == 1 then
819 s = t[1]
820 elseif #t == 2 then
821 s = t:join(' and ')
822 elseif #t >= 3 then
823 s = t:slice(1,#t-1):join(', ')..', and '..t[#t]
824 end
825 return s
826 end
827
828
829 function penlight.tablex.map_slice(func, T, j1, j2)
830 if type(j1) == 'string' then
831 return penlight.array2d.map_slice(func, {T}, ','..j1)[1]
832 else
833 return penlight.array2d.map_slice(func, {T}, 1, j1, 1, j2)[1]
834 end
835 end
836
837 penlight.array2d.map_slice1 = penlight.tablex.map_slice
838
839
840
841 function penlight.tablex.kkeys(t)
842 local keys = {}
843 for k, _ in penlight.utils.kpairs(t) do
844 keys[#keys+1] = k
845 end
846 return keys
847 end
848
849
850
851
852 -- todo option for multiple filters with AND logic, like the filter files??
853 function penlight.tablex.filterstr(t, exp, case)
854 -- case = case sensitive
855 case = penlight.hasval(case)
856 -- apply lua patterns to a table to filter iter
857 -- str or table of str's can be passed, OR logic is used if table is passed
858 if case then
859 return penlight.tablex.filter(t, bind(string.containsany,_1,exp))
860 else
861 return penlight.tablex.filter(t, bind(string.containsanycase,_1,exp))
862 end
863 end
864
865
866 function penlight.tablex.train(t,seq,reind)
867 local t_new = {}
868 local num = 0
869 for k, v in penlight.seq.tbltrain(t, seq) do
870 if reind and type(v) == 'number' then
871 num = num + 1
872 k = num
873 end
874 t_new[k] = v
875 end
876 return t_new
877 end
878
879
880
881 function penlight.trysplitcomma(s)
882 strip = strip or false
883 if type(s) == 'number' then s = tostring(s) end
884 if type(s) == 'string' then
885 return s:splitstrip(',')
886 end
887 return s
888 end
889
890
891 function penlight.findfiles(kv)
892 if type(kv) == 'string' then kv = penlight.luakeys.parse(kv) end
893 kv = penlight.tablex.update({dir={'.'}, fn={'*'}, ext={''}, sub=false}, kv)
894 kv.dir = penlight.trysplitcomma(kv.dir)
895 kv.fn = penlight.trysplitcomma(kv.fn)
896 kv.ext = penlight.trysplitcomma(kv.ext)
897 --local files_all = penlight.getallfilesdirs(kv.dir, kv.sub)
898 local getfiles = penlight.dir.getfiles
899 if penlight.hasval(kv.sub) then
900 getfiles = function(dir, fn) return penlight.dir.getallfiles(dir, '*'..fn) end -- need * in front so folder does not affect result
901 end
902 local files = penlight.List{}
903 for fn, ext in penlight.seq.prod(kv.fn, kv.ext) do
904 for _, dir in ipairs(kv.dir) do
905 files:extend(getfiles(dir, fn..ext))
906 end
907 end
908 files = pl.List(penlight.tablex.keys(pl.Set(files))) -- clear duplicates
909 files = files:map(function(s) return s:gsub('\\','/') end) -- change slash for latex
910 return files
911 end
912
913 penlight.dir.findfiles = penlight.findfiles
914
915 --todo add doc
916 function penlight.utils.filterfiles(...)
917 -- f1 is a series of filtering patterns, or condition
918 -- f2 is a series of filtering patters, or condition
919 -- (f1_a or f2_...) and (f2 .. ) must match
920 local args = table.pack(...)
921 -- dir, recursive[bool], filt1, filt2 etc...
922 -- OR recursive[bool], filt1, filt2, etc..
923 -- OR filt1, filt2, filt3, etc..
924 -- this could allow one to omit dir
925 -- if boolean given ar arg 1, assume dir = '.'
926 local nstart = 3
927 local r = args[2] -- recursive
928 local dir = args[1] -- start dir
929 if type(args[1]) == 'boolean' then
930 dir = '.'
931 r = args[1]
932 nstart = 2
933 elseif type(args[2]) ~= 'boolean' then -- if boolean given ar arg 1, assume dir = '.'
934 dir = '.'
935 r = false
936 nstart = 1
937 end
938
939 local files
940 if r then files = penlight.dir.getallfiles(dir)
941 else files = penlight.dir.getfiles(dir)
942 end
943 for i=nstart,args.n do
944 files = penlight.tablex.filter(files, penlight.func.compose(bind(string.containsanycase,_1, args[i]), penlight.path.basename))
945 end
946 return files
947 end
948
949
950
951 -- -- -- -- -- -- -- -- functions below extend the array2d module
952
953
954 function penlight.array2d.map_slice(func, M, i1, j1, i2, j2) -- map a function to a slice of a Matrix
955 func = penlight.utils.function_arg(1, func)
956 for i,j in penlight.array2d.iter(M, true, i1, j1, i2, j2) do
957 M[i][j] = func(M[i][j])
958 end
959 return M
960 end
961
962 penlight.array2d.map_slice2 = penlight.array2d.map_slice
963
964 function penlight.array2d.map_cols(func, M, j1, j2) -- map function to columns of matrix
965 if type(j1) == 'string' then
966 return penlight.array2d.map_slice(func, M, ','..j1)
967 else
968 j2 = j2 or -1
969 return penlight.array2d.map_slice(func, M, 1, j1, -1, j2)
970 end
971 end
972
973 penlight.array2d.map_columns = penlight.array2d.map_cols
974
975 function penlight.array2d.map_rows(func, M, i1, i2) -- map function to rows of matrix
976 if type(i1) == 'string' then
977 return penlight.array2d.map_slice(func, M, i1)
978 else
979 i2 = i2 or -1
980 return penlight.array2d.map_slice(func, M, i1, 1, i2, -1)
981 end
982 end
983
984
985 -- -- -- -- -- -- -- --
986
987 function penlight.array2d.sortOP(M, op, ele) -- sort a 2d array based on operator criteria, ele is column, ie sort on which element
988 M_new = {}
989 for row in penlight.seq.sort(M, comp_2ele_func(op, ele)) do
990 M_new[#M_new+1] = row
991 end
992 return M_new
993 end
994
995 function penlight.array2d.like(M1, v)
996 v = v or 0
997 r, c = penlight.array2d.size(M1)
998 return penlight.array2d.new(r,c,v)
999 end
1000
1001 function penlight.array2d.from_table(t) -- turns a labelled table to a 2d, label-free array
1002 t_new = {}
1003 for k, v in pairs(t) do
1004 if type(v) == 'table' then
1005 t_new_row = {k}
1006 for _, v_ in ipairs(v) do
1007 t_new_row[#t_new_row+1] = v_
1008 end
1009 t_new[#t_new+1] = t_new_row
1010 else
1011 t_new[#t_new+1] = {k, v}
1012 end
1013 end
1014 return t_new
1015 end
1016
1017 function penlight.array2d.toTeX(M, EL) --puts & between columns, can choose to end line with \\ if EL is true (end-line)
1018 EL = EL or false
1019 if EL then EL = '\\\\' else EL = '' end
1020 return penlight.array2d.reduce2(_1..EL.._2, _1..'&'.._2, M)..EL
1021 end
1022
1023
1024 local function parse_numpy1d(i1, i2, iS)
1025 i1 = tonumber(i1)
1026 i2 = tonumber(i2)
1027 if iS == ':' then
1028 if i1 == nil then i1 = 1 end
1029 if i2 == nil then i2 = -1 end
1030 else
1031 if i1 == nil then
1032 i1 = 1
1033 i2 = -1
1034 else
1035 i2 = i1
1036 end
1037 end
1038 return i1, i2
1039 end
1040
1041 function penlight.array2d.parse_numpy2d_str(s)
1042 s = s:gsub('%s+', '')
1043 _, _, i1, iS, i2, j1, jS, j2 = string.find(s, "(%-?%d*)(:?)(%-?%d*),?(%-?%d*)(:?)(%-?%d*)")
1044 i1, i2 = parse_numpy1d(i1, i2, iS)
1045 j1, j2 = parse_numpy1d(j1, j2, jS)
1046 return i1, j1, i2, j2
1047 end
1048
1049
1050
1051 if penlight.debug_available then
1052 penlight.COMP = penlight.comprehension.new() -- for comprehensions
1053 local _parse_range = penlight.clone_function(penlight.array2d.parse_range)
1054
1055 function penlight.array2d.parse_range(s) -- edit parse range to do numpy string if no letter passed
1056 penlight.utils.assert_arg(1,s,'string')
1057 if not s:find'%a' then
1058 return penlight.array2d.parse_numpy2d_str(s)
1059 end
1060 return _parse_range(s)
1061 end
1062 end
1063
1064
1065
1066 function penlight.List:inject(l2, pos)
1067 pos = pos or 1
1068 if pos < 1 then
1069 pos = #self + pos + 1
1070 end
1071 l2 = penlight.List(l2):reverse()
1072 for i in l2:iter() do
1073 self:insert(pos, i)
1074 end
1075 return self
1076 end
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086 -- https://tex.stackexchange.com/questions/38150/in-lualatex-how-do-i-pass-the-content-of-an-environment-to-lua-verbatim
1087 penlight.tex.recordedbuf = ""
1088 function penlight.tex.readbuf(buf)
1089 i,j = string.find(buf, '\\end{%w+}')
1090 if i==nil then -- if not ending an environment
1091 penlight.tex.recordedbuf = penlight.tex.recordedbuf .. buf .. "\n"
1092 return ""
1093 else
1094 return nil
1095 end
1096 end
1097
1098 function penlight.tex.startrecording()
1099 penlight.tex.recordedbuf = ""
1100 luatexbase.add_to_callback('process_input_buffer', penlight.tex.readbuf, 'readbuf')
1101 end
1102
1103 function penlight.tex.stoprecording()
1104 luatexbase.remove_from_callback('process_input_buffer', 'readbuf')
1105 penlight.tex.recordedbuf = penlight.tex.recordedbuf:gsub("\\end{%w+}\n","")
1106 end
1107
1108
1109
1110 __PDFmetadata__ = {}
1111 penlight.tex.add_xspace_intext = true
1112
1113
1114 function penlight.tex.checkPDFkey(k)
1115 k = k:delspace():upfirst()
1116 local keys_allowed = 'Title Author Subject Date Language Keywords Publisher Copyright CopyrightURL Copyrighted Owner CertificateURL Coverage PublicationType Relation Source Doi ISBN URLlink Journaltitle Journalnumber Volume Issue Firstpage Lastpage CoverDisplayDate CoverDate Advisory BaseURL Identifier Nickname Thumbnails '
1117 if not keys_allowed:find(k ..' ') then
1118 penlight.tex.pkgerror('penlightplus', 'invalid PDF metadata key assigned "'..k..'"')
1119 end
1120 return k
1121 end
1122
1123 function penlight.tex.makePDFtablekv(kv)
1124 local t_new = {}
1125 for k, v in pairs(penlight.luakeys.parse(kv)) do
1126 k = penlight.tex.checkPDFkey(k)
1127 v = penlight.tex.makePDFvarstr(v)
1128 t_new[k] = v
1129 end
1130 return t_new
1131 end
1132
1133 function penlight.tex.updatePDFtable(k, v, o) -- update pdf table
1134 if o == nil then o = true end
1135 k = k:strip():upfirst()
1136 if penlight.hasval(o) or (__PDFmetadata__[k] == nil) then
1137 __PDFmetadata__[penlight.tex.checkPDFkey(k)] = penlight.tex.makePDFvarstr(v)
1138 end
1139 end
1140
1141
1142 penlight.tex.writePDFmetadata = function(t) -- write PDF metadata to xmpdata file
1143 t = t or __PDFmetadata__
1144 local str = ''
1145 for k, v in pairs(t) do
1146 str = str..'\\'..k..'{'..v..'}'..'\n'
1147 end
1148 penlight.utils.writefile(tex.jobname:gsub('"','')..'.xmpdata', str)
1149 end
1150
1151
1152 function penlight.tex.makePDFvarstr(s)
1153 s = s:gsub('%s*\\sep%s+','\0'):gsub('%s*\\and%s+','\0') -- turn \and into \sep
1154 -- todo preserve \%, \{, \}, \backslash, and \copyright
1155 s = penlight.tex.clear_cmds_str(s)
1156 s = s:gsub('\0','\\sep ')
1157 --penlight.tex.help_wrt(s,'PDF var string')
1158 return s
1159 end
1160
1161 function penlight.tex.clear_cmds_str(s)
1162 return s:gsub('%s+', ' '):gsub('\\\\',' '):gsub('\\%a+',''):gsub('{',' '):gsub('}',' '):gsub('%s+',' '):strip()
1163 end
1164
1165 function penlight.tex.makeInTextstr(s)
1166 local s, c_and = s:gsub('%s*\\and%s+','\0')
1167 s = penlight.tex.clear_cmds_str(s)
1168 if penlight.tex.add_xspace_intext then
1169 s = s..'\\xspace'
1170 end
1171 if c_and == 1 then
1172 s = s:gsub('\0',' and ')
1173 elseif c_and > 1 then
1174 s = s:gsub('\0',', ', c_and - 1)
1175 s = s:gsub('\0',', and ')
1176 end
1177 --penlight.tex.help_wrt(s,'in text var string')
1178 return s
1179 end
1180
1181
1182
1183
1184
1185
1186
1187
1188 function penlight.toggle_luaexpr(expr)
1189 if expr then
1190 tex.sprint('\\toggletrue{luaexpr}')
1191 else
1192 tex.sprint('\\togglefalse{luaexpr}')
1193 end
1194 end
1195
1196
1197
1198
1199 function penlight.caseswitch(s, c, kv)
1200 local kvtbl = penlight.luakeys.parse(kv)
1201 local sw = kvtbl[c] -- the returned switch
1202 if sw == nil then -- if switch not found
1203 if s == penlight.tex.xTrue then -- if star, throw error
1204 penlight.tex.pkgerror('penlight', 'case: "'..c..'" not found in key-vals: "'..kv..'"')
1205 sw = ''
1206 else
1207 sw = kvtbl['__'] or '' -- use __ as not found case
1208 end
1209 end
1210 tex.sprint(sw)
1211 end
1212
1213
1214
1215
1216
1217
1218
1219
1220 -- global setting type stuff
1221
1222 function penlight.make_tex_global()
1223 for k,v in pairs(penlight.tex) do -- make tex functions global
1224 _G[k] = v
1225 end
1226 end
1227
1228
1229 penlight.kpairs = penlight.utils.kpairs
1230 penlight.npairs = penlight.utils.npairs
1231 penlight.writefile = penlight.utils.writefile
1232 penlight.readfile = penlight.utils.readfile
1233 penlight.readlines = penlight.utils.readfile
1234 penlight.filterfiles = penlight.utils.filterfiles
1235
1236 -- adopt table functions in tablex
1237 penlight.tablex.concat = table.concat
1238 penlight.tablex.insert = table.insert
1239 penlight.tablex.maxn = table.maxn
1240 penlight.tablex.remove = table.remove
1241 penlight.tablex.sort = table.sort
1242
1243 penlight.tbx = penlight.tablex
1244 penlight.a2d = penlight.array2d
1245
1246 if penlight.hasval(__PL_GLOBALS__) then
1247 -- iterators
1248 kpairs = penlight.utils.kpairs
1249 npairs = penlight.utils.npairs
1250
1251 hasval = penlight.hasval
1252 COMP = penlight.COMP
1253
1254 for k,v in pairs(penlight.tablex) do -- extend the table table to contain tablex functions
1255 if k == 'sort' then
1256 table.sortk = v
1257 elseif k == 'move' then
1258 table.xmove = v
1259 else
1260 _G['table'][k] = v
1261 end
1262 end
1263 table.join = table.concat -- alias
1264
1265 a2d = penlight.array2d
1266 tbx = penlight.tablex
1267 end
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277 -- graveyard
1278
1279 --todo decide on above or below
1280
1281
1282
1283 penlight.tex.list2comma = penlight.tablex.list2comma
1284
1285 function penlight.tex.split2comma(s, d)
1286 local t = penlight.List(s:split(d)):map(string.strip)
1287 penlight.tex.prt(penlight.tex.list2comma(t))
1288 end
1289
1290 function penlight.tex.split2items(s, d)
1291 local t = penlight.List(s:split(d)):map(string.strip)
1292 for n, v in ipairs(t) do
1293 penlight.tex.prtn('\\item '..v)
1294 end
1295 end
1296
1297
1298 --
1299 --\subsection*{Splitting strings}
1300 --Splitting text (or a cmd) into oxford comma format via:
1301 --\cmd{\splittocomma[expansion level]{text}{text to split on}}:
1302 --
1303 --\begin{LTXexample}[width=0.3\linewidth]
1304 -- \splittocomma{ j doe }{\and}-\\
1305 --\splittocomma{ j doe \and s else }{\and}-\\
1306 --\splittocomma{ j doe \and s else \and a per }{\and}-\\
1307 --\splittocomma{ j doe \and s else \and a per \and f guy}{\and}-
1308 --
1309 --\def\authors{j doe \and s else \and a per \and f guy}
1310 --\splittocomma[o]{\authors}{\and}
1311 --\end{LTXexample}
1312 --
1313 --The expansion level is up to two characters, \cmd{n|o|t|f}, to control the expansion of each argument.
1314 --
1315 --You can do a similar string split but to \cmd{\item} instead of commas with \cmd{\splittoitems}
1316 --\begin{LTXexample}
1317 --\begin{itemize}
1318 -- \splittoitems{kale\and john}{\and}
1319 -- \splittoitems{kale -john -someone else}{-}
1320 -- \splittoitems{1,2,3,4}{,}
1321 --\end{itemize}
1322 --\end{LTXexample}
1323
1324
1325
1326 --
1327 --\NewDocumentCommand{\splittocomma}{ O{nn} m m }{%
1328 -- \MakeluastringCommands[nn]{#1}%
1329 -- \luadirect{penlight.tex.split2comma(\plluastringA{#2},\plluastringB{#3})}%
1330 --}
1331 --
1332 --\NewDocumentCommand{\splittoitems}{ O{NN} m m }{%
1333 -- \MakeluastringCommands[nn]{#1}%
1334 -- \luadirect{penlight.tex.split2items(\plluastringA{#2},\plluastringB{#3})}%
1335 --}