summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/tex/context/base/mkxl/lpdf-tag.lmt
blob: 3cb3f44a0a31043cecb0e752075fd7b4722dc46f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
if not modules then modules = { } end modules ['lpdf-tag'] = {
    version   = 1.001,
    comment   = "companion to lpdf-tag.mkiv",
    author    = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
    copyright = "PRAGMA ADE / ConTeXt Development Team",
    license   = "see context related readme files"
}

local next, type = next, type
local format, match, gmatch, find = string.format, string.match, string.gmatch, string.find
local concat, sortedhash = table.concat, table.sortedhash
local lpegmatch, P, S, C = lpeg.match, lpeg.P, lpeg.S, lpeg.C
local settings_to_hash = utilities.parsers.settings_to_hash
local formatters = string.formatters

local trace_tags = false  trackers.register("structures.tags",      function(v)
    trace_tags = v
end)
local trace_info = false  trackers.register("structures.tags.info", function(v)
    trace_info = v
end)
local trace_math = false  trackers.register("structures.tags.math", function(v)
    trace_math = v
    attributes.viewerlayers.enable() -- somehow has to happen
end)

local report_tags = logs.reporter("backend","tags")

local pdfbackend          = backends.registered.pdf
local nodeinjections      = pdfbackend.nodeinjections
local codeinjections      = pdfbackend.codeinjections

local enableaction        = nodes.tasks.enableaction
local disableaction       = nodes.tasks.disableaction

local lpdf                = lpdf
local pdfdictionary       = lpdf.dictionary
local pdfarray            = lpdf.array
local pdfboolean          = lpdf.boolean
local pdfconstant         = lpdf.constant
local pdfreference        = lpdf.reference
local pdfunicode          = lpdf.unicode
local pdfmakenametree     = lpdf.makenametree

local addtocatalog        = lpdf.addtocatalog
local addtopageattributes = lpdf.addtopageattributes

local pdfflushobject      = lpdf.flushobject
local pdfreserveobject    = lpdf.reserveobject
local pdfpagereference    = lpdf.pagereference

local texgetcount         = tex.getcount

local nodes               = nodes
local nodecodes           = nodes.nodecodes

local hlist_code          <const> = nodecodes.hlist
local vlist_code          <const> = nodecodes.vlist
local glyph_code          <const> = nodecodes.glyph

local a_tagged            <const> = attributes.private('tagged')
local a_image             <const> = attributes.private('image')
local a_mathblob          <const> = attributes.private('mathblob')

local nuts                = nodes.nuts

local nodepool            = nuts.pool
local setstate            = nodepool.setstate
local register            = nodepool.register

local getid               = nuts.getid
local getattr             = nuts.getattr
local getattrs            = nuts.getattrs
local getprev             = nuts.getprev
local getnext             = nuts.getnext
local getlist             = nuts.getlist
local getchar             = nuts.getchar

local tailoflist          = nuts.tail
local setlink             = nuts.setlink
local setlist             = nuts.setlist

local copy_node           = nuts.copy
local tosequence          = nuts.tosequence

local nextnode            = nuts.traversers.node

local structure_kids   -- delayed
local structure_ref    -- delayed
local parent_ref       -- delayed
local root             -- delayed
local names               = { }
local tree                = { }
local firstintree         = false
local lastintree          = false
local elements            = { }

local structurestags      = structures.tags
local taglist             = structurestags.taglist
local specifications      = structurestags.specifications
local usedlabels          = structurestags.labels
local properties          = structurestags.properties
local usewithcare         = structurestags.usewithcare

local usedmapping         = { }

----- tagsplitter         = structurestags.patterns.splitter

local embeddedtags        = false -- true will id all, for tracing, otherwise table
local f_tagid             = formatters["%s-%04X"]      -- todo: auto adapt to nofblobs
local f_tagfn             = formatters["%s-%04X.xml"]
local embeddedfilelist    = pdfarray() -- /AF crap

-- for testing, not that it was ever used:

directives.register("structures.tags.embed",function(v)
    if type(v) == "string" then
        if type(embeddedtags) ~= "table" then
            embeddedtags = { }
        end
        for s in gmatch(v,"([^, ]+)") do
            embeddedtags[s] = true
        end
    elseif v and not embeddedtags then
        embeddedtags = true
    end
end)

-- for old times sake, not that it was ever used:

directives.register("structures.tags.embedmath",function(v)
    if not v then
        -- only enable
    elseif embeddedtags == true then
        -- already all tagged
    elseif embeddedtags then
        embeddedtags.math = true
    else
        embeddedtags = { math = true }
    end
end)

function codeinjections.maptag(original,target,kind)
    mapping[original] = { target, kind or "inline" }
end

-- mostly the same as the annotations tree

local usenamespace = false  experiments.register("structures.tags.namespaces", function(v) usenamespace = v end)

local namespaceurls = {
    mathml = "http://www.w3.org/1998/Math/MathML",
}

local function finishstructure()
    if root and #structure_kids > 0 then
        local nums   = pdfarray()
        local n      = 0
        for i=firstintree,lastintree do
            local ti = tree[i]
            if ti then
                n = n + 1 ; nums[n] = i - 1
                n = n + 1 ; nums[n] = pdfreference(pdfflushobject(ti))
            else
                report_tags("beware: missing page %i in tree", i)
            end
        end
        local parenttree = pdfdictionary {
            Nums = nums
        }
        local idtree = pdfmakenametree(names)
        --
        local rolemaps = usenamespace and { }
        local rolemap  = pdfdictionary() -- main one
        for k, v in next, usedmapping do
            local k = usedlabels[k] or k
            local p = properties[k]
            if not p then
                report_tags("beware: missing property %s", k)
            end
            local n = p and p.namespace
            if rolemaps and n then
                local r = rolemaps[n]
                if not r then
                    r = pdfdictionary()
                    rolemaps[n] = r
                end
                r[k] = pdfconstant(k) -- maybe other tag
            else
                rolemap[k] = pdfconstant(p and p.pdf or "Span") -- or "Div"
            end
        end
        local namespaces = rolemaps and next(rolemaps) and pdfarray { } or nil
        if namespaces then
            for k, v in table.sortedhash(rolemaps) do
                namespaces[#namespaces+1] = pdfdictionary {
                    Type      = pdfconstant("Namespace"),
                    NS        = pdfunicode(namespaceurls[k] or k),
                    RoleMapNS = v,
                }
            end
        end
        local structuretree = pdfdictionary {
            Type       = pdfconstant("StructTreeRoot"),
            K          = pdfreference(pdfflushobject(structure_kids)),
            ParentTree = pdfreference(pdfflushobject(parent_ref,parenttree)),
            IDTree     = idtree,
            RoleMap    = rolemap, -- sorted ?
            Namespaces = namespaces,
        }
        pdfflushobject(structure_ref,structuretree)
        addtocatalog("StructTreeRoot",pdfreference(structure_ref))
        --
        if lpdf.majorversion() == 1 then
            local markinfo = pdfdictionary {
                Marked         = pdfboolean(true) or nil,
             -- UserProperties = pdfboolean(true), -- maybe some day
             -- Suspects       = pdfboolean(true) or nil,
             -- AF             = #embeddedfilelist > 0 and pdfreference(pdfflushobject(embeddedfilelist)) or nil,
            }
            addtocatalog("MarkInfo",pdfreference(pdfflushobject(markinfo)))
        end
        --
        for fulltag, element in sortedhash(elements) do -- sorting is easier on comparing pdf
            local kids = element.kids
         -- if element.tag == "link" then
         --     local d = kids[2]
         --     if type(d) == "table" then
         --         local refatt = element.refatt
         --         if refatt then
         --             local refobj = codeinjections.getrefobj(refatt)
         --             if refobj then
         --                 d.Obj = pdfreference(refobj)
         --             end
         --         end
         --     end
         -- end
            pdfflushobject(element.knum,kids)
        end
    end
end

lpdf.registerdocumentfinalizer(finishstructure,"document structure")

local index, pageref, pagenum, list = 0, nil, 0, nil

local pdf_mcr            = pdfconstant("MCR")
local pdf_struct_element = pdfconstant("StructElem")
local pdf_s              = pdfconstant("S")
local pdf_objr           = pdfconstant("OBJR")

local function initializepage()
    index   = 0
    pagenum = texgetcount("realpageno")
    pageref = pdfreference(pdfpagereference(pagenum))
    list    = pdfarray()
    -- hm, can be later than 1
    if not firstintree then
        if pagenum > 1 then
            report_tags("beware: first page in tree is %i", pagenum)
        end
        firstintree = pagenum
        lastintree  = pagenum
    end
    if pagenum > lastintree then
        lastintree = pagenum
    else
     -- report_tags("beware: page order problem in tree at page %i", pagenum)
    end
    tree[pagenum] = list -- we can flush after done, todo
end

local function finishpage()
    -- flush what can be flushed
    addtopageattributes("StructParents",pagenum-1)
    -- there might be more
    addtopageattributes("Tabs",s)
end

-- here we can flush and free elements that are finished

local pdf_userproperties = pdfconstant("UserProperties")

-- /O /Table
-- /Headers [ ]

local function makeattribute(t)
    if t and next(t) then
        local properties = pdfarray()
        for k, v in sortedhash(t) do -- easier on comparing pdf
            properties[#properties+1] = pdfdictionary {
                N = pdfunicode(k),
                V = pdfunicode(v),
            }
        end
        return pdfdictionary {
            O = pdf_userproperties,
            P = properties,
        }
    end
end

local shared  = { }
local bindex  = 0
local btags   = { }

local function makeelement(fulltag,parent)
    local specification = specifications[fulltag]
    local tagname       = specification.tagname
    local tagnameused   = tagname
    local attributes    = nil
    if tagname == "ignore" then
        return false
    elseif tagname == "mstackertop" or tagname == "mstackerbot" or tagname == "mstackermid" then
        -- TODO
        return true
    elseif tagname == "tabulatecell" then
        local d = structurestags.gettabulatecell(fulltag)
        if d and d.kind == 1 then
            tagnameused = "tabulateheadcell"
        end
    elseif tagname == "tablecell" then
        -- will become a plugin model
        local d = structurestags.gettablecell(fulltag)
        if d then
            if d.kind == 1 then
                tagnameused = "tableheadcell"
            end
            local rows = d.rows    or 1
            local cols = d.columns or 1
            if rows > 1 or cols > 1 then
                attributes = pdfdictionary {
                    O       = pdfconstant("Table"),
                    RowSpan = rows > 1 and rows or nil,
                    ColSpan = cols > 1 and cols or nil,
                }
            end
        end
 -- elseif tagname == "math" then
 --     if specification.mode == "display" then
 --         tagnameused = "displaymath"
 --     else
 --         tagnameused = "inlinemath"
 --     end
    end
    --
    local detail     = specification.detail
    local userdata   = specification.userdata
    local actualtext = nil
    --
    usedmapping[tagname] = true
    --
    -- specification.attribute is unique
    --
    local af  = nil
    local id  = nil
    if embeddedtags then
        local tagindex = specification.tagindex
        if embeddedtags == true or embeddedtags[tagname] then
            id = f_tagid(tagname,tagindex)
            local blob = specification.blob
            if blob then
                local blobindex = mathematics.getblobindex(blob)
                if blobindex then
                    local index = shared[blobindex]
                    if index then
                        af = index[1]
                        btags[blob] = index[2]
                    else
                        bindex = bindex + 1
                        local blobname = f_tagid(tagname,blobindex)
                        local blobfile = f_tagfn(tagname,blobindex)
                        local blobdata = mathematics.getmathblob(blobindex)
                        af = codeinjections.embedfile {
                            force          = true,
                            data           = blobdata,
                            name           = blobname,
                            file           = blobfile,
                         -- hash           = hash,
                            hash           = id,
                            forcereference = true,
                         -- title          = "whatever",
                            mimetype       = "application/mathml+xml",
                            relation       = "Supplement", -- bah
                        }
                     -- af = pdfarray { af } -- maybe also share this
                        af = pdfreference(pdfflushobject(pdfarray { af })) -- maybe also share this
                        shared[blobindex] = { af, blobname }
                        btags[blob] = blobname
                    end
                    actualtext = mathematics.gettextblob(specification.language or "en",blobindex)
                    if actualtext then
                        actualtext = pdfunicode(actualtext)
                    end
                end

            else

             -- af = job.fileobjreferences.collected[id]
             -- if af then
             --     local r = pdfreference(af)
             --     af = pdfarray { r }
             --  -- embeddedfilelist[#embeddedfilelist+1] = r
             -- end

            end

        end
    end
    --
    local k = pdfarray()
    local r = pdfreserveobject()
    local t = usedlabels[tagnameused] or tagnameused
 -- local a = nil
    local d = pdfdictionary {
        Type       = pdf_struct_element,
        S          = pdfconstant(t),
        ID         = id,
        T          = detail and detail or nil,
        P          = parent.pref,
        Pg         = pageref,
        K          = pdfreference(r),
     -- A          = a and makeattribute(a) or nil,
        A          = attributes,
     -- Alt        = "Who cares",
        ActualText = actualtext or nil,
        AF         = af,
    }
    local s = pdfreference(pdfflushobject(d))
    if id and names then
        names[id] = s
    end
    local kids = parent.kids
    kids[#kids+1] = s
    local e = {
        tag  = t,
        pref = s,
        kids = k,
        knum = r,
        pnum = pagenum
    }
    elements[fulltag] = e
    return e
end

local f_BDC = formatters["/%s <</MCID %s>> BDC"]

local a_destination <const> = attributes.private('destination')
local a_reference   <const> = attributes.private('reference')

local function makecontent(start,parent,id,specification)
    local tag  = parent.tag
    local kids = parent.kids
    local last = index
    if id == "image" then
        local list  = specification.taglist
        local data  = usewithcare.images[list[#list]]
        local label = data and data.label
        local d = pdfdictionary {
            Type = pdf_mcr,
            Pg   = pageref,
            MCID = last,
            Alt  = pdfunicode(label ~= "" and label or "image"),
        }
        kids[#kids+1] = d
    elseif pagenum == parent.pnum then
        kids[#kids+1] = last
     -- if tag == "link" then
     --     local ra = getattr(start,a_reference)
     --     if ra then
     --         parent.refatt = ra
     --         kids[#kids+1] = pdfdictionary {
     --             Type = pdf_objr,
     --             Obj  = pdfreference(0),
     --         }
     --     end
     -- end
    else
        local d = pdfdictionary {
            Type = pdf_mcr,
            Pg   = pageref,
            MCID = last,
        }
     -- kids[#kids+1] = pdfreference(pdfflushobject(d))
        kids[#kids+1] = d
    end
    --
    index = index + 1
    list[index] = parent.pref -- page related list
    --
    return f_BDC(tag,last)
end

local function makeignore(specification)
    return "/Artifact BMC"
end

-- no need to adapt head, as we always operate on lists

local EMCliteral     = nil
local visualizetags  = nil
local visualizeblobs = nil

local enabled = true
local reduced = false

updaters.register("tagging.state.disable", function() enabled = false end)
updaters.register("tagging.state.enable",  function() enabled = true  end)

directives.register("tagging.state.reduced", function(v) reduced = v end)

function codeinjections.reducetags()
    report_tags("only outer level document tag used")
    reduced = true
end

local detailedmath = false

directives.register("structures.tags.math.detail", function(v) detailedmath = v end)

function nodeinjections.addtags(head)

    if not enabled then
        return
    end

    if not EMCliteral then
        EMCliteral = register(setstate("EMC"))
    end

    local last      = nil
    local ranges    = { }
    local range     = nil
    local nofranges = 0

    if not root then
        structure_kids = pdfarray()
        structure_ref  = pdfreserveobject()
        parent_ref     = pdfreserveobject()
        root           = { pref = pdfreference(structure_ref), kids = structure_kids }
        names          = pdfarray()
    end

    initializepage()

    if reduced then

        local list = getlist(head)

        if list then

            ranges = {
                { 1, "glyph", list, tailoflist(list), head }
            }

            nofranges = 1

            taglist = {
                {
                    attribute = 1,
                    metadata  = { },
                    tagindex  = 1,
                    taglist   = { "document>1" },
                    tagname   = "document",
                },
            }

        end

    else

        local mblob = false

        local function collectranges(head,list)

            for n, id, subtype in nextnode, head do
                if id == glyph_code then
                    -- maybe also disc
                    if getchar(n) ~= 0 then
                        local at, blob = getattrs(n,a_tagged,a_mathblob)
                        if not at then
                            at = false
                        end
                        if detailedmath then
                            -- skip
                        elseif blob then
                            if blob == mblob then
                                ranges[nofranges] = range
                                last = at
                            else
                                mblob = blob
                            end
                        else
                            mblob = false
                        end
                        if last ~= at then
                            range = { at, "glyph", n, n, list, blob } -- attr id start stop list
                            nofranges = nofranges + 1
                            ranges[nofranges] = range
                            last = at
                        elseif range then
                            range[4] = n -- stop
                        end
                    end
                elseif id == hlist_code or id == vlist_code then
                    local at = getattr(n,a_image) --todo: gettags
                    if at then
                        local at = getattr(n,a_tagged) or false -- false: pagebody or so, so artifact
                        nofranges = nofranges + 1
                        ranges[nofranges] = { at, "image", n, n, list } -- attr id start stop list
                        last = nil
                    else
                        local list = getlist(n)
                        if list then
                            collectranges(list,n)
                        end
                    end
                end
            end
        end

        collectranges(head)

    end

-- inspect(taglist)
-- inspect(ranges)

    if trace_tags then
        for i=1,nofranges do
            local range = ranges[i]
            local attr  = range[1]
            local id    = range[2]
            local start = range[3]
            local stop  = range[4]
            local tags  = taglist[attr]
            if tags then -- not ok ... only first lines
                report_tags("%s => %s : %05i % t",tosequence(start,start),tosequence(stop,stop),attr,tags.taglist)
            end
        end
    end

    local top    = nil
    local noftop = 0

    local blobdone = { }

    local function inject(start,stop,list,literal,left,right)
        local prev = getprev(start)
        if prev then
            setlink(prev,literal)
        end
        if left then
            setlink(literal,left,start)
        else
            setlink(literal,start)
        end
        if list and not prev then
            setlist(list,literal)
        end
        local literal = copy_node(EMCliteral)
        -- use insert instead:
        local next = getnext(stop)
        if next then
            setlink(literal,next)
        end
        if right then
            setlink(stop,right,literal)
        else
            setlink(stop,literal)
        end
    end

--     local function inject(start,stop,list,literal,left,right)
--         setlink(getprev(start) or list or true,literal,left or true,start)
--         setlink(stop,right or true,copy_node(EMCliteral),getnext(stop))
--     end

    for i=1,nofranges do

        local range = ranges[i]
        local mblob = false

        local attr  = range[1]
        local id    = range[2]
        local start = range[3]
        local stop  = range[4]
        local list  = range[5]
        local blob  = range[6]

        if attr then

            local specification = taglist[attr]
            local taglist       = specification.taglist
            local noftags       = #taglist
            local common        = 0
            local literal       = nil
            local ignore        = false

            if top then
                for i=1,noftags >= noftop and noftop or noftags do
                    if top[i] == taglist[i] then
                        common = i
                    else
                        break
                    end
                end
            end

            local prev = common > 0 and elements[taglist[common]] or root

            if blob and not detailedmath then
                for j=common+1,noftags do
                    local tag = taglist[j]
                    local prv = elements[tag] or makeelement(tag,prev)
                    if prv == false then
                        -- ignore this one
                        prev   = false
                        ignore = true
                        break
                    elseif prv == true then
                        -- skip this one
                    else
                        prev = prv
                    end
                    -- this is an ugly hack but ok for now
                    if find(tag,"^math>") then
                        break
                    end
                end
            else
                for j=common+1,noftags do
                    local tag = taglist[j]
                    local prv = elements[tag] or makeelement(tag,prev)
                    if prv == false then
                        -- ignore this one
                        prev   = false
                        ignore = true
                        break
                    elseif prv == true then
                        -- skip this one
                    else
                        prev = prv
                    end
                end
            end
            if prev then
                literal = setstate(makecontent(start,prev,id,specification))
            elseif ignore then
                literal = setstate(makeignore(specification))
            else
                -- maybe also ignore or maybe better: comment or so
            end

            if literal then
                local left,right
                if trace_info then
                    local name = specification.tagname
                    if name then
                        if not visualizetags then
                            visualizetags  = nodes.visualizers.register("tags")
                            visualizeblobs = nodes.visualizers.register("blobs",nil,nil,2.5,true)
                        end
                        if blob and not blobdone[blob] then
                            local bname = btags[blob]
                            if bname then
                                bname = "M " .. blob .. " " .. bname
                            else
                                bname = "M " .. blob
                            end
                            blobdone[blob] = true
                            if detailedmath then
                                left  = visualizeblobs(bname,name)
                                right = visualizeblobs()
                            else
                                left  = visualizetags(bname)
                                right = visualizetags()
                            end
                        else
                            left  = visualizetags(name)
                            right = visualizetags()
                        end
                    end
                elseif trace_math then
                    if not visualizetags then
                        visualizetags  = nodes.visualizers.register("tags")
                        visualizeblobs = nodes.visualizers.register("blobs",nil,nil,2.5,true)
                    end
                    if blob and not blobdone[blob] then
                        local bname = btags[blob]
                        if bname then
                            bname = "M " .. blob .. " " .. bname
                        else
                            bname = "M " .. blob
                        end
                        blobdone[blob] = true
                        if detailedmath then
                            left  = visualizeblobs(bname,name)
                            right = visualizeblobs()
                        else
                            left  = visualizetags(bname)
                            right = visualizetags()
                        end
                    end
                end
                inject(start,stop,list,literal,left,right)
            end

            top    = taglist
            noftop = noftags

        else

            local literal = setstate(makeignore(specification))

            inject(start,stop,list,literal)

        end

    end

    finishpage()

    return head

end

-- variant: more structure but funny collapsing in viewer, only in lua
-- file as commented anyway

-- this belongs elsewhere (export is not pdf related)

local permitted = true
local enabled   = false
local shipout   = true

directives.register("structures.tags.shipout",function(v) shipout = v end)

function codeinjections.settaggingsupport(option)
    if option == false then
        if enabled then
            disableaction("shipouts","structures.tags.handler")
         -- disableaction("shipouts","nodes.handlers.accessibility") -- maybe not this one
            disableaction("math","noads.handlers.tags")
            enabled = false
        end
        if permitted then
            if trace_tags then
                report_tags("blocking structure tags")
            end
            permitted = false
        end
    end
end

function codeinjections.enabletags()
    if permitted and not enabled then
        structures.tags.handler = nodeinjections.addtags
        if shipout then
            enableaction("shipouts","structures.tags.handler")
        end
     -- enableaction("shipouts","nodes.handlers.accessibility")
        enableaction("math","noads.handlers.tags")
        --
        if embeddedtags then
            embeddedtags.math = true
        else
            embeddedtags = { math = true }
        end
        --
        if trace_tags then
            report_tags("enabling structure tags")
        end
        enabled = true
    end
end