Debian Codegraph @

texmf-dist/source/latex/tagpdf/tagpdf-backend.dtx

raw
1 % \iffalse meta-comment
2 %
3 %% File: tagpdf-backend.dtx
4 %
5 % Copyright (C) 2019-2026 Ulrike Fischer
6 %
7 % It may be distributed and/or modified under the conditions of the
8 % LaTeX Project Public License (LPPL), either version 1.3c of this
9 % license or (at your option) any later version. The latest version
10 % of this license is in the file
11 %
12 % https://www.latex-project.org/lppl.txt
13 %
14 % This file is part of the "tagpdf bundle" (The Work in LPPL)
15 % and all files in that bundle must be distributed together.
16 %
17 % -----------------------------------------------------------------------
18 %
19 % The development version of the bundle can be found at
20 %
21 % https://github.com/latex3/tagpdf
22 %
23 % for those people who are interested.
24 %
25 %<*driver>
26 \DocumentMetadata{tagging=on}
27 \documentclass{l3in2edoc}
28 \usepackage{array,booktabs,caption}
29 \hypersetup{pdfauthor=Ulrike Fischer,
30 pdftitle=tagpdf-mc module (tagpdf)}
31 \begin{document}
32 \DocInput{\jobname.dtx}
33 \end{document}
34 %</driver>
35 % \fi
36 % \title{^^A
37 % The \pkg{tagpdf} driver for luatex ^^A
38 % }
39 %
40 % \author{^^A
41 % Ulrike Fischer\thanks
42 % {^^A
43 % E-mail:
44 % \href{mailto:[email protected]}
45 % {[email protected]}^^A
46 % }^^A
47 % }
48 %
49 % \date{Version 1.0c, released 2026-05-17}
50 % \maketitle
51 % \begin{implementation}
52 % \begin{macrocode}
53 %<@@=tag>
54 %<*luatex>
55 \ProvidesExplFile {tagpdf-luatex.def} {2026-05-17} {1.0c}
56 {tagpdf~driver~for~luatex}
57 % \end{macrocode}
58 % \section{Loading the lua}
59 % The space code requires that the fall back font has been loaded and initialized,
60 % so we force that first. But perhaps this could be done in the kernel.
61 %
62 % \begin{macrocode}
63 {
64 \fontencoding{TU}\fontfamily{lmr}\fontseries{m}\fontshape{n}\fontsize{10pt}{10pt}\selectfont
65 }
66 \lua_now:e { tagpdf=require('tagpdf.lua') }
67 % \end{macrocode}
68 %
69 % The following defines wrappers around prop and seq commands to store the
70 % data also in lua tables.
71 % I probably want also lua tables
72 % I put them in the ltx.@@.tables namespaces
73 % The tables will be named like the variables but without backslash
74 % To access such a table with a dynamical name create a string and then use
75 % ltx.@@.tables[string]
76 % Old code, I'm not quite sure if this was a good idea. Now I have mix of table in
77 % ltx.@@.tables and ltx.@@.mc/struct. And a lot is probably not needed.
78 % TODO: this should be cleaned up, but at least roles are currently using
79 % the table!
80 %
81 % \begin{macro}
82 % {
83 % \@@_prop_new:N,
84 % \@@_seq_new:N,
85 % \@@_prop_gput:Nnn,
86 % \@@_seq_gput_right:Nn,
87 % \@@_seq_gput_left:Nn,
88 % \@@_seq_item:cn,
89 % \@@_prop_item:cn,
90 % \@@_seq_show:N,
91 % \@@_prop_show:N
92 % }
93 % \begin{macrocode}
94 \cs_set_protected:Npn \@@_prop_new:N #1
95 {
96 \prop_new:N #1
97 \lua_now:e { ltx.@@.tables['\cs_to_str:N#1'] = {} }
98 }
99
100 \cs_set_protected:Npn \@@_prop_new_linked:N #1
101 {
102 \prop_new_linked:N #1
103 \lua_now:e { ltx.@@.tables['\cs_to_str:N#1'] = {} }
104 }
105
106
107 \cs_set_protected:Npn \@@_seq_new:N #1
108 {
109 \seq_new:N #1
110 \lua_now:e { ltx.@@.tables['\cs_to_str:N#1'] = {} }
111 }
112
113
114 \cs_set_protected:Npn \@@_prop_gput:Nnn #1 #2 #3
115 {
116 \prop_gput:Nnn #1 { #2 } { #3 }
117 \lua_now:e { ltx.@@.tables['\cs_to_str:N#1'] ["#2"] = "\lua_escape:n{#3}" }
118 }
119
120 \cs_set_protected:Npn \@@_seq_gput_right:Nn #1 #2
121 {
122 \seq_gput_right:Nn #1 { #2 }
123 \lua_now:e { table.insert(ltx.@@.tables['\cs_to_str:N#1'], "#2") }
124 }
125 % \end{macrocode}
126 %
127 % this inserts on the right of the lua table, but as the lua table is not used for kids
128 % this is ignored for now.
129 % \begin{macrocode}
130 \cs_set_protected:Npn \@@_seq_gput_left:Nn #1 #2
131 {
132 \seq_gput_left:Nn #1 { #2 }
133 \lua_now:e { table.insert(ltx.@@.tables['\cs_to_str:N#1'], "#2") }
134 }
135
136 %Hm not quite sure about the naming
137 \cs_set:Npn \@@_seq_item:cn #1 #2
138 {
139 \lua_now:e { tex.sprint(\int_use:N\c_document_cctab,ltx.@@.tables['#1'][#2]) }
140 }
141
142 \cs_set:Npn \@@_prop_item:cn #1 #2
143 {
144 \lua_now:e { tex.sprint(\int_use:N\c_document_cctab,ltx.@@.tables['#1']["#2"]) }
145 }
146
147 %for debugging commands that show both the seq/prop and the lua tables
148 \cs_set_protected:Npn \@@_seq_show:N #1
149 {
150 \seq_show:N #1
151 \lua_now:e { ltx.@@.trace.log ("lua~sequence~array~\cs_to_str:N#1",1) }
152 \lua_now:e { ltx.@@.trace.show_seq (ltx.@@.tables['\cs_to_str:N#1']) }
153 }
154
155 \cs_set_protected:Npn \@@_prop_show:N #1
156 {
157 \prop_show:N #1
158 \lua_now:e {ltx.@@.trace.log ("lua~property~table~\cs_to_str:N#1",1) }
159 \lua_now:e {ltx.@@.trace.show_prop (ltx.@@.tables['\cs_to_str:N#1']) }
160 }
161 % \end{macrocode}
162 % \end{macro}
163 %
164 % \begin{macrocode}
165 %</luatex>
166 % \end{macrocode}
167 % The module declaration
168 % \begin{macrocode}
169 %<*lua>
170 -- tagpdf.lua
171 -- Ulrike Fischer
172
173 local ProvidesLuaModule = {
174 name = "tagpdf",
175 version = "1.0c", --TAGVERSION
176 date = "2026-05-17", --TAGDATE
177 description = "tagpdf lua code",
178 license = "The LATEX Project Public License 1.3c"
179 }
180
181 if luatexbase and luatexbase.provides_module then
182 luatexbase.provides_module (ProvidesLuaModule)
183 end
184
185 --[[
186 The code has quite probably a number of problems
187 - more variables should be local instead of global
188 - the naming is not always consistent due to the development of the code
189 - the traversing of the shipout box must be tested with more complicated setups
190 - it should probably handle more node types
191 -
192 --]]
193
194 % \end{macrocode}
195 % Some comments about the lua structure.
196 % \begin{macrocode}
197 --[[
198 the main table is named ltx.@@. It contains the functions and also the data
199 collected during the compilation.
200
201 ltx.@@.mc will contain mc connected data.
202 ltx.@@.role will contain data related to parent-child relations.
203 ltx.@@.struct will contain structure related data.
204 ltx.@@.page will contain page data
205 ltx.@@.tables contains also data from mc and struct (from older code). This needs cleaning up.
206 There are certainly dublettes, but I don't dare yet ...
207 ltx.@@.func will contain (public) functions.
208 ltx.@@.trace will contain tracing/logging functions.
209 local functions starts with __
210 functions meant for users will be in ltx.tag
211
212 functions
213 ltx.@@.func.get_num_from (tag): takes a tag (string) and returns the id number
214 ltx.@@.func.output_num_from (tag): takes a tag (string) and prints (to tex) the id number
215 ltx.@@.func.get_tag_from (num): takes a num and returns the tag
216 ltx.@@.func.output_tag_from (num): takes a num and prints (to tex) the tag
217 ltx.@@.func.store_mc_data (num,key,data): stores key=data in ltx.@@.mc[num]
218 ltx.@@.func.store_mc_label (label,num): stores label=num in ltx.@@.mc.labels
219 ltx.@@.func.store_mc_kid (mcnum,kid,page): stores the mc-kids of mcnum on page page
220 ltx.@@.func.store_mc_in_page(mcnum,mcpagecnt,page): stores in the page table the number of mcnum on this page
221 ltx.@@.func.store_struct_mcabs (structnum,mcnum): stores relations structnum<->mcnum (abs)
222 ltx.@@.func.mc_insert_kids (mcnum): inserts the /K entries for mcnum by wandering through the [kids] table
223 ltx.@@.func.mark_page_elements(box,mcpagecnt,mccntprev,mcopen,name,mctypeprev) : the main function
224 ltx.@@.func.mark_shipout (): a wrapper around the core function which inserts the last EMC
225 ltx.@@.func.fill_parent_tree_line (page): outputs the entries of the parenttree for this page
226 ltx.@@.func.output_parenttree(): outputs the content of the parenttree
227 ltx.@@.func.pdf_object_ref(name,index): outputs the object reference for the object name
228 ltx.@@.func.markspaceon(), ltx.@@.func.markspaceoff(): (de)activates the marking of positions for space chars
229 ltx.@@.func.linkbin() returns the number of OBJR stored in the linkbin structure
230 ltx.@@.trace.show_mc_data (num,loglevel): shows ltx.@@.mc[num] is the current log level is >= loglevel
231 ltx.@@.trace.show_all_mc_data (max,loglevel): shows a maximum about mc's if the current log level is >= loglevel
232 ltx.@@.trace.show_seq: shows a sequence (array)
233 ltx.@@.trace.show_struct_data (num): shows data of structure num
234 ltx.@@.trace.show_prop: shows a prop
235 ltx.@@.trace.log
236 ltx.@@.trace.showspaces : boolean
237
238 ltx.tag.get_structnum: number, shows the current structure number
239 ltx.tag.get_structnum_next: number, shows the next structure number
240 --]]
241
242 % \end{macrocode}
243 % This set-ups the main attribute registers.
244 % The mc_type attribute stores the type (P, Span etc) encoded as a num,
245 % The mc_cnt attribute stores the absolute number and allows so to see
246 % if a node belongs to the same mc-chunk.
247 % The structnum attribute stores the structure number.
248 % The interwordspace attr is set by the function |@@_mark_spaces|, and marks
249 % the place where spaces should be inserted.
250 % The interwordfont attr is set by the function |@@_mark_spaces| too and
251 % stores the font, so that we can decide which font
252 % to use for the real space char.
253 % The interwordspaceOff attr allows to locally suppress the insertion of
254 % real space chars, e.g. when they are inserted by other means (e.g. with |\char|).
255 % The softhyphenattribute allows to decide how to handle a soft hyphen:
256 % if unset it is surrounded by an Artifact mc, if set to 1 the char is changed.
257 % Other values will perhaps be used later.
258 % \begin{macrocode}
259 local mctypeattributeid = luatexbase.new_attribute ("g_@@_mc_type_attr")
260 local mccntattributeid = luatexbase.new_attribute ("g_@@_mc_cnt_attr")
261 local structnumattributeid = luatexbase.new_attribute ("g_@@_structnum_attr")
262 local iwspaceOffattributeid = luatexbase.new_attribute ("g_@@_interwordspaceOff_attr")
263 local iwspaceattributeid = luatexbase.new_attribute ("g_@@_interwordspace_attr")
264 local iwfontattributeid = luatexbase.new_attribute ("g_@@_interwordfont_attr")
265 local softhyphenattribute = luatexbase.new_attribute ("l_@@_softhyphen_attr")
266 % \end{macrocode}
267 % with this token we can query the state of the boolean
268 % and so detect if unmarked nodes should be marked as attributes
269 % \begin{macrocode}
270 local tagunmarkedbool= token.create("g_@@_tagunmarked_bool")
271 local truebool = token.create("c_true_bool")
272 % \end{macrocode}
273 % with this token we can query the state of the softhyphen boolean
274 % and so detect if hyphens from hyphenation should be replaced by soft-hyphens.
275 % \begin{macrocode}
276 local softhyphenbool = token.create("g_@@_softhyphen_bool")
277 % \end{macrocode}
278
279 % Now a number of local versions from global tables.
280 % Not all is perhaps needed, most node variants were copied from lua-debug.
281 % \begin{macrocode}
282 local catlatex = luatexbase.registernumber("catcodetable@latex")
283 local tableinsert = table.insert
284 local nodeid = node.id
285 local nodecopy = node.copy
286 local nodegetattribute = node.get_attribute
287 local nodesetattribute = node.set_attribute
288 local nodehasattribute = node.has_attribute
289 local nodenew = node.new
290 local nodetail = node.tail
291 local nodeslide = node.slide
292 local noderemove = node.remove
293 local nodetraverseid = node.traverse_id
294 local nodetraverse = node.traverse
295 local nodeinsertafter = node.insert_after
296 local nodeinsertbefore = node.insert_before
297 local pdfpageref = pdf.pageref
298
299 local fonthashes = fonts.hashes
300 local identifiers = fonthashes.identifiers
301 local fontid = font.id
302
303 local HLIST = node.id("hlist")
304 local VLIST = node.id("vlist")
305 local RULE = node.id("rule")
306 local DISC = node.id("disc")
307 local GLUE = node.id("glue")
308 local GLYPH = node.id("glyph")
309 local KERN = node.id("kern")
310 local PENALTY = node.id("penalty")
311 local LOCAL_PAR = node.id("local_par")
312 local MATH = node.id("math")
313
314 local NEXT = next
315 local explicit_disc = 1
316 local regular_disc = 3
317 % \end{macrocode}
318 % Now we setup the main table structure. ltx is used by other latex code too!
319 % \begin{macrocode}
320 ltx = ltx or { }
321 ltx.tag = ltx.tag or { } -- user commands
322 ltx.@@ = ltx.@@ or { }
323 ltx.@@.mc = ltx.@@.mc or { } -- mc data
324 ltx.@@.role = ltx.@@.role or { } -- parent-child data
325 ltx.@@.role.states = ltx.@@.role.states or { } -- the states
326 ltx.@@.role.index = ltx.@@.role.index or { } -- standard types to index
327 --- numbers
328 ltx.@@.role.matrix = ltx.@@.role.matrix or { } -- implements the matrix
329 ltx.@@.struct = ltx.@@.struct or { } -- struct data
330 ltx.@@.tables = ltx.@@.tables or { } -- tables created with new prop and new seq.
331 -- wasn't a so great idea ...
332 -- g_@@_role_tags_seq used by tag<-> is in this tables!
333 -- used for pure lua tables too now!
334 ltx.@@.page = ltx.@@.page or { } -- page data, currently only i->{0->mcnum,1->mcnum,...}
335 ltx.@@.trace = ltx.@@.trace or { } -- show commands
336 ltx.@@.func = ltx.@@.func or { } -- functions
337 ltx.@@.conf = ltx.@@.conf or { } -- configuration variables
338 % \end{macrocode}
339 %
340 % \section{User commands to access data}
341 % Code like the one in luamml will have to access the current state in some places.
342
343 % \begin{macro}{\}
344 % \begin{macrocode}
345 local @@_get_struct_num =
346 function()
347 local a = token.get_macro("g_@@_struct_stack_current_tl")
348 return a
349 end
350
351 local @@_get_struct_counter =
352 function()
353 local a = tex.getcount("c@g_@@_struct_abs_int")
354 return a
355 end
356
357 local @@_get_struct_num_next =
358 function()
359 local a = tex.getcount("c@g_@@_struct_abs_int") + 1
360 return a
361 end
362
363 ltx.tag.get_struct_num = @@_get_struct_num
364 ltx.tag.get_struct_counter = @@_get_struct_counter
365 ltx.tag.get_struct_num_next = @@_get_struct_num_next
366 % \end{macrocode}
367 % \end{macro}
368 % \section{Logging functions}
369 %
370 % \begin{macro}{@@_log,ltx.@@.trace.log}
371 % This rather simple log function takes as argument a
372 % message (string) and a number and
373 % will output the message to the log/terminal if the current loglevel
374 % is greater or equal than num.
375 % \begin{macrocode}
376 local @@_log =
377 function (message,loglevel)
378 if (loglevel or 3) <= tex.count["l_@@_loglevel_int"] then
379 texio.write_nl("tagpdf: ".. message)
380 end
381 end
382
383 ltx.@@.trace.log = @@_log
384 % \end{macrocode}
385 % \end{macro}
386 % \begin{macro}{ltx.@@.trace.show_seq}
387 % This shows the content of a seq as stored in the tables table.
388 % It is used by the |\@@_seq_show:N| function. It is not used
389 % in user commands, only for debugging, and so requires log level >0.
390 % \begin{macrocode}
391 function ltx.@@.trace.show_seq (seq)
392 if (type(seq) == "table") then
393 for i,v in ipairs(seq) do
394 @@_log ("[" .. i .. "] => " .. tostring(v),1)
395 end
396 else
397 @@_log ("sequence " .. tostring(seq) .. " not found",1)
398 end
399 end
400 % \end{macrocode}
401 % \end{macro}
402 % \begin{macro}{ @@_pairs_prop,ltx.@@.trace.show_prop}
403 % This shows the content of a prop as stored in the tables table.
404 % It is used by the |\@@_prop_show:N| function.
405 % \begin{macrocode}
406 local @@_pairs_prop =
407 function (prop)
408 local a = {}
409 for n in pairs(prop) do tableinsert(a, n) end
410 table.sort(a)
411 local i = 0 -- iterator variable
412 local iter = function () -- iterator function
413 i = i + 1
414 if a[i] == nil then return nil
415 else return a[i], prop[a[i]]
416 end
417 end
418 return iter
419 end
420
421
422 function ltx.@@.trace.show_prop (prop)
423 if (type(prop) == "table") then
424 for i,v in @@_pairs_prop (prop) do
425 @@_log ("[" .. i .. "] => " .. tostring(v),1)
426 end
427 else
428 @@_log ("prop " .. tostring(prop) .. " not found or not a table",1)
429 end
430 end
431 % \end{macrocode}
432 % \end{macro}
433 % \begin{macro}{ltx.@@.trace.show_mc_data}
434 % This shows some data for a mc given by |num|.
435 % If something is shown depends on the log level.
436 % The function is used by the following function and then in
437 % |\ShowTagging|
438 % \begin{macrocode}
439 function ltx.@@.trace.show_mc_data (num,loglevel)
440 if ltx.@@ and ltx.@@.mc and ltx.@@.mc[num] then
441 for k,v in pairs(ltx.@@.mc[num]) do
442 @@_log ("mc"..num..": "..tostring(k).."=>"..tostring(v),loglevel)
443 end
444 if ltx.@@.mc[num]["kids"] then
445 @@_log ("mc" .. num .. " has " .. #ltx.@@.mc[num]["kids"] .. " kids",loglevel)
446 for k,v in ipairs(ltx.@@.mc[num]["kids"]) do
447 @@_log ("mc ".. num .. " kid "..k.." =>" .. v.kid.." on page " ..v.page,loglevel)
448 end
449 end
450 else
451 @@_log ("mc"..num.." not found",loglevel)
452 end
453 end
454 % \end{macrocode}
455 % \end{macro}
456 % \begin{macro}{ltx.@@.trace.show_all_mc_data}
457 % This shows data for the mc's between |min| and |max| (numbers).
458 % It is used by the |\ShowTagging| function.
459 % \begin{macrocode}
460 function ltx.@@.trace.show_all_mc_data (min,max,loglevel)
461 for i = min, max do
462 ltx.@@.trace.show_mc_data (i,loglevel)
463 end
464 texio.write_nl("")
465 end
466 % \end{macrocode}
467 % \end{macro}
468
469 % \begin{macro}
470 % {
471 % ltx.@@.trace.show_struct_data
472 % }
473 % This function shows some struct data.
474 % Unused but kept for debugging.
475 % \begin{macrocode}
476 function ltx.@@.trace.show_struct_data (num)
477 if ltx.@@ and ltx.@@.struct and ltx.@@.struct[num] then
478 for k,v in ipairs(ltx.@@.struct[num]) do
479 @@_log ("struct "..num..": "..tostring(k).."=>"..tostring(v),1)
480 end
481 else
482 @@_log ("struct "..num.." not found ",1)
483 end
484 end
485 % \end{macrocode}
486 % \end{macro}
487
488 %
489 % \section{Helper functions}
490 % \subsection{Retrieve data functions}
491 % \begin{macro}{@@_get_mc_cnt_type_tag}
492 % This takes a node as argument and returns the mc-cnt, the mc-type and
493 % and the tag (calculated from the mc-cnt.
494 % \begin{macrocode}
495 local @@_get_mc_cnt_type_tag = function (n)
496 local mccnt = nodegetattribute(n,mccntattributeid) or -1
497 local mctype = nodegetattribute(n,mctypeattributeid) or -1
498 local tag = ltx.@@.func.get_tag_from(mctype)
499 return mccnt,mctype,tag
500 end
501 % \end{macrocode}
502 % \end{macro}
503 %
504 % \begin{macro}{@@_get_mathsubtype}
505 % This function allows to detect if we are at the begin or the end of math.
506 % It takes as argument a mathnode.
507 % \begin{macrocode}
508 local function @@_get_mathsubtype (mathnode)
509 if mathnode.subtype == 0 then
510 subtype = "beginmath"
511 else
512 subtype = "endmath"
513 end
514 return subtype
515 end
516 % \end{macrocode}
517 % \end{macro}
518 %
519 % \begin{variable}{ltx.@@.tables.role_tag_attribute,ltx.@@.tables.role_tag_attribute}
520 % The first is a table with key a tag and value a number (the attribute)
521 % The second is an array with the attribute value as key.
522 % \begin{macrocode}
523 ltx.@@.tables.role_tag_attribute = {}
524 ltx.@@.tables.role_attribute_tag = {}
525 % \end{macrocode}
526 % \end{variable}
527 % \begin{macro}{ltx.@@.func.alloctag}
528 % \begin{macrocode}
529 local @@_alloctag =
530 function (tag)
531 if not ltx.@@.tables.role_tag_attribute[tag] then
532 table.insert(ltx.@@.tables.role_attribute_tag,tag)
533 ltx.@@.tables.role_tag_attribute[tag]=#ltx.@@.tables.role_attribute_tag
534 @@_log ("Add "..tag.." "..ltx.@@.tables.role_tag_attribute[tag],3)
535 end
536 end
537 ltx.@@.func.alloctag = @@_alloctag
538 % \end{macrocode}
539 % \end{macro}
540 % \begin{macro}
541 % {
542 % @@_get_num_from,
543 % ltx.@@.func.get_num_from,
544 % ltx.@@.func.output_num_from
545 % }
546 % These functions take as argument a string |tag|, and return the number
547 % under which is it recorded (and so the attribute value).
548 % The first function outputs the number for lua, while the |output| function
549 % outputs to tex.
550 % \begin{macrocode}
551 local @@_get_num_from =
552 function (tag)
553 if ltx.@@.tables.role_tag_attribute[tag] then
554 a= ltx.@@.tables.role_tag_attribute[tag]
555 else
556 a= -1
557 end
558 return a
559 end
560
561 ltx.@@.func.get_num_from = @@_get_num_from
562
563 function ltx.@@.func.output_num_from (tag)
564 local num = @@_get_num_from (tag)
565 tex.sprint(catlatex,num)
566 if num == -1 then
567 @@_log ("Unknown tag "..tag.." used")
568 end
569 end
570 % \end{macrocode}
571 % \end{macro}
572 %
573 % \begin{macro}
574 % {
575 % @@_get_tag_from ,
576 % ltx.@@.func.get_tag_from,
577 % ltx.@@.func.output_tag_from
578 % }
579 % These functions are the opposites to the previous function:
580 % they take as argument a number (the attribute value) and return the string |tag|.
581 % The first function outputs the string for lua, while the |output| function
582 % outputs to tex.
583 % \begin{macrocode}
584 local @@_get_tag_from =
585 function (num)
586 if ltx.@@.tables.role_attribute_tag[num] then
587 a = ltx.@@.tables.role_attribute_tag[num]
588 else
589 a= "UNKNOWN"
590 end
591 return a
592 end
593
594 ltx.@@.func.get_tag_from = @@_get_tag_from
595
596 function ltx.@@.func.output_tag_from (num)
597 tex.sprint(catlatex,@@_get_tag_from (num))
598 end
599 % \end{macrocode}
600 % \end{macro}
601 % \begin{macro}
602 % {
603 % ltx.@@.func.store_mc_data
604 % }
605 % This function stores for |key|=|data| for mc-chunk |num|. It is used in the
606 % tagpdf-mc code, to store for example the tag string, and the raw options.
607 % \begin{macrocode}
608 function ltx.@@.func.store_mc_data (num,key,data)
609 ltx.@@.mc[num] = ltx.@@.mc[num] or { }
610 ltx.@@.mc[num][key] = data
611 @@_log ("INFO TEX-STORE-MC-DATA: "..num.." => "..tostring(key).." => "..tostring(data),3)
612 end
613 % \end{macrocode}
614 % \end{macro}
615 %
616 % \begin{macro}
617 % {
618 % ltx.@@.func.store_mc_label
619 % }
620 % This function stores the |label|=|num| relationship in the |labels| subtable.
621 % TODO: this is probably unused and can go.
622 % \begin{macrocode}
623 function ltx.@@.func.store_mc_label (label,num)
624 ltx.@@.mc["labels"] = ltx.@@.mc["labels"] or { }
625 ltx.@@.mc.labels[label] = num
626 end
627 % \end{macrocode}
628 % \end{macro}
629 % \begin{macro}
630 % {
631 % ltx.@@.func.store_mc_kid
632 % }
633 % This function is used in the traversing code. It stores
634 % a sub-chunk of a mc |mcnum| into the |kids| table.
635 % \begin{macrocode}
636 function ltx.@@.func.store_mc_kid (mcnum,kid,page)
637 @@_log("INFO TAG-STORE-MC-KID: "..mcnum.." => " .. kid.." on page " .. page,3)
638 ltx.@@.mc[mcnum]["kids"] = ltx.@@.mc[mcnum]["kids"] or { }
639 local kidtable = {kid=kid,page=page}
640 tableinsert(ltx.@@.mc[mcnum]["kids"], kidtable )
641 end
642 % \end{macrocode}
643 % \end{macro}
644
645 % \begin{macro}
646 % {
647 % ltx.@@.func.mc_num_of_kids
648 % }
649 % This function returns the number of kids a mc |mcnum| has. We need to account for
650 % the case that a mc can have no kids.
651 % \begin{macrocode}
652 function ltx.@@.func.mc_num_of_kids (mcnum)
653 local num = 0
654 if ltx.@@.mc[mcnum] and ltx.@@.mc[mcnum]["kids"] then
655 num = #ltx.@@.mc[mcnum]["kids"]
656 end
657 @@_log ("INFO MC-KID-NUMBERS: " .. mcnum .. "has " .. num .. "KIDS",4)
658 return num
659 end
660 % \end{macrocode}
661 % \end{macro}
662 % \subsection{Functions to insert the pdf literals}
663 % \begin{macro}{@@_backend_create_emc_node,@@_insert_emc_node}
664 % This insert the emc node. We support also dvips and dvipdfmx backend
665 % \begin{macrocode}
666 local @@_backend_create_emc_node
667 if tex.outputmode == 0 then
668 if token.get_macro("c_sys_backend_str") == "dvipdfmx" then
669 function @@_backend_create_emc_node ()
670 local emcnode = nodenew("whatsit","special")
671 emcnode.data = "pdf:code EMC"
672 return emcnode
673 end
674 else -- assume a dvips variant
675 function @@_backend_create_emc_node ()
676 local emcnode = nodenew("whatsit","special")
677 emcnode.data = "ps:SDict begin mark /EMC pdfmark end"
678 return emcnode
679 end
680 end
681 else -- pdf mode
682 function @@_backend_create_emc_node ()
683 local emcnode = nodenew("whatsit","pdf_literal")
684 emcnode.data = "EMC"
685 emcnode.mode=1
686 return emcnode
687 end
688 end
689
690 local function @@_insert_emc_node (head,current)
691 local emcnode= @@_backend_create_emc_node()
692 head = node.insert_before(head,current,emcnode)
693 return head
694 end
695 % \end{macrocode}
696 % \end{macro}
697 % \begin{macro}{@@_backend_create_bmc_node,@@_insert_bmc_node}
698 % This inserts a simple bmc node
699 % \begin{macrocode}
700 local @@_backend_create_bmc_node
701 if tex.outputmode == 0 then
702 if token.get_macro("c_sys_backend_str") == "dvipdfmx" then
703 function @@_backend_create_bmc_node (tag)
704 local bmcnode = nodenew("whatsit","special")
705 bmcnode.data = "pdf:code /"..tag.." BMC"
706 return bmcnode
707 end
708 else -- assume a dvips variant
709 function @@_backend_create_bmc_node (tag)
710 local bmcnode = nodenew("whatsit","special")
711 bmcnode.data = "ps:SDict begin mark/"..tag.." /BMC pdfmark end"
712 return bmcnode
713 end
714 end
715 else -- pdf mode
716 function @@_backend_create_bmc_node (tag)
717 local bmcnode = nodenew("whatsit","pdf_literal")
718 bmcnode.data = "/"..tag.." BMC"
719 bmcnode.mode=1
720 return bmcnode
721 end
722 end
723
724 local function @@_insert_bmc_node (head,current,tag)
725 local bmcnode = @@_backend_create_bmc_node (tag)
726 head = node.insert_before(head,current,bmcnode)
727 return head
728 end
729 % \end{macrocode}
730 % \end{macro}
731 % \begin{macro}{@@_backend_create_bdc_node,@@_insert_bdc_node}
732 % This inserts a bcd node with a fix dict.
733 % TODO: check if this is still used, now that we create properties.
734 % \begin{macrocode}
735 local @@_backend_create_bdc_node
736
737 if tex.outputmode == 0 then
738 if token.get_macro("c_sys_backend_str") == "dvipdfmx" then
739 function @@_backend_create_bdc_node (tag,dict)
740 local bdcnode = nodenew("whatsit","special")
741 bdcnode.data = "pdf:code /"..tag.."<<"..dict..">> BDC"
742 return bdcnode
743 end
744 else -- assume a dvips variant
745 function @@_backend_create_bdc_node (tag,dict)
746 local bdcnode = nodenew("whatsit","special")
747 bdcnode.data = "ps:SDict begin mark/"..tag.."<<"..dict..">> /BDC pdfmark end"
748 return bdcnode
749 end
750 end
751 else -- pdf mode
752 function @@_backend_create_bdc_node (tag,dict)
753 local bdcnode = nodenew("whatsit","pdf_literal")
754 bdcnode.data = "/"..tag.."<<"..dict..">> BDC"
755 bdcnode.mode=1
756 return bdcnode
757 end
758 end
759
760 local function @@_insert_bdc_node (head,current,tag,dict)
761 bdcnode= @@_backend_create_bdc_node (tag,dict)
762 head = node.insert_before(head,current,bdcnode)
763 return head
764 end
765 % \end{macrocode}
766 % \end{macro}
767 % \begin{macro}{@@_pdf_object_ref}
768 % This allows to reference a pdf object reserved with the l3pdf command by name.
769 % The return value is |n 0 R|, if the object doesn't exist, n is 0.
770 % \begin{macrocode}
771 local function @@_pdf_object_ref (name,index)
772 local object
773 if ltx.pdf.object_id then
774 object = ltx.pdf.object_id (name,index) ..' 0 R'
775 else
776 local tokenname = 'c__pdf_object_'..name..'/'..index..'_int'
777 object = token.create(tokenname).mode ..' 0 R'
778 end
779 return object
780 end
781 ltx.@@.func.pdf_object_ref = @@_pdf_object_ref
782 % \end{macrocode}
783 % \end{macro}
784 %
785 % \section{Function for the real space chars}
786 % \begin{macro}{@@_show_spacemark}
787 % A debugging function, it is used to
788 % inserts red color markers in the places where space chars can go, it can have
789 % side effects so not always reliable, but ok.
790 % \begin{macrocode}
791 local function @@_show_spacemark (head,current,color,height)
792 local markcolor = color or "1 0 0"
793 local markheight = height or 10
794 local pdfstring
795 if tex.outputmode == 0 then
796 -- ignore dvi mode for now
797 else
798 pdfstring = node.new("whatsit","pdf_literal")
799 pdfstring.data =
800 string.format("q "..markcolor.." RG "..markcolor.." rg 0.4 w 0 %g m 0 %g l S Q",-3,markheight)
801 head = node.insert_after(head,current,pdfstring)
802 return head
803 end
804 end
805 % \end{macrocode}
806 % \end{macro}
807 % \begin{macro}{@@_fakespace,ltx.@@.func.fakespace}
808 % This is used to define a lua version of |\pdffakespace|
809 % \begin{macrocode}
810 local function @@_fakespace()
811 tex.setattribute(iwspaceattributeid,1)
812 tex.setattribute(iwfontattributeid,font.current())
813 end
814 ltx.@@.func.fakespace = @@_fakespace
815 % \end{macrocode}
816 % \end{macro}
817 % \begin{macro}{@@_mark_spaces}
818 % a function to mark up places where real space chars should be inserted.
819 % It only sets attributes, these are then be used in a later traversing
820 % which inserts the actual spaces.
821 % When space handling is activated this function is inserted in some callbacks.
822 % \begin{macrocode}
823 --[[ a function to mark up places where real space chars should be inserted
824 it only sets an attribute.
825 --]]
826
827 local function @@_mark_spaces (head)
828 local inside_math = false
829 for n in nodetraverse(head) do
830 local id = n.id
831 if id == GLYPH then
832 local glyph = n
833 default_currfontid = glyph.font
834 if glyph.next and (glyph.next.id == GLUE)
835 and not inside_math and (glyph.next.width >0)
836 then
837 nodesetattribute(glyph.next,iwspaceattributeid,1)
838 nodesetattribute(glyph.next,iwfontattributeid,glyph.font)
839 -- for debugging
840 if ltx.@@.trace.showspaces then
841 @@_show_spacemark (head,glyph)
842 end
843 elseif glyph.next and (glyph.next.id==KERN) and not inside_math then
844 local kern = glyph.next
845 if kern.next and (kern.next.id== GLUE) and (kern.next.width >0)
846 -- the attribute is also set on the kern in case the kern+glue is
847 -- discarded at a line break tagging issue #1102
848 -- TODO iterate back through all discardable nodes.
849 then
850 nodesetattribute(kern,iwspaceattributeid,1)
851 nodesetattribute(kern,iwfontattributeid,glyph.font)
852 nodesetattribute(kern.next,iwspaceattributeid,1)
853 nodesetattribute(kern.next,iwfontattributeid,glyph.font)
854 end
855 end
856 -- look also back
857 if glyph.prev and (glyph.prev.id == GLUE)
858 and not inside_math
859 and (glyph.prev.width >0)
860 and not nodehasattribute(glyph.prev,iwspaceattributeid)
861 then
862 nodesetattribute(glyph.prev,iwspaceattributeid,1)
863 nodesetattribute(glyph.prev,iwfontattributeid,glyph.font)
864 -- for debugging
865 if ltx.@@.trace.showspaces then
866 @@_show_spacemark (head,glyph)
867 end
868 end
869 elseif id == PENALTY then
870 local glyph = n
871 -- @@_log ("PENALTY ".. n.subtype.."VALUE"..n.penalty,3)
872 if glyph.next and (glyph.next.id == GLUE)
873 and not inside_math and (glyph.next.width >0) and n.subtype==0
874 then
875 nodesetattribute(glyph.next,iwspaceattributeid,1)
876 -- changed 2024-01-18, issue #72
877 nodesetattribute(glyph.next,iwfontattributeid,default_currfontid)
878 -- for debugging
879 if ltx.@@.trace.showspaces then
880 @@_show_spacemark (head,glyph)
881 end
882 end
883 elseif id == MATH then
884 inside_math = (n.subtype == 0)
885 end
886 end
887 return head
888 end
889 % \end{macrocode}
890 % \end{macro}
891 % \begin{macro}
892 % {
893 % @@_activate_mark_space,
894 % ltx.@@.func.markspaceon,
895 % @@_activate_mark_space,
896 % ltx.@@.func.markspaceoff
897 % }
898 % These functions add/remove the function which marks the spaces to the callbacks
899 % |pre_linebreak_filter| and |hpack_filter|
900 % \begin{macrocode}
901 local function @@_activate_mark_space ()
902 if not luatexbase.in_callback ("pre_linebreak_filter","markspaces") then
903 luatexbase.add_to_callback("pre_linebreak_filter",@@_mark_spaces,"markspaces")
904 luatexbase.add_to_callback("hpack_filter",@@_mark_spaces,"markspaces")
905 end
906 end
907
908 ltx.@@.func.markspaceon=@@_activate_mark_space
909
910 local function @@_deactivate_mark_space ()
911 if luatexbase.in_callback ("pre_linebreak_filter","markspaces") then
912 luatexbase.remove_from_callback("pre_linebreak_filter","markspaces")
913 luatexbase.remove_from_callback("hpack_filter","markspaces")
914 end
915 end
916
917 ltx.@@.func.markspaceoff=@@_deactivate_mark_space
918 % \end{macrocode}
919 % \end{macro}
920 % We need two local variable to setup a default space char.
921 % \begin{macrocode}
922 local default_space_char = nodenew(GLYPH)
923 local default_fontid = fontid("TU/lmr/m/n/10")
924 local default_currfontid = fontid("TU/lmr/m/n/10")
925 default_space_char.char = 32
926 default_space_char.font = default_fontid
927 % \end{macrocode}
928 % And a function to check as best as possible if a font has a space:
929 % \begin{macrocode}
930 local function @@_font_has_space (fontid)
931 t= fonts.hashes.identifiers[fontid]
932 if luaotfload.aux.slot_of_name(fontid,"space")
933 or t and t.characters and t.characters[32] and t.characters[32]["unicode"]==32
934 then
935 return true
936 else
937 return false
938 end
939 end
940 % \end{macrocode}
941 % \begin{macro}
942 % {
943 % @@_space_chars_shipout,
944 % ltx.@@.func.space_chars_shipout,
945 % }
946 % These is the main function to insert real space chars. It inserts a
947 % glyph before every glue which has been marked previously. The attributes
948 % are copied from the glue, so if the tagging is done later,
949 % it will be tagged like it.
950 % \begin{macrocode}
951 local function @@_space_chars_shipout (box)
952 local head = box.head
953 if head then
954 for n in node.traverse(head) do
955 local spaceattr = -1
956 if not nodehasattribute(n,iwspaceOffattributeid) then
957 spaceattr = nodegetattribute(n,iwspaceattributeid) or -1
958 end
959 if n.id == HLIST then -- enter the hlist
960 @@_space_chars_shipout (n)
961 elseif n.id == VLIST then -- enter the vlist
962 @@_space_chars_shipout (n)
963 elseif n.id == GLUE then
964 if ltx.@@.trace.showspaces and spaceattr==1 then
965 @@_show_spacemark (head,n,"0 1 0")
966 end
967 if spaceattr==1 then
968 local space
969 local space_char = node.copy(default_space_char)
970 local curfont = nodegetattribute(n,iwfontattributeid)
971 @@_log ("INFO SPACE-FUNCTION-FONT: ".. tostring(curfont),3)
972 if curfont and
973 -- luaotfload.aux.slot_of_name(curfont,"space")
974 @@_font_has_space (curfont)
975 then
976 space_char.font=curfont
977 end
978 head, space = node.insert_before(head, n, space_char) --
979 n.width = n.width - space.width
980 space.attr = n.attr
981 end
982 end
983 end
984 box.head = head
985 end
986 end
987
988 function ltx.@@.func.space_chars_shipout (box)
989 @@_space_chars_shipout (box)
990 end
991 % \end{macrocode}
992 % \end{macro}
993 %
994 % \section{Function for the tagging}
995 % \begin{macro}
996 % {
997 % ltx.@@.func.mc_insert_kids
998 % }
999 % This is the main function to insert the
1000 % K entry into a StructElem object. It is used in tagpdf-mc-luacode module.
1001 % The |single| attribute allows to handle the case that a single
1002 % mc on the tex side can have more than one kid after the processing here,
1003 % and so we get the correct array/non array setup.
1004 % \begin{macrocode}
1005 function ltx.@@.func.mc_insert_kids (mcnum,single)
1006 if ltx.@@.mc[mcnum] then
1007 @@_log("INFO TEX-MC-INSERT-KID-TEST: " .. mcnum,4)
1008 if ltx.@@.mc[mcnum]["kids"] then
1009 if #ltx.@@.mc[mcnum]["kids"] > 1 and single==1 then
1010 tex.sprint(catlatex,"[")
1011 end
1012 for i,kidstable in ipairs( ltx.@@.mc[mcnum]["kids"] ) do
1013 local kidnum = kidstable["kid"]
1014 local kidpage = kidstable["page"]
1015 local kidpageobjnum = pdfpageref(kidpage)
1016 @@_log("INFO TEX-MC-INSERT-KID: " .. mcnum ..
1017 " insert KID " ..i..
1018 " with num " .. kidnum ..
1019 " on page " .. kidpage.."/"..kidpageobjnum,3)
1020 tex.sprint(catlatex,"<</Type /MCR /Pg "..kidpageobjnum .. " 0 R /MCID "..kidnum.. ">> " )
1021 end
1022 if #ltx.@@.mc[mcnum]["kids"] > 1 and single==1 then
1023 tex.sprint(catlatex,"]")
1024 end
1025 else
1026 -- this is typically not a problem, e.g. empty hbox in footer/header can
1027 -- trigger this warning.
1028 @@_log("WARN TEX-MC-INSERT-NO-KIDS: "..mcnum.." has no kids",2)
1029 if single==1 then
1030 tex.sprint(catlatex,"null")
1031 end
1032 end
1033 else
1034 @@_log("WARN TEX-MC-INSERT-MISSING: "..mcnum.." doesn't exist",0)
1035 end
1036 end
1037 % \end{macrocode}
1038 % \end{macro}
1039 % \begin{macro}{ltx.@@.func.store_struct_mcabs}
1040 % This function is used in the tagpdf-mc-luacode. It store the absolute count
1041 % of the mc into the current structure. This must be done ordered.
1042 % \begin{macrocode}
1043 function ltx.@@.func.store_struct_mcabs (structnum,mcnum)
1044 ltx.@@.struct[structnum]=ltx.@@.struct[structnum] or { }
1045 ltx.@@.struct[structnum]["mc"]=ltx.@@.struct[structnum]["mc"] or { }
1046 -- a structure can contain more than on mc chunk, the content should be ordered
1047 tableinsert(ltx.@@.struct[structnum]["mc"],mcnum)
1048 @@_log("INFO TEX-MC-INTO-STRUCT: "..
1049 mcnum.." inserted in struct "..structnum,3)
1050 -- but every mc can only be in one structure
1051 ltx.@@.mc[mcnum]= ltx.@@.mc[mcnum] or { }
1052 ltx.@@.mc[mcnum]["parent"] = structnum
1053 end
1054
1055 % \end{macrocode}
1056 % \end{macro}
1057 % \begin{macro}{ltx.@@.func.store_mc_in_page}
1058 % This is used in the traversing code and stores the relation between
1059 % abs count and page count.
1060 % \begin{macrocode}
1061 -- pay attention: lua counts arrays from 1, tex pages from one
1062 -- mcid and arrays in pdf count from 0.
1063 function ltx.@@.func.store_mc_in_page (mcnum,mcpagecnt,page)
1064 ltx.@@.page[page] = ltx.@@.page[page] or {}
1065 ltx.@@.page[page][mcpagecnt] = mcnum
1066 @@_log("INFO TAG-MC-INTO-PAGE: page " .. page ..
1067 ": inserting MCID " .. mcpagecnt .. " => " .. mcnum,3)
1068 end
1069 % \end{macrocode}
1070 % \end{macro}
1071 %
1072 % \begin{macro}{ltx.@@.func.update_mc_attributes}
1073 % This updates the mc-attributes of a box. It should only be used on boxes
1074 % which don't contain structure elements.
1075 % The arguments are a box, the mc-num and the type (as a number)
1076 % \begin{macrocode}
1077 local function @@_update_mc_attributes (head,mcnum,type)
1078 for n in node.traverse(head) do
1079 node.set_attribute(n,mccntattributeid,mcnum)
1080 node.set_attribute(n,mctypeattributeid,type)
1081 if n.id == HLIST or n.id == VLIST then
1082 @@_update_mc_attributes (n.list,mcnum,type)
1083 end
1084 end
1085 return head
1086 end
1087 ltx.@@.func.update_mc_attributes = @@_update_mc_attributes
1088 % \end{macrocode}
1089 % \end{macro}
1090 %
1091 % \begin{macro}{ltx.@@.func.mark_page_elements}
1092 % This is the main traversing function. See the lua comment for more details.
1093 % \begin{macrocode}
1094 --[[
1095 Now follows the core function
1096 It wades through the shipout box and checks the attributes
1097 ARGUMENTS
1098 box: is a box,
1099 mcpagecnt: num, the current page cnt of mc (should start at -1 in shipout box), needed for recursion
1100 mccntprev: num, the attribute cnt of the previous node/whatever - if different we have a chunk border
1101 mcopen: num, records if some bdc/emc is open
1102 These arguments are only needed for log messages, if not present are replaces by fix strings:
1103 name: string to describe the box
1104 mctypeprev: num, the type attribute of the previous node/whatever
1105
1106 there are lots of logging messages currently. Should be cleaned up in due course.
1107 One should also find ways to make the function shorter.
1108 --]]
1109
1110 function ltx.@@.func.mark_page_elements (box,mcpagecnt,mccntprev,mcopen,name,mctypeprev)
1111 local name = name or ("SOMEBOX")
1112 local mctypeprev = mctypeprev or -1
1113 local abspage = status.total_pages + 1 -- the real counter is increased
1114 -- inside the box so one off
1115 -- if the callback is not used. (???)
1116 @@_log ("INFO TAG-ABSPAGE: " .. abspage,3)
1117 @@_log ("INFO TAG-ARGS: pagecnt".. mcpagecnt..
1118 " prev "..mccntprev ..
1119 " type prev "..mctypeprev,4)
1120 @@_log ("INFO TAG-TRAVERSING-BOX: ".. tostring(name)..
1121 " TYPE ".. node.type(node.getid(box)),3)
1122 local head = box.head -- ShipoutBox is a vlist?
1123 if head then
1124 mccnthead, mctypehead,taghead = @@_get_mc_cnt_type_tag (head)
1125 @@_log ("INFO TAG-HEAD: " ..
1126 node.type(node.getid(head))..
1127 " MC"..tostring(mccnthead)..
1128 " => TAG " .. tostring(mctypehead)..
1129 " => ".. tostring(taghead),3)
1130 else
1131 @@_log ("INFO TAG-NO-HEAD: head is "..
1132 tostring(head),3)
1133 end
1134 for n in node.traverse(head) do
1135 local mccnt, mctype, tag = @@_get_mc_cnt_type_tag (n)
1136 local spaceattr = nodegetattribute(n,iwspaceattributeid) or -1
1137 @@_log ("INFO TAG-NODE: "..
1138 node.type(node.getid(n))..
1139 " MC".. tostring(mccnt)..
1140 " => TAG ".. tostring(mctype)..
1141 " => " .. tostring(tag),3)
1142 if n.id == HLIST
1143 then -- enter the hlist
1144 mcopen,mcpagecnt,mccntprev,mctypeprev=
1145 ltx.@@.func.mark_page_elements (n,mcpagecnt,mccntprev,mcopen,"INTERNAL HLIST",mctypeprev)
1146 elseif n.id == VLIST then -- enter the vlist
1147 mcopen,mcpagecnt,mccntprev,mctypeprev=
1148 ltx.@@.func.mark_page_elements (n,mcpagecnt,mccntprev,mcopen,"INTERNAL VLIST",mctypeprev)
1149 elseif n.id == GLUE and not n.leader then -- at glue real space chars are inserted, but this has
1150 -- been done if the previous shipout wandering, so here it is ignored
1151 elseif n.id == LOCAL_PAR then -- local_par is ignored
1152 elseif n.id == PENALTY then -- penalty is ignored
1153 elseif n.id == KERN then -- kern is ignored
1154 @@_log ("INFO TAG-KERN-SUBTYPE: "..
1155 node.type(node.getid(n)).." "..n.subtype,4)
1156 else
1157 -- math is currently only logged.
1158 -- we could mark the whole as math
1159 -- for inner processing the mlist_to_hlist callback is probably needed.
1160 if n.id == MATH then
1161 @@_log("INFO TAG-MATH-SUBTYPE: "..
1162 node.type(node.getid(n)).." "..@@_get_mathsubtype(n),4)
1163 end
1164 -- endmath
1165 @@_log("INFO TAG-MC-COMPARE: current "..
1166 mccnt.." prev "..mccntprev,4)
1167 if mccnt~=mccntprev then -- a new mc chunk
1168 @@_log ("INFO TAG-NEW-MC-NODE: "..
1169 node.type(node.getid(n))..
1170 " MC"..tostring(mccnt)..
1171 " <=> PREVIOUS "..tostring(mccntprev),4)
1172 if mcopen~=0 then -- there is a chunk open, close it (hope there is only one ...
1173 box.list=@@_insert_emc_node (box.list,n)
1174 mcopen = mcopen - 1
1175 @@_log ("INFO TAG-INSERT-EMC: " ..
1176 mcpagecnt .. " MCOPEN = " .. mcopen,3)
1177 if mcopen ~=0 then
1178 @@_log ("WARN TAG-OPEN-MC: " .. mcopen,1)
1179 end
1180 end
1181 if ltx.@@.mc[mccnt] then
1182 if ltx.@@.mc[mccnt]["artifact"] then
1183 @@_log("INFO TAG-INSERT-ARTIFACT: "..
1184 tostring(ltx.@@.mc[mccnt]["artifact"]),3)
1185 if ltx.@@.mc[mccnt]["artifact"] == "" then
1186 box.list = @@_insert_bmc_node (box.list,n,"Artifact")
1187 else
1188 box.list = @@_insert_bdc_node (box.list,n,"Artifact", "/Type /"..ltx.@@.mc[mccnt]["artifact"])
1189 end
1190 else
1191 @@_log("INFO TAG-INSERT-TAG: "..
1192 tostring(tag),3)
1193 mcpagecnt = mcpagecnt +1
1194 @@_log ("INFO TAG-INSERT-BDC: "..mcpagecnt,3)
1195 local dict= "/MCID "..mcpagecnt
1196 if ltx.@@.mc[mccnt]["raw"] then
1197 @@_log("INFO TAG-USE-RAW: "..
1198 tostring(ltx.@@.mc[mccnt]["raw"]),3)
1199 dict= dict .. " " .. ltx.@@.mc[mccnt]["raw"]
1200 end
1201 if ltx.@@.mc[mccnt]["alt"] then
1202 @@_log("INFO TAG-USE-ALT: "..
1203 tostring(ltx.@@.mc[mccnt]["alt"]),3)
1204 dict= dict .. " " .. ltx.@@.mc[mccnt]["alt"]
1205 end
1206 if ltx.__tag.mc[mccnt]["lang"] then
1207 __tag_log("INFO TAG-USE-LANG: "..
1208 tostring(ltx.__tag.mc[mccnt]["lang"]),3)
1209 dict= dict .. " " .. ltx.__tag.mc[mccnt]["lang"]
1210 end
1211 if ltx.@@.mc[mccnt]["actualtext"] then
1212 @@_log("INFO TAG-USE-ACTUALTEXT: "..
1213 tostring(ltx.@@.mc[mccnt]["actualtext"]),3)
1214 dict= dict .. " " .. ltx.@@.mc[mccnt]["actualtext"]
1215 end
1216 box.list = @@_insert_bdc_node (box.list,n,tag, dict)
1217 ltx.@@.func.store_mc_kid (mccnt,mcpagecnt,abspage)
1218 ltx.@@.func.store_mc_in_page(mccnt,mcpagecnt,abspage)
1219 ltx.@@.trace.show_mc_data (mccnt,3)
1220 end
1221 mcopen = mcopen + 1
1222 else
1223 if tagunmarkedbool.mode == truebool.mode then
1224 @@_log("INFO TAG-NOT-TAGGED: this has not been tagged, using artifact",2)
1225 box.list = @@_insert_bmc_node (box.list,n,"Artifact")
1226 mcopen = mcopen + 1
1227 else
1228 @@_log("WARN TAG-NOT-TAGGED: this has not been tagged",1)
1229 end
1230 end
1231 mccntprev = mccnt
1232 end
1233 end -- end if
1234 end -- end for
1235 if head then
1236 mccnthead, mctypehead,taghead = @@_get_mc_cnt_type_tag (head)
1237 @@_log ("INFO TAG-ENDHEAD: " ..
1238 node.type(node.getid(head))..
1239 " MC"..tostring(mccnthead)..
1240 " => TAG "..tostring(mctypehead)..
1241 " => "..tostring(taghead),4)
1242 else
1243 @@_log ("INFO TAG-ENDHEAD: ".. tostring(head),4)
1244 end
1245 @@_log ("INFO TAG-QUITTING-BOX "..
1246 tostring(name)..
1247 " TYPE ".. node.type(node.getid(box)),4)
1248 return mcopen,mcpagecnt,mccntprev,mctypeprev
1249 end
1250
1251 % \end{macrocode}
1252 % \end{macro}
1253 % \begin{macro}{ltx.@@.func.mark_shipout}
1254 % This is the function used in the callback. Beside calling the traversing
1255 % function it also checks if there is an open MC-chunk from a page
1256 % break and insert the needed EMC literal.
1257 % \begin{macrocode}
1258 function ltx.@@.func.mark_shipout (box)
1259 mcopen = ltx.@@.func.mark_page_elements (box,-1,-100,0,"Shipout",-1)
1260 if mcopen~=0 then -- there is a chunk open, close it (hope there is only one ...
1261 local emcnode = @@_backend_create_emc_node ()
1262 local list = box.list
1263 if list then
1264 list = node.insert_after (list,node.tail(list),emcnode)
1265 mcopen = mcopen - 1
1266 @@_log ("INFO SHIPOUT-INSERT-LAST-EMC: MCOPEN " .. mcopen,3)
1267 else
1268 @@_log ("WARN SHIPOUT-UPS: this shouldn't happen",0)
1269 end
1270 if mcopen ~=0 then
1271 @@_log ("WARN SHIPOUT-MC-OPEN: " .. mcopen,1)
1272 end
1273 end
1274 end
1275 % \end{macrocode}
1276 % \end{macro}
1277
1278 % \section{Parenttree}
1279 % \begin{macro}
1280 % {
1281 % ltx.@@.func.fill_parent_tree_line,
1282 % ltx.@@.func.output_parenttree
1283 % }
1284 % These functions create the parent tree. The second, main function
1285 % is used in the tagpdf-tree code.
1286 % TODO check if the tree code can move into the backend code.
1287 % \begin{macrocode}
1288 function ltx.@@.func.fill_parent_tree_line (page)
1289 -- we need to get page-> i=kid -> mcnum -> structnum
1290 -- pay attention: the kid numbers and the page number in the parent tree start with 0!
1291 local numsentry =""
1292 local pdfpage = page-1
1293 if ltx.@@.page[page] and ltx.@@.page[page][0] then
1294 mcchunks=#ltx.@@.page[page]
1295 @@_log("INFO PARENTTREE-NUM: page "..
1296 page.." has "..mcchunks.."+1 Elements ",4)
1297 for i=0,mcchunks do
1298 -- what does this log??
1299 @@_log("INFO PARENTTREE-CHUNKS: "..
1300 ltx.@@.page[page][i],4)
1301 end
1302 if mcchunks == 0 then
1303 -- only one chunk so no need for an array
1304 local mcnum = ltx.@@.page[page][0]
1305 local structnum = ltx.@@.mc[mcnum]["parent"]
1306 local propname = "g_@@_struct_"..structnum.."_prop"
1307 --local objref = ltx.@@.tables[propname]["objref"] or "XXXX"
1308 local objref = @@_pdf_object_ref('@@/struct',structnum)
1309 @@_log("INFO PARENTTREE-STRUCT-OBJREF: =====>"..
1310 tostring(objref),5)
1311 numsentry = pdfpage .. " [".. objref .. "]"
1312 @@_log("INFO PARENTTREE-NUMENTRY: page " ..
1313 page.. " num entry = ".. numsentry,3)
1314 else
1315 numsentry = pdfpage .. " ["
1316 for i=0,mcchunks do
1317 local mcnum = ltx.@@.page[page][i]
1318 local structnum = ltx.@@.mc[mcnum]["parent"] or 0
1319 local propname = "g_@@_struct_"..structnum.."_prop"
1320 --local objref = ltx.@@.tables[propname]["objref"] or "XXXX"
1321 local objref = @@_pdf_object_ref('@@/struct',structnum)
1322 numsentry = numsentry .. " ".. objref
1323 end
1324 numsentry = numsentry .. "] "
1325 @@_log("INFO PARENTTREE-NUMENTRY: page " ..
1326 page.. " num entry = ".. numsentry,3)
1327 end
1328 else
1329 @@_log ("INFO PARENTTREE-NO-DATA: page "..page,3)
1330 numsentry = pdfpage.." []"
1331 end
1332 return numsentry
1333 end
1334
1335 function ltx.@@.func.output_parenttree (abspage)
1336 for i=1,abspage do
1337 line = ltx.@@.func.fill_parent_tree_line (i) .. "^^J"
1338 tex.sprint(catlatex,line)
1339 end
1340 end
1341 % \end{macrocode}
1342 % \end{macro}
1343 %
1344 % \begin{macro}
1345 % {
1346 % process_softhyphen_pre
1347 % process_softhyphen_post
1348 % }
1349 % First some local definitions. Since these are only needed locally everything gets wrapped into a block.
1350 % \begin{macrocode}
1351 do
1352 local properties = node.get_properties_table()
1353 local is_soft_hyphen_prop = 'tagpdf.rewrite-softhyphen.is_soft_hyphen'
1354 local hyphen_char = 0x2D
1355 local soft_hyphen_char = 0xAD
1356 % \end{macrocode}
1357 %
1358 % A lookup table to test if the font supports the soft hyphen glyph.
1359 % \begin{macrocode}
1360 local softhyphen_fonts = setmetatable({}, {__index = function(t, fid)
1361 local fdir = identifiers[fid]
1362 local format = fdir and fdir.format
1363 local result = (format == 'opentype' or format == 'truetype')
1364 local characters = fdir and fdir.characters
1365 result = result and (characters and characters[soft_hyphen_char]) ~= nil
1366 t[fid] = result
1367 return result
1368 end})
1369 % \end{macrocode}
1370 %
1371 % A pre shaping callback to mark hyphens as being hyphenation hyphens.
1372 % This runs before shaping to avoid affecting hyphens moved into
1373 % discretionaries during shaping.
1374 % \begin{macrocode}
1375 local function process_softhyphen_pre(head, _context, _dir)
1376 if softhyphenbool.mode ~= truebool.mode then return true end
1377 for disc, sub in node.traverse_id(DISC, head) do
1378 if sub == explicit_disc or sub == regular_disc then
1379 for n, _ch, _f in node.traverse_char(disc.pre) do
1380 local props = properties[n]
1381 if not props then
1382 props = {}
1383 properties[n] = props
1384 end
1385 props[is_soft_hyphen_prop] = true
1386 end
1387 end
1388 end
1389 return true
1390 end
1391
1392 % \end{macrocode}
1393 %
1394 % Finally do the actual replacement after shaping. No checking for double processing here
1395 % since the operation is idempotent.
1396 % \begin{macrocode}
1397 local function process_softhyphen_post(head, _context, _dir)
1398 if softhyphenbool.mode ~= truebool.mode then return true end
1399 for disc, sub in node.traverse_id(DISC, head) do
1400 for n, ch, fid in node.traverse_glyph(disc.pre) do
1401 local props = properties[n]
1402 if softhyphen_fonts[fid] and ch == hyphen_char and props and props[is_soft_hyphen_prop] then
1403 if nodegetattribute(n,softhyphenattribute) then
1404 n.char = soft_hyphen_char
1405 props.glyph_info = nil
1406 else
1407 nodesetattribute(n,mctypeattributeid,-2147483647)
1408 nodesetattribute(n,mccntattributeid,-2147483647)
1409 end
1410 end
1411 end
1412 end
1413 return true
1414 end
1415
1416 luatexbase.add_to_callback('pre_shaping_filter', process_softhyphen_pre, 'tagpdf.rewrite-softhyphen')
1417 luatexbase.add_to_callback('post_shaping_filter', process_softhyphen_post, 'tagpdf.rewrite-softhyphen')
1418 end
1419 % \end{macrocode}
1420 % \end{macro}
1421 %
1422 % \section{parent-child rules}
1423 %
1424 % \begin{macro}{role_get_parent_child_rule,ltx.@@.func.role_get_parent_child_rule}
1425 % \begin{macrocode}
1426 local function role_get_parent_child_rule (parent,child)
1427 local state=
1428 ltx.@@.role.matrix[ltx.@@.role.index[parent]]
1429 and ltx.@@.role.matrix[ltx.@@.role.index[parent]][ltx.@@.role.index[child]] or 0
1430 return state
1431 end
1432 ltx.@@.func.role_get_parent_child_rule=role_get_parent_child_rule
1433 % \end{macrocode}
1434 % \end{macro}
1435 %
1436 % \begin{macro}{check_update_stashed,check_parent_child_rules,
1437 % ltx.@@.func.check_parent_child_rules}
1438 % These function allows to check the parent-child rules for
1439 % the current set of structures. It should normally be used
1440 % at the end of the document. Some stashed structures can
1441 % still have a parentrole setting containing the STASHED keyword,
1442 % there must be updated first, this is done with a helper command.
1443 % To avoid that a faulty structure (where e.g. two structures point to each other)
1444 % creates an endless loop we check for the real parent only for 10 loops.
1445 % \begin{macrocode}
1446 function check_update_stashed (struct,loglevel,loop)
1447 loop = (loop or 0) + 1
1448 if loop > 10 then
1449 @@_log ('Warning: Too deeply nested stashed structures',0)
1450 return
1451 end
1452 @@_log ('updating parentrole for stashed structure '..struct,loglevel)
1453 local parent = ltx.@@.tables['g_@@_struct_'..struct..'_prop']['parentnum']
1454 if parent then
1455 local ptag =
1456 string.match(ltx.@@.tables['g_@@_struct_'..parent..'_prop']['parentrole'], "{(.-)}{(.-)}")
1457 if ptag == 'STASHED' then
1458 -- look at the parent and update it first
1459 check_update_stashed (parent,loglevel,loop)
1460 end
1461 -- now copy the parent role from the parent
1462 ltx.@@.tables['g_@@_struct_'..struct..'_prop']['parentrole']
1463 =
1464 ltx.@@.tables['g_@@_struct_'..parent..'_prop']['parentrole']
1465 @@_log
1466 ('new parentrole: ' .. ltx.@@.tables['g_@@_struct_'..struct..'_prop']['parentrole'], loglevel)
1467 else
1468 @@_log ('Warning: structure '..struct.. 'has no parent.',0)
1469 end
1470 end
1471
1472 function check_parent_child_rules (loglevel)
1473 texio.write_nl('\n')
1474 @@_log ('checking parent-child rules ...' ,0)
1475 for i=2,ltx.tag.get_struct_counter() do
1476 local t,tNS=
1477 string.match(ltx.@@.tables['g_@@_struct_'..i..'_prop']['tag'], "{(.-)}{(.-)}")
1478 local r,rNS=
1479 string.match(ltx.@@.tables['g_@@_struct_'..i..'_prop']['rolemap'], "{(.-)}{(.-)}")
1480 local p,pNS=
1481 string.match(ltx.@@.tables['g_@@_struct_'..i..'_prop']['parentrole'], "{(.-)}{(.-)}")
1482 local parent=ltx.@@.tables['g_@@_struct_'..i..'_prop']['parentnum']
1483 if parent then
1484 @@_log (i..': '.. t..':'..tNS,loglevel)
1485 @@_log (i..': '.. r..':'..rNS,loglevel)
1486 @@_log (i..': '.. p..':'..pNS,loglevel)
1487 @@_log ('parent of ' ..i..': '.. parent,loglevel )
1488 if p == 'STASHED' then
1489 check_update_stashed (i,loglevel,0)
1490 p,pNS=
1491 string.match(ltx.@@.tables['g_@@_struct_'..i..'_prop']['parentrole'], "{(.-)}{(.-)}")
1492 end
1493 local pt,ptNS=
1494 string.match(ltx.@@.tables['g_@@_struct_'..parent..'_prop']['tag'], "{(.-)}{(.-)}")
1495 local pr,prNS=
1496 string.match(ltx.@@.tables['g_@@_struct_'..parent..'_prop']['rolemap'], "{(.-)}{(.-)}")
1497 local pp,ppNS=
1498 string.match(ltx.@@.tables['g_@@_struct_'..parent..'_prop']['parentrole'], "{(.-)}{(.-)}")
1499 if pp == 'STASHED' then
1500 check_update_stashed (parent,loglevel,0)
1501 pp,ppNS=
1502 string.match(ltx.@@.tables['g_@@_struct_'..parent..'_prop']['parentrole'], "{(.-)}{(.-)}")
1503 end
1504 @@_log (parent..': '.. pt..':'..ptNS,loglevel)
1505 @@_log (parent..': '.. pr..':'..prNS,loglevel)
1506 @@_log (parent..': '.. pp..':'..ppNS,loglevel)
1507 -- now check the rule.
1508 -- at first rolemap of child against rolemap of parent.
1509 local state=ltx.@@.func.role_get_parent_child_rule (pr,r)
1510 @@_log ('rule of '..pr.."->"..r..' is '..state,loglevel)
1511 -- if the state is 7 we check against parentrole of the parent
1512 if state == 7 then
1513 state=ltx.@@.func.role_get_parent_child_rule (pp,r)
1514 @@_log ('Parent-Child relation '..pp.."->"..r..' is '..state,loglevel)
1515 end
1516 if state == 0 then
1517 @@_log
1518 ('Warning: Parent-Child relation '
1519 ..ptNS..':'..pt..' -> '..tNS..':'..t..' is unknown',0)
1520 @@_log
1521 ('Structure ' ..parent..' -> '..i,0)
1522 end
1523 if state == -1 then
1524 @@_log
1525 ('Warning: Parent-Child relation '
1526 ..ptNS..':'..pt..' -> '..tNS..':'..t..' is not allowed',0)
1527 @@_log
1528 ('Structure ' ..parent..' -> '..i,0)
1529 end
1530 -- check also for MC
1531 state =ltx.__tag.func.role_get_parent_child_rule ( r ,'MC')
1532 local curtag=r
1533 if state == 7 then
1534 state =ltx.__tag.func.role_get_parent_child_rule ( p ,'MC')
1535 local curtag=p
1536 end
1537 if state == -1 then
1538 if ltx.__tag.struct[i] and NEXT(ltx.__tag.struct[i]) then
1539 @@_log
1540 ('Warning: Real content (MC) is not allowed in ' ..curtag,0)
1541 end
1542 end
1543 @@_log('=======================================',loglevel)
1544 end
1545 end -- end for
1546 end
1547
1548 ltx.@@.func.check_parent_child_rules=check_parent_child_rules
1549
1550 % \end{macrocode}
1551 % \end{macro}
1552 % \section{Link annotations}
1553 % If the linksplit code has been loaded we use it to add the OBJR of links to the
1554 % structure tree.
1555 % \begin{macrocode}
1556 local linkbincnt = 0
1557
1558 function ltx.__tag.func.linkbin()
1559 return linkbincnt
1560 end
1561
1562 if luatexbase.callbacktypes['linksplit'] then
1563 luatexbase.add_to_callback('linksplit', function(start_link, position)
1564 if start_link == nil then return end
1565 local structnum =
1566 node.get_attribute(start_link,luatexbase.attributes.g__tag_structnum_attr)
1567 if structnum and structnum > -1 then
1568 local s = ltx.__tag.tables['g__tag_struct_'..structnum..'_prop']['rolemap']
1569 if s and (string.find(s,'Link') or string.find(s,'Reference')) then
1570 local struct_insert_annot_shipout = token.create'__tag_struct_insert_annot_shipout:nnn'
1571 local parentnum = tex.count['c@g__tag_parenttree_obj_int']
1572 start_link.link_attr =
1573 start_link.link_attr ..
1574 ' /LTEX_position /' .. position ..
1575 '/StructParent ' .. parentnum
1576 tex.sprint(catlatex,struct_insert_annot_shipout,'{'..
1577 structnum..'}{'..
1578 start_link.objnum..' 0 R}{'..
1579 parentnum ..'}')
1580 -- the counter must be set explicitly as struct_insert_annot_shipout doesn't do it!
1581 tex.setcount('global','c@g__tag_parenttree_obj_int',parentnum +1)
1582 __tag_log(position .. " link part has object id " .. start_link.objnum .. " and structparent id " .. parentnum,2)
1583 else
1584 local linkbin = token.get_macro("c__tag_struct_link_bin_tl")
1585 if linkbin then
1586 local struct_insert_annot_shipout = token.create'__tag_struct_insert_annot_shipout:nnn'
1587 local parentnum = tex.count['c@g__tag_parenttree_obj_int']
1588 start_link.link_attr = string.gsub (start_link.link_attr, "/Contents%s+<%w+>","")
1589 start_link.link_attr =
1590 start_link.link_attr ..
1591 ' /LTEX_position /' .. position ..
1592 '/StructParent ' .. parentnum .. '/Contents (artifact)'
1593 tex.sprint(catlatex,struct_insert_annot_shipout,'{'..
1594 linkbin..'}{'..
1595 start_link.objnum..' 0 R}{'..
1596 parentnum ..'}')
1597 tex.setcount('global','c@g__tag_parenttree_obj_int',parentnum +1)
1598 linkbincnt=linkbincnt+1
1599 if linkbincnt == 1 then
1600 __tag_log('Info: some Link annotation(s) are not in Link or Reference structure elements',0)
1601 __tag_log(' moved into a container at the end of the structure tree\n',0)
1602 end
1603 else
1604 __tag_log('Warning: Link not in Link or Reference structure element',0)
1605 __tag_log('OBJR not created',0)
1606 __tag_log('',0)
1607 end
1608 end
1609 end
1610 end, 'tagpdf')
1611 end
1612 % \end{macrocode}
1613 % \begin{macrocode}
1614 %</lua>
1615 % \end{macrocode}
1616 % \end{implementation}
1617 % \PrintIndex