Debian Codegraph @

texmf-dist/tex/optex/base/optex.lua

raw
1 -- This is part of the OpTeX project, see http://petr.olsak.net/optex
2
3 -- Basic Lua functions and declarations used in \OpTeX/ are defined here
4 --
5 -- Local imports of standard Lua or \LuaTeX/ functions and constants are the first thing we do.
6 -- They mostly serve one of several purposes:
7 --
8 -- \begitems
9 -- * shorthands for commonly used functions,
10 -- * speed of access for commonly executed functions,
11 -- * common constants to be used consistently,
12 -- * use of local definition that can't be externally overwritten.
13 -- \enditems
14
15 local fmt = string.format
16
17 local node_id = node.id
18 local node_subtype = node.subtype
19 local flush_node = node.flush_node
20 local flush_list = node.flush_list
21 local node_traverse = node.traverse
22 local glyph_id = node_id("glyph")
23 local rule_id = node_id("rule")
24 local glue_id = node_id("glue")
25 local hlist_id = node_id("hlist")
26 local vlist_id = node_id("vlist")
27 local disc_id = node_id("disc")
28 local kern_id = node_id("kern")
29 local whatsit_id = node_id("whatsit")
30 local pdfliteral_id = node_subtype("pdf_literal")
31 local pdfsave_id = node_subtype("pdf_save")
32 local pdfrestore_id = node_subtype("pdf_restore")
33 local token_getmacro = token.get_macro
34
35 local direct = node.direct
36 local todirect = direct.todirect
37 local tonode = direct.tonode
38 local getfield = direct.getfield
39 local setfield = direct.setfield
40 local getwhd = direct.getwhd
41 local getid = direct.getid
42 local getlist = direct.getlist
43 local setlist = direct.setlist
44 local getleader = direct.getleader
45 local getattribute = direct.get_attribute
46 local setattribute = direct.set_attribute
47 local insertbefore = direct.insert_before
48 local copy = direct.copy
49 local traverse = direct.traverse
50 local one_bp = tex.sp("1bp")
51
52 local tex_print = tex.print
53 local tex_setbox = tex.setbox
54 local tex_getcount = tex.getcount
55 local tex_setcount = tex.setcount
56 local token_scanint = token.scan_int
57 local token_scanlist = token.scan_list
58 local token_setmacro = token.set_macro
59 --
60 -- \medskip\secc General^^M
61 --
62 -- Define namespace where \"public" \OpTeX/ functions will be added.
63
64 local optex = _ENV.optex or {}
65 _ENV.optex = optex
66
67 -- Error function used by following functions for critical errors.
68 local function err(...)
69 local message = fmt(...)
70 error("\nerror: "..message.."\n")
71 end
72 --
73 -- For a `\chardef`'d, `\countdef`'d, etc., csname return corresponding register
74 -- number. The responsibility of providing a `\XXdef`'d name is on the caller.
75 local function registernumber(name)
76 return token.create(name).index
77 end
78 _ENV.registernumber = registernumber
79 optex.registernumber = registernumber
80 --
81 -- MD5 hash of given file.
82 function optex.mdfive(file)
83 local fh = io.open(file, "rb")
84 if fh then
85 local data = fh:read("*a")
86 fh:close()
87 tex_print(md5.sumhexa(data))
88 end
89 end
90
91 -- The \`optex.raw_ht``()` function measures the height plus depth of given
92 -- `\vbox` saved by `\setbox`. It solves the \"dimension too large" problem with big boxes.
93 -- It is used in the \^`\_rawht` macro.
94
95 function optex.raw_ht()
96 local nod = tex.box[token_scanint()] -- read head node of the given box
97 local ht = 0
98 if nod and nod.id == vlist_id then
99 for n in node_traverse(nod.head) do
100 if n.id == hlist_id or n.id == vlist_id or n.id == rule_id then
101 ht = ht + n.height + n.depth
102 elseif n.id == glue_id then
103 ht = ht + n.width
104 elseif n.id == kern_id then
105 ht = ht + n.kern
106 end
107 end
108 end
109 tex_print(fmt('%.0f', ht/65536))
110 end
111
112 --
113 -- \medskip\secc[lua-alloc] Allocators^^M
114 local alloc = _ENV.alloc or {}
115 _ENV.alloc = alloc
116 --
117 -- An attribute allocator in Lua that cooperates with normal \OpTeX/ allocator.
118 local attributes = {}
119 function alloc.new_attribute(name)
120 local cnt = tex.count["_attributealloc"] + 1
121 if cnt > 65534 then
122 tex.error("No room for a new attribute")
123 else
124 tex.setcount("global", "_attributealloc", cnt)
125 texio.write_nl("log", '"'..name..'"=\\attribute'..tostring(cnt))
126 attributes[name] = cnt
127 return cnt
128 end
129 end
130 --
131 -- Allocator for Lua functions ("pseudoprimitives"). It passes variadic
132 -- arguments (\"`...`") like `"global"` to `token.set_lua`.
133 local function_table = lua.get_functions_table()
134 local function define_lua_command(csname, fn, ...)
135 local luafnalloc = #function_table + 1
136 token.set_lua(csname, luafnalloc, ...) -- WARNING: needs LuaTeX 1.08 (2019) or newer
137 function_table[luafnalloc] = fn
138 end
139 _ENV.define_lua_command = define_lua_command
140 optex.define_lua_command = define_lua_command
141 --
142 -- \medskip\secc[callbacks] Callbacks^^M
143 local callback = _ENV.callback or {}
144 _ENV.callback = callback
145 --
146 -- Save \`callback.register` function for internal use.
147 local callback_register = callback.register
148 function callback.register(name, fn)
149 err("direct registering of callbacks is forbidden, use 'callback.add_to_callback'")
150 end
151 --
152 -- Table with lists of functions for different callbacks.
153 local callback_functions = {}
154 -- Table that maps callback name to a list of descriptions of its added
155 -- functions. The order corresponds with \`callback_functions`.
156 local callback_description = {}
157 --
158 -- Table used to differentiate user callbacks from standard callbacks. Contains
159 -- user callbacks as keys.
160 local user_callbacks = {}
161 -- Table containing default functions for callbacks, which are called if either
162 -- a user created callback is defined, but doesn't have added functions or for
163 -- standard callbacks that are \"extended" (see `mlist_to_hlist` and its pre/post
164 -- filters below).
165 local default_functions = {}
166 --
167 -- Table that maps standard (and later user) callback names to their types.
168 local callback_types = {
169 -- file discovery
170 find_read_file = "exclusive",
171 find_write_file = "exclusive",
172 find_font_file = "data",
173 find_output_file = "data",
174 find_format_file = "data",
175 find_vf_file = "data",
176 find_map_file = "data",
177 find_enc_file = "data",
178 find_pk_file = "data",
179 find_data_file = "data",
180 find_opentype_file = "data",
181 find_truetype_file = "data",
182 find_type1_file = "data",
183 find_image_file = "data",
184
185 open_read_file = "exclusive",
186 read_font_file = "exclusive",
187 read_vf_file = "exclusive",
188 read_map_file = "exclusive",
189 read_enc_file = "exclusive",
190 read_pk_file = "exclusive",
191 read_data_file = "exclusive",
192 read_truetype_file = "exclusive",
193 read_type1_file = "exclusive",
194 read_opentype_file = "exclusive",
195
196 -- data processing
197 process_input_buffer = "data",
198 process_output_buffer = "data",
199 process_jobname = "data",
200 input_level_string = "data",
201
202 -- node list processing
203 contribute_filter = "simple",
204 buildpage_filter = "simple",
205 build_page_insert = "exclusive",
206 pre_linebreak_filter = "list",
207 linebreak_filter = "exclusive",
208 append_to_vlist_filter = "exclusive",
209 post_linebreak_filter = "reverselist",
210 hpack_filter = "list",
211 vpack_filter = "list",
212 hpack_quality = "list",
213 vpack_quality = "list",
214 process_rule = "exclusive",
215 pre_output_filter = "list",
216 hyphenate = "simple",
217 ligaturing = "simple",
218 kerning = "simple",
219 insert_local_par = "simple",
220 mlist_to_hlist = "exclusive",
221
222 -- information reporting
223 pre_dump = "simple",
224 start_run = "simple",
225 stop_run = "simple",
226 start_page_number = "simple",
227 stop_page_number = "simple",
228 show_error_hook = "simple",
229 show_error_message = "simple",
230 show_lua_error_hook = "simple",
231 start_file = "simple",
232 stop_file = "simple",
233 call_edit = "simple",
234 finish_synctex = "simple",
235 wrapup_run = "simple",
236
237 -- pdf related
238 finish_pdffile = "data",
239 finish_pdfpage = "data",
240 page_order_index = "data",
241 process_pdf_image_content = "data",
242
243 -- font related
244 define_font = "exclusive",
245 glyph_not_found = "exclusive",
246 glyph_info = "exclusive",
247
248 -- undocumented
249 glyph_stream_provider = "exclusive",
250 provide_charproc_data = "exclusive",
251 }
252 --
253 -- Return a list containing descriptions of added callback functions for
254 -- specific callback.
255 function callback.callback_descriptions(name)
256 return callback_description[name] or {}
257 end
258
259 local valid_callback_types = {
260 exclusive = true,
261 simple = true,
262 data = true,
263 list = true,
264 reverselist = true,
265 }
266 --
267 -- Create a user callback that can only be called manually using
268 -- \`call_callback`. A default function is only needed by "exclusive" callbacks.
269 function callback.create_callback(name, cbtype, default)
270 if callback_types[name] then
271 err("cannot create callback '%s' - it already exists", name)
272 elseif not valid_callback_types[cbtype] then
273 err("cannot create callback '%s' with invalid callback type '%s'", name, cbtype)
274 elseif cbtype == "exclusive" and not default then
275 err("unable to create exclusive callback '%s', default function is required", name)
276 end
277
278 callback_types[name] = cbtype
279 default_functions[name] = default or nil
280 user_callbacks[name] = true
281 end
282 --
283 -- Add a function to the list of functions executed when callback is called.
284 -- For standard luatex callback a proxy function that calls our machinery is
285 -- registered as the real callback function. This doesn't happen for user
286 -- callbacks, that are called manually by user using `call_callback` or for
287 -- standard callbacks that have default functions -- like `mlist_to_hlist` (see
288 -- below).
289 local call_callback
290 function callback.add_to_callback(name, fn, description)
291 if user_callbacks[name] or callback_functions[name] or default_functions[name] then
292 -- either:
293 -- a) user callback - no need to register anything
294 -- b) standard callback that has already been registered
295 -- c) standard callback with default function registered separately
296 -- (mlist_to_hlist)
297 elseif callback_types[name] then
298 -- This is a standard luatex callback with first function being added,
299 -- register a proxy function as a real callback. Assert, so we know
300 -- when things break, like when callbacks get redefined by future
301 -- luatex.
302 callback_register(name, function(...)
303 return call_callback(name, ...)
304 end)
305 else
306 err("cannot add '%s' to callback '%s' - no such callback exists", description, name)
307 end
308
309 if not description or description == "" then
310 err("missing description when adding a callback to '%s'", name)
311 end
312
313 local prev_descriptions = callback_description[name] or {}
314 for _, desc in ipairs(prev_descriptions) do
315 if desc == description then
316 err("for callback '%s' there already is '%s' added", name, description)
317 end
318 end
319
320 if callback_types[name] == "exclusive" and #prev_descriptions == 1 then
321 err("can't register '%s' as callback '%s' - exclusive callback occupied by '%s'",
322 description, name, prev_descriptions[1])
323 end
324
325 if type(fn) ~= "function" then
326 err("expected Lua function to be added as '%s' for callback '%s'", description, name)
327 end
328
329 -- add function to callback list for this callback
330 callback_functions[name] = callback_functions[name] or {}
331 table.insert(callback_functions[name], fn)
332
333 -- add description to description list
334 callback_description[name] = callback_description[name] or {}
335 table.insert(callback_description[name], description)
336 end
337 --
338 -- Remove a function from the list of functions executed when callback is
339 -- called. If last function in the list is removed delete the list entirely.
340 function callback.remove_from_callback(name, description)
341 local descriptions = callback_description[name]
342 local index
343 for i, desc in ipairs(descriptions) do
344 if desc == description then
345 index = i
346 break
347 end
348 end
349
350 if not index then
351 err("can't remove '%s' from callback '%s': not found", description, name)
352 end
353
354 table.remove(descriptions, index)
355 local fn = table.remove(callback_functions[name], index)
356
357 if #descriptions == 0 then
358 -- Delete the list entirely to allow easy checking of "truthiness".
359 callback_functions[name] = nil
360
361 if not user_callbacks[name] and not default_functions[name] then
362 -- this is a standard callback with no added functions and no
363 -- default function (i.e. not mlist_to_hlist), restore standard
364 -- behaviour by unregistering.
365 callback_register(name, nil)
366 end
367 end
368
369 return fn, description
370 end
371 --
372 -- helper iterator generator for iterating over reverselist callback functions
373 local function reverse_ipairs(t)
374 local i, n = #t + 1, 1
375 return function()
376 i = i - 1
377 if i >= n then
378 return i, t[i]
379 end
380 end
381 end
382 --
383 -- Call all functions added to callback. This function handles standard
384 -- callbacks as well as user created callbacks. It can happen that this
385 -- function is called when no functions were added to callback -- like for user
386 -- created callbacks or `mlist_to_hlist` (see below), these are handled either
387 -- by a default function (like for `mlist_to_hlist` and those user created
388 -- callbacks that set a default function) or by doing nothing for empty
389 -- function list.
390 function callback.call_callback(name, ...)
391 local cbtype = callback_types[name]
392 -- either take added functions or the default function if there is one
393 local functions = callback_functions[name] or {default_functions[name]}
394
395 if cbtype == nil then
396 err("cannot call callback '%s' - no such callback exists", name)
397 elseif cbtype == "exclusive" then
398 -- only one function, at least default function is guaranteed by
399 -- create_callback
400 return functions[1](...)
401 elseif cbtype == "simple" then
402 -- call all functions one after another, no passing of data
403 for _, fn in ipairs(functions) do
404 fn(...)
405 end
406 return
407 elseif cbtype == "data" then
408 -- pass data (first argument) from one function to other, while keeping
409 -- other arguments
410 local data = (...)
411 for _, fn in ipairs(functions) do
412 data = fn(data, select(2, ...))
413 end
414 return data
415 end
416
417 -- list and reverselist are like data, but "true" keeps data (head node)
418 -- unchanged and "false" ends the chain immediately
419 local iter
420 if cbtype == "list" then
421 iter = ipairs
422 elseif cbtype == "reverselist" then
423 iter = reverse_ipairs
424 end
425
426 local head = (...)
427 local new_head
428 for _, fn in iter(functions) do
429 new_head = fn(head, select(2, ...))
430 if new_head == false then
431 return false
432 elseif new_head ~= true then
433 head = new_head
434 end
435 end
436 return head
437 end
438 call_callback = callback.call_callback
439 --
440 -- Create \"virtual" callbacks `pre/post_mlist_to_hlist_filter` by setting
441 -- `mlist_to_hlist` callback. The default behaviour of `mlist_to_hlist` is kept by
442 -- using a default function, but it can still be overridden by using
443 -- `add_to_callback`.
444 default_functions["mlist_to_hlist"] = node.mlist_to_hlist
445 callback.create_callback("pre_mlist_to_hlist_filter", "list")
446 callback.create_callback("post_mlist_to_hlist_filter", "reverselist")
447 callback_register("mlist_to_hlist", function(head, ...)
448 -- pre_mlist_to_hlist_filter
449 local new_head = call_callback("pre_mlist_to_hlist_filter", head, ...)
450 if new_head == false then
451 flush_list(head)
452 return nil
453 else
454 head = new_head
455 end
456 -- mlist_to_hlist means either added functions or standard luatex behavior
457 -- of node.mlist_to_hlist (handled by default function)
458 head = call_callback("mlist_to_hlist", head, ...)
459 -- post_mlist_to_hlist_filter
460 new_head = call_callback("post_mlist_to_hlist_filter", head, ...)
461 if new_head == false then
462 flush_list(head)
463 return nil
464 end
465 return new_head
466 end)
467 --
468 -- Create \"virtual" callback `pre_append_to_vlist_filter` by setting
469 -- `append_to_vlist_filter` callback. The default behaviour of `append_to_vlist_filter` is kept by
470 -- using a default function, but it can still be overridden by using
471 -- `add_to_callback`.
472 default_functions["append_to_vlist_filter"] = function(n, _, prevdepth)
473 return node.prepend_prevdepth(n, prevdepth)
474 end
475 callback.create_callback("pre_append_to_vlist_filter","list")
476 callback_register("append_to_vlist_filter", function(box,locationcode,prevdepth,mirrored)
477 local current = call_callback("pre_append_to_vlist_filter",
478 box, locationcode, prevdepth,mirrored)
479 if not current then
480 flush_node(box)
481 return
482 end
483 -- append_to_vlist_filter means either added functions or standard luatex behavior
484 -- of node.prepend_prevdepth (handled by default function)
485 return call_callback("append_to_vlist_filter",
486 current, locationcode, prevdepth, mirrored)
487 end
488 )
489 --
490 -- For preprocessing boxes just before shipout we define custom callback. This
491 -- is used for coloring based on attributes.
492 -- There is however a challenge - how to call this callback? We could redefine
493 -- `\shipout` and `\pdfxform` (which both run `ship_out` procedure internally),
494 -- but they would lose their primitive meaning – i.e. `\immediate` wouldn't work
495 -- with `\pdfxform`. The compromise is to require anyone to run
496 -- \`\_preshipout``<destination box number><box specification>` just before
497 -- `\shipout` or `\pdfxform` if they want to call `pre_shipout_filter` (and
498 -- achieve colors and possibly more).
499 callback.create_callback("pre_shipout_filter", "list")
500
501 define_lua_command("_preshipout", function()
502 local boxnum = token_scanint()
503 local head = token_scanlist()
504 head = call_callback("pre_shipout_filter", head)
505 tex_setbox(boxnum, head)
506 end)
507 --
508 -- Compatibility with \LaTeX/ through luatexbase namespace. Needed for
509 -- luaotfload.
510 _ENV.luatexbase = {
511 registernumber = registernumber,
512 attributes = attributes,
513 -- `provides_module` is needed by older version of luaotfload
514 provides_module = function() end,
515 new_attribute = alloc.new_attribute,
516 callback_descriptions = callback.callback_descriptions,
517 create_callback = callback.create_callback,
518 add_to_callback = callback.add_to_callback,
519 remove_from_callback = callback.remove_from_callback,
520 call_callback = callback.call_callback,
521 callbacktypes = {},
522 }
523 --
524 -- `\tracingmacros` callback registered.
525 -- Use `\tracingmacros=3` or `\tracingmacros=4` if you want to see the result.
526 callback.add_to_callback("input_level_string", function(n)
527 if tex.tracingmacros > 3 then
528 return "[" .. n .. "] "
529 elseif tex.tracingmacros > 2 then
530 return "~" .. string.rep(".",n)
531 else
532 return ""
533 end
534 end, "_tracingmacros")
535 --
536 -- \medskip\secc[lua-pdf-utils] PDF object utilities^^M
537 --
538 -- The PDF format defines various kinds of \"objects": numbers, names, arrays,
539 -- dictionaries. A PDF document is mostly a tree of these objects (i.e. objects
540 -- contain other objects), with either direct (\"in-place") or indirect
541 -- references.
542 --
543 -- These objects are saved in the PDF file in a serialized form, often
544 -- compressed. While \LuaTeX/ takes care of the compression, and most of the
545 -- structure of the PDF format, sometimes we want to insert our own PDF objects
546 -- - and there are places where \LuaTeX/ allows us to use our own objects to
547 -- insert anything, but it already expects a serialized form of the objects. The
548 -- serialized form for some kinds of objects has various formatting and escaping
549 -- rules, and is inconvenient to produce in \TeX/ especially when some of the
550 -- e.g. names and strings are {\it user input}.
551 --
552 -- Here we define a couple of utilities for both Lua and \TeX/ that aid with
553 -- representation and serialization of objects. The functions are exported, but
554 -- may still evolve in incompatible ways.
555 --
556 -- A reference for the serialization is the \"Syntax" section of the PDF
557 -- specification\fnote{\url{https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf}}.
558 --
559 -- \`\pdfname``{<name>}` serializes a \"PDF name" to bytes.
560 local function name_escape(char)
561 return fmt("#%02X", char:byte())
562 end
563 --
564 local function pdf_name(name)
565 -- Delimiters (i.e. "()<>[]{}/%") and control characters (0x00-0x1f, and 0x7f),
566 -- space (" ", 0x20) as well as number sign ("#", 0x23) characters have to be escaped
567 return "/" .. name:gsub("[%(%)<>%[%]{}/%%%c #]", name_escape)
568 end
569 optex.pdf_name = pdf_name
570 define_lua_command("_pdfname", function()
571 tex_print(-2, pdf_name(token.scan_string()))
572 end)
573 --
574 -- \`\pdfstring``{<string>}` serializes a PDF string to bytes.
575 local function pdf_string(str)
576 local out = {"<FEFF"}
577 for _, c in utf8.codes(str) do
578 if c < 0x10000 then
579 out[#out+1] = fmt("%04X", c)
580 else
581 c = c - 0x10000
582 local high = bit32.rshift(c, 10) + 0xD800
583 local low = bit32.band(c, 0x3FF) + 0xDC00
584 out[#out+1] = fmt("%04X%04X", high, low)
585 end
586 end
587 out[#out+1] = ">"
588 return table.concat(out)
589 end
590 optex.pdf_string = pdf_string
591 define_lua_command("_pdfstring", function()
592 tex_print(-2, pdf_string(token.scan_string()))
593 end)
594 --
595 local function pdf_ref(id)
596 return fmt("%d 0 R", id)
597 end
598 optex.pdf_ref = pdf_ref
599 --
600 local pdfdict_mt = {
601 __tostring = function(dict)
602 local out = {"<<"}
603 for k, v in pairs(dict) do
604 out[#out+1] = fmt("%s %s", pdf_name(k), tostring(v))
605 end
606 out[#out+1] = ">>"
607 return table.concat(out, "\n")
608 end,
609 }
610 local function pdf_dict(t)
611 return setmetatable(t or {}, pdfdict_mt)
612 end
613 optex.pdf_dict = pdf_dict
614 --
615 tex.print ("\\_public \\pdfname \\pdfstring ;")
616 --
617 -- \medskip\secc[lua-pdf-resources] Management of PDF page resources^^M
618 --
619 -- Traditionally, pdf\TeX/ allowed managing PDF page resources (graphics
620 -- states, patterns, shadings, etc.) using a single toks register,
621 -- `\pdfpageresources`. This is insufficient due to the expected PDF object
622 -- structure and also because many \"packages" want to add page resources and
623 -- thus fight for the access to that register. We add a finer alternative,
624 -- which allows adding different kinds of resources to a global page resources
625 -- dictionary. Note that some resource types (fonts and XObjects) are already
626 -- managed by \LuaTeX/ and shouldn't be added!
627 --
628 -- XObject forms can also use resources, but there are several ways to make
629 -- \LuaTeX/ reference resources from forms. It is hence left up to the user to
630 -- insert page resources managed by us, if they need them. For that, use
631 -- `pdf.get_page_resources()`, or the below \TeX/ alternative for that.
632 --
633 --
634 local resource_dict_objects = {}
635 local page_resources = {}
636 function pdf.add_page_resource(type, name, value)
637 local resources = page_resources[type]
638 if not resources then
639 local obj = pdf.reserveobj()
640 pdf.setpageresources(fmt("%s %s %s", pdf.get_page_resources(), pdf_name(type), pdf_ref(obj)))
641 resource_dict_objects[type] = obj
642 resources = pdf_dict()
643 page_resources[type] = resources
644 end
645 page_resources[type][name] = value
646 end
647 function pdf.get_page_resources()
648 return pdf.getpageresources() or ""
649 end
650 --
651 -- New \"pseudo" primitives are introduced.
652 -- \`\_addpageresource``{<type>}{<PDF name>}{<PDF dict>}` adds more resources
653 -- of given resource <type> to our data structure.
654 -- \`\_pageresources` expands to the saved <type>s and object numbers.
655 define_lua_command("_addpageresource", function()
656 pdf.add_page_resource(token.scan_string(), token.scan_string(), token.scan_string())
657 end)
658 define_lua_command("_pageresources", function()
659 tex_print(pdf.get_page_resources())
660 end)
661 --
662 -- We write the objects with resources to the PDF file in the `finish_pdffile`
663 -- callback.
664 callback.add_to_callback("finish_pdffile", function()
665 for type, dict in pairs(page_resources) do
666 local obj = resource_dict_objects[type]
667 pdf.immediateobj(obj, tostring(dict))
668 end
669 end, "_pageresources")
670 --
671 -- \medskip\secc[lua-colors] Handling of colors and transparency using attributes^^M
672 --
673 -- Because \LuaTeX/ doesn't do anything with attributes, we have to add meaning
674 -- to them. We do this by intercepting \TeX/ just before it ships out a page and
675 -- inject PDF literals according to attributes.
676 --
677 -- The attribute for coloring is allocated in `colors.opm`
678 local color_attribute = registernumber("_colorattr")
679 local transp_attribute = registernumber("_transpattr")
680 --
681 -- Now we define function which creates whatsit nodes with PDF literals. We do
682 -- this by creating a base literal, which we then copy and customize.
683 --
684 local pdf_base_literal = direct.new("whatsit", "pdf_literal")
685 setfield(pdf_base_literal, "mode", 2) -- direct mode
686 local function pdfliteral(str)
687 local literal = copy(pdf_base_literal)
688 setfield(literal, "data", str)
689 return literal
690 end
691 optex.directpdfliteral = pdfliteral
692 --
693 -- The function \`colorize``(head, current, current_stroke, current_tr)`
694 -- goes through a node list and injects PDF literals according to attributes.
695 -- Its arguments are the head of the list to be colored and the current color
696 -- for fills and strokes and the current transparency attribute.
697 -- It is a recursive function – nested
698 -- horizontal and vertical lists are handled in the same way. Only the
699 -- attributes of “content” nodes (glyphs, rules, etc.) matter. Users drawing
700 -- with PDF literals have to set color themselves.
701 --
702 -- Whatsit node with color setting PDF literal is injected only when a different
703 -- color or transparency is needed. Our injection does not care about boxing levels,
704 -- but this isn't a problem, since PDF literal whatsits just instruct the
705 -- `\shipout` related procedures to emit the literal.
706 --
707 -- We also set the stroke and non-stroke colors separately. This is because
708 -- stroke color is not always needed – \LuaTeX/ itself only uses it for rules
709 -- whose one dimension is less than or equal to 1 bp and for fonts whose `mode`
710 -- is set to 1 (outline) or 2 (outline and fill). Catching these cases is a
711 -- little bit involved. For example rules are problematic, because at this
712 -- point their dimensions can still be running ($-2^{30}$) – they may or may
713 -- not be below the one big point limit. Also the text direction is involved.
714 -- Because of the negative value for running dimensions the simplistic check,
715 -- while not fully correct, should produce the right results. We currently
716 -- don't check for the font mode at all, and instead conservatively consider
717 -- glyphs to always need stroke color. But users can set
718 -- `\directlua{`\`optex.glyphstroked``=false}` if they are sure that their document
719 -- doesn't include colorized fonts in mode 1 or 2. Then the PDF output can be smaller
720 -- in its size (when there is huge amount of color switching, like in this document).
721 --
722 -- Leaders (represented by glue nodes with leader field) are not handled fully.
723 -- They are problematic, because their content is repeated more times and it
724 -- would have to be ensured that the coloring would be right even for e.g.
725 -- leaders that start and end on a different color. We came to conclusion that
726 -- this is not worth, hence leaders are handled just opaquely and only the
727 -- attribute of the glue node itself is checked. For setting different colors
728 -- inside leaders, raw PDF literals have to be used.
729 --
730 -- We use the `node.direct` way of working with nodes. This is less safe, and
731 -- certainly not idiomatic Lua, but faster and codewise more close to the way
732 -- \TeX/ works with nodes.
733 --
734 optex.glyphstroked = true -- default: insert stroke color for glyphs too.
735
736 local function is_color_needed(head, n, id, subtype) -- returns fill, stroke color needed
737 if id == glyph_id then
738 return true, optex.glyphstroked
739 elseif id == glue_id then
740 n = getleader(n)
741 if n then
742 return true, true
743 end
744 elseif id == rule_id then
745 local width, height, depth = getwhd(n)
746 if width <= one_bp or height + depth <= one_bp then
747 -- running (-2^30) may need both
748 return true, true
749 end
750 return true, false
751 elseif id == whatsit_id and (subtype == pdfliteral_id
752 or subtype == pdfsave_id
753 or subtype == pdfrestore_id) then
754 return true, true
755 end
756 return false, false
757 end
758
759 local function colorize(head, current, current_stroke, current_tr)
760 for n, id, subtype in traverse(head) do
761 if id == hlist_id or id == vlist_id then
762 -- nested list, just recurse
763 local list = getlist(n)
764 list, current, current_stroke, current_tr =
765 colorize(list, current, current_stroke, current_tr)
766 setlist(n, list)
767 elseif id == disc_id then
768 -- at this point only no-break (replace) list is of any interest
769 local replace = getfield(n, "replace")
770 if replace then
771 replace, current, current_stroke, current_tr =
772 colorize(replace, current, current_stroke, current_tr)
773 setfield(n, "replace", replace)
774 end
775 else
776 local fill_needed, stroke_needed = is_color_needed(head, n, id, subtype)
777 local new = getattribute(n, color_attribute) or 0
778 local newtr = getattribute(n, transp_attribute) or 0
779 local newliteral = nil
780 if current ~= new and fill_needed then
781 newliteral = token_getmacro("_color:"..new)
782 current = new
783 end
784 if current_stroke ~= new and stroke_needed then
785 local stroke_color = token_getmacro("_color-s:"..current)
786 if stroke_color then
787 if newliteral then
788 newliteral = fmt("%s %s", newliteral, stroke_color)
789 else
790 newliteral = stroke_color
791 end
792 current_stroke = new
793 end
794 end
795 if newtr ~= current_tr and fill_needed then -- (fill_ or stroke_needed) = fill_neded
796 if newliteral ~= nil then
797 newliteral = fmt("%s /tr%d gs", newliteral, newtr)
798 else
799 newliteral = fmt("/tr%d gs", newtr)
800 end
801 current_tr = newtr
802 end
803 if newliteral then
804 head = insertbefore(head, n, pdfliteral(newliteral))
805 end
806 end
807 end
808 return head, current, current_stroke, current_tr
809 end
810 --
811 -- Colorization should be run just before shipout. We use our custom callback
812 -- for this. See the definition of `pre_shipout_filter` for details on
813 -- limitations.
814 callback.add_to_callback("pre_shipout_filter", function(list)
815 -- By setting initial color to -1 we force initial setting of color on
816 -- every page. This is useful for transparently supporting other default
817 -- colors than black (although it has a price for each normal document).
818 local list = colorize(todirect(list), -1, -1, 0)
819 return tonode(list)
820 end, "_colors")
821 --
822 -- We also hook into `luaotfload`'s handling of color and transparency. Instead
823 -- of the default behavior (inserting colorstack whatsits) we set our own
824 -- attribute. On top of that, we take care of transparency resources ourselves.
825 --
826 -- The hook has to be registered {\em after} `luaotfload` is loaded.
827 local color_count = registernumber("_colorcnt")
828 local function set_node_color(n, color) -- "1 0 0 rg" or "0 g", etc.
829 local attr = tonumber(token_getmacro("_color::"..color))
830 if not attr then
831 attr = tex_getcount(color_count)
832 tex_setcount(color_count, attr + 1)
833 local strattr = tostring(attr)
834 token_setmacro("_color::"..color, strattr, "global")
835 token_setmacro("_color:"..strattr, color, "global")
836 token_setmacro("_color-s:"..strattr, string.upper(color), "global")
837 end
838 setattribute(todirect(n), color_attribute, attr)
839 end
840 optex.set_node_color = set_node_color
841 --
842 function optex.hook_into_luaotfload()
843 -- color support for luaotfload v3.13+, otherwise broken
844 pcall(luaotfload.set_colorhandler, function(head, n, rgbcolor) -- rgbcolor = "1 0 0 rg"
845 set_node_color(n, rgbcolor)
846 return head, n
847 end)
848
849 -- transparency support for luaotfload v3.22+, otherwise broken
850 pcall(function()
851 luatexbase.add_to_callback("luaotfload.parse_transparent", function(input) -- from "00" to "FF"
852 -- in luaotfload: 0 = transparent, 255 = opaque
853 -- in optex: 0 = opaque, 255 = transparent
854 local alpha = tonumber(input, 16)
855 if not alpha then
856 tex.error("Invalid transparency specification passed to font")
857 return nil
858 elseif alpha == 255 then
859 return nil -- this allows luaotfload to skip calling us for opaque style
860 end
861 local transp = 255 - alpha
862 local transpv = fmt("%.3f", alpha / 255)
863 pdf.add_page_resource("ExtGState", fmt("tr%d", transp), pdf_dict{ca = transpv, CA = transpv})
864 pdf.add_page_resource("ExtGState", "tr0", pdf_dict{ca = 1, CA = 1})
865 return transp -- will be passed to the below function
866 end, "optex")
867
868 luaotfload.set_transparenthandler(function(head, n, transp)
869 setattribute(n, transp_attribute, transp)
870 return head, n
871 end)
872 end)
873 end
874
875 -- \`\_beglocalcontrol` `<tokens>` `\_endlocalcontrol` runs `<tokens>` fully at
876 -- expand processor level despite the fact that `<tokens>` processes unexpandable commands.
877
878 define_lua_command("_beglocalcontrol", function()
879 return tex.runtoks(token.get_next)
880 end)
881
882 -- History:
883 -- 2025-11-25 pre_append_to_vlist_filter callback added
884 -- 2025-05-12 optex.glyphstoked introduced
885 -- 2025-05-11 if not \vbox then raw_ht retunts zero instead error
886 -- 2024-12-18 \pdfstring etc. introduced
887 -- 2024-09-06 raw_ht() implemented
888 -- 2024-06-02 more checking in add_to_callback and remove_from_callback
889 -- 2024-02-18 \_beglocalcontrol added
890 -- 2022-08-25 expose some useful functions in `optex` namespace
891 -- 2022-08-24 luaotfload transparency with attributes added
892 -- 2022-03-07 transparency in the colorize() function, current_tr added
893 -- 2022-03-05 resources management added
894 -- 2021-07-16 support for colors via attributes added
895 -- 2020-11-11 optex.lua released