Debian Codegraph @

texmf-dist/tex/luatex/minim-pdf/minim-pdf.lua

raw
1
2 local M = { }
3 local alloc = require('minim-alloc')
4 local cb = require('minim-callbacks')
5 alloc.remember('minim-pdf')
6
7 -- 1 helper functions
8
9 local HLIST_NODE = node.id 'hlist'
10 local GLUE_NODE = node.id 'glue'
11 local GLYPH_NODE = node.id 'glyph'
12 local RULE_NODE = node.id 'rule'
13 local DISC_NODE = node.id 'disc'
14 local WHATSIT_NODE = node.id 'whatsit'
15 local USER_DEFINED = node.subtype 'user_defined'
16 local START_LINK = node.subtype 'pdf_start_link'
17
18 local function insert_formatted(t, ...)
19 table.insert(t, string.format(...))
20 end
21
22 local function add_to_catalog(...)
23 pdf.setcatalog((pdf.getcatalog() or '') .. string.format(...) .. ' ')
24 end
25
26 local function add_to_names(...)
27 pdf.setnames((pdf.getnames() or '') .. string.format(...) .. ' ')
28 end
29
30 local pdf_name = alloc.pdf_name
31 local pdf_string = alloc.pdf_string
32 local options_scanner = alloc.options_scanner
33
34 local function singleton(t)
35 local v = next(t)
36 v = v and not next(t, v)
37 return v and true or false
38 end
39
40 -- in-depth node list traversal; returns current and parent node
41 -- only dives into hbox, vbox and ins nodes, and in disc no-break text
42 -- returns node and enclosing box
43 local function full_traverse(head)
44 return function(stack, last)
45 local next = last.next
46 if not next then
47 next, stack.box = table.unpack(table.remove(stack))
48 else
49 while next.list do
50 table.insert(stack, { next, stack.box })
51 next, stack.box = next.list, next
52 end
53 end
54 return next, stack.box
55 end, { { } }, { next = head }
56 end
57
58 local function pdf_err(n, msg, ...)
59 local m = node.new('whatsit', 'pdf_literal')
60 m.mode, m.token = 2, '%% Warning: '..string.format(msg, ...)
61 node.insert_after(n, n, m)
62 end
63
64 -- 1 infrastructure and bookkeeping
65
66 local function tagging_enabled()
67 return tex.count['writedocumentstructure'] > 0
68 end
69
70 local function spaces_enabled()
71 return tex.count['writehyphensandspaces'] > 0
72 end
73
74 -- we start with the document at the top level
75 local structure = { {
76 index = 1,
77 struct = 'Document',
78 children = { },
79 level = 0, -- for debugging only
80 } }
81
82 -- the parent tree will be filled automatically and separately
83 local parent_tree = { } -- list of list of structure elements
84
85 -- Our four helper attributes
86 local current_struct = alloc.registernumber('tagging:current:se')
87 local current_order = alloc.registernumber('tagging:element:order')
88 local current_status = alloc.registernumber('tagging:current:status')
89 local current_lang = alloc.registernumber('tagging:current:language')
90
91 local function current_structure_element()
92 return structure[tex.attribute[current_struct]]
93 end
94
95 -- Marker whatsits
96 local marker_whatsit = alloc.new_whatsit('tagged pdf marker')
97
98 local function make_whatsit(t, se, order)
99 local n = node.new('whatsit', 'user_defined');
100 n.user_id, n.type = marker_whatsit, 108
101 n[current_struct] = se or tex.attribute['tagging:current:se']
102 n[current_order] = order or tex.attribute['tagging:element:order']
103 n.value = t
104 return n
105 end
106
107 alloc.luadef('tagging:mci:content', function()
108 node.write(make_whatsit{ what = 'content' })
109 end, 'protected')
110 alloc.luadef('tagging:mci:markstart', function()
111 node.write(make_whatsit{ what = 'mci_start' })
112 end, 'protected')
113 alloc.luadef('tagging:mci:markstop', function()
114 node.write(make_whatsit{ what = 'mci_stop' })
115 end, 'protected')
116 alloc.luadef('tagging:art:markstart', function()
117 node.write(make_whatsit{ what = 'art_start', it = token.scan_string() })
118 end, 'protected')
119 alloc.luadef('tagging:art:markstop', function()
120 node.write(make_whatsit{ what = 'art_stop' })
121 end, 'protected')
122
123 -- 1 structure type table and type aliases
124
125 local structure_types = alloc.saved_table('structure types', {
126 -- grouping types that may carry a bookmark
127 Document = { type = 'section' },
128 Part = { type = 'section' },
129 Art = { type = 'section' },
130 Sect = { type = 'section' },
131 Div = { type = 'group' },
132 -- grouping elements
133 BlockQuote = { type = 'group' },
134 Caption = { type = 'group' },
135 TOC = { type = 'group', contains = { TOC=1, TOCI=1, Caption=1 } },
136 TOCI = { contains = { Lbl=1, Reference=1, P=1, NonStruct=1, TOC=1 }, contained = { TOC=1 } },
137 Index = { type = 'group' },
138 NonStruct = { type = 'none' }, -- meaningless grouping
139 -- illustration elements
140 Figure = { type = 'inline', needsalt=1 },
141 Formula = { type = 'inline', needsalt=1 },
142 Form = { type = 'inline', needsalt=1 },
143 -- block level structure elements (BLSE)
144 P = { type = 'block' },
145 H = { type = 'block' },
146 H1 = { type = 'block' }, -- for nonhierarchical tagging (do not use)
147 H2 = { type = 'block' }, -- __________ „ __________
148 H3 = { type = 'block' }, -- __________ „ __________
149 H4 = { type = 'block' }, -- __________ „ __________
150 H5 = { type = 'block' }, -- __________ „ __________
151 H6 = { type = 'block' }, -- __________ „ __________
152 L = { type = 'block', contains = { LI=1, Caption=1 } },
153 LI = { contains = { Lbl=1, LBody=1 }, contained = { L=1 } },
154 LBody = { type = 'contain', contained = { LI=1 } },
155 Lbl = { type = 'block', contained = { Note=1, Bibentry=1, LI=1, TOCI=1 } },
156 -- tables (neither BLSE nor ILSE)
157 Table = { type = 'block', contains = { TR=1, THead=1, TBody=1, TFoot=1, Caption=1 } },
158 THead = { contains = { TR=1 }, contained = { Table=1 } },
159 TBody = { contains = { TR=1 }, contained = { Table=1 } },
160 TFoot = { contains = { TR=1 }, contained = { Table=1 } },
161 TR = { contains = { TH=1, TD=1 }, contained = { THead=1, TBody=1, TFoot=1 } },
162 TH = { type = 'contain', contained = { TR=1 } }, -- header cell
163 TD = { type = 'contain', contained = { TR=1 } }, -- data cell
164 -- inline structure elements ILSE
165 Span = { type = 'inline' },
166 Quote = { type = 'inline' },
167 Note = { type = 'extern' },
168 Reference = { type = 'inline' },
169 BibEntry = { type = 'inline' },
170 Code = { type = 'inline', attributes = { ['CSS-2.00'] = { ['white-space'] = '(pre)' } } },
171 Link = { type = 'inline' }, -- contains link objects
172 Annot = { type = 'inline' }, -- contains other annotations
173 -- ruby/warichu
174 Ruby = { type = 'inline', contains = { RB=1, RT=1, RP=1 } },
175 RB = { contains = { }, contained = { Ruby=1 } },
176 RT = { contains = { }, contained = { Ruby=1 } },
177 RP = { contains = { }, contained = { Ruby=1 } },
178 Warichu = { type = 'inline', contains = { WT=1, WP=1 } },
179 WT = { contains = { }, contained = { Warichu=1 } },
180 WP = { contains = { }, contained = { Warichu=1 } },
181 })
182
183 local structure_type_compatibility = {
184 none = { none=1, section=1, group=1, block=1, inline=1, contain=1 },
185 section = { none=1, section=1, group=1, block=1 },
186 group = { none=1, group=1, block=1 },
187 extern = { none=1, group=1, block=1 },
188 block = { none=1, inline=1, extern=1 },
189 inline = { none=1, inline=1, extern=1 },
190 contain = { none=1, inline=1, block=1, group=1, extern=1 },
191 }
192
193 local function check_structure_compatibility(parent, child, childtype)
194 local p, c = structure_types[parent], structure_types[child]
195 childtype = childtype or c.type
196 if p.contains then
197 return p.contains[child]
198 elseif c.contained then
199 return c.contained[parent]
200 elseif childtype == 'section' and parent == child then
201 return false
202 else
203 return structure_type_compatibility[p.type][childtype]
204 end
205 end
206
207 local function determine_parent_node(current, se)
208 local c = current
209 if tex.count['strictstructuretagging'] > 0 then
210 c = check_structure_compatibility(c.struct, se.struct, c.type) and c
211 else
212 while c and not check_structure_compatibility(c.struct, se.struct, c.type) do
213 c = c.parent
214 end
215 end
216 if not c then
217 if tagging_enabled() then
218 alloc.err('Structure type mismatch: %s in %s',
219 pdf_name(se.struct), pdf_name(current.struct))
220 else
221 alloc.msg('Warning (minim-pdf): Structure type mismatch (%s in %s)',
222 pdf_name(se.struct), pdf_name(current.struct))
223 end
224 end
225 return c or current
226 end
227
228 function M.add_structure_alias(stype, alias, settings)
229 local t, attr = { }, { }
230 local info = structure_types[stype] or
231 alloc.err('Unknown structure type ‘%s’', stype) and {}
232 for k, v in pairs(info) do t[k] = v end
233 for k,v in pairs(t.attributes or {}) do attr[k] = v end -- copy to new table
234 t.attributes = nil
235 for k, v in pairs(settings or {}) do t[k] = v end -- may re-set attributes
236 for k,v in pairs(t.attributes or {}) do attr[k] = v end
237 if #attr > 0 then t.attributes = attr end
238 for _, s in pairs(structure_types) do
239 if s.contains and s.contains[stype] then s.contains[alias] = 1 end
240 if s.contained and s.contained[stype] then s.contained[alias] = 1 end
241 end
242 t.aliasof, t.inuse = t.aliasof or stype, false
243 structure_types[alias] = t
244 end
245
246 alloc.luadef('struct:addalias', function()
247 local settings = load(token.scan_string())()
248 local stype = token.scan_string()
249 local alias = token.scan_string()
250 M.add_structure_alias(stype, alias, settings)
251 end, 'protected')
252
253 -- 1 writing the document structure
254
255 local function stable_sort_on_order_field(unsorted)
256 -- n.b. ‘unsorted’ is likely to closely resemble two concatenated
257 -- monotonously increasing lists.
258 local sorted, oldsorted = { unsorted[1] }
259 local i, next, c = 2, unsorted[2], nil
260 while next do
261 oldsorted, sorted = sorted, { }
262 for _, e in ipairs(oldsorted) do
263 c = e.order
264 while next and next.order < c do
265 table.insert(sorted, next);
266 i = i+1; next = unsorted[i]
267 end
268 table.insert(sorted, e);
269 end
270 while next and c <= next.order do
271 c = next.order
272 table.insert(sorted, next);
273 i = i+1; next = unsorted[i]
274 end
275 end
276 return sorted
277 end
278
279 local function format_K_array(se)
280 local res = { '[' }
281 for _, k in ipairs(stable_sort_on_order_field(se.children)) do
282 se.mainpage = se.mainpage or k.pageobj
283 if k.mcid then
284 if se.mainpage == k.pageobj then
285 insert_formatted(res, '%d', k.mcid)
286 else
287 insert_formatted(res, '<< /Type/MCR /Pg %d 0 R /MCID %d >>', k.pageobj, k.mcid)
288 end
289 elseif k.children then
290 insert_formatted(res, '%s 0 R', k.objnum)
291 else
292 if se.mainpage == k.pageobj then
293 insert_formatted(res, '<< /Type/OBJR /Obj %d 0 R >>', k.objnum)
294 else
295 insert_formatted(res, '<< /Type/OBJR /Obj %d 0 R /Pg %s 0 R >>', k.objnum, k.pageobj)
296 end
297 end
298 end
299 table.insert(res, ']')
300 return table.concat(res, ' ')
301 end
302
303 local function make_rolemap()
304 local aliases = { }
305 for k, v in pairs(structure_types) do
306 if v.aliasof and v.inuse and v.aliasof ~= k then
307 insert_formatted(aliases, '%s%s', pdf_name(k), pdf_name(v.aliasof))
308 end
309 end
310 if #aliases > 0 then
311 return '\n/RoleMap << ' .. table.concat(aliases,' ') .. ' >>'
312 end
313 return ''
314 end
315
316 local function make_attributes(t)
317 local res = { }
318 -- is there just one attribute?
319 local list = not singleton(t)
320 if list then table.insert(res, '[') end
321 for ao, ac in pairs(t) do
322 insert_formatted(res, '<< /O %s', pdf_name(ao))
323 for k,v in pairs(ac) do
324 insert_formatted(res, '%s %s', pdf_name(k), v)
325 end
326 table.insert(res, '>>')
327 end
328 if list then table.insert(res, ']') end
329 return table.concat(res, ' ')
330 end
331
332 local attribute_classes = alloc.saved_table('attribute classes')
333 local function make_classmap()
334 local classes = { }
335 for c, as in pairs(attribute_classes) do
336 insert_formatted(classes, '\n%s', pdf_name(c))
337 table.insert(classes, make_attributes(as))
338 end
339 if #classes > 0 then
340 return '\n/ClassMap << ' .. table.concat(classes, ' ') .. ' >>'
341 end
342 return ''
343 end
344
345 local id_tree = { }
346
347 local function write_structure_element(se)
348 local res = { '<<' }
349 insert_formatted(res, '/Type/StructElem /S%s /P %d 0 R', pdf_name(se.struct), se.parent.objnum)
350 if se.id then insert_formatted(res, '/ID %s', pdf_string(se.id)) end
351 if se.lang and se.lang ~= se.parent.lang then insert_formatted(res, '/Lang %s', pdf_string(se.lang)) end
352 if se.alt then insert_formatted(res, '/Alt %s', pdf_string(se.alt)) end
353 if se.actual then insert_formatted(res, '/ActualText %s', pdf_string(se.actual)) end
354 if se.title then insert_formatted(res, '/T %s', pdf_string(se.title)) end
355 if #se.children > 0 then insert_formatted(res, '\n/K %s', format_K_array(se)) end
356 if se.mainpage then insert_formatted(res, '/Pg %d 0 R', se.mainpage) end
357 if se.class then
358 table.insert(res, '/C')
359 if #se.class > 1 then table.insert(res, '[') end
360 for _, c in ipairs(se.class) do
361 insert_formatted(res, '%s', pdf_name(c))
362 end
363 if #se.class > 1 then table.insert(res, ']') end
364 end
365 if se.ref then
366 table.insert(res, '/Ref')
367 table.insert(res, '[')
368 for _, c in ipairs(se.ref) do
369 local onum = id_tree[c]
370 if onum then
371 insert_formatted(res, '%d 0 R', onum)
372 else
373 alloc.err('Invalid structure element ID: %s', c)
374 end
375 end
376 table.insert(res, ']')
377 end
378 if next(se.attributes or {}) then
379 table.insert(res, '/A')
380 table.insert(res, make_attributes(se.attributes))
381 end
382 if se.files then
383 table.insert(res, '/AF [')
384 for _, fs in ipairs(se.files) do
385 insert_formatted(res, '%d 0 R', fs)
386 end
387 table.insert(res, ']')
388 end
389 table.insert(res, '>>')
390 pdf.immediateobj(se.objnum, table.concat(res, ' '))
391 end
392
393 local function write_structure()
394 if #structure == 1 then return end
395 -- reserve object numbers, prepare for writing
396 local root_obj, parent_tree_obj, id_tree_obj =
397 pdf.reserveobj(), pdf.reserveobj(), pdf.reserveobj()
398 structure[1].parent = { objnum = root_obj }
399 for _, se in ipairs(structure) do
400 if not se.hidden then
401 se.objnum = pdf.reserveobj()
402 if se.id then
403 id_tree[se.id] = se.objnum
404 end
405 end
406 end
407 -- update the document catalog
408 if tex.count['pdfuaconformancelevel'] > 0 then
409 add_to_catalog('/MarkInfo << /Marked true /Suspects false >>')
410 else
411 add_to_catalog('/MarkInfo << /Marked true >>')
412 end
413 add_to_catalog('/StructTreeRoot %s 0 R', root_obj)
414 -- write the structure tree root
415 pdf.immediateobj(root_obj, string.format(
416 '<< /Type/StructTreeRoot /K %d 0 R /ParentTree %d 0 R /IDTree %d 0 R%s%s >>',
417 structure[1].objnum, parent_tree_obj, id_tree_obj, make_rolemap(), make_classmap()))
418 -- write structure elements
419 for _, se in ipairs(structure) do
420 if not se.hidden then
421 write_structure_element(se)
422 end
423 end
424 -- write the parent tree (a number tree)
425 local res = { '<< /Nums [' }
426 for i, parents in ipairs(parent_tree) do
427 -- i, parents = StructParents index + 1, list of structure elems
428 if type(parents) == 'number' then
429 table.insert(res, string.format('%d %d 0 R', i-1, structure[parents].objnum))
430 else
431 local entry = { }
432 insert_formatted(entry, '%d [', i-1)
433 for _, p in ipairs(parents) do
434 insert_formatted(entry, '%d 0 R', p.objnum)
435 end
436 table.insert(entry, ']')
437 table.insert(res, table.concat(entry, ' '))
438 end
439 end
440 table.insert(res, '] >>')
441 pdf.immediateobj(parent_tree_obj, table.concat(res, '\n'))
442 -- write the id tree (a name tree)
443 local ids = { }
444 for k, _ in pairs(id_tree) do
445 -- luatex uses the C locale,
446 table.insert(ids, k)
447 end
448 table.sort(ids)
449 res = { '<< /Names ['}
450 for _, id in ipairs(ids) do
451 insert_formatted(res, '%s %d 0 R', pdf_string(id), id_tree[id])
452 end
453 table.insert(res, '] >>')
454 pdf.immediateobj(id_tree_obj, table.concat(res, '\n'))
455 end
456
457 -- 1 languages
458
459 -- name|code ↦ nr & nr ↦ code
460 local language_codes = alloc.saved_table('language codes')
461
462 function M.set_language_code(name, code)
463 if not language_codes[code] then
464 table.insert(language_codes, code)
465 language_codes[code] = #language_codes
466 end
467 language_codes[name] = language_codes[code]
468 end
469
470 if not language_codes.sumerian then
471 local defaults = require('minim-languagecodes')
472 for name, code in pairs(defaults) do
473 M.set_language_code(name, code)
474 end
475 end
476
477 -- \setlanguagecode dutch nl_BE
478 alloc.luadef('setlanguagecode', function()
479 M.set_language_code(token.scan_string(), token.scan_string())
480 end, 'protected')
481
482 function M.get_language_code(name_or_code)
483 local nr = language_codes[name_or_code]
484 return nr and language_codes[nr] or name_or_code
485 end
486
487 function M.get_current_language_code()
488 return language_codes[tex.attribute['tagging:current:language']]
489 end
490
491 function M.set_document_language(code)
492 structure[1].lang = code
493 end
494
495 alloc.luadef('setdocumentlanguage', function()
496 M.set_document_language(M.get_language_code(token.scan_string()))
497 end, 'protected')
498
499 -- \uselanguage patch; provide default document language
500 -- and associate names with numbers
501 cb.register('uselanguage', function(name)
502 local nr = language_codes[name] or alloc.err('No language code known for ‘%s’', name) and 1
503 if not structure[1].lang then M.set_document_language(language_codes[nr]) end
504 tex.attribute['tagging:current:language'] = nr
505 end)
506
507 local function write_language()
508 add_to_catalog('/Lang %s', pdf_string(structure[1].lang or 'und'))
509 end
510
511 -- 1 marking structure elements
512
513 local function get_ancestor_of_type(se, stype)
514 while se and se.struct ~= stype do
515 se = se.parent
516 end
517 return se and se.parent
518 end
519
520 function M.close_structure_node(stype, raiseerror)
521 local strict = tex.count['strictstructuretagging'] > 0
522 local current = current_structure_element()
523 local open
524 if strict then
525 open = current.struct == stype and current.parent
526 else
527 open = get_ancestor_of_type(current, stype)
528 end
529 if open then
530 tex.setattribute(current_struct, open.index)
531 elseif strict then
532 alloc.err('Cannot close structure element %s: %s still open', stype, current.struct)
533 elseif raiseerror then
534 alloc.err('Cannot close structure element %s: no open tag found', stype)
535 end
536 end
537
538 alloc.luadef('tagging:stopelement', function()
539 M.close_structure_node(token.scan_string(), true)
540 end, 'protected')
541
542 alloc.luadef('tagging:ensurestopelement', function()
543 M.close_structure_node(token.scan_string(), false)
544 end, 'protected')
545
546 function M.open_structure_node(n)
547 -- retrieve defaults for the structure type
548 local info = structure_types[n.struct]
549 if not info then
550 alloc.err('Unknown structure type %s replaced with NonStruct', n.struct)
551 n.struct, info = 'NonStruct', structure_types.NonStruct
552 end
553 info.inuse = true
554 -- attributes: set default from se info
555 n.attributes = n.attr or { }; n.attr = nil
556 if info.attributes then
557 for o,kv in pairs(info.attributes) do
558 n.attributes[o] = n.attributes[o] or { }
559 for k, v in pairs(kv) do
560 n.attributes[o][k] = n.attributes[o][k] or v
561 end
562 end
563 end
564 -- bookkeeping: order and parent can be forced (needed for asynchronous elements)
565 n.index = #structure + 1
566 n.children = { }
567 n.order = n.order or tex.getattribute(current_order)
568 n.parent = (n.parent and structure[n.parent])
569 or determine_parent_node(current_structure_element(), n)
570 n.level = n.parent.level + 1
571 table.insert(structure, n)
572 -- determine the proper language code
573 if n.lang then
574 n.lang = M.get_language_code(n.lang)
575 else
576 local lang = tex.getattribute(current_lang)
577 n.lang = language_codes[lang]
578 end
579 -- hacks for out-of-sync elements
580 if not n.hidden then table.insert(n.parent.children, n) end
581 if not n.async then tex.setattribute(current_struct, #structure) end
582 end
583
584 alloc.luadef('tagging:startelement', function()
585 local s = options_scanner()
586 :string('id')
587 :string('ref', true)
588 :string('type') -- 'section', 'group', 'block' etc.
589 :argument('alt')
590 :argument('actual')
591 :argument('title')
592 :string('lang')
593 :subtable('attr')
594 :string('class', true)
595 :scan()
596 s.struct = token.scan_string()
597 M.open_structure_node(s)
598 end, 'protected')
599
600 alloc.luadef('tagging:alt', function()
601 current_structure_element().alt = token.scan_string()
602 end)
603
604 alloc.luadef('tagging:actual', function()
605 current_structure_element().actual = token.scan_string()
606 end)
607
608 local function add_attribute(se, o, k, v)
609 se.attributes = se.attributes or { }
610 se.attributes[o] = se.attributes[o] or { }
611 se.attributes[o][k] = v
612 end
613
614 alloc.luadef('tagging:attribute', function()
615 add_attribute(current_structure_element(),
616 token.scan_string(), token.scan_string(), token.scan_string())
617 end)
618
619 alloc.luadef('tagging:ignore:attribute', function()
620 -- if \tagging:enabled is false
621 token.scan_string()
622 token.scan_string()
623 token.scan_string()
624 end)
625
626 alloc.luadef('newattributeclass', function()
627 local s = options_scanner():subtable('attr')
628 attribute_classes[token.scan_string()] = s:scan().attr
629 end, 'protected')
630
631 alloc.luadef('tagging:tagid', function()
632 current_structure_element().id = token.scan_string()
633 end)
634
635 alloc.luadef('tagging:getshowstructure', function()
636 local e, lst = current_structure_element(), { string.format ('%d',
637 tex.attribute[current_struct]) }
638 while e do
639 table.insert(lst, string.format('%s (%d)', e.struct, e.index))
640 e = e.parent
641 end
642 tex.toks['tagging:showtoks'] = table.concat(lst, ' < ')
643 end, 'protected')
644
645 -- 1 marking content items
646
647 -- All content items should be explicitly opened and closed, per page, by the
648 -- late_lua nodes constructed beneath. After the page is finished, the MCIDs
649 -- will be stored in the parent tree entry associated to the page.
650
651 -- For the insertion of these late_lua nodes, see the next section; this one
652 -- only deals with the bookkeeping mechanics.
653
654 -- Note that we do not nest artifacts within marked content items. This would
655 -- be allowed by the spec, but confuses some pdf readers (e.g. poppler).
656
657 local mcid_list, pageobj
658
659 local function clear_page_tagging_parameters()
660 mcid_list, pageobj = { }, nil
661 _open_mci_node_ = function (se_num, order) --luacheck: ignore 111
662 pageobj = pageobj or pdf.getpageref(status.total_pages + 1)
663 local se = structure[se_num]
664 pdf.print(string.format('%s <</MCID %d>> BDC ', pdf_name(se.struct), #mcid_list))
665 table.insert(se.children, { mcid = #mcid_list, order = order, pageobj = pageobj })
666 table.insert(mcid_list, se)
667 -- unhide hidden parents (done here to preserve the correct order)
668 if se.hidden then
669 table.insert(se.parent.children, se)
670 se.hidden = false
671 end
672 end
673 end
674 clear_page_tagging_parameters()
675
676 local function new_open_mci_node(se, order)
677 local n = node.new('whatsit', 'late_lua')
678 n.token = string.format('_open_mci_node_(%d, %d)', se, order)
679 return n
680 end
681
682 local function pdf_literal(token)
683 local n = node.new('whatsit', 'pdf_literal')
684 n.mode, n.token = 1, token
685 return n
686 end
687
688 local open_artifacts = { }
689
690 cb.register('finish_pdfpage', function(shippingout)
691 if shippingout then
692 local pageattr = string.gsub(pdf.getpageattributes() or '', ' */StructParents %d+', '' )
693 if #mcid_list > 0 then
694 pageattr = pageattr..string.format('/StructParents %d', #parent_tree)
695 table.insert(parent_tree, mcid_list)
696 end
697 pdf.setpageattributes(pageattr)
698 clear_page_tagging_parameters()
699 end
700 end)
701
702 -- 1 content item boundaries and linking (in pre-shipout)
703
704 function M.mark_content_items(box)
705 local se, order, art, open
706 local start_node, end_node, parent_node
707 local lastpageobj = pdf.getpageref(status.total_pages + 1)
708 -- helper functions for inserting mci markers
709 local insert_tags = function(end_parent)
710 if not open then return end
711 parent_node.list = node.insert_before(parent_node.list, start_node, open)
712 node.insert_after(end_parent.list, end_node, pdf_literal('EMC'))
713 start_node, end_node, parent_node, open = nil, nil, nil, nil
714 end
715 local start_content = function(n, b)
716 se, order = n[current_struct], n[current_order]
717 start_node, end_node, parent_node = n, n, b
718 end
719 -- traversing all nodes
720 for n, b in full_traverse(box) do
721 local marker = n.id == WHATSIT_NODE and n.subtype == USER_DEFINED
722 and n.user_id == marker_whatsit and n.value
723 local stat = n[current_status]
724 -- first we start with marking artifacts
725 if marker and marker.what == 'art_start' then
726 insert_tags(b)
727 start_content(n, b)
728 local a = string.format('/Artifact << /Type/%s >> BDC', marker.it)
729 open_artifacts[stat], open, art = a, pdf_literal(a), stat
730 elseif marker and marker.what == 'art_stop' then
731 end_node = n
732 insert_tags(b)
733 if art then open_artifacts[art], art = nil, nil end
734 elseif stat and stat >10 and stat ~=art then -- broken artifact
735 insert_tags(b);
736 start_content(n, b)
737 local a = open_artifacts[stat]
738 if not a then
739 alloc.err('Encountered tail of unknown artifact (see pdf)')
740 pdf_err(n, 'unknown artifact nr. %d (this should not be possible)', stat)
741 a = '/Artifact << /Type/Unknown >> BDC'
742 end
743 open, art = pdf_literal(a), stat
744 elseif stat then -- inside artifact or tagging disabled
745 end_node = n
746 -- then attach links to Link elements
747 elseif n.id == WHATSIT_NODE and n.subtype == START_LINK then
748 local _se, _order = n[current_struct], n[current_order]
749 local link = structure[_se]
750 if link.struct == 'Link' then
751 table.insert(link.children, { objnum = n.objnum, order = _order, lastpageobj = lastpageobj })
752 n.link_attr = string.format('%s /StructParent %d', n.link_attr, #parent_tree)
753 table.insert(parent_tree, _se)
754 else
755 alloc.err('Link found outside Link structure element (see pdf)')
756 pdf_err(n, 'unmarked link')
757 end
758 -- handle explicit start and stop nodes
759 elseif marker and marker.what == 'mci_start' then
760 insert_tags(b);
761 start_content(n, b)
762 open = new_open_mci_node(se, order)
763 elseif marker and marker.what == 'mci_stop' then
764 end_node = end_node and n; insert_tags(b)
765 -- finally, see if we need to intervene between content nodes
766 elseif n.id == RULE_NODE or n.id == GLYPH_NODE or n.id == DISC_NODE
767 or marker and marker.what == 'content' then
768 local _se, _order = n[current_struct], n[current_order]
769 if n.id == RULE_NODE and (n.width == 0 or n.height == 0 and n.depth == 0) then
770 -- ignore invisible rules
771 elseif not _se or not _order then
772 -- unmarkable content should not be possible (but is)
773 alloc.err('Unmarkable content on page %d (see pdf)', status.total_pages + 1)
774 pdf_err(n, 'possible unmarked content')
775 elseif se ~= _se or order ~= _order or not end_node then
776 -- new content item on changing attributes
777 insert_tags(b);
778 start_content(n, b)
779 open = new_open_mci_node(se, order)
780 else -- nothing changed: continue current mci
781 end_node = n
782 end
783 elseif n.id == GLUE_NODE and n.subtype > 2 and n.subtype < 8 then
784 -- parskip or displayskip always closes mci
785 insert_tags(b)
786 end
787 end
788 -- close the last mci
789 insert_tags(box)
790 end
791
792 cb.register('pre_shipout', function(nr)
793 if tagging_enabled() then
794 M.mark_content_items(tex.box[nr])
795 end
796 end)
797
798 -- 1 links and destinations
799
800 local dest_count = alloc.new_count('link dest count')
801 local function new_dest_name()
802 local dest_nr = tex.count[dest_count] + 1
803 tex.setcount('global', dest_count, dest_nr)
804 return 'hyper:dest:'..dest_nr
805 end
806
807 local function last_dest_name()
808 return 'hyper:dest:'..tex.count[dest_count]
809 end
810
811 local function write_new_dest()
812 local name = new_dest_name()
813 tex.sprint(string.format('\\nameddestination{%s}', name))
814 return name
815 end
816
817 -- make available as \newdestinationname, \lastdestinationname
818 alloc.luadef('newdestinationname', function() tex.sprint(new_dest_name()) end)
819 alloc.luadef('lastdestinationname', function() tex.sprint(last_dest_name()) end)
820
821 -- provide the arguments to \pdfextension startlink
822 local link_types = { }
823 local function make_link_attr(s)
824 local attr = { 'attr {\\csname minim:linkattr\\endcsname' }
825 if s.attr then table.insert(attr, s.attr) end
826 if s.alt or s.contents then insert_formatted(attr, '/Contents %s', pdf_string(s.alt or s.contents)) end
827 table.insert(attr, '}')
828 return attr
829 end
830 alloc.luadef('hyper:makelink', function()
831 local s = options_scanner()
832 :argument('alt'):argument('contents') -- same thing
833 :argument('attr')
834 :scan()
835 local type = token.scan_word()
836 local userf = link_types[type]
837 if not userf then
838 alloc.err('Unknown hyperlink type: %s', type)
839 userf = link_types.first
840 end
841 local user = userf()
842 local attr = make_link_attr(s)
843 tex.sprint(table.concat(attr, ' '))
844 tex.sprint('user {')
845 tex.write(user)
846 tex.sprint('}\\ignorespaces')
847 end)
848
849 local function scan_escaped_argument(chars_to_escape)
850 local stored = { }
851 for _, char in utf8.codes(chars_to_escape) do
852 stored[char] = tex.getcatcode(char)
853 tex.setcatcode(char, 12)
854 end
855 local res = token.scan_argument()
856 for char, code in pairs(stored) do
857 tex.setcatcode(char, code)
858 end
859 return res
860 end
861
862 function link_types.dest()
863 return string.format('/Subtype/Link /A <</S/GoTo /D %s>>', pdf_string(token.scan_argument()))
864 end
865 function link_types.url()
866 local url = scan_escaped_argument ('~#$%^&_')
867 return string.format('/Subtype/Link /A <</S/URI /URI %s>>', pdf_string(url))
868 end
869
870 function link_types.user() return token.scan_argument() end
871 function link_types.next() return '/Subtype/Link /A <</S/Named /N/NextPage>>' end
872 function link_types.prev() return '/Subtype/Link /A <</S/Named /N/PrevPage>>' end
873 function link_types.first() return '/Subtype/Link /A <</S/Named /N/FirstPage>>' end
874 function link_types.last() return '/Subtype/Link /A <</S/Named /N/LastPage>>' end
875
876 -- 1 bookmarks (outlines)
877
878 -- start with a dummy top-level bookmark
879 local bookmarks = { { count = 0, level = 0 } }
880 structure[1].bookmark = bookmarks[1]
881
882 local function write_bookmarks()
883 if #bookmarks == 1 then return end
884 -- reserve objects in a row
885 for i=1, #bookmarks do
886 bookmarks[i].outline_obj = pdf.reserveobj()
887 end
888 -- write outlines object
889 add_to_catalog('/Outlines %s 0 R', bookmarks[1].outline_obj)
890 pdf.immediateobj(bookmarks[1].outline_obj, string.format(
891 ' <</Type /Outlines /First %s 0 R /Last %s 0 R /Count %s >> ',
892 bookmarks[2].outline_obj, bookmarks[1].last.outline_obj, #bookmarks - 1))
893 -- write bookmark objects
894 for i=2, #bookmarks do -- skip the root (i=1)
895 local bm, res = bookmarks[i], { }
896 insert_formatted(res, '<< /Title %s\n/Parent %s 0 R /Dest %s', pdf_string(bm.title),
897 bm.parent and bm.parent.outline_obj or bookmarks[1].outline_obj, pdf_string(bm.dest))
898 if bm.next then insert_formatted(res, '/Next %s 0 R', bm.next.outline_obj) end
899 if bm.prev then insert_formatted(res, '/Prev %s 0 R', bm.prev.outline_obj) end
900 if bm.struct and bm.struct.objnum then -- false if no structures are written out
901 insert_formatted(res, '/SE %s 0 R', bm.struct.objnum)
902 end
903 if bm.count > 0 then
904 insert_formatted(res, '/First %s 0 R /Last %s 0 R /Count %s%s',
905 bm.first.outline_obj, bm.last.outline_obj, bm.open and '' or '-', bm.count)
906 end
907 pdf.immediateobj(bm.outline_obj, table.concat(res,'\n')..' >>')
908 end
909 end
910
911 function M.add_bookmark(bm)
912 local pbm
913 if bm.level then
914 for i = #bookmarks, 1, -1 do
915 pbm = bookmarks[i]
916 if pbm.level < bm.level then
917 break
918 end
919 end
920 else
921 local se = current_structure_element()
922 if se.bookmark then
923 return alloc.err('Structure element %s already has a bookmark', pdf_name(se.struct))
924 end
925 se.bookmark, bm.struct = bm, se
926 -- derive parent from strucrure
927 pbm = se.parent
928 while not pbm.bookmark do
929 pbm = pbm.parent
930 end
931 pbm = pbm.bookmark
932 end
933 -- initial values; links to other bookmarks
934 bm.parent, bm.count = false, 0
935 bm.dest = bm.dest or write_new_dest()
936 if pbm.last then pbm.last.next = bm end
937 bm.parent, bm.prev = pbm, pbm.last
938 pbm.first, pbm.last = pbm.first or bm, bm
939 bm.level = bm.level or (pbm.level + 1)
940 -- update the count until the first closed bookmarks
941 repeat
942 pbm.count = pbm.count + 1
943 pbm = pbm.open and pbm.parent
944 until not pbm
945 -- append to the list
946 table.insert(bookmarks, bm)
947 end
948
949 alloc.luadef('outline', function()
950 local bm = options_scanner()
951 :keyword('open', 'closed')
952 :string('dest')
953 :int('level')
954 :scan()
955 bm.title = token.scan_string()
956 M.add_bookmark(bm)
957 end, 'protected')
958
959
960 -- 1 associated files
961
962 local attached_files = { }
963 local function write_fileattachments()
964 if #attached_files > 0 then
965 table.sort(attached_files, function(a,b) return a.name < b.name end)
966 local afs = { '/AF [' }
967 local nms = { '<< /Names [' }
968 for _, t in ipairs(attached_files) do
969 insert_formatted(afs, '%d 0 R', t.objnum)
970 insert_formatted(nms, '%s %d 0 R', t.name, t.objnum)
971 end
972 table.insert(afs, ']')
973 table.insert(nms, '] >>')
974 add_to_catalog(table.concat(afs, ' '))
975 local efs = pdf.immediateobj(table.concat(nms, ' '))
976 add_to_names('/EmbeddedFiles %d 0 R', efs)
977 end
978 end
979
980 function M.embed_file(t)
981 -- default moddate
982 if not t.moddate then
983 tex.runtoks(function() tex.print('\\csname minim:makedefaultmoddate\\endcsname') end)
984 local moddate = tex.toks['embeddedfiles:moddate']
985 if moddate ~= '' then t.moddate = moddate end
986 end
987 -- embed the file
988 local attr = { '/Type/EmbeddedFile' }
989 if t.mimetype then insert_formatted(attr, '/Subtype%s', pdf_name(t.mimetype)) end
990 if t.moddate then insert_formatted(attr, '/Params << /ModDate %s >>', alloc.pdf_date(t.moddate)) end
991 local ef = pdf.obj {
992 immediate = true,
993 compresslevel = t.uncompressed and 0 or nil,
994 type = 'stream',
995 file = t.file and kpse.find_file(t.file),
996 string = t.string,
997 attr = table.concat(attr, ' ') }
998 -- write the filespec
999 local res = { '<< /Type/Filespec' }
1000 insert_formatted(res, '/F %s /UF %s /EF << /F %d 0 R /UF %d 0 R >>', t.name, t.name, ef, ef)
1001 if t.desc then insert_formatted(res, '/Desc %s', pdf_string(t.desc)) end
1002 if t.relation then insert_formatted(res, '/AFRelationship /%s', t.relation) end
1003 table.insert(res, '>>')
1004 local fs = pdf.immediateobj(table.concat(res, ' '))
1005 -- (globally) attach the file
1006 return fs, ef
1007 end
1008
1009 alloc.luadef('embedfile', function()
1010 local t = options_scanner()
1011 :string('desc')
1012 :string('file')
1013 :string('string')
1014 :string('mimetype')
1015 :string('moddate')
1016 :string('relation')
1017 :string('name')
1018 :keyword('global')
1019 :keyword('uncompressed')
1020 :scan()
1021 if not t.name then
1022 t.name = t.file or alloc.err('No name specified for embedded file stream')
1023 end
1024 t.name = pdf_string(t.name or '(unnamed)')
1025 local fs, _ = M.embed_file(t, t.global)
1026 -- where to attach?
1027 if t.global then
1028 table.insert(attached_files, { name = t.name, objnum = fs } )
1029 elseif tagging_enabled() then
1030 local se = current_structure_element()
1031 se.files = se.files or { }
1032 table.insert(se.files, fs)
1033 else
1034 alloc.err('In untagged pdf, \\embedfile must be used with ‘global’ keyword')
1035 table.insert(attached_files, { name = t.name, objnum = fs } )
1036 end
1037 end, 'protected')
1038
1039
1040 -- 1 hyphenation
1041
1042 function M.mark_discretionaries(head, gc)
1043 if not spaces_enabled() then return end
1044 for disc in node.traverse_id(DISC_NODE, head) do
1045 if disc.subtype ~= 2 then -- ‘automatic’ (exclude explicit hyphens)
1046 local pre, post, replace = disc.pre, disc.post, disc.replace
1047 local se, order = disc[current_struct], disc[current_order]
1048 -- get the replacement text
1049 local actual = { }
1050 for c in node.traverse_id(GLYPH_NODE, replace) do
1051 table.insert(actual, c.char)
1052 end
1053 -- special case: a single hyphen
1054 if #actual == 0 and pre and pre.char and pre.char == 0x2D then
1055 actual = '­' -- soft hyphen U+00AD
1056 elseif #actual > 0 then
1057 actual = utf8.char(table.unpack(actual))
1058 else
1059 goto continue
1060 end
1061 -- reserve a structure element (but hide it)
1062 M.open_structure_node { hidden = true, async = true,
1063 struct = 'Span', parent = se, order = order, actual = actual }
1064 -- apply the new se to pre and post
1065 for n, _ in full_traverse(pre) do n[current_struct] = #structure end
1066 for n, _ in full_traverse(post) do n[current_struct] = #structure end
1067 end
1068 ::continue::
1069 end
1070 return true
1071 end
1072
1073 cb.register('pre_linebreak_filter', M.mark_discretionaries)
1074
1075 -- 1 spaces
1076
1077 local space_attr = alloc.new_attribute('space insertion marker')
1078
1079 function M.mark_spaces(head, gc)
1080 if not spaces_enabled() then return end
1081 for g in node.traverse_id(GLUE_NODE, head) do
1082 if g.prev and g.subtype == 13 or g.subtype == 14 then -- (x)spaceskip
1083 local p = g.prev
1084 p[space_attr] = p.id == GLYPH_NODE and p.font
1085 or g.next and g.next.id == GLYPH_NODE and g.next.font
1086 or font.current()
1087 end
1088 end
1089 return true
1090 end
1091
1092 local function create_space(n)
1093 local s = node.new('glyph')
1094 s.char, s.font, s.attr = 0x20, n[space_attr], n.attr
1095 local b = node.hpack(s)
1096 b.width, b.height, b.depth = 0, 0, 0
1097 return b
1098 end
1099
1100 local function insert_spaces(head)
1101 for n in node.traverse(head) do
1102 if n[space_attr] then
1103 node.insert_after(head, n, create_space(n))
1104 end
1105 end
1106 end
1107
1108 function M.insert_spaces(head, gc)
1109 if not spaces_enabled() then return end
1110 for line in node.traverse_id(HLIST_NODE, head) do
1111 insert_spaces(line.head)
1112 end
1113 return true
1114 end
1115
1116 function M.mark_and_insert_spaces(head, gc, ...)
1117 if not spaces_enabled() then return end
1118 M.mark_spaces(head, gc)
1119 insert_spaces(head)
1120 return true
1121 end
1122
1123 cb.register('pre_linebreak_filter', M.mark_spaces)
1124 cb.register('post_linebreak_filter', M.insert_spaces)
1125 cb.register('hpack_filter', M.mark_and_insert_spaces)
1126
1127 -- 1 page labels
1128
1129 local pagelabels = { }
1130
1131 function M.page_labels(abs_nr, nr, style, prefix)
1132 table.insert(pagelabels, { start = abs_nr, st = nr, s = style, p = prefix })
1133 end
1134
1135 local pagelabel_styles = {
1136 Decimal = 'D',
1137 Roman = 'R',
1138 roman = 'r',
1139 Alphabetic = 'A',
1140 alphabetic = 'a',
1141 none = false }
1142
1143 alloc.luadef('setpagelabels', function()
1144 local prefix = token.scan_keyword('prefix') and token.scan_string()
1145 local style = token.scan_word()
1146 local nr = token.scan_int()
1147 local st = pagelabel_styles[style]
1148 if st == nil then alloc.err('Unknown page label style »%s«', style) end
1149 M.page_labels(status.total_pages, nr, st, prefix)
1150 end, 'protected')
1151
1152 local function write_pagelabels()
1153 if #pagelabels == 0 then return end
1154 if pagelabels[1].start ~= 0 then
1155 table.insert(pagelabels, 1, { start = 0, st = 1, s = 'D' })
1156 end
1157 local res = { '/PageLabels << /Nums [' }
1158 for _, l in ipairs(pagelabels) do
1159 local s, p = l.s and '/S/'..l.s, l.p and ' /P '..pdf_string(l.p)
1160 table.insert(res, string.format('%d << /St %d %s%s >>', l.start, l.st, s or '', p or ''))
1161 end
1162 table.insert(res, '] >>')
1163 add_to_catalog(table.concat(res, ' '))
1164 end
1165
1166 -- 1 output intents
1167
1168 local output_intents = { }
1169
1170 function M.add_output_intent(t)
1171 table.insert(output_intents, t)
1172 end
1173
1174 local function write_output_intents()
1175 if #output_intents == 0 then return end
1176 local res = { '[' }
1177 for _, oi in ipairs(output_intents) do
1178 local p = pdf.obj { type = 'stream',
1179 file = kpse.find_file(oi.path),
1180 compresslevel = 9,
1181 attr = string.format('/N %d', oi.N),
1182 immediate = true }
1183 insert_formatted(res, '<< /Type/OutputIntent /DestOutputProfile %d 0 R', p)
1184 insert_formatted(res, '/S/%s /OutputConditionIdentifier %s', oi.subtype, pdf_string(oi.id))
1185 if oi.info then insert_formatted(res, '/Info %s', pdf_string(oi.info)) end
1186 if oi.condition then insert_formatted(res, '/OutputCondition %s', pdf_string(oi.condition)) end
1187 if oi.registry then insert_formatted(res, '/RegistryName %s', pdf_string(oi.registry)) end
1188 table.insert(res, '>>')
1189 end
1190 table.insert(res, ']')
1191 local objnum = pdf.immediateobj(table.concat(res, ' '))
1192 add_to_catalog('/OutputIntents %d 0 R', objnum)
1193 end
1194
1195 function M.add_default_rgb_output_intent(t)
1196 t = t or {}
1197 M.add_output_intent {
1198 subtype = t.subtype or 'GTS_PDFA1',
1199 info = t.info or 'IEC 61966-2.1 Default RGB colour space - sRGB',
1200 condition = t.condition,
1201 registry = 'http://www.iev.ch',
1202 id = 'IEC sRGB',
1203 N = 3, path = 'sRGB.icc' }
1204 end
1205
1206 function M.add_default_cmyk_output_intent(t)
1207 t = t or {}
1208 M.add_output_intent {
1209 subtype = t.subtype or 'GTS_PDFA1',
1210 info = t.info or 'FOGRA39L Coated',
1211 condition = t.condition or 'FOGRA39L Coated',
1212 registry = 'http://www.fogra.org',
1213 id = 'Offset printing, according to ISO 12647-2:2004/Amd 1, OFCOM, paper type 1 or 2 = coated art, 115 g/m2, tone value increase curves A (CMY) and B (K)',
1214 N = 4, path = 'FOGRA39L_coated.icc' }
1215 end
1216
1217 alloc.luadef('minim:default:rgb:profile', function() M.add_default_rgb_output_intent() end)
1218 alloc.luadef('minim:default:cmyk:profile', function() M.add_default_cmyk_output_intent() end)
1219
1220 -- 1 pdf/ua
1221
1222 alloc.luadef('tagging:enablepdfua', function()
1223 add_to_catalog('/ViewerPreferences << /DisplayDocTitle true >>')
1224 local pageattr = pdf.getpageattributes()
1225 if pageattr then
1226 pdf.setpageattributes(pageattr .. ' /Tabs /S')
1227 else
1228 pdf.setpageattributes('/Tabs /S')
1229 end
1230 end)
1231
1232 local function perform_pdfua_checks()
1233 local xmp = require 'minim-xmp'
1234 if xmp.get_metadata('dc:title') == '' then
1235 alloc.err('PDF/UA error: no dc:title metadata')
1236 end
1237 end
1238
1239 --
1240
1241 cb.register('finish_pdffile', function()
1242 if tex.count['pdfuaconformancelevel'] > 0 then
1243 perform_pdfua_checks()
1244 end
1245 if tagging_enabled() then
1246 write_language()
1247 write_structure()
1248 end
1249 write_bookmarks()
1250 write_pagelabels()
1251 write_output_intents()
1252 write_fileattachments()
1253 end)
1254
1255 return M
1256