Debian Codegraph @

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

raw
1 --% Kale Ewasiuk ([email protected])
2 --% 2025-01-06
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
27
28 local lutabt = {}
29
30 local pl = penlight
31 local T = pl.tablex
32
33 lutabt.luakeys = require'luakeys'()
34
35
36 lutabt.tablelevel = 0
37
38 lutabt.debug = false
39
40 lutabt.auto_topbot = false
41 lutabt.auto_topbot_old = false
42
43 lutabt.auto_crules = {} -- {{span,trim}, } appearance is like this, 'range|trim', -- auto_rules created by MC
44 lutabt.auto_midrules = {}
45
46 lutabt.col_spec1 = {} -- column spec if one column wide (since makcell nests a tabular, preserve col_spec below)
47 lutabt.col_spec = {} -- tab column spec if above 1
48 lutabt.col = '' -- current column spec, single char, only applies to tabular with more than 1 column
49 lutabt.col_num = 1 -- current column number
50 lutabt.row_num = 0 -- current row number
51
52 lutabt.actlvl = 1 -- 'active' level on which to apply midrules, normally 1
53
54 lutabt.col_ver_repl = {
55 m = 'm',
56 M = 'm',
57 b = 'b',
58 }
59
60 lutabt.col_hor_repl = { -- horizontal cell alignment that multicolumn should use if () or [hori] not passed to func
61 l = 'l',
62 c = 'c',
63 r = 'r',
64 p = 'l',
65 P = 'c',
66 X = 'l',
67 Y = 'c',
68 Z = 'l',
69 N = 'c',
70 L = 'l',
71 R = 'r',
72 C = 'c',
73 }
74
75 -- allow user to place their own replacements in for a table, say if they define a column that expands to multiple
76 lutabt.col_replaces = {
77 --x = 'lll'
78 }
79
80 lutabt.SI_cols = {'S', 'N', 'Q', 'L', 'R'}
81
82
83
84 -----
85 ----- utility funcs
86 -----
87
88
89 function lutabt.debugtalk(s, ss)
90 ss = ss or ''
91 if lutabt.debug then
92 pl.tex.help_wrt(s, ss..' (lutabulartools)')
93 end
94 end
95
96 function __lutabt__debugprtall()
97 pl.help_wrt(lutabt, '(lutabulartools state)')
98 end
99
100
101 function lutabt.set_tabular(sett)
102 sett = lutabt.luakeys.parse(sett)
103 local trim = ''
104 for k, v in pairs(sett) do
105 if k == 'tbrule' then
106 lutabt.auto_topbot = v
107 elseif k == 'nopad' then
108 if pl.hasval(v) then trim = '@{}' end -- set to trim
109 tex.print('\\newcolumntype{\\lttltrim}{'..trim..'}')
110 tex.print('\\newcolumntype{\\lttrtrim}{'..trim..'}')
111 elseif k =='rowsep' then
112 tex.print('\\gdef\\arraystretch{'..v..'}')
113 elseif k =='colsep' then
114 tex.print('\\global\\setlength{\\tabcolsep}{'..(v*6)..'pt'..'}')
115 end
116 end
117 end
118
119
120 -----
121 ----- tabular utility funcs
122 -----
123
124 function lutabt.reset_rows()
125 if lutabt.isactlevel() then
126 lutabt.row_num = 0
127 end
128 end
129
130 function lutabt.set_col_num()
131 -- register current column info (column number and specification)
132 local nest
133 for i = tex.nest.ptr, 1, -1 do
134 local tail = tex.nest[i].tail
135 if tail.id == node.id'glue' and tail.subtype == table.swapped(node.subtypes'glue').tabskip then
136 nest = tex.nest[i]
137 break
138 end
139 end
140 if nest then
141 local col = 1
142 for _, sub in node.traverse_id(node.id'unset', nest.head) do
143 col = col + sub + 1
144 end
145 lutabt.col_num = col
146 else
147 lutabt.col_num = 1
148 end
149 lutabt.col = lutabt.col_spec[lutabt.col_num]
150 lutabt.debugtalk('col_num='..lutabt.col_num..'; col_spec='..lutabt.col,'set_col_num')
151 end
152
153
154 function lutabt.set_col_spec(zz)
155 -- contents of string 'zz'
156 -- register the table column specification
157 zz = zz:gsub ( "%*%s-{(%d-)}%s-(%b{})" , -- expand expressions such as "*{5}{l}" to "lllll"
158 function(y, z ) z = z:sub (2 , -2) return string.rep (z, y) end ) --
159 zz = zz:gsub ( "%b{}" , "" ) -- omit all stuff in curly braces and square
160 zz = zz:gsub ( "%b[]" , "" )
161 zz = zz:gsub ( "[@!|><%s%*\']" , "" ) -- some more characters to ignore
162 zz = zz:gsub('%a', lutabt.col_replaces) -- sub extra column
163 _col_spec = zz:totable() -- requires pl extras
164 --help_wrt(_col_spec, 'helpme')
165 if #_col_spec > 1 then
166 lutabt.col_spec = _col_spec
167 else
168 lutabt.col_spec1 = _col_spec
169 end
170 lutabt.debugtalk(lutabt.col_spec,'set_col_spec')
171 end
172
173
174 --todo
175 -- if p{} column, and multirow is 1, use {=} instead of {*}
176 -- but note, makecell will not work. So you may want to skip it.multicolumn
177 -- this case should be considered in this code.
178 -- for example: \multirow{2}{=}
179
180
181 -----
182 ----- magic cell and helpers
183 -----
184
185 function lutabt.MagicCell(s0,spec,mcspec,pre,content,trim)
186 -- todo delete trim!!!
187 --
188 lutabt.set_col_num() -- register current column number and column spec
189
190 local STR = ''
191 pl.tex.reset_bkt_cnt()
192
193 local spec, iscmidrule, trim = lutabt.check_MC_cmidrule(spec) -- check for cmidrule and clean spec
194
195 local v, h, r, c, mrowsym, skipmakecell = lutabt.parse_MagicCell_spec(spec) -- get v/h align, number rows/columns
196
197 local mcspec = mcspec or ''
198
199 h, mcspec, c = lutabt.get_HColSpec(h, mcspec, c) -- infer horizontal alignment, num columns
200
201 lutabt.debugtalk(pl.List{v, h, r, c, mcspec}:join'; ','v, h, r, c, mcspec')
202
203 --help_wrt(_CurTabColAbv,'current column')
204 if s0 == pl.tex._xTrue or (pl.List(lutabt.SI_cols):contains(lutabt.col) -- special columns for SI
205 and c == '') then -- multicolumn cannot have {} around it
206 STR = STR .. '{' -- multirow and makcell must have {} around it S column is used
207 pl.tex.add_bkt_cnt()
208 end
209
210 if c ~= '' then
211 STR = STR .. "\\multicolumn{"..c.."}{"..mcspec.."}{"
212 pl.tex.add_bkt_cnt()
213 end
214
215 if r ~= '' then
216 STR = STR .."\\multirow["..v.."]{"..r.."}{"..mrowsym.."}{" -- optional arg here
217 pl.tex.add_bkt_cnt()
218 end
219
220 if not skipmakecell then
221 if pre ~= '' then
222 STR = STR.."\\renewcommand{\\cellset}{"..pre.."}"
223 end
224
225 STR = STR.."\\makecell[{"..v.."}{"..h.."}]{"
226 pl.tex.add_bkt_cnt()
227 else
228 content = content:gsub('\\\\', '\\newline')
229 end
230
231 STR = STR..content..pl.tex.close_bkt_cnt()
232 --Troubleshooting
233 --help_wrt(STR..' <<< magic cell string')
234 lutabt.debugtalk(STR,'MagicCell')
235 tex.sprint(STR)--tex print the STR
236
237 if iscmidrule then
238 local en
239 if c == '' then en = lutabt.col_num else en = lutabt.col_num + c -1 end
240 lutabt.add_auto_crule(lutabt.col_num, en, trim)
241 end
242 end
243
244
245 function lutabt.check_MC_cmidrule(spec)
246 local iscmidrule = false
247 local trim = ''
248 local st, en = spec:find('_')
249 if st ~= nil then
250 trim = spec:sub(st+1, #spec)
251 spec = spec:sub(1,st-1)
252 iscmidrule = true
253 end
254 return spec, iscmidrule, trim
255 end
256
257 function lutabt.parse_MagicCell_spec(spec)
258 local mrowsym = '*' -- * = natural width, = will match p{2cm} for example
259 local skipmakecell = false
260 if string.find(spec, '=') then
261 spec = spec:gsub('=', '')
262 mrowsym = '='
263 skipmakecell = true
264 end
265
266 spec = spec:lower():gsub('%s','') -- take lower case and remove space
267 local vh, rc = spec:gextract('%a') -- extract characters
268 local v = vh:gfirst({'t', 'm', 'b'}) or lutabt.col_ver_repl[lutabt.col] or 't'
269 local h = vh:gfirst({'l', 'c', 'r'}) or ''
270 v = v:gsub('m', 'c')
271
272 local rc_ = (rc):split(',')
273 local c = rc_[1] or '' --num columns, width
274 local r = rc_[2] or '' --num rows, height
275 if c == '0' or c == '1' then c = '' end
276 if r == '0' or r == '1' then r = '' end
277
278 return v, h, r, c, mrowsym, skipmakecell
279 end
280
281
282 function lutabt.get_HColSpec(h, mcspec, c) -- take horizontal alignment
283 -- c is num columns, h is horizontal alginment,
284 --Assumes _TabColNum was calculated previosly
285 if c == '+' then -- fill row to end
286 c = tostring(#lutabt.col_spec - lutabt.col_num + 1)
287 end
288 if h == '' then -- if horizontal not provided, use declared column
289 h = lutabt.col_hor_repl[lutabt.col] or 'l'
290 end
291 if c ~= '' then -- only make new mcspec if column nums > 0
292 if mcspec == '' then -- and if no mcspec was passed
293 mcspec = h
294 if lutabt.col_num == 1 then -- if first column, auto detect padding
295 mcspec = '@{}'..mcspec
296 end
297 if (lutabt.col_num + tonumber(c) - 1) == #lutabt.col_spec then -- if end on last column
298 mcspec = mcspec..'@{}'
299 end
300 else -- if mcspec if given, extract the alignment
301 lutabt.set_col_spec(mcspec)
302 h = lutabt.col_spec1[1] -- get 1 character column spec from mcspec and override h
303 end
304 end
305 return h, mcspec, c
306 end
307
308
309 -----
310 ----- autorules (with \MC() or auto top bot or midrule X, performed after \\
311 -----
312
313 function lutabt.add_auto_midrules(rows)
314 lutabt.auto_midrules = rows:split(',')
315 end
316
317 function lutabt.add_auto_crule(st,en,trim)
318 if trim ~= 'x' then
319 lutabt.auto_crules[#lutabt.auto_crules + 1] = {math.floor(st)..'-'..math.floor(en), trim} -- append here
320 -- {{span 1-2, trim}, ..}
321 end
322 end
323
324 function lutabt.isactlevel()
325 lutabt.tablelevel = tonumber(lutabt.tablelevel)
326 lutabt.actlvl = tonumber(lutabt.actlvl)
327 return lutabt.actlvl == lutabt.tablelevel
328 end
329
330
331 function lutabt.process_auto_rules()
332 if lutabt.isactlevel() then
333 lutabt.row_num = lutabt.row_num + 1
334 if lutabt.auto_crules ~= {} then
335 for _, v in ipairs(lutabt.auto_crules) do
336 lutabt.make1cmidrule('', v[2], v[1], 'cmidrule')
337 end
338 for i, v in ipairs(lutabt.auto_midrules) do
339 if tonumber(v) == lutabt.row_num then
340 _ = table.remove(lutabt.auto_midrules,i)
341 tex.print('\\midrule ')
342 end
343 end
344 end
345 if lutabt.mrX.settings.on then
346 lutabt.mrX.midruleX()
347 end
348 end
349 lutabt.auto_crules = {}
350 end
351
352
353
354
355 function lutabt.process_auto_topbot_rule(rule)
356 if lutabt.isactlevel() then
357 if lutabt.auto_topbot then
358 tex.print('\\'..rule..'rule ')
359 end
360 end
361 end
362
363
364
365
366
367
368 -----
369 ----- extra midrule
370 -----
371
372
373
374 function lutabt.get_midrule_col(s)
375 if string.find(s, '+') then
376 s = s:gsub('+', '')
377 if (s == '') or (s == '0') then
378 s = 1
379 end
380 s = tostring(#lutabt.col_spec - tonumber(s) + 1) -- use number of tabular columns above 0,
381 end
382 return s
383 end
384
385
386 function lutabt.make1cmidrule(s, r, c, cmd) -- s=square r=round c=curly
387 cmd = '\\'..cmd
388 if s ~= '' then
389 cmd = cmd..'['..s..']'
390 end
391 if r ~= '' then
392 cmd = cmd..'('..r..')'
393 end
394 t = string.split(c, '-')
395 if t[2] == '' then
396 t[2] = '+'
397 end
398 if t[2] == nil then
399 t[2] = t[1]
400 end
401 c = lutabt.get_midrule_col(t[1])..'-'..lutabt.get_midrule_col(t[2])
402 cmd = cmd..'{'..c..'}'
403 lutabt.debugtalk(cmd,'make1cmidrule')
404 tex.print(cmd)
405 end
406
407 function lutabt.makecmidrules(s, r, c, cmd)
408 for k, c1 in pairs(string.split(c, ',')) do
409 r1, c2 = c1:gextract('%a')
410 if r1 == '' then -- if nothing passed in with the column
411 r1 = r -- set to the global value passed in round brackets
412 end
413 lutabt.make1cmidrule(s, r1:strip(), c2:strip(), cmd)
414 end
415 end
416
417
418 -----
419 ----- midruleX
420 -----
421
422 lutabt.mrX = {}
423 lutabt.mrX.resets = {long=false, cntr=0, head=nil, longx=false, on=true} -- settings that reset when \setmidruleX used
424 lutabt.mrX.resets['head*'] = nil
425 lutabt.mrX.settings = T.update(T.copy(lutabt.mrX.resets), {pgcntr=0, step=5, rule='midrule'}) -- current settings, not overwritten with each call
426 lutabt.mrX.settings.on = false
427
428 function lutabt.mrX.reset_midruleX(n)
429 lutabt.mrX.settings.cntr = tonumber(n)
430 end
431
432 function lutabt.mrX.off()
433 if lutabt.isactlevel() then
434 lutabt.mrX.settings.on = false
435 end
436 end
437
438 function lutabt.mrX.set_midruleX(new_sett, def)
439 lutabt.mrX.settings = T.update(lutabt.mrX.settings, T.union(lutabt.mrX.resets, lutabt.luakeys.parse(new_sett)))
440 lutabt.debugtalk(lutabt.mrX.settings, 'new midruleX settings')
441 if lutabt.mrX.settings.head ~= nil then
442 lutabt.mrX.settings.cntr = -1*tonumber(lutabt.mrX.settings.head)
443 elseif lutabt.mrX.settings['head*'] ~= nil then
444 lutabt.mrX.settings.cntr = -1*tonumber(lutabt.mrX.settings['head*'])
445 lutabt.auto_midrules[#lutabt.auto_midrules + 1] = lutabt.mrX.settings['head*']
446 lutabt.mrX.settings['head*'] = nil -- for some reason need to do this to clear head*
447 end
448 if lutabt.mrX.settings.longx then -- longtable X messes with the tablelevel settings, hack to fix, use longx keyword
449 lutabt.actlvl = 3
450 lutabt.mrX.settings.long = true
451 else
452 lutabt.actlvl = 1
453 end
454 end
455
456
457 function lutabt.mrX.midruleX(n)
458 n = n or '' -- todo placeholder for noalign ?
459 lutabt.debugtalk(lutabt.mrX.settings, 'midruleX here')
460 local s = lutabt.mrX.settings
461 local rule = s.rule
462 if pl.hasval(s.long) and lutabt.mrX.add_label_and_check_page_change() then lutabt.mrX.settings.cntr = 0 end -- reset to number on page change -- longhead not used anymore
463 lutabt.mrX.settings.cntr = lutabt.mrX.settings.cntr + 1
464 if lutabt.mrX.settings.cntr == s.step then
465 if not rule:startswith('\\') then rule = '\\'..rule end -- todo consider allowing \gmidrule syntax, possible issue with expansion
466 lutabt.debugtalk(rule, 'apply midruleX')
467 tex.sprint(rule)
468 lutabt.mrX.settings.cntr = 0
469 end
470 end
471
472 function lutabt.mrX.add_label_and_check_page_change()
473 lutabt.mrX.settings.pgcntr = lutabt.mrX.settings.pgcntr + 1
474 tex.print('\\noalign{\\label{ltt@tabular@row@'..lutabt.mrX.settings.pgcntr..'}}')
475 local rcurr = pl.tex.get_ref_info('ltt@tabular@row@'..lutabt.mrX.settings.pgcntr)
476 local rprev = pl.tex.get_ref_info('ltt@tabular@row@'..lutabt.mrX.settings.pgcntr-1)
477 --local rcurrc, _, _ = pl.tex.get_ref_info_all_cref('ltt@tabular@row@'..lutabt.mrX.settings.pgcntr)
478 lutabt.debugtalk('curr: '..rcurr[2]..' prev: '..rprev[2]..' row: '..lutabt.mrX.settings.pgcntr, 'check midruleX page change')
479 lutabt.debugtalk(rcurr, 'miduleX current reference info for row: '..lutabt.mrX.settings.pgcntr)
480 --lutabt.debugtalk(rcurrc, 'miduleX current cleveref cref info')
481 if rcurr[2] ~= rprev[2] then -- pg no is second element
482 return true
483 end
484 return false
485 end
486
487
488 return lutabt -- lutabulartools
489
490
491
492 --http://ctan.mirror.rafal.ca/macros/latex/contrib/multirow/multirow.pdf
493 --http://ctan.mirror.colo-serv.net/macros/latex/contrib/makecell/makecell.pdf
494 -- https://tex.stackexchange.com/questions/331716/newline-in-multirow-environment
495
496
497
498
499
500