Debian Codegraph @

texmf-dist/tex/luatex/lua-widow-control/lua-widow-control.lua

raw
1 --[[
2 lua-widow-control
3 https://github.com/gucci-on-fleek/lua-widow-control
4 SPDX-License-Identifier: MPL-2.0+
5 SPDX-FileCopyrightText: 2022 Max Chernoff
6 ]]
7
8 --- Tell the linter about node attributes
9 --- @class node
10 --- @field depth integer
11 --- @field height integer
12 --- @field id integer
13 --- @field list node
14 --- @field next node
15 --- @field penalty integer
16 --- @field prev node
17 --- @field subtype integer
18
19 -- Initial setup
20 lwc = lwc or {}
21 lwc.name = "lua-widow-control"
22
23 -- Locals for `debug_print`
24 local string_rep = string.rep
25 local write_nl = texio.write_nl
26
27 local write_log
28 if status.luatex_engine == "luametatex" then
29 write_log = "logfile"
30 else
31 write_log = "log"
32 end
33
34 --- Prints debugging messages to the log, only if `debug` is set to `true`.
35 ---
36 --- @param title string The "title" to use
37 --- @param text string? The "content" to print
38 --- @return nil
39 local function debug(title, text)
40 if not lwc.debug then return end
41
42 -- The number of spaces we need
43 local filler = 15 - #title
44
45 if text then
46 write_nl(
47 write_log,
48 "LWC (" ..
49 title ..
50 string_rep(" ", filler) ..
51 "): " ..
52 text
53 )
54 else
55 write_nl(write_log, "LWC: " .. string_rep(" ", 18) .. title)
56 end
57 end
58
59
60 --[[
61 \lwc/ is intended to be format-agonistic. It only runs on Lua\TeX{} and
62 LuaMeta\TeX{}, but there are still some slight differences between formats.
63 Here, we detect the format name then set some flags for later processing.
64 ]]
65 local format = tex.formatname
66 local context, latex, plain, optex, lmtx
67
68 if status.luatex_engine == "luametatex" then
69 lmtx = true
70 end
71
72 if format:find("cont") then -- cont-en, cont-fr, cont-nl, ...
73 context = true
74 elseif format:find("latex") then -- lualatex, lualatex-dev, ...
75 latex = true
76 elseif format == "luatex" or
77 format == "luahbtex" or
78 format:find("plain")
79 then -- Plain
80 plain = true
81 elseif format:find("optex") then -- OpTeX
82 optex = _G.optex
83 end
84
85 --[[
86 Save some local copies of the node library to reduce table lookups.
87 This is probably a useless micro-optimization, but it is done in all of the
88 ConTeXt and expl3 Lua code, so I should probably do it here too.
89 ]]
90 -- Node ID's
91 -- (We need to hardcode the subid's sadly)
92 local id_from_name = node.id
93 local baselineskip_subid = 2
94 local glue_id = id_from_name("glue")
95 local glyph_id = id_from_name("glyph")
96 local hlist_id = id_from_name("hlist")
97 local insert_id = id_from_name("insert") or id_from_name("ins")
98 local line_subid = 1
99 local linebreakpenalty_subid = 1
100 local par_id = id_from_name("par") or id_from_name("local_par")
101 local penalty_id = id_from_name("penalty")
102 local parfill_subids = {
103 parfillleftskip = 17,
104 parfillrightskip = 16,
105 parinitleftskip = 19,
106 parinitrightskip = 18,
107 }
108 local vlist_id = id_from_name("vlist")
109
110 -- Local versions of globals
111 local abs = math.abs
112 local copy = node.copy
113 local copy_list = node.copy_list or node.copylist
114 local effective_glue = node.effective_glue or node.effectiveglue
115 local find_attribute = node.find_attribute or node.findattribute
116 local free = node.free
117 local free_list = node.flush_list or node.flushlist
118 local get_attribute = node.get_attribute or node.getattribute
119 local hpack = node.hpack
120 local insert_token = token.put_next or token.putnext
121 local is_node = node.is_node or node.isnode
122 local last = node.slide
123 local linebreak = tex.linebreak
124 local new_node = node.new
125 local remove = node.remove
126 local set_attribute = node.set_attribute or node.setattribute
127 local str_byte = string.byte
128 local str_char = string.char
129 local str_format = string.format
130 local subtype = node.subtype
131 local tex_box = tex.box
132 local tex_count = tex.count
133 local tex_dimen = tex.dimen
134 local tex_lists = tex.lists
135 local traverse = node.traverse
136 local traverse_id = node.traverse_id or node.traverseid
137 local vpack = node.vpack
138
139 -- Misc. Constants
140 local iffalse = token.create("iffalse")
141 local iftrue = token.create("iftrue")
142 local INFINITY = 10000
143 local INSERT_CLASS_MULTIPLE = 1000 * 1000
144 local INSERT_FIRST_MULTIPLE = 1000
145 local PAGE_MULTIPLE = 100
146 local SINGLE_LINE = 50
147
148 lwc.colours = {
149 expanded = {0.00, 0.70, 0.25},
150 failure = {0.90, 0.00, 0.25},
151 moved = {0.25, 0.25, 1.00},
152 cost = {0.50, 0.50, 0.50},
153 }
154
155
156 --[[ Package/module initialization.
157
158 Here, we replace any format/engine-specific variables/functions with some
159 generic equivalents. This way, we can write the rest of the module without
160 worrying about any format/engine differences.
161 ]]
162 local contrib_head,
163 draft_offset,
164 emergencystretch,
165 hold_head,
166 info,
167 insert_attribute,
168 max_cost,
169 page_head,
170 paragraph_attribute,
171 set_whatsit_field,
172 shrink_order,
173 stretch_order,
174 warning
175
176 if lmtx then
177 -- LMTX has removed underscores from most of the Lua parts
178 debug("LMTX")
179 contrib_head = "contributehead"
180 shrink_order = "shrinkorder"
181 stretch_order = "stretchorder"
182 hold_head = "holdhead"
183 page_head = "pagehead"
184 set_whatsit_field = node.setwhatsitfield
185 else
186 contrib_head = "contrib_head"
187 shrink_order = "shrink_order"
188 stretch_order = "stretch_order"
189 hold_head = "hold_head"
190 page_head = "page_head"
191 set_whatsit_field = node.setfield
192 end
193
194 if context then
195 debug("ConTeXt")
196
197 warning = logs.reporter(lwc.name, "warning")
198 local _info = logs.reporter(lwc.name, "info")
199 --[[ We don't want the info messages on the terminal, but ConTeXt doesn't
200 provide any logfile-only reporters, so we need this hack.
201 ]]
202 info = function (text)
203 logs.pushtarget("logfile")
204 _info(text)
205 logs.poptarget()
206 end
207 paragraph_attribute = attributes.public(lwc.name .. "_paragraph")
208 insert_attribute = attributes.public(lwc.name .. "_insert")
209
210 -- Dimen/count names
211 emergencystretch = "lwc_emergency_stretch"
212 draft_offset = "lwc_draft_offset"
213 max_cost = "lwc_max_cost"
214 elseif plain or latex or optex then
215 -- Dimen names
216 if tex.isdimen("g__lwc_emergencystretch_dim") then
217 emergencystretch = "g__lwc_emergencystretch_dim"
218 draft_offset = "g__lwc_draftoffset_dim"
219 max_cost = "g__lwc_maxcost_int"
220 else
221 emergencystretch = "lwcemergencystretch"
222 draft_offset = "lwcdraftoffset"
223 max_cost = "lwcmaxcost"
224 end
225
226 if plain or latex then
227 debug("Plain/LaTeX")
228 luatexbase.provides_module {
229 name = lwc.name,
230 date = "2024/03/11", --%%slashdate
231 version = "3.0.1", --%%version
232 description = [[
233
234 This module provides a LuaTeX-based solution to prevent
235 widows and orphans from appearing in a document. It does
236 so by increasing or decreasing the lengths of previous
237 paragraphs.]],
238 }
239 warning = function(str) luatexbase.module_warning(lwc.name, str) end
240 info = function(str) luatexbase.module_info(lwc.name, str) end
241 paragraph_attribute = luatexbase.new_attribute(lwc.name .. "_paragraph")
242 insert_attribute = luatexbase.new_attribute(lwc.name .. "_insert")
243 elseif optex then
244 debug("OpTeX")
245
246 warning = function(str) write_nl(lwc.name .. " Warning: " .. str) end
247 info = function(str) write_nl("log", lwc.name .. " Info: " .. str) end
248 paragraph_attribute = alloc.new_attribute(lwc.name .. "_paragraph")
249 insert_attribute = alloc.new_attribute(lwc.name .. "_insert")
250 end
251 else -- This shouldn't ever happen
252 error [[Unsupported format.
253
254 Please use LaTeX, Plain TeX, ConTeXt or OpTeX.]]
255 end
256
257 -- We can't get the value of \\horigin from Lua, but we can guess it
258 -- based on the format.
259 local horigin
260 if optex or (lmtx and context) then
261 horigin = 0
262 else
263 horigin = tex.sp("1in")
264 end
265
266 -- Plain is the only format without a `pre_shipout_filter`
267 if plain then
268 luatexbase.create_callback('pre_shipout_filter', 'list')
269 end
270
271
272 --[[ Select the fonts
273
274 We want to use cmr6 for the draft mode cost displays, and the easiest
275 way to do so is to just hardcode the font id's. This relies on some
276 implementation details; however, it is very unlikely to ever be an issue.
277 ]]
278 local SMALL_FONT
279 if plain then
280 SMALL_FONT = 5
281 elseif latex then
282 SMALL_FONT = 6
283 elseif optex then
284 SMALL_FONT = 8
285 elseif context then
286 SMALL_FONT = fonts.definers.define({
287 name = "LMRoman6-Regular",
288 size = tex.sp("6pt"),
289 })
290 end
291
292 -- Global variables
293 local paragraphs = {} -- The expanded paragraphs on each page
294 local inserts = {} -- Copies of all the inserts on each page
295 local costs = {} -- All of the paragraph costs for the document
296 local pagenum = 1 -- The current page/column number
297
298 --[[ Function definitions
299 ]]
300
301 --- Gets the current paragraph and page locations
302 --- @return string
303 local function get_location()
304 return "At " .. pagenum .. "/" .. #paragraphs
305 end
306
307
308 --- Prints the starting glyphs and glue of an `hlist`.
309 ---
310 --- Useful for debugging purposes.
311 ---
312 --- @param head node
313 --- @return nil
314 local function get_chars(head)
315 if not lwc.debug then return end
316
317 local chars = ""
318 for n in traverse(head) do
319 if n.id == glyph_id then
320 if n.char < 127 then -- Only ASCII
321 chars = chars .. str_char(n.char)
322 else
323 chars = chars .. "#" -- Replacement for an unknown glyph
324 end
325 elseif n.id == glue_id then
326 chars = chars .. " " -- Any glue goes to a space
327 end
328 if #chars > 25 then
329 break
330 end
331 end
332
333 debug(get_location(), chars)
334 end
335
336
337 --- The "cost function" to use. Users can redefine this if they wish.
338 ---
339 --- @param demerits number The demerits of the broken paragraph
340 --- @param lines number The number of lines in the broken paragraph
341 --- @param nat_demerits number The demerits of the naturally-broken paragraph
342 --- @param nat_lines number The number of lines in the naturally-broken paragraph
343 --- @param head node The head of the broken paragraph
344 --- @return number cost The cost of the broken paragraph
345 function lwc.paragraph_cost(demerits, lines, nat_demerits, nat_lines, head)
346 return demerits / math.sqrt(lines)
347 end
348
349
350 --- Checks if the ConTeXt "grid snapping" is active
351 ---
352 --- @return boolean
353 local function grid_mode_enabled()
354 -- Compare the token "mode" to see if `\\ifgridsnapping` is `\\iftrue`
355 return token.create("ifgridsnapping").mode == iftrue.mode
356 end
357
358
359 --- Gets the next node of a specified type/subtype in a node list
360 ---
361 --- @param head node The head of the node list
362 --- @param id number The node type
363 --- @param args table?
364 --- subtype: number = The node subtype
365 --- reverse: bool = Whether we should iterate backwards
366 --- @return node?
367 local function next_of_type(head, id, args)
368 args = args or {}
369
370 if lmtx or not args.reverse then
371 for n, subtype in traverse_id(id, head, args.reverse) do
372 if (subtype == args.subtype) or (args.subtype == nil) then
373 return n
374 end
375 end
376 else
377 -- Only LMTX has the built-in backwards traverser, so we need to do
378 -- it manually otherwise.
379 while head do
380 if head.id == id and
381 (head.subtype == args.subtype or args.subtype == nil)
382 then
383 return head
384 end
385 head = head.prev
386 end
387 end
388
389 -- Needed for the special `tex.lists` nodes
390 if head and head.id == id and
391 (head.subtype == args.subtype or args.subtype == nil)
392 then
393 return head
394 end
395 end
396
397
398 --- Ensures that a paragraph is ready to be broken
399 ---
400 --- Only applies to LuaMetaTeX
401 ---
402 --- @param head node
403 --- @return nil
404 local function prepare_linebreak(head)
405 if not lmtx then
406 return
407 end
408
409 -- See how many of the par[left/right][init/fill]skips we have
410 local parfills = {}
411 local count = 0
412 for name, subid in pairs(parfill_subids) do
413 parfills[name] = next_of_type(head, glue_id, { subtype = subid })
414 if parfills[name] then
415 count = count + 1
416 end
417 end
418
419 if count == 0 then
420 -- Usual case
421 tex.preparelinebreak(head)
422 elseif count == 4 then
423 -- Already prepared for some reason, ignored
424 else
425 -- Uh oh
426 warning("Weird par(fill/init)skips found!")
427 tex.preparelinebreak(head) -- Try to fix it
428 end
429 end
430
431
432 --- Breaks a paragraph one line longer than natural
433 ---
434 --- @param head node The unbroken paragraph
435 --- @param parfillskip table<number> The {width, stretch, shrink,
436 --- stretch_order, shrink_order} to set
437 --- for the \\parfillskip
438 --- @return node long_node The broken paragraph
439 --- @return table long_info An info table about the broken paragraph
440 local function long_paragraph(head, parfillskip)
441 -- We can't modify the original paragraph
442 head = copy_list(head)
443
444 prepare_linebreak(head)
445
446 -- TODO node.setglue is broken in LMTX, so we have to do this manually
447 local n = last(head)
448 n.width = parfillskip[1]
449 n.stretch = parfillskip[2]
450 n.shrink = parfillskip[3]
451 n[stretch_order] = parfillskip[4]
452 n[shrink_order] = parfillskip[5]
453
454 -- Break the paragraph 1 line longer than natural
455 local long_node, long_info = linebreak(head, {
456 looseness = 1,
457 emergencystretch = tex_dimen[emergencystretch],
458 })
459
460 -- Mark the last line for the costs display
461 set_attribute(
462 last(long_node),
463 paragraph_attribute,
464 -1 * (#paragraphs + 1 + (PAGE_MULTIPLE * pagenum))
465 )
466
467 return long_node, long_info
468 end
469
470
471 --- Breaks a paragraph at its natural length
472 ---
473 --- @param head node The unbroken paragraph
474 --- @return table natural_info An info table about the broken paragraph
475 local function natural_paragraph(head)
476 -- We can't modify the original paragraph
477 head = copy_list(head)
478
479 prepare_linebreak(head)
480
481 -- Break the paragraph naturally to get \\prevgraf
482 local natural_node, natural_info = linebreak(head)
483 free_list(natural_node)
484
485 return natural_info
486 end
487
488
489 local show_colours = false
490 --- Changes the text colour in a node list if draft mode is active
491 ---
492 --- @param head node The first node to colour
493 --- @param colour string The name of a colour in `lwc.colours`
494 --- @return node head The coloured node
495 local function colour_list(head, colour)
496 if not show_colours then
497 return head
498 end
499
500 local pdf_colour = str_format(
501 "%.2f %.2f %.2f rg",
502 table.unpack(lwc.colours[colour])
503 )
504
505 if optex and optex.set_node_color then
506 for n in node.traverse(head) do
507 optex.set_node_color(n, pdf_colour)
508 end
509
510 return head
511 end
512
513 if context then
514 nodes.tracers.colors.setlist(head, "lwc_" .. colour)
515 return head
516 end
517
518 -- Adapted from https://tex.stackexchange.com/a/372437 and
519 -- https://github.com/zauguin/luametalatex/issues/8.
520 local start_colour = new_node("whatsit", subtype("pdf_colorstack"))
521 set_whatsit_field(start_colour, "stack", 0)
522 set_whatsit_field(start_colour, "command", 1)
523 set_whatsit_field(start_colour, "data", pdf_colour)
524
525 local end_colour = new_node("whatsit", subtype("pdf_colorstack"))
526 set_whatsit_field(end_colour, "stack", 0)
527 set_whatsit_field(end_colour, "command", 2)
528
529 start_colour.next = head
530 last(head).next = end_colour
531
532 return start_colour
533 end
534
535
536 --- Saves each paragraph, but lengthened by 1 line
537 ---
538 --- Called by the `pre_linebreak_filter` callback
539 ---
540 --- @param head node The pre-broken paragraph
541 --- @return node head The unmodified `head` argument
542 function lwc.save_paragraphs(head)
543 if (head.id ~= par_id and context) or -- Make sure that `head` is a paragraph
544 status.output_active or -- Don't run during the output routine
545 tex.nest.ptr > 1 -- Don't run inside boxes
546 then
547 return head
548 end
549
550 -- Prevent the "underfull hbox" warnings when we store a potential paragraph
551 local renable_box_warnings
552 if (context or optex) or
553 #luatexbase.callback_descriptions("hpack_quality") == 0
554 then -- See #18 and michal-h21/linebreaker#3
555 renable_box_warnings = true
556 lwc.callbacks.disable_box_warnings.enable()
557 end
558
559 natural_info = natural_paragraph(head)
560
561 -- Prevent ultra-short last lines (\TeX{}book p. 104). Equivalent to
562 -- \\parfillskip=0.75\\hsize plus 0.05\\hsize minus 0.75\\hsize.
563 -- From http://petr.olsak.net/ftp/olsak/tbn/tbn.pdf p. 234 (via Jan Sustek)
564 long_node, long_info = long_paragraph(
565 head,
566 {0.75 * tex.hsize, 0.05 * tex.hsize, 0.75 * tex.hsize, 0, 0}
567 )
568
569 if long_info.prevgraf ~= natural_info.prevgraf + 1 then
570 -- The \\parfillskip settings with \\looseness=1 can sometimes
571 -- lengthen paragraphs by two lines instead of one. If this happens,
572 -- we fall back to a slightly-worse \\parfillskip setting.
573 free_list(long_node)
574 long_node, long_info = long_paragraph(
575 head,
576 {0, 0.8 * tex.hsize, false, 0, false}
577 )
578 end
579
580 if renable_box_warnings then
581 lwc.callbacks.disable_box_warnings.disable()
582 end
583
584 if not grid_mode_enabled() then
585 -- Offset the \\prevdepth differences between natural and long
586 local prevdepth = new_node("glue")
587 prevdepth.width = natural_info.prevdepth - long_info.prevdepth
588 last(long_node).next = prevdepth
589 end
590
591 local long_cost = lwc.paragraph_cost(
592 long_info.demerits,
593 long_info.prevgraf,
594 natural_info.demerits,
595 natural_info.prevgraf,
596 long_node
597 )
598
599 if long_info.prevgraf ~= natural_info.prevgraf + 1 or
600 long_cost < 10 -- Any paragraph that is "free" to expand is suspicious
601 then
602 -- This paragraph is infinitely bad
603 long_cost = math.maxinteger
604 end
605
606 -- The initial glue can disappear in ConTeXt's grid mode, so we
607 -- save starting at the first hlsit
608 local saved_node = next_of_type(long_node, hlist_id, { subtype = line_subid })
609
610 for n in traverse_id(hlist_id, saved_node) do
611 n.list = colour_list(n.list, "expanded")
612 end
613
614 table.insert(paragraphs, {
615 cost = long_cost,
616 node = copy_list(saved_node)
617 })
618
619 free_list(long_node)
620
621 costs[#paragraphs + (PAGE_MULTIPLE * pagenum)] = long_cost
622
623 -- Print some debugging information
624 if lwc.debug then
625 get_chars(head)
626 debug(get_location(), "nat lines " .. natural_info.prevgraf)
627 debug(
628 get_location(),
629 "nat cost " ..
630 lwc.paragraph_cost(natural_info.demerits, natural_info.prevgraf)
631 )
632 debug(get_location(), "long lines " .. long_info.prevgraf)
633 debug(
634 get_location(),
635 "long cost " ..
636 lwc.paragraph_cost(long_info.demerits, long_info.prevgraf)
637 )
638 end
639
640 -- \ConTeXt{} crashes if we return `true`
641 return head
642 end
643
644
645 --- Tags the beginning and the end of each paragraph as it is added to the page.
646 ---
647 --- We add an attribute to the first and last node of each paragraph. The ID is
648 --- some arbitrary number for \lwc/, and the value corresponds to the
649 --- paragraphs index, which is negated for the end of the paragraph.
650 ---
651 --- @param head node
652 --- @return nil
653 local function mark_paragraphs(head)
654 -- Tag the paragraphs
655 if status.output_active then
656 -- Don't run during the output routine
657 return
658 end
659
660 -- Get the start and end of the paragraph
661 local top = next_of_type(head, hlist_id, { subtype = line_subid })
662 local bottom = last(head)
663
664 -- The inserts disappear before `pre_output_routine`, so we shouldn't
665 -- mark them.
666 while bottom.id == insert_id do
667 bottom = bottom.prev
668 end
669
670 if top ~= bottom then
671 set_attribute(
672 top,
673 paragraph_attribute,
674 #paragraphs + (PAGE_MULTIPLE * pagenum)
675 )
676 set_attribute(
677 bottom,
678 paragraph_attribute,
679 -1 * (#paragraphs + (PAGE_MULTIPLE * pagenum))
680 )
681 else
682 -- We need a special tag for a 1-line paragraph since the node can only
683 -- have a single attribute value
684 set_attribute(
685 top,
686 paragraph_attribute,
687 #paragraphs + (PAGE_MULTIPLE * pagenum) + SINGLE_LINE
688 )
689 end
690 end
691
692
693 --- Tags the each line with the indices of any corresponding inserts.
694 ---
695 --- We need to tag the first element of the hlist before the any insert nodes
696 --- since the insert nodes are removed before `pre_output_filter` gets called.
697 ---
698 --- @param head node
699 --- @return nil
700 local function mark_inserts(head)
701 local insert_indices = {}
702 for insert in traverse_id(insert_id, head) do
703 -- Save the found insert nodes for later
704 inserts[#inserts+1] = copy(insert)
705
706 -- Tag the insert's content so that we can find it later
707 set_attribute(insert.list, insert_attribute, #inserts)
708
709 -- We need to tag all lines---not just the start and the end---since
710 -- \TeX{} can split the insert between pages at any point.
711 for n in traverse(insert.list.next) do
712 set_attribute(n, insert_attribute, -1 * #inserts)
713 end
714
715 -- Each hlist/line can have multiple inserts, but so we can't just tag
716 -- the hlist as we go. Instead, we need save up all of their indices,
717 -- then tag the hlist with the first and last indices.
718 insert_indices[#insert_indices+1] = #inserts
719
720 if not insert.next or
721 insert.next.id ~= insert_id
722 then
723 local hlist_before = next_of_type(insert, hlist_id, { reverse = true} )
724
725 local insert_class
726 if lmtx then
727 insert_class = insert.index
728 else
729 insert_class = insert.subtype
730 end
731
732 -- We tag the first element of the hlist/line with an integer
733 -- that holds the insert class and the first and last indices
734 -- of the inserts contained in the line. This won't work if
735 -- the line has multiple classes of inserts, but I don't think
736 -- that happens in real-world documents. If this does turn out
737 -- to be an issue, we can get the insert's class from it's copy
738 -- at `pre_output_filter` instead of saving it now.
739 set_attribute(
740 hlist_before.list,
741 insert_attribute,
742 insert_class * INSERT_CLASS_MULTIPLE +
743 insert_indices[1] * INSERT_FIRST_MULTIPLE +
744 insert_indices[#insert_indices]
745 )
746
747 -- Clear the indices to prepare for the next line
748 insert_indices = {}
749 end
750 end
751 end
752
753
754 --- Saves the inserts and tags a typeset paragraph. Called by the
755 --- `post_linebreak_filter` callback.
756 ---
757 --- @param head node The head of the broken paragraph
758 --- @return node head The unmodified `head` parameter
759 function lwc.mark_paragraphs(head)
760 mark_paragraphs(head)
761 mark_inserts(head)
762
763 return head
764 end
765
766
767 --- Checks to see if a penalty matches the widow/orphan/broken penalties
768 ---
769 --- @param penalty number
770 --- @return boolean
771 local function is_matching_penalty(penalty)
772 local widowpenalty = tex.widowpenalty
773 local clubpenalty = tex.clubpenalty
774 local displaywidowpenalty = tex.displaywidowpenalty
775 local brokenpenalty = tex.brokenpenalty
776
777 penalty = penalty - tex.interlinepenalty
778
779 -- Adapted from https://tug.org/TUGboat/tb39-3/tb123mitt-widows-code.pdf.
780 -- This only takes into account the original \TeX{} penalties, not the
781 -- "new" \eTeX{} \\(club/widow/broken)penalties commands.
782 return penalty ~= 0 and
783 penalty < INFINITY and (
784 penalty == widowpenalty or
785 penalty == displaywidowpenalty or
786 penalty == clubpenalty or
787 penalty == clubpenalty + widowpenalty or
788 penalty == clubpenalty + displaywidowpenalty or
789 penalty == brokenpenalty or
790 penalty == brokenpenalty + widowpenalty or
791 penalty == brokenpenalty + displaywidowpenalty or
792 penalty == brokenpenalty + clubpenalty or
793 penalty == brokenpenalty + clubpenalty + widowpenalty or
794 penalty == brokenpenalty + clubpenalty + displaywidowpenalty
795 )
796 end
797
798
799 --- Determines if we should "activate" \lwc/ for the current page/column.
800 ---
801 --- Users can redefine this if they wish.
802 ---
803 --- @param penalty number The \\outputpenalty for the current page/column
804 --- @param paragraphs table<table<string, node|number>> The `paragraphs` table
805 --- @param head node The head of the current page/column
806 --- @return boolean activate True if \lwc/ should move the last line on this page
807 function lwc.should_remove_widows(penalty, paragraphs, head)
808 return is_matching_penalty(penalty)
809 end
810
811 --- Reset any state saved between pages
812 ---
813 --- This function is *vital* to ensure that we don't leak any nodes.
814 --- If we do leak nodes, then very large documents will slow down and
815 --- eventually fail to compile.
816 ---
817 --- @return nil
818 local function reset_state()
819 for _, paragraph in ipairs(paragraphs) do
820 free_list(paragraph.node)
821 end
822 paragraphs = {}
823
824 for _, insert in ipairs(inserts) do
825 free(insert)
826 end
827 inserts = {}
828
829 pagenum = pagenum + 1
830 end
831
832
833 --- When we are unable to remove a widow/orphan, print a warning
834 ---
835 --- @return nil
836 local function remove_widows_fail()
837 warning("Widow/Orphan/Broken Hyphen NOT removed on page " .. pagenum)
838
839 local last_line = next_of_type(
840 last(tex_lists[page_head]),
841 hlist_id,
842 { subtype = line_subid, reverse = true }
843 )
844 if last_line then
845 last_line.list = colour_list(last_line.list, "failure")
846 end
847
848 local next_first_line = next_of_type(
849 tex_lists[contrib_head],
850 hlist_id,
851 { subtype = line_subid }
852 )
853 if next_first_line then
854 next_first_line.list = colour_list(next_first_line.list, "failure")
855 end
856
857 reset_state()
858 end
859
860
861 --- Finds the first and last paragraphs present on a page
862 ---
863 --- @param head node The node representing the start of the page
864 --- @return number first_index The index of the first paragraph on the page in
865 --- the `paragraphs` table
866 --- @return number last_index The index of the last paragraph on the page in the
867 --- `paragraphs` table
868 local function first_last_paragraphs(head)
869 local first_index, last_index
870
871 -- Find the last paragraph on the page, starting at the end, heading in reverse
872 local n = last(head)
873 while n do
874 local value = get_attribute(n, paragraph_attribute)
875 if value then
876 last_index = value % PAGE_MULTIPLE
877 break
878 end
879
880 n = n.prev
881 end
882
883 -- Find the first paragraph on the page, from the top
884 local first_val, first_head = find_attribute(head, paragraph_attribute)
885 while abs(first_val) // PAGE_MULTIPLE == pagenum - 1 do
886 -- If the first complete paragraph on the page was initially broken on the
887 -- previous page, then we can't expand it here. Why can't we expand it?
888 -- Well, expanding it will nearly always change how the first few lines
889 -- are printed, but we can't modify those since they've already been
890 -- shipped out. So, we need to skip these paragraphs.
891 first_val, first_head = find_attribute(
892 first_head.next,
893 paragraph_attribute
894 )
895 end
896
897 first_index = first_val % PAGE_MULTIPLE
898
899 if first_index >= SINGLE_LINE then
900 first_index = first_index - SINGLE_LINE
901 end
902
903 debug("first/last", first_index .. "/" .. last_index)
904
905 return first_index, last_index
906 end
907
908
909 --- Selects the "best" paragraph on the page to expand
910 ---
911 --- @param head node The node representing the start of the page
912 --- @return number? best_index The index of the paragraph to expand in the
913 --- `paragraphs` table
914 local function best_paragraph(head)
915 local first_paragraph_index, last_paragraph_index = first_last_paragraphs(head)
916
917 -- Find the paragraph on the page with the least cost.
918 local best_index = 1
919 local best_cost = paragraphs[best_index].cost
920
921 -- We find the current "best" replacement
922 for index, paragraph in pairs(paragraphs) do
923 if paragraph.cost < best_cost and
924 index < last_paragraph_index and
925 index >= first_paragraph_index
926 then
927 best_index, best_cost = index, paragraph.cost
928 end
929 end
930
931 debug(
932 "selected para",
933 pagenum .. "/" .. best_index .. " (" .. best_cost .. ")"
934 )
935
936 if best_cost > tex_count[max_cost] or
937 best_index == last_paragraph_index or -- Shouldn't happen
938 best_cost == math.maxinteger
939 then
940 return nil
941 else
942 return best_index
943 end
944 end
945
946
947 --- Gets any inserts present in the moved line
948 ---
949 --- @param last_line node The moved last line
950 --- @return table<node> inserts A list of the present inserts
951 local function get_inserts(last_line)
952 local selected_inserts = {}
953
954 local n = last_line.list
955 while n do -- Iterate through the last line
956 local line_value
957 line_value, n = find_attribute(n, insert_attribute)
958
959 if not n then
960 break
961 end
962
963 -- Demux the insert values
964 local class = line_value // INSERT_CLASS_MULTIPLE
965 local first_index = (line_value % INSERT_CLASS_MULTIPLE)
966 // INSERT_FIRST_MULTIPLE
967 local last_index = line_value % INSERT_FIRST_MULTIPLE
968
969 -- Get the output box containing the insert boxes
970 local insert_box
971
972 if lmtx then
973 insert_box = tex.getinsertcontent(class)
974 -- `getinsertcontent` resets the insert box, so we need to
975 -- re-set it.
976 tex.setinsertcontent(class, insert_box)
977 else
978 insert_box = tex_box[class]
979 end
980
981 -- Get any portions of the insert "held over" until the next page
982 local split_insert
983 if lmtx then
984 split_insert = next_of_type(
985 tex_lists[hold_head],
986 insert_id,
987 { index = class }
988 )
989 else
990 split_insert = next_of_type(
991 tex_lists[hold_head],
992 insert_id,
993 { subtype = class }
994 )
995 end
996
997 -- We use the same procedure for this page and the next page
998 for i, insert in ipairs { insert_box, split_insert } do
999 local m = insert and insert.list
1000
1001 while m do -- Iterate through the insert box
1002 local box_value
1003 box_value, m = find_attribute(m, insert_attribute)
1004 local next = m.next
1005
1006 if not m then
1007 break
1008 end
1009
1010 if abs(box_value) >= first_index and
1011 abs(box_value) <= last_index
1012 then
1013 -- Remove the respective contents from the insert box
1014 insert.list = remove(insert.list, m)
1015
1016 if box_value > 0 and i == 1 then
1017 table.insert(selected_inserts, copy(inserts[box_value]))
1018 end
1019
1020 free(m)
1021 end
1022
1023 m = next
1024 end
1025 end
1026
1027 -- If the box has no contents, then void it so that any \\ifvoid
1028 -- tests work correctly in the output routine.
1029 if not insert_box.list then
1030 tex_box[class] = nil
1031 end
1032
1033 if split_insert and not split_insert.list then
1034 remove(tex_lists[hold_head], split_insert)
1035 end
1036
1037 n = n.next
1038 end
1039
1040 if #selected_inserts ~= 0 then
1041 -- This is a somewhat-risky process, so we print an info
1042 -- message just in case something goes wrong. We can probably
1043 -- remove this in the future if we're sure that everything
1044 -- is working correctly.
1045 info("Moving footnotes on page " .. pagenum)
1046 end
1047
1048 return selected_inserts
1049 end
1050
1051
1052 lwc.nobreak_behaviour = "keep"
1053 --- Moves the last line of the page onto the following page.
1054 ---
1055 --- This is the most complicated function of the module since it needs to
1056 --- look back to see if there is a heading preceding the last line, then it does
1057 --- some low-level node shuffling.
1058 ---
1059 --- @param head node The node representing the start of the page
1060 --- @return boolean success Set to false if something went wrong
1061 local function move_last_line(head)
1062 -- Start of final paragraph
1063 debug("remove_widows", "moving last line")
1064
1065 -- Here we check to see if the widow/orphan was preceded by a large penalty
1066 local big_penalty_found, last_line, hlist_head
1067 local n = last(head).prev
1068 while n do
1069 if n.id == glue_id then
1070 -- Ignore any glue nodes
1071 elseif n.id == penalty_id and n.penalty >= INFINITY then
1072 -- Infinite break penalty
1073 big_penalty_found = true
1074 elseif big_penalty_found and n.id == hlist_id then
1075 -- Line before the penalty
1076 if lwc.nobreak_behaviour == "keep" then
1077 hlist_head = n
1078 big_penalty_found = false
1079 elseif lwc.nobreak_behaviour == "split" then
1080 n = last(head)
1081 break
1082 elseif lwc.nobreak_behaviour == "warn" then
1083 debug("last line", "heading found")
1084 return false
1085 end
1086 else
1087 -- Not found
1088 if hlist_head then
1089 n = hlist_head
1090 else
1091 n = last(head)
1092 end
1093 break
1094 end
1095 n = n.prev
1096 end
1097
1098 local potential_penalty = n.prev.prev
1099
1100 if potential_penalty and
1101 potential_penalty.id == penalty_id and
1102 potential_penalty.subtype == linebreakpenalty_subid and
1103 is_matching_penalty(potential_penalty.penalty)
1104 then
1105 warning("Making a new widow/orphan/broken hyphen on page " .. pagenum)
1106
1107 local second_last_line = next_of_type(
1108 potential_penalty,
1109 hlist_id,
1110 { subtype = line_subid, reverse = true }
1111 )
1112 second_last_line.list = colour_list(second_last_line.list, "failure")
1113 end
1114
1115 last_line = copy_list(n)
1116
1117 last_line.list = colour_list(last_line.list, "moved")
1118
1119 -- Reinsert any inserts originally present in this moved line
1120 local selected_inserts = get_inserts(last_line)
1121 for _, insert in ipairs(selected_inserts) do
1122 last(last_line).next = insert
1123 end
1124
1125 -- Add back in the content from the next page
1126 last(last_line).next = copy_list(tex_lists[contrib_head])
1127
1128 free_list(n.prev.prev.next)
1129 n.prev.prev.next = nil
1130
1131 -- Set the content of the next page
1132 free_list(tex_lists[contrib_head])
1133 tex_lists[contrib_head] = last_line
1134
1135 return true
1136 end
1137
1138
1139 --- Replace the chosen paragraph with its expanded version.
1140 ---
1141 --- This is the "core function" of the module since it is what ultimately causes
1142 --- the expansion to occur.
1143 ---
1144 --- @param head node
1145 --- @param paragraph_index number
1146 local function replace_paragraph(head, paragraph_index)
1147 -- Remove any inserts. They are completely ignored after
1148 -- the page has been broken, but they can upset LuaMetaLaTeX if
1149 -- they're found somewhere unexpected.
1150 local target_node, last_target_node
1151 for n in traverse(paragraphs[paragraph_index].node) do
1152 -- Just removing the inserts from the list doesn't work properly,
1153 -- so we instead copy over everything that isn't an insert.
1154 if n.id ~= insert_id then
1155 if not target_node then
1156 target_node = copy(n)
1157 last_target_node = target_node
1158 else
1159 last_target_node.next = copy(n)
1160 last_target_node = last_target_node.next
1161 end
1162 end
1163 end
1164
1165 local start_found = false
1166 local end_found = false
1167 local free_nodes_begin
1168
1169 -- Loop through all of the nodes on the page with the \lwc/ attribute
1170 local n = head
1171 while n do
1172 local value
1173 value, n = find_attribute(n, paragraph_attribute)
1174
1175 if not n then
1176 break
1177 end
1178
1179 debug("remove_widows", "found " .. value)
1180
1181 -- Insert the start of the replacement paragraph
1182 if value == paragraph_index + (PAGE_MULTIPLE * pagenum) or
1183 value == paragraph_index + (PAGE_MULTIPLE * pagenum) + SINGLE_LINE
1184 then
1185 debug("remove_widows", "replacement start")
1186 start_found = true
1187
1188 -- Fix the `\\baselineskip` glue between paragraphs
1189 height_difference = (
1190 next_of_type(n, hlist_id, { subtype = line_subid }).height -
1191 next_of_type(
1192 target_node, hlist_id, { subtype = line_subid }
1193 ).height
1194 )
1195
1196 local prev_bls = next_of_type(
1197 n,
1198 glue_id,
1199 { subtype = baselineskip_subid, reverse = true }
1200 )
1201
1202 if prev_bls then
1203 prev_bls.width = prev_bls.width + height_difference
1204 end
1205
1206 n.prev.next = target_node
1207 free_nodes_begin = n
1208 end
1209
1210 -- Insert the end of the replacement paragraph
1211 if value == -(paragraph_index + (PAGE_MULTIPLE * pagenum)) or
1212 value == paragraph_index + (PAGE_MULTIPLE * pagenum) + SINGLE_LINE
1213 then
1214 debug("remove_widows", "replacement end")
1215 end_found = true
1216
1217 local target_node_last = last(target_node)
1218
1219 if grid_mode_enabled() then
1220 -- Account for the difference in depth
1221 local after_glue = new_node("glue")
1222 after_glue.width = n.depth - target_node_last.depth
1223 target_node_last.next = after_glue
1224
1225 after_glue.next = n.next
1226 else
1227 target_node_last.next = n.next
1228 end
1229
1230 n.next = nil
1231
1232 break
1233 end
1234
1235 n = n.next
1236 end
1237
1238 if start_found and end_found then
1239 free_list(free_nodes_begin)
1240 else
1241 warning("Paragraph NOT expanded on page " .. pagenum)
1242 end
1243 end
1244
1245
1246 --- Remove the widows and orphans from the page, just after the output routine.
1247 ---
1248 --- This is called just after the end of the output routine, before the page is
1249 --- shipped out. If the output penalty indicates that the page was broken at a
1250 --- widow or an orphan, we replace one paragraph with the same paragraph, but
1251 --- lengthened by one line. Then, we can push the bottom line of the page to the
1252 --- next page.
1253 ---
1254 --- @param head node
1255 --- @return node
1256 function lwc.remove_widows(head)
1257 debug("outputpenalty", tex.outputpenalty .. " " .. #paragraphs)
1258
1259 -- See if there is a widow/orphan for us to remove
1260 if not lwc.should_remove_widows(tex.outputpenalty, paragraphs, head) then
1261 reset_state()
1262 return head
1263 end
1264
1265 info("Widow/orphan/broken hyphen detected. Attempting to remove")
1266
1267 -- Nothing that we can do if there aren't any paragraphs available to expand
1268 if #paragraphs == 0 then
1269 debug("failure", "no paragraphs to expand")
1270 remove_widows_fail()
1271 return head
1272 end
1273
1274 -- Check the original height of \\box255
1275 local vsize = tex_dimen.vsize
1276 local orig_vpack = vpack(head)
1277 local orig_height_diff = orig_vpack.height - vsize
1278 orig_vpack.list = nil
1279 free(orig_vpack)
1280
1281 -- Find the paragraph to expand
1282 local paragraph_index = best_paragraph(head)
1283
1284 if not paragraph_index then
1285 debug("failure", "no good paragraph")
1286 remove_widows_fail()
1287 return head
1288 end
1289
1290 -- Move the last line of the page to the next page
1291 if not move_last_line(head) then
1292 debug("failure", "can't move last line")
1293 remove_widows_fail()
1294 return head
1295 end
1296
1297 -- Replace the chosen paragraph with its expanded version
1298 replace_paragraph(head, paragraph_index)
1299
1300 -- The final \\box255 needs to be exactly \\vsize tall to avoid
1301 -- over/underfull box warnings, so we correct any discrepancies
1302 -- here.
1303 local new_vpack = vpack(head)
1304 local new_height_diff = new_vpack.height - vsize
1305 new_vpack.list = nil
1306 free(new_vpack)
1307 -- We need the original height discrepancy in case there are \\vfill's
1308 local net_height_diff = orig_height_diff - new_height_diff
1309 local bls = tex.skip.baselineskip
1310 local bls_width = bls.width
1311 free(bls)
1312
1313 if abs(net_height_diff) > 0 and
1314 -- A difference larger than 0.25\\baselineskip is probably not from
1315 -- \lwc/, so we let those warnings surface
1316 abs(net_height_diff) < bls_width / 4
1317 then
1318 local bottom_glue = new_node("glue")
1319 bottom_glue.width = net_height_diff
1320 last(head).next = bottom_glue
1321 end
1322
1323 info(
1324 "Widow/orphan/broken hyphen successfully removed at paragraph "
1325 .. paragraph_index
1326 .. " on page "
1327 .. pagenum
1328 )
1329
1330 reset_state()
1331
1332 return head
1333 end
1334
1335
1336 local show_costs = false
1337 --- Add the paragraph to the list of paragraphs on the page.
1338 ---
1339 --- Called immediately before the page is shipped out so that we can get
1340 --- the costs on the correct side in multi-column layouts.
1341 ---
1342 --- To evenly align all of the costs in the margins, we need to know the
1343 --- the exact position of the start and end of the paragraph on the page.
1344 --- This is surprisingly complicated.
1345 ---
1346 --- @param head node The box to be shipped out
1347 --- @return true
1348 function lwc.show_costs (head)
1349 if not show_costs then
1350 return true
1351 end
1352
1353 local pagewidth = tex.pagewidth or layouts.getpagedimensions()
1354
1355 --- Loop over each sublist, add up the total width, and show the costs.
1356 ---
1357 --- @param n node The node to loop over
1358 --- @param width number The accumulated width so far
1359 --- @param parent node The parent node of the current list
1360 --- @return nil
1361 local function recurse(n, width, parent)
1362 for m in traverse(n) do
1363 -- Anything with an \\hbox parent and a width is actual width.
1364 -- (If it had a \\vbox parent, then n.width would actually be height.)
1365 local self_width = 0
1366 if m.id == glue_id and parent.id == hlist_id then
1367 self_width = effective_glue(m, parent)
1368 elseif m.width and parent.id == hlist_id then
1369 self_width = m.width
1370 end
1371
1372 -- A node's "shift" attribute is horizontal only if the parent is
1373 -- a \\vbox. This corresponds to the primatives \\moveleft and
1374 -- \\moveright. (If the parent is a \\hbox, then n.shift is
1375 -- vertical and corresponds to \\raise.)
1376 local shift = 0
1377 if m.shift and
1378 (parent.id == vlist_id or
1379 not is_node(parent))
1380 then
1381 shift = m.shift
1382 end
1383
1384 width = width + self_width
1385
1386 local attr = get_attribute(m, paragraph_attribute)
1387 if attr and abs(attr) % PAGE_MULTIPLE >= SINGLE_LINE then
1388 attr = -1 * (abs(attr) - SINGLE_LINE)
1389 end
1390
1391 local cost = costs[abs(attr or 0)]
1392
1393 if attr and attr < 0 and cost and m.list then
1394 -- We've found the end of a marked paragraph!
1395
1396 -- Generate the \\hbox containing the formatted cost
1397 local cost_str
1398 if not cost then
1399 return
1400 elseif cost < math.maxinteger then
1401 cost_str = str_format("%.0f", cost)
1402 else
1403 cost_str = "infinite"
1404 end
1405
1406 local prev, first
1407 for letter in cost_str:gmatch(".") do
1408 local curr = new_node("glyph")
1409 curr.font = SMALL_FONT
1410 curr.char = str_byte(letter)
1411
1412 if not first then
1413 first = curr
1414 else
1415 prev.next = curr
1416 end
1417 prev = curr
1418 end
1419
1420 local text = hpack(colour_list(first, "cost"))
1421
1422 -- Make an \\hss to make sure that our `\\hbox`es aren't overfull
1423 local hss = new_node("glue")
1424 hss.stretch = 1
1425 hss[stretch_order] = 1
1426 hss.shrink = 1
1427 hss[shrink_order] = 1
1428
1429 local hbox
1430 local offset = new_node("glue")
1431
1432 if (width >= pagewidth / 2) or
1433 (m.width >= 0.4 * pagewidth)
1434 then -- Right column or single-column
1435 -- Costs in the right margin
1436 offset.width = (
1437 pagewidth -
1438 width -
1439 m.width -
1440 shift -
1441 tex_dimen[draft_offset]
1442 )
1443 text.next = hss
1444 hbox = hpack(text, 0, "exactly")
1445 else -- Left column
1446 -- Costs in the left margin
1447 offset.width = (
1448 tex_dimen[draft_offset] -
1449 m.width -
1450 width -
1451 shift
1452 )
1453 hss.next = text
1454 hbox = hpack(hss, 0, "exactly")
1455 end
1456
1457 last(m.list).next = offset
1458 offset.next = hbox
1459 elseif m.list then
1460 recurse(m.list, width - self_width + shift, m)
1461 end
1462 end
1463 end
1464
1465 -- Start at the root of the page
1466 recurse(head.list, (tex.hoffset or 0) + horigin, {})
1467
1468 -- LaTeX requires us to always return true here
1469 return true
1470 end
1471
1472
1473 --- Create a table of functions to enable or disable a given callback
1474 ---
1475 --- @param t table Parameters of the callback to create
1476 --- callback: string = The \LuaTeX{} callback name
1477 --- func: function = The function to call
1478 --- name: string = The name/ID of the callback
1479 --- category: string = The category for a \ConTeXt{} "Action"
1480 --- position: string = The "position" for a \ConTeXt{} "Action"
1481 --- lowlevel: boolean = If we should use a lowlevel \LuaTeX{} callback
1482 --- instead of a \ConTeXt{} "Action"
1483 --- @return table t Enablers/Disablers for the callback
1484 --- enable: function = Enable the callback
1485 --- disable: function = Disable the callback
1486 local function register_callback(t)
1487 if plain or latex then -- Both use \LuaTeX{}Base for callbacks
1488 return {
1489 enable = function()
1490 luatexbase.add_to_callback(t.callback, t.func, t.name)
1491 end,
1492 disable = function()
1493 luatexbase.remove_from_callback(t.callback, t.name)
1494 end,
1495 }
1496 elseif context and not t.lowlevel then
1497 return {
1498 -- Register the callback when the table is created,
1499 -- but activate it when `enable()` is called.
1500 enable = nodes.tasks.appendaction(t.category, t.position, "lwc." .. t.name)
1501 or function()
1502 nodes.tasks.enableaction(t.category, "lwc." .. t.name)
1503 end,
1504 disable = function()
1505 nodes.tasks.disableaction(t.category, "lwc." .. t.name)
1506 end,
1507 }
1508 elseif context and t.lowlevel then
1509 -- Some of the callbacks in \ConTeXt{} have no associated "actions".
1510 -- Unlike with \LuaTeX{}base, \ConTeXt{} leaves some \LuaTeX{} callbacks
1511 -- unregistered and unfrozen. Because of this, we need to register some
1512 -- callbacks at the engine level. This is fragile though, because a
1513 -- future \ConTeXt{} update may decide to register one of these
1514 -- functions, in which case \lwc/ will crash with a cryptic error
1515 -- message.
1516 return {
1517 enable = function() callback.register(t.callback, t.func) end,
1518 disable = function() callback.register(t.callback, nil) end,
1519 }
1520 elseif optex then -- Op\TeX{} is luckily very similar to luatexbase
1521 return {
1522 enable = function()
1523 callback.add_to_callback(t.callback, t.func, t.name)
1524 end,
1525 disable = function()
1526 callback.remove_from_callback(t.callback, t.name)
1527 end,
1528 }
1529 end
1530 end
1531
1532
1533 -- Add all of the callbacks
1534 lwc.callbacks = {
1535 disable_box_warnings = register_callback({
1536 callback = "hpack_quality",
1537 func = function() end,
1538 name = "disable_box_warnings",
1539 lowlevel = true,
1540 }),
1541 remove_widows = register_callback({
1542 callback = "pre_output_filter",
1543 func = lwc.remove_widows,
1544 name = "remove_widows",
1545 lowlevel = true,
1546 }),
1547 save_paragraphs = register_callback({
1548 callback = "pre_linebreak_filter",
1549 func = lwc.save_paragraphs,
1550 name = "save_paragraphs",
1551 category = "processors",
1552 position = "after",
1553 }),
1554 mark_paragraphs = register_callback({
1555 callback = "post_linebreak_filter",
1556 func = lwc.mark_paragraphs,
1557 name = "mark_paragraphs",
1558 category = "finalizers",
1559 position = "after",
1560 }),
1561 show_costs = register_callback({
1562 callback = "pre_shipout_filter",
1563 func = lwc.show_costs,
1564 name = "show_costs",
1565 category = "shipouts",
1566 position = "finishers",
1567 }),
1568 }
1569
1570
1571 local lwc_enabled = false
1572 --- Enables the paragraph callbacks
1573 function lwc.enable_callbacks()
1574 debug("callbacks", "enabling")
1575 if not lwc_enabled then
1576 lwc.callbacks.save_paragraphs.enable()
1577 lwc.callbacks.mark_paragraphs.enable()
1578
1579 lwc_enabled = true
1580 else
1581 info("Already enabled")
1582 end
1583 end
1584
1585
1586 --- Disables the paragraph callbacks
1587 function lwc.disable_callbacks()
1588 debug("callbacks", "disabling")
1589 if lwc_enabled then
1590 lwc.callbacks.save_paragraphs.disable()
1591 lwc.callbacks.mark_paragraphs.disable()
1592
1593 -- We do *not* disable `remove_widows` callback, since we still want
1594 -- to expand any of the previously-saved paragraphs if we hit an orphan
1595 -- or a widow.
1596 lwc_enabled = false
1597 else
1598 info("Already disabled")
1599 end
1600 end
1601
1602 function lwc.if_lwc_enabled()
1603 debug("iflwc")
1604 if lwc_enabled then
1605 insert_token(iftrue)
1606 else
1607 insert_token(iffalse)
1608 end
1609 end
1610
1611
1612 --- Mangles a macro name so that it's suitable for a specific format
1613 ---
1614 --- @param name string The plain name
1615 --- @param args table<string> The TeX types of the function arguments
1616 --- @return string name The mangled name
1617 local function mangle_name(name, args)
1618 if plain then
1619 return "lwc@" .. name:gsub("_", "@")
1620 elseif optex then
1621 return "_lwc_" .. name
1622 elseif context then
1623 return "lwc_" .. name
1624 elseif latex then
1625 return "__lwc_" .. name .. ":" .. string_rep("n", #args)
1626 end
1627 end
1628
1629
1630 --- Creates a TeX command that evaluates a Lua function
1631 ---
1632 --- @param name string The name of the csname to define
1633 --- @param func function
1634 --- @param args table<string> The TeX types of the function arguments
1635 --- @return nil
1636 local function register_tex_cmd(name, func, args)
1637 local scanning_func
1638 name = mangle_name(name, args)
1639
1640 if not context then
1641 local scanners = {}
1642 for _, arg in ipairs(args) do
1643 scanners[#scanners+1] = token['scan_' .. arg]
1644 end
1645
1646 -- An intermediate function that properly "scans" for its arguments
1647 -- in the \TeX{} side.
1648 scanning_func = function()
1649 local values = {}
1650 for _, scanner in ipairs(scanners) do
1651 values[#values+1] = scanner()
1652 end
1653
1654 func(table.unpack(values))
1655 end
1656 end
1657
1658 if optex then
1659 define_lua_command(name, scanning_func)
1660 return
1661 elseif plain or latex then
1662 local index = luatexbase.new_luafunction(name)
1663 lua.get_functions_table()[index] = scanning_func
1664 token.set_lua(name, index)
1665 elseif context then
1666 interfaces.implement {
1667 name = name,
1668 public = true,
1669 arguments = args,
1670 actions = func
1671 }
1672 end
1673 end
1674
1675 --[[ Make all of the \lwc/ Lua commands available from \TeX{}
1676 ]]
1677 register_tex_cmd("if_enabled", lwc.if_lwc_enabled, {})
1678 register_tex_cmd("enable", lwc.enable_callbacks, {})
1679 register_tex_cmd("disable", lwc.disable_callbacks, {})
1680 register_tex_cmd(
1681 "nobreak",
1682 function(str)
1683 lwc.nobreak_behaviour = str
1684 end,
1685 { "string" }
1686 )
1687 register_tex_cmd(
1688 "debug",
1689 function(str)
1690 lwc.debug = str ~= "0" and str ~= "false" and str ~= "stop"
1691 end,
1692 { "string" }
1693 )
1694 register_tex_cmd(
1695 "show_costs",
1696 function(str)
1697 show_costs = str ~= "0" and str ~= "false" and str ~= "stop"
1698 end,
1699 { "string" }
1700 )
1701 register_tex_cmd(
1702 "show_colours",
1703 function(str)
1704 show_colours = str ~= "0" and str ~= "false" and str ~= "stop"
1705 end,
1706 { "string" }
1707 )
1708 register_tex_cmd(
1709 "pre_shipout",
1710 function(box)
1711 luatexbase.call_callback('pre_shipout_filter', tex_box[box])
1712 end,
1713 { "int" }
1714 )
1715
1716 --- Silence the luatexbase "Enabling/Removing <callback>" info messages
1717 ---
1718 --- Every time that a paragraph is typeset, \lwc/ hooks in
1719 --- and typesets the paragraph 1 line longer. Some of these longer paragraphs
1720 --- will have pretty bad badness values, so TeX will issue an over/underfull
1721 --- hbox warning. To block these warnings, we hook into the `hpack_quality`
1722 --- callback and disable it so that no warning is generated.
1723 ---
1724 --- However, each time that we enable/disable the null `hpack_quality` callback,
1725 --- luatexbase puts an info message in the log. This completely fills the log
1726 --- file with useless error messages, so we disable it here.
1727 ---
1728 --- This uses the Lua `debug` library to internally modify the log upvalue in
1729 --- the `add_to_callback` function. This is almost certainly a terrible idea,
1730 --- but I don't know of a better way to do it.
1731 ---
1732 --- @return nil
1733 local function silence_luatexbase()
1734 local debug_lib = require("debug")
1735
1736 -- On TL24, the `debug` library no longer exists, so there's nothing that
1737 -- we can do here.
1738 if not debug_lib or
1739 not debug_lib.getinfo or
1740 not debug_lib.getupvalue or
1741 not debug_lib.setupvalue then
1742 return
1743 end
1744
1745 local nups = debug_lib.getinfo(luatexbase.add_to_callback).nups
1746
1747 for i = 1, nups do
1748 local name, func = debug_lib.getupvalue(luatexbase.add_to_callback, i)
1749 if name == "luatexbase_log" then
1750 debug_lib.setupvalue(
1751 luatexbase.add_to_callback,
1752 i,
1753 function(text)
1754 if text:match("^Inserting") or text:match("^Removing") then
1755 return
1756 else
1757 func(text)
1758 end
1759 end
1760 )
1761 return
1762 end
1763 end
1764 end
1765
1766
1767 -- Call `silence_luatexbase` in Plain and LaTeX, unless the undocmented global
1768 -- `LWC_NO_DEBUG` is set. We provide this opt-out in case something goes awry
1769 -- with the `debug` library calls.
1770 if (plain or latex) and
1771 not LWC_NO_DEBUG --- @diagnostic disable-line
1772 then
1773 silence_luatexbase()
1774 end
1775
1776 -- Register colours for ConTeXt
1777 if context then
1778 for colour, values in pairs(lwc.colours) do
1779 attributes.colors.defineprocesscolor(
1780 "lwc_" .. colour,
1781 str_format("r=%.2f, g=%.2f, b=%.2f", table.unpack(values))
1782 )
1783 end
1784 end
1785
1786 -- Activate \lwc/
1787 lwc.callbacks.remove_widows.enable()
1788 lwc.callbacks.show_costs.enable()
1789
1790 return lwc
1791