Debian Codegraph @

texmf-dist/tex/lualatex/longmath/longmath.lua

raw
1 --
2 -- longmath.lua is part of longmath version 1.0.
3 --
4 -- (c) 2024 Hans-Jürgen Matschull
5 --
6 -- This work may be distributed and/or modified under the
7 -- conditions of the LaTeX Project Public License, either version 1.3
8 -- of this license or (at your option) any later version.
9 -- The latest version of this license is in
10 -- http://www.latex-project.org/lppl.txt
11 -- and version 1.3 or later is part of all distributions of LaTeX
12 -- version 2005/12/01 or later.
13 --
14 -- This work has the LPPL maintenance status 'maintained'.
15 --
16 -- The Current Maintainer of this work is Hans-Jürgen Matschull
17 --
18 -- see README for a list of files belonging to longmath.
19 --
20
21 -- Attribute numbers.
22 local attr_info = luatexbase.registernumber( 'longmath@info' )
23 local attr_limits = luatexbase.registernumber( 'longmath@limits' )
24
25 -- Character for tagging parent groups.
26 local parent = '+'
27
28
29 -- Check for specific node types.
30 local ntypes = node.types()
31 local function is_noad( nd ) return nd and ntypes[ nd.id ] == 'noad' and nd.subtype end
32 local function is_fence( nd ) return nd and ntypes[ nd.id ] == 'fence' and nd.subtype end
33 local function is_hlist( nd ) return nd and ntypes[ nd.id ] == 'hlist' and nd.subtype end
34 local function is_style( nd ) return nd and ntypes[ nd.id ] == 'style' and nd.subtype end
35 local function is_whatsit( nd ) return nd and ntypes[ nd.id ] == 'whatsit' and nd.subtype end
36
37 -- Read a command whatsit.
38 local function get_comm( nd )
39 if is_whatsit( nd ) == 3 and node.has_attribute( nd, attr_info ) then
40 local comm, data = nd.data:match( '^([^:]+):?(.*)$' )
41 if data == '' then data = nil end
42 return comm, data, node.get_attribute( nd, attr_info )
43 end
44 end
45
46 -- Iterator over all fields of a node to be copied.
47 -- Returns the field name and a boolean indicating if a deep copy is needed.
48 -- If the node already has fixed dimensions, its head field is ignored.
49 -- If the limits attribute is set on a large operator, scripts are ignored in display style.
50 local function fields( nd, disp )
51 local list, oper = {}, is_noad( nd )
52 for _, fld in ipairs( node.fields( nd.id, nd.subtype ) ) do
53 list[fld] = not not node.is_node( nd[fld] )
54 end
55 list.id, list.subtype, list.attr = nil, nil, list.attr and false
56 if list.height ~= nil and list.depth ~= nil then list.head = nil end
57 if ( disp and oper == 1 or oper == 2 ) and node.has_attribute( nd, attr_limits ) then
58 list.sub, list.sup = nil, nil
59 end
60 return pairs( list )
61 end
62
63 -- Tables representing special delimiters.
64 local delim_null = { small_fam = 0, small_char = 0, large_fam = 0, large_char = 0 }
65 local delim_auto = { small_fam = 0xF, small_char = 0xEF, large_fam = 0xE, large_char = 0xFE }
66
67 -- Check if two delimiters (either real nodes or tables) are equal.
68 local function delim_eq( da, db )
69 for i in pairs( delim_null ) do if da[i] ~= db[i] then return false end end
70 return true
71 end
72
73 -- Make the delimiter node or table da equal to db.
74 local function delim_set( da, db )
75 for i in pairs( delim_null ) do da[i] = db[i] end
76 return da
77 end
78
79 -- Metatable for delimiter sequences. Internalises the overflow check.
80 local meta_delims = {}
81 function meta_delims.__index( tab, ix )
82 if type( ix ) ~= 'number' then return nil end
83 if ix > #tab then ix = #tab end
84 if ix < 1 then ix = 1 end
85 return rawget( tab, ix )
86 end
87
88 -- Stack to store auto delimiters.
89 -- The last entry in this table is the current one.
90 -- It contains two tables "opn" and "cls".
91 -- Each contains a sequence of delimiter data for each level.
92 local delimiters = {}
93
94 -- Scans a sample of auto delimiters.
95 -- Inserts the opening and closing delimites into the "opn" and "cls" tables in "tab".
96 local function scan_sample( head, tab )
97 local opn, cls
98 for pos in node.traverse( head ) do
99 if is_fence( pos ) == 1 then opn = delim_set( {}, pos.delim )
100 elseif is_fence( pos ) == 3 then cls = delim_set( {}, pos.delim )
101 elseif is_noad( pos ) == 9 then scan_sample( pos.nucleus.head, tab ) end
102 end
103 if opn and cls then table.insert( tab.opn, opn ) table.insert( tab.cls, cls ) end
104 end
105
106 -- This function is triggered by a "set" command.
107 -- The "sample" is a node containing a nested list if delimiter groups.
108 -- Push a new item on the stack and scan the sample.
109 local function set_auto( sample )
110 local tab = { opn = setmetatable( {}, meta_delims ), cls = setmetatable( {}, meta_delims ) }
111 table.insert( delimiters, tab )
112 scan_sample( sample, tab )
113 end
114
115 -- This function is triggered by a "res" command.
116 -- Remove the topmost item from the stack.
117 local function res_auto()
118 table.remove( delimiters )
119 end
120
121 -- Adapt a fake delimiter group to the given data.
122 -- "head" is the node containing the "\math___{}" object.
123 -- "level" is the nesting level to be used if this is an auto delimiter.
124 -- "ht" and "dp" are the height and depth of the content of the group.
125 -- Returns the level if this was an auto delimiter
126 -- or a fixed one equal to the auto delimiter of some level.
127 local function set_delim( head, level, ht, dp )
128 local type, delim, hbox = head.subtype == 6 and 'opn' or head.subtype == 7 and 'cls'
129 while is_noad( head ) do
130 node.unset_attribute( head, attr_info ) head = head.nucleus
131 node.unset_attribute( head, attr_info ) head = head.head
132 end
133 for pos in node.traverse( head ) do
134 node.unset_attribute( pos, attr_info )
135 if is_fence( pos ) == 3 then delim = pos.delim end
136 if is_noad( pos ) == 0 then hbox = pos.nucleus.head end
137 end
138 if not ( delim and hbox ) then return end
139 local auto = delim_eq( delim, delim_auto )
140 local brks = delimiters[#delimiters]
141 if brks then brks = brks[type] end
142 if type and auto and brks then
143 delim_set( delim, brks[level] )
144 else
145 level = nil
146 end
147 local scale = node.get_attribute( hbox, attr_info )
148 hbox.height, hbox.depth = ht * scale // 1000, dp * scale // 1000
149 if delim_eq( delim, delim_null ) then
150 hbox.width = -2 * tex.dimen.nulldelimiterspace
151 else
152 hbox.width = -tex.dimen.nulldelimiterspace
153 end
154 return level
155 end
156
157 -- This creates a deep copy of the node list from start to stop (inclusive).
158 -- Ignores whatsits and the content of nodes that have fixed dimension.
159 -- Ignores limits of large operators if flagged and "disp" is true.
160 -- Ignores nodes that have the info attribute set. These are unprocessed delimiters.
161 -- Tries to keep track of the current math style.
162 local function copy_list( start, stop, disp )
163 local old, new, copy, last = start
164 while old do
165 if is_style( old ) then disp = old.style:match( 'display' ) end
166 local ign = is_noad( old ) and node.has_attribute( old, attr_info ) or is_whatsit( old )
167 if not ign then
168 new = node.new( old.id, old.subtype )
169 for field, deep in fields( old, disp ) do
170 if deep then
171 local disp = disp and ( field == 'nucleus' or field == 'head' or field == 'display' )
172 new[field] = copy_list( old[field], nil, disp )
173 else
174 new[field] = old[field]
175 end
176 end
177 if not copy then last, copy = new, new
178 else last, copy = new, node.insert_after( copy, last, new ) end
179 end
180 if old == stop then break end
181 old = node.next( old )
182 end
183 return copy
184 end
185
186 -- Creates a math style node.
187 local function style_node( style )
188 local nd = node.new( "style" )
189 nd.style = style
190 return nd
191 end
192
193 -- Copies the node list from "start" to "stop" and packs it into a temporary hbox.
194 -- Returns the height and depth of that box when typeset in "style".
195 local function dimensions( start, stop, style )
196 local disp = style == 'display' or style == 0 or style == 1
197 local copy = copy_list( start, stop, disp )
198 if not copy then return 0, 0 end
199 if style then copy = node.insert_before( copy, copy, style_node( style ) ) end
200 local box = node.mlist_to_hlist( copy, 'text', false )
201 if not box then return 0, 0 end
202 local wd, ht, dp = node.dimensions( box )
203 node.flush_list( box )
204 return ht, dp
205 end
206
207 -- Table containing information read from the aux file.
208 local oldgroups = {}
209 -- Table containing information to be written to the aux file.
210 local newgroups = {}
211 -- Table containing tables of tags that are synonyms for the same group.
212 local equals = {}
213
214 -- Merge information of a group with the inforation from the aux file
215 -- and store the new information to be written to the aux file.
216 -- A group table contains the following information:
217 -- "tags": table of tags attached to the group (as keys with value "true").
218 -- "ht", "dp": dimensions
219 -- "lv": the maximal level of automatic delimiters used for subgroups.
220 local function max( a, b ) return a and b and math.max( a, b ) or a or b end
221 local function merge( group )
222 local tags = group.tags
223 if not tags or not next( tags ) then return end
224 if next( tags, ( next( tags ) ) ) then table.insert( equals, tags ) end
225 for tag in pairs( tags ) do
226 local ngrp = newgroups[tag] or {}
227 newgroups[tag] = ngrp
228 ngrp.ht = max( ngrp.ht, group.ht )
229 ngrp.dp = max( ngrp.dp, group.dp )
230 ngrp.lv = max( ngrp.lv, group.lv )
231 end
232 for tag in pairs( tags ) do
233 local ogrp = oldgroups[tag]
234 if ogrp then
235 group.ht = max( group.ht, ogrp.ht )
236 group.dp = max( group.dp, ogrp.dp )
237 group.lv = max( group.lv, ogrp.lv )
238 end
239 end
240 end
241
242
243 -- Parses a math list and process all delimiters.
244 -- "pargrp" is the parent group.
245 -- "head" is the head of the math list.
246 -- "open" is the opening delimiter if this is a recursive call.
247 -- "pos" is the position where to start the scan.
248 -- "style" is the current math style, if known.
249 -- This will otherwise be set when th first command is detected.
250 -- "group" is the group table for this group.
251 -- Returns a modified head, and sets information in the parent group.
252 -- "delims" collects all delimiters belonging to this group.
253 -- When a longmath special is detected, it is removed and the next node is processed:
254 -- set/res: set or reset auto delimiters.
255 -- opn: an opening delimiter follows. The function is called recursively.
256 -- cls: a closing delimiter follows. The current group ends
257 -- mid: an inner delimiter follows.
258 -- For every other node in the list, its subnodes are parsed recursively.
259 local function parse( pargrp, head, open, pos, style, group )
260 if not head then return end
261 local delims, subgrp = { open }
262 group = group or {}
263 pos = pos or head
264 while pos do
265 local comm, data, info = get_comm( pos )
266 if comm then head, pos = node.remove( head, pos )
267 if comm == 'set' then set_auto( pos ) return head end
268 if comm == 'res' then res_auto() return head end
269 style = style or info
270 group.tags = group.tags or {}
271 if comm == 'opn' then
272 local subgrp = { tags = {} }
273 if data then subgrp.tags[data] = true end
274 head, pos = parse( group, head, pos, node.next( pos ), info, subgrp )
275 elseif comm == 'mid' then
276 if data then group.tags[data] = true end
277 table.insert( delims, pos )
278 pos = node.next( pos )
279 elseif comm == 'cls' then
280 if data then group.tags[data] = true end
281 table.insert( delims, pos )
282 break
283 end
284 else
285 for field, deep in fields( pos ) do if deep then
286 pos[field] = parse( group, pos[field] )
287 end end
288 pos = node.next( pos )
289 end
290 end
291 -- if this is an actual delimiter group, measure its demensions.
292 if group.tags then group.ht, group.dp = dimensions( open or head, pos, style ) end
293 -- merge information with aux file
294 merge( group )
295 -- finally set the delimiters and parse any scripts attached to them.
296 local level, auto = group.lv or 0
297 for _, del in ipairs( delims ) do
298 auto = set_delim( del, level+1, group.ht, group.dp ) or auto
299 del.sub = parse( group, del.sub )
300 del.sup = parse( group, del.sup )
301 end
302 if pos and not open then
303 -- this group started without an opening delimiter.
304 -- we use a tail call and proceed as if there was one and this function was called from a parent.
305 pargrp = { lv = auto or group.lv, tags = {} }
306 if group.tags then for tag in pairs( group.tags ) do pargrp.tags[tag..parent] = true end end
307 return parse( {}, head, nil, node.next( pos ), style, pargrp )
308 else
309 -- inform the parent about the auto delimiter level and any tags used in subgroups.
310 pargrp.lv = max( pargrp.lv, auto or group.lv )
311 if pargrp.tags and group.tags then for tag in pairs( group.tags ) do pargrp.tags[tag..parent] = true end end
312 return head, pos
313 end
314 end
315
316 -- Callback that scans a math list.
317 local function scan( head, style, pen )
318 head = parse( {}, head, nil, nil, style )
319 return node.mlist_to_hlist( head, style, true )
320 end
321 luatexbase.add_to_callback( 'mlist_to_hlist', scan, 'longmath parse' )
322
323 -- Creates a glue node.
324 local function glue_node( wd )
325 local nd = node.new( "glue", 8 )
326 nd.width = wd
327 return nd
328 end
329
330 -- Applies a stepwise shift to the hlists in a vlist if "extra" is non-zero.
331 local function shift( head )
332 local extra = tex.dimen['longmath@extra']
333 if extra == 0 then return true end
334 local lines = {}
335 for nd in node.traverse( head ) do
336 if is_hlist( nd ) == 1 then table.insert( lines, nd ) end
337 end
338 local n = #lines - 1
339 if n > 0 then
340 for i, nd in ipairs( lines ) do
341 nd.width = nd.width + extra
342 nd.head = node.insert_before( nd.head, nd.head, glue_node( (i-1) * extra / n ) )
343 nd.head = node.insert_after( nd.head, node.tail( nd.head ), glue_node( (n-i+1) * extra / n ) )
344 end
345 end
346 return true
347 end
348 luatexbase.add_to_callback( 'post_linebreak_filter', shift, 'longmath shift' )
349
350 -- Table for functions to be called from TeX.
351 longmath = {}
352
353 -- Read data for a collection of identical groups.
354 function longmath.read_group( tags, tab )
355 for _, tag in ipairs( tags ) do oldgroups[tag] = tab end
356 end
357
358 -- Check if a tag is not already in a set.
359 -- If a subgroup or parent is in the set, inserts it into a the "loops" table.
360 local loops = {}
361 local loop_patt = '[' .. parent .. ']*$'
362 local function is_new( tag, set )
363 if set[tag] then return false end
364 tag = tag:gsub( loop_patt, '' )
365 for tagg in pairs( set ) do if tag == tagg:gsub( loop_patt, '' ) then
366 loops[ tag:gsub( '@$', '' ) ] = true
367 return false
368 end end
369 return true
370 end
371
372 -- Given a set of tags attached to the same group,
373 -- add all other tags attached to the same group to the set.
374 local function find_eq( set )
375 local new = {}
376 for tag in pairs( set ) do
377 local app = ''
378 while true do
379 for _, w in ipairs( equals ) do if w[tag] then for tagg in pairs( w ) do
380 if is_new( tagg..app, set ) then new[tagg..app] = true end
381 end end end
382 if tag:sub(-1) ~= parent then break end
383 tag, app = tag:sub(1,-2), app .. parent
384 end
385 end
386 if not next( new ) then return set end
387 for tag in pairs( new ) do set[tag] = true end
388 return find_eq( set )
389 end
390
391 local loop_mess = '\\PackageWarningNoLine{longmath}{Cyclic delimiter group%s %s detected}'
392 local data_mess = '\\PackageWarningNoLine{longmath}{Delimiters may have changed. Rerun to get them right}'
393
394 -- Save all groups to the aux file.
395 -- Tags that belong to the same group are collected into a single entry.
396 function longmath.save_groups( aux )
397 local check, done = true, {}
398 for tag, grp in pairs( newgroups ) do if not done[tag] then
399 local tags, vals, eqs = {}, {}, find_eq( { [tag] = true } )
400 for tagg in pairs( eqs ) do
401 check, done[tagg] = check and oldgroups[tagg], true
402 table.insert( tags, string.format( '%q', tagg ) )
403 while tagg do
404 if newgroups[tagg] then
405 grp.ht, grp.dp = max( grp.ht, newgroups[tagg].ht ), max( grp.dp, newgroups[tagg].dp )
406 grp.lv = max( grp.lv, newgroups[tagg].lv )
407 end
408 tagg = tagg:match( '^(.*)[' .. parent .. ']$' )
409 end
410 end
411 for k, v in pairs( grp ) do
412 table.insert( vals, string.format( '%s=%d', k, v ) )
413 for tagg in pairs( eqs ) do check = check and v == oldgroups[tagg][k] end
414 end
415 tags, vals = table.concat( tags, ',' ), table.concat( vals, ',' )
416 texio.write( aux, string.format( '\\longmath@group{%s}{%s}\n', tags, vals ) )
417 end end
418 local lps = {}
419 for l in pairs( loops ) do
420 if #lps > 5 then table.insert( lps, '...' ) break end
421 table.insert( lps, l )
422 end
423 if #lps > 0 then
424 tex.print( string.format( loop_mess, #lps > 1 and 's' or '', table.concat( lps, ', ' ) ) )
425 end
426 if not check then tex.print( data_mess ) end
427 end
428
429 return