summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/tex/context/base/mkiv/strc-lst.lua
blob: be8e07112f2776135f12f269e9182a054dee7ba5 (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
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
if not modules then modules = { } end modules ['strc-lst'] = {
    version   = 1.001,
    comment   = "companion to strc-lst.mkiv",
    author    = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
    copyright = "PRAGMA ADE / ConTeXt Development Team",
    license   = "see context related readme files"
}

-- when all datastructures are stable a packer will be added which will
-- bring down memory consumption a bit; we can use for instance a pagenumber,
-- section, metadata cache (internal then has to move up one level) or a
-- shared cache [we can use a fast and stupid serializer]

-- todo: tag entry in list is crap
--
-- move more to commands

local tonumber, type = tonumber, type
local concat, insert, remove, sort = table.concat, table.insert, table.remove, table.sort
local lpegmatch = lpeg.match

local setmetatableindex = table.setmetatableindex
local sortedkeys        = table.sortedkeys

local settings_to_set   = utilities.parsers.settings_to_set
local allocate          = utilities.storage.allocate
local checked           = utilities.storage.checked

local trace_lists       = false  trackers.register("structures.lists", function(v) trace_lists = v end)

local report_lists      = logs.reporter("structure","lists")

local context           = context
local commands          = commands
local implement         = interfaces.implement
local conditionals      = tex.conditionals

local structures        = structures
local lists             = structures.lists
local sections          = structures.sections
local helpers           = structures.helpers
local documents         = structures.documents
local tags              = structures.tags
local counters          = structures.counters
local references        = structures.references

local collected         = allocate()
local tobesaved         = allocate()
local cached            = allocate()
local pushed            = allocate()
local kinds             = allocate()
local names             = allocate()

lists.collected         = collected
lists.tobesaved         = tobesaved

lists.enhancers         = lists.enhancers or { }
-----.internals         = allocate(lists.internals or { }) -- to be checked
lists.ordered           = allocate(lists.ordered   or { }) -- to be checked
lists.cached            = cached
lists.pushed            = pushed
lists.kinds             = kinds
lists.names             = names

local sorters           = sorters
local sortstripper      = sorters.strip
local sortsplitter      = sorters.splitters.utf
local sortcomparer      = sorters.comparers.basic

local sectionblocks     = allocate()
lists.sectionblocks     = sectionblocks

references.specials     = references.specials or { }

local matchingtilldepth = sections.matchingtilldepth
local numberatdepth     = sections.numberatdepth
local getsectionlevel   = sections.getlevel
local typesetnumber     = sections.typesetnumber
local autosectiondepth  = sections.autodepth

local variables         = interfaces.variables

local v_all             = variables.all
local v_reference       = variables.reference
local v_title           = variables.title
local v_command         = variables.command
local v_text            = variables.text
local v_current         = variables.current
local v_previous        = variables.previous
local v_intro           = variables.intro
local v_here            = variables.here
local v_component       = variables.component
local v_reference       = variables.reference
local v_local           = variables["local"]
local v_default         = variables.default

-- for the moment not public --

local function zerostrippedconcat(t,separator)
    local f, l = 1, #t
    for i=f,l do
        if t[i] == 0 then
            f = f + 1
        end
    end
    for i=l,f,-1 do
        if t[i] == 0 then
            l = l - 1
        end
    end
    return concat(t,separator,f,l)
end

-- -- -- -- -- --

local function initializer()
    -- create a cross reference between internal references
    -- and list entries
    local collected     = lists.collected
    local internals     = checked(references.internals)
    local ordered       = lists.ordered
    local usedinternals = references.usedinternals
    local blockdone     = { }
    local lastblock     = nil
    for i=1,#collected do
        local c = collected[i]
        local m = c.metadata
        local r = c.references
        if m then
            -- access by internal reference
            if r then
                local internal = r.internal
                if internal then
                    internals[internal] = c
                    usedinternals[internal] = r.used
                end
                local block = r.block
                if not block then
                    -- shouldn't happen
                elseif lastblock == block then
                    -- we're okay
                elseif lastblock then
                    if blockdone[block] then
                        report_lists("out of order sectionsblocks, maybe use \\setsectionblock")
                    else
                        blockdone[block] = true
                        sectionblocks[#sectionblocks+1] = block
                    end
                    lastblock = block
                elseif not blockdone[block] then
                    blockdone[block] = true
                    sectionblocks[#sectionblocks+1] = block
                    lastblock = block
                end
            end
            -- access by order in list
            local kind = m.kind
            local name = m.name
            if kind and name then
                local ok = ordered[kind]
                if ok then
                    local on = ok[name]
                    if on then
                        on[#on+1] = c
                    else
                        ok[name] = { c }
                    end
                else
                    ordered[kind] = { [name] = { c } }
                end
                kinds[kind] = true
                names[name] = true
            elseif kind then
                kinds[kind] = true
            elseif name then
                names[name] = true
            end
        end
        if r then
            r.listindex = i -- handy to have
        end
    end
end

local function finalizer()
    local flaginternals = references.flaginternals
    local usedviews     = references.usedviews
    for i=1,#tobesaved do
        local r = tobesaved[i].references
        if r then
            local i = r.internal
            local f = flaginternals[i]
            if f then
                r.used = usedviews[i] or true
            end
        end
    end
end

job.register('structures.lists.collected', tobesaved, initializer, finalizer)

local groupindices = setmetatableindex("table")

function lists.groupindex(name,group)
    local groupindex = groupindices[name]
    return groupindex and groupindex[group] or 0
end

-- we could use t (as hash key) in order to check for dup entries

function lists.addto(t) -- maybe more more here (saves parsing at the tex end)
    local metadata   = t.metadata
    local userdata   = t.userdata
    local numberdata = t.numberdata
    if userdata and type(userdata) == "string" then
        t.userdata = helpers.touserdata(userdata)
    end
    if not metadata.level then
        metadata.level = structures.sections.currentlevel() -- this is not used so it will go away
    end
    --
 -- if not conditionals.inlinelefttoright then
 --     metadata.idir = "r2l"
 -- end
 -- if not conditionals.displaylefttoright then
 --     metadata.ddir = "r2l"
 -- end
    --
    if numberdata then
        local numbers = numberdata.numbers
        if type(numbers) == "string" then
            numberdata.numbers = counters.compact(numbers,nil,true)
        end
    end
    local group = numberdata and numberdata.group
    local name  = metadata.name
    local kind  = metadata.kind
    if not group then
        -- forget about it
    elseif group == "" then
        group, numberdata.group = nil, nil
    else
        local groupindex = groupindices[name][group]
        if groupindex then
            numberdata.numbers = cached[groupindex].numberdata.numbers
        end
    end
    local setcomponent = references.setcomponent
    if setcomponent then
        setcomponent(t) -- can be inlined
    end
    local r = t.references
    if r and not r.section then
        r.section = structures.sections.currentid()
    end
    local i = r and r.internal or 0 -- brrr
    if r and kind and name then
        local tag = tags.getid(kind,name)
        if tag and tag ~= "?" then
            r.tag = tag -- todo: use internal ... is unique enough
        end
    end
    local p = pushed[i]
    if not p then
        p = #cached + 1
        cached[p] = helpers.simplify(t)
        pushed[i] = p
        if r then
            r.listindex = p
        end
    end
    if group then
        groupindices[name][group] = p
    end
    if trace_lists then
        report_lists("added %a, internal %a",name,p)
    end
    return p
end

function lists.discard(n)
    n = tonumber(n)
    if not n then
        -- maybe an error message
    elseif n == #cached then
        cached[n] = nil
        n = n - 1
        while n > 0 and cached[n] == false do
            cached[n] = nil -- collect garbage
            n = n - 1
        end
    else
        cached[n] = false
    end
end

function lists.iscached(n)
    return cached[tonumber(n)]
end

-- this is the main pagenumber enhancer

local enhanced = { }

local synchronizepage = function(r)  -- bah ... will move
    synchronizepage = references.synchronizepage
    return synchronizepage(r)
end

function lists.enhance(n)
    local l = cached[n]
    if not l then
        report_lists("enhancing %a, unknown internal",n)
    elseif enhanced[n] then
        if trace_lists then
            report_lists("enhancing %a, name %a, duplicate ignored",n,name)
        end
    else
        local metadata   = l.metadata
        local references = l.references
        --
        l.directives = nil -- might change
        -- save in the right order (happens at shipout)
        lists.tobesaved[#lists.tobesaved+1] = l
        -- default enhancer (cross referencing)
        synchronizepage(references)
        -- tags
        local kind = metadata.kind
        local name = metadata.name
        if trace_lists then
            report_lists("enhancing %a, name %a, page %a",n,name,references.realpage or 0)
        end
--         if references then
--             -- is this used ?
--             local tag = tags.getid(kind,name)
--             if tag and tag ~= "?" then
--                 references.tag = tag
--             end
--         end
        -- specific enhancer (kind of obsolete)
        local enhancer = kind and lists.enhancers[kind]
        if enhancer then
            enhancer(l)
        end
        --
        enhanced[n] = true
        return l
    end
end

-- we can use level instead but we can also decide to remove level from the metadata

local nesting = { }

function lists.pushnesting(i)
    local parent     = lists.result[i]
    local name       = parent.metadata.name
    local numberdata = parent and parent.numberdata
    local numbers    = numberdata and numberdata.numbers
    local number     = numbers and numbers[getsectionlevel(name)] or 0
    insert(nesting, {
        number = number,
        name   = name,
        result = lists.result,
        parent = parent
    })
end

function lists.popnesting()
    local old = remove(nesting)
    if old then
        lists.result = old.result
    else
        report_lists("nesting error")
    end
end

-- Historically we had blocks but in the mkiv approach that could as well be a level
-- which would simplify things a bit.

local splitter = lpeg.splitat(":") -- maybe also :: or have a block parameter

local listsorters = {
    [v_command] = function(a,b)
        if a.metadata.kind == "command" or b.metadata.kind == "command" then
            return a.references.internal < b.references.internal
        else
            return a.references.order < b.references.order
        end
    end,
    [v_all] = function(a,b)
        return a.references.internal < b.references.internal
    end,
    [v_title] = function(a,b)
        local da = a.titledata
        local db = b.titledata
        if da and db then
            local ta = da.title
            local tb = db.title
            if ta and tb then
                local sa = da.split
                if not sa then
                    sa = sortsplitter(sortstripper(ta))
                    da.split = sa
                end
                local sb = db.split
                if not sb then
                    sb = sortsplitter(sortstripper(tb))
                    db.split = sb
                end
                return sortcomparer(da,db) == -1
            end
        end
        return a.references.internal < b.references.internal
    end
}

-- was: names, criterium, number, collected, forced, nested, sortorder

local filters = setmetatableindex(function(t,k) return t[v_default] end)

local function filtercollected(specification)
    --
    local names     = specification.names     or { }
    local criterium = specification.criterium or v_default
    local number    = 0 -- specification.number
    local reference = specification.reference or ""
    local collected = specification.collected or lists.collected
    local forced    = specification.forced    or { }
    local nested    = specification.nested    or false
    local sortorder = specification.sortorder or specification.order
    --
    local numbers   = documents.data.numbers
    local depth     = documents.data.depth
    local block     = false -- all
    local wantedblock, wantedcriterium = lpegmatch(splitter,criterium) -- block:criterium
    if wantedblock == "" or wantedblock == v_all or wantedblock == v_text then
        criterium = wantedcriterium ~= "" and wantedcriterium or criterium
    elseif not wantedcriterium then
        block = documents.data.block
    else
        block, criterium = wantedblock, wantedcriterium
    end
    if block == "" then
        block = false
    end
    if type(names) == "string" then
        names = settings_to_set(names)
    end
    local all = not next(names) or names[v_all] or false
    --
    specification.names     = names
    specification.criterium = criterium
    specification.number    = 0 -- obsolete
    specification.reference = reference -- new
    specification.collected = collected
    specification.forced    = forced -- todo: also on other branched, for the moment only needed for bookmarks
    specification.nested    = nested
    specification.sortorder = sortorder
    specification.numbers   = numbers
    specification.depth     = depth
    specification.block     = block
    specification.all       = all
    --
    if trace_lists then
        report_lists("filtering names %,t, criterium %a, block %a",sortedkeys(names), criterium, block or "*")
    end
    local result = filters[criterium](specification)
    if trace_lists then
        report_lists("criterium %a, block %a, found %a",specification.criterium, specification.block or "*", #result)
    end
    --
    if sortorder then -- experiment
        local sorter = listsorters[sortorder]
        if sorter then
            if trace_lists then
                report_lists("sorting list using method %a",sortorder)
            end
            for i=1,#result do
                result[i].references.order = i
            end
            sort(result,sorter)
        end
    end
    --
    return result
end

filters[v_intro] = function(specification)
    local collected = specification.collected
    local result    = { }
    local nofresult = #result
    local all       = specification.all
    local names     = specification.names
    for i=1,#collected do
        local v = collected[i]
        local metadata = v.metadata
        if metadata and (all or names[metadata.name or false]) then
            local r = v.references
            if r and r.section == 0 then
                nofresult = nofresult + 1
                result[nofresult] = v
            end
        end
    end
    return result
end

filters[v_reference] = function(specification)
    local collected = specification.collected
    local result    = { }
    local nofresult = #result
    local names     = specification.names
    local sections  = sections.collected
    local reference = specification.reference
    if reference ~= "" then
        local prefix, rest = lpegmatch(references.prefixsplitter,reference) -- p::r
        local r = prefix and rest and references.derived[prefix][rest] or references.derived[""][reference]
        local s = r and r.numberdata -- table ref !
        if s then
            local depth   = getsectionlevel(r.metadata.name)
            local numbers = s.numbers
            for i=1,#collected do
                local v = collected[i]
                local r = v.references
                if r and (not block or not r.block or block == r.block) then
                    local metadata = v.metadata
                    if metadata and names[metadata.name or false] then
                        local sectionnumber = (r.section == 0) or sections[r.section]
                        if sectionnumber then
                            if matchingtilldepth(depth,numbers,sectionnumber.numbers) then
                                nofresult = nofresult + 1
                                result[nofresult] = v
                            end
                        end
                    end
                end
            end
        else
            report_lists("unknown reference %a specified",reference)
        end
    else
        report_lists("no reference specified")
    end
    return result
end

filters[v_all] = function(specification)
    local collected = specification.collected
    local result    = { }
    local nofresult = #result
    local block     = specification.block
    local all       = specification.all
    local forced    = specification.forced
    local names     = specification.names
    local sections  = sections.collected
    for i=1,#collected do
        local v = collected[i]
        local r = v.references
        if r and (not block or not r.block or block == r.block) then
            local metadata = v.metadata
            if metadata then
                local name = metadata.name or false
                local sectionnumber = (r.section == 0) or sections[r.section]
                if forced[name] or (sectionnumber and not metadata.nolist and (all or names[name])) then -- and not sectionnumber.hidenumber then
                    nofresult = nofresult + 1
                    result[nofresult] = v
                end
            end
        end
    end
    return result
end

filters[v_text] = filters[v_all]

filters[v_current] = function(specification)
    if specification.depth == 0 then
        specification.nested    = false
        specification.criterium = v_intro
        return filters[v_intro](specification)
    end
    local collected = specification.collected
    local result    = { }
    local nofresult = #result
    local depth     = specification.depth
    local block     = specification.block
    local all       = specification.all
    local names     = specification.names
    local numbers   = specification.numbers
    local sections  = sections.collected
    for i=1,#collected do
        local v = collected[i]
        local r = v.references
        if r and (not block or not r.block or block == r.block) then
            local sectionnumber = sections[r.section]
            if sectionnumber then -- and not sectionnumber.hidenumber then
                local cnumbers = sectionnumber.numbers
                local metadata = v.metadata
                if cnumbers then
                    if metadata and not metadata.nolist and (all or names[metadata.name or false]) and #cnumbers > depth then
                        local ok = true
                        for d=1,depth do
                            local cnd = cnumbers[d]
                            if not (cnd == 0 or cnd == numbers[d]) then
                                ok = false
                                break
                            end
                        end
                        if ok then
                            nofresult = nofresult + 1
                            result[nofresult] = v
                        end
                    end
                end
            end
        end
    end
    return result
end

filters[v_here] = function(specification)
    -- this is quite dirty ... as cnumbers is not sparse we can misuse #cnumbers
    if specification.depth == 0 then
        specification.nested    = false
        specification.criterium = v_intro
        return filters[v_intro](specification)
    end
    local collected = specification.collected
    local result    = { }
    local nofresult = #result
    local depth     = specification.depth
    local block     = specification.block
    local all       = specification.all
    local names     = specification.names
    local numbers   = specification.numbers
    local sections  = sections.collected
    for i=1,#collected do
        local v = collected[i]
        local r = v.references
        if r then -- and (not block or not r.block or block == r.block) then
            local sectionnumber = sections[r.section]
            if sectionnumber then -- and not sectionnumber.hidenumber then
                local cnumbers = sectionnumber.numbers
                local metadata = v.metadata
                if cnumbers then
                    if metadata and not metadata.nolist and (all or names[metadata.name or false]) and #cnumbers >= depth then
                        local ok = true
                        for d=1,depth do
                            local cnd = cnumbers[d]
                            if not (cnd == 0 or cnd == numbers[d]) then
                                ok = false
                                break
                            end
                        end
                        if ok then
                            nofresult = nofresult + 1
                            result[nofresult] = v
                        end
                    end
                end
            end
        end
    end
    return result
end

filters[v_previous] = function(specification)
    if specification.depth == 0 then
        specification.nested    = false
        specification.criterium = v_intro
        return filters[v_intro](specification)
    end
    local collected = specification.collected
    local result    = { }
    local nofresult = #result
    local block     = specification.block
    local all       = specification.all
    local names     = specification.names
    local numbers   = specification.numbers
    local sections  = sections.collected
    local depth     = specification.depth
    for i=1,#collected do
        local v = collected[i]
        local r = v.references
        if r and (not block or not r.block or block == r.block) then
            local sectionnumber = sections[r.section]
            if sectionnumber then -- and not sectionnumber.hidenumber then
                local cnumbers = sectionnumber.numbers
                local metadata = v.metadata
                if cnumbers then
                    if metadata and not metadata.nolist and (all or names[metadata.name or false]) and #cnumbers >= depth then
                        local ok = true
                        for d=1,depth-1 do
                            local cnd = cnumbers[d]
                            if not (cnd == 0 or cnd == numbers[d]) then
                                ok = false
                                break
                            end
                        end
                        if ok then
                            nofresult = nofresult + 1
                            result[nofresult] = v
                        end
                    end
                end
            end
        end
    end
    return result
end

filters[v_local] = function(specification)
    local numbers = specification.numbers
    local nested  = nesting[#nesting]
    if nested then
        return filtercollected {
            names     = specification.names,
            criterium = nested.name,
            collected = specification.collected,
            forced    = specification.forced,
            nested    = nested,
            sortorder = specification.sortorder,
        }
    else
        specification.criterium = autosectiondepth(numbers) == 0 and v_all or v_current
        specification.nested    = false
        return filtercollected(specification) -- rechecks, so better (for determining all)
    end
end


filters[v_component] = function(specification)
    -- special case, no structure yet
    local collected = specification.collected
    local result    = { }
    local nofresult = #result
    local all       = specification.all
    local names     = specification.names
    local component = resolvers.jobs.currentcomponent() or ""
    if component ~= "" then
        for i=1,#collected do
            local v = collected[i]
            local r = v.references
            local m = v.metadata
            if r and r.component == component and (m and names[m.name] or all) then
                nofresult = nofresult + 1
                result[nofresult] = v
            end
        end
    end
    return result
end

-- local number = tonumber(number) or numberatdepth(depth) or 0
-- if number > 0 then
--     ...
-- end

filters[v_default] = function(specification) -- is named
    local collected = specification.collected
    local result    = { }
    local nofresult = #result
    ----- depth     = specification.depth
    local block     = specification.block
    local criterium = specification.criterium
    local all       = specification.all
    local names     = specification.names
    local numbers   = specification.numbers
    local sections  = sections.collected
    local reference = specification.reference
    local nested    = specification.nested
    --
    if reference then
        reference = tonumber(reference)
    end
    --
    local depth     = getsectionlevel(criterium)
    local pnumbers  = nil
    local pblock    = block
    local parent    = nested and nested.parent
    --
    if parent then
        pnumbers = parent.numberdata.numbers or pnumbers -- so local as well as nested
        pblock   = parent.references.block or pblock
        if trace_lists then
            report_lists("filtering by block %a and section %a",pblock,criterium)
        end
    end
    --
    for i=1,#collected do
        local v = collected[i]
        local r = v.references
        if r and (not block or not r.block or pblock == r.block) then
            local sectionnumber = sections[r.section]
            if sectionnumber then
                local metadata = v.metadata
                local cnumbers = sectionnumber.numbers
                if cnumbers then
                    if all or names[metadata.name or false] then
                        if reference then
                            -- filter by number
                            if reference == cnumbers[depth] then
                                nofresult = nofresult + 1
                                result[nofresult] = v
                            end
                        else
                            if #cnumbers >= depth and matchingtilldepth(depth,cnumbers,pnumbers) then
                                nofresult = nofresult + 1
                                result[nofresult] = v
                            end
                        end
                    end
                end
            end
        end
    end
    return result
end

-- names, criterium, number, collected, forced, nested, sortorder) -- names is hash or string

lists.filter = filtercollected

lists.result = { }

function lists.getresult(r)
    return lists.result[r]
end

function lists.process(specification)
    lists.result = filtercollected(specification)
    local specials = settings_to_set(specification.extras or "")
    specials = next(specials) and specials or nil
    for i=1,#lists.result do
        local r = lists.result[i]
        local m = r.metadata
        local s = specials and r.numberdata and specials[zerostrippedconcat(r.numberdata.numbers,".")] or ""
        context.strclistsentryprocess(m.name,m.kind,i,s)
    end
end

function lists.analyze(specification)
    lists.result = filtercollected(specification)
end

function lists.userdata(name,r,tag) -- to tex (todo: xml)
    local result = lists.result[r]
    if result then
        local userdata, metadata = result.userdata, result.metadata
        local str = userdata and userdata[tag]
        if str then
            return str, metadata
        end
    end
end

function lists.uservalue(name,r,tag,default) -- to lua
    local str = lists.result[r]
    str = str and str.userdata
    str = str and str[tag]
    return str or default
end

function lists.size()
    return #lists.result
end

function lists.location(n)
    local l = lists.result[n]
    return l and l.references.internal or n
end

function lists.label(n,default)
    local l = lists.result[n]
    local t = l.titledata
    return t and t.label or default or ""
end

function lists.sectionnumber(name,n,spec)
    local data = lists.result[n]
    local sectiondata = sections.collected[data.references.section]
    -- hm, prefixnumber?
    typesetnumber(sectiondata,"prefix",spec,sectiondata) -- data happens to contain the spec too
end

-- some basics (todo: helpers for pages)

function lists.title(name,n,tag) -- tag becomes obsolete
    local data = lists.result[n]
    if data then
        local titledata = data.titledata
        if titledata then
            helpers.title(titledata[tag] or titledata.list or titledata.title or "",data.metadata)
        end
    end
end

function lists.hastitledata(name,n,tag)
    local data = cached[tonumber(n)]
    if data then
        local titledata = data.titledata
        if titledata then
            return (titledata[tag] or titledata.title or "") ~= ""
        end
    end
    return false
end

function lists.haspagedata(name,n)
    local data = lists.result[n]
    if data then
        local references = data.references
        if references and references.realpage then -- or references.pagedata
            return true
        end
    end
    return false
end

function lists.hasnumberdata(name,n)
    local data = lists.result[n]
    if data then
        local numberdata = data.numberdata
        if numberdata and not numberdata.hidenumber then -- the hide number is true
            return true
        end
    end
    return false
end

function lists.prefix(name,n,spec)
    helpers.prefix(lists.result[n],spec)
end

function lists.page(name,n,pagespec)
    helpers.page(lists.result[n],pagespec)
end

function lists.prefixedpage(name,n,prefixspec,pagespec)
    helpers.prefixpage(lists.result[n],prefixspec,pagespec)
end

function lists.realpage(name,n)
    local data = lists.result[n]
    if data then
        local references = data.references
        return references and references.realpage or 0
    else
        return 0
    end
end

-- numbers stored in entry.numberdata + entry.numberprefix

function lists.number(name,n,spec)
    local data = lists.result[n]
    if data then
        local numberdata = data.numberdata
        if numberdata then
            typesetnumber(numberdata,"number",spec or false,numberdata or false)
        end
    end
end

function lists.prefixednumber(name,n,prefixspec,numberspec,forceddata)
    local data = lists.result[n]
    if data then
        helpers.prefix(data,prefixspec)
        local numberdata = data.numberdata or forceddata
        if numberdata then
            typesetnumber(numberdata,"number",numberspec or false,numberdata or false)
        end
    end
end

-- todo, do this in references namespace ordered instead (this is an experiment)
--
-- also see lpdf-ano (maybe move this there)

local splitter = lpeg.splitat(":")

function references.specials.order(var,actions) -- references.specials !
    local operation = var.operation
    if operation then
        local kind, name, n = lpegmatch(splitter,operation)
        local order = lists.ordered[kind]
        order = order and order[name]
        local v = order[tonumber(n)]
        local r = v and v.references.realpage
        if r then
            actions.realpage = r
            var.operation = r -- brrr, but test anyway
            return references.specials.page(var,actions)
        end
    end
end

-- interface (maybe strclistpush etc)

if not lists.reordered then
    function lists.reordered(data)
        return data.numberdata
    end
end

implement { name = "pushlist", actions = lists.pushnesting, arguments = "integer" }
implement { name = "poplist",  actions = lists.popnesting  }

implement {
    name      = "addtolist",
    actions   = { lists.addto, context },
    arguments = {
        {
            { "references", {
                    { "internal", "integer" },
                    { "block" },
                    { "section", "integer" },
                    { "location" },
                    { "prefix" },
                    { "reference" },
                    { "view" },
                    { "order", "integer" },
                }
            },
            { "metadata", {
                    { "kind" },
                    { "name" },
                    { "level", "integer" },
                    { "catcodes", "integer" },
                    { "coding" },
                    { "xmlroot" },
                    { "setup" },
                }
            },
            { "userdata" },
            { "titledata", {
                    { "label" },
                    { "title" },
                    { "bookmark" },
                    { "marking" },
                    { "list" },
                }
            },
            { "prefixdata", {
                    { "prefix" },
                    { "separatorset" },
                    { "conversionset" },
                    { "conversion" },
                    { "set" },
                    { "segments" },
                    { "connector" },
                }
            },
            { "numberdata", {
                    { "numbers" },
                    { "groupsuffix" },
                    { "group" },
                    { "counter" },
                    { "separatorset" },
                    { "conversionset" },
                    { "conversion" },
                    { "starter" },
                    { "stopper" },
                    { "segments" },
                }
            }
        }
    }
}

implement {
    name      = "enhancelist",
    actions   = lists.enhance,
    arguments = "integer"
}

implement {
    name      = "processlist",
    actions   = lists.process,
    arguments = {
        {
            { "names" },
            { "criterium" },
            { "reference" },
            { "extras" },
            { "order" },
        }
    }
}

implement {
    name      = "analyzelist",
    actions   = lists.analyze,
    arguments = {
        {
            { "names" },
            { "criterium" },
            { "reference" },
        }
    }
}

implement {
    name      = "listtitle",
    actions   = lists.title,
    arguments = { "string", "integer" }
}

implement {
    name      = "listprefixednumber",
    actions   = lists.prefixednumber,
    arguments = {
        "string",
        "integer",
        {
            { "prefix" },
            { "separatorset" },
            { "conversionset" },
            { "starter" },
            { "stopper" },
            { "set" },
            { "segments" },
            { "connector" },
        },
        {
            { "separatorset" },
            { "conversionset" },
            { "starter" },
            { "stopper" },
            { "segments" },
        }
    }
}

implement {
    name      = "listprefixedpage",
    actions   = lists.prefixedpage,
    arguments = {
        "string",
        "integer",
        {
            { "separatorset" },
            { "conversionset" },
            { "set" },
            { "segments" },
            { "connector" },
        },
        {
            { "prefix" },
            { "conversionset" },
            { "starter" },
            { "stopper" },
        }
    }
}

implement { name = "listsize",       actions = { lists.size, context } }
implement { name = "listlocation",   actions = { lists.location, context }, arguments = "integer" }
implement { name = "listlabel",      actions = { lists.label, context }, arguments = { "integer", "string" } }
implement { name = "listrealpage",   actions = { lists.realpage, context }, arguments = { "string", "integer" } }
implement { name = "listgroupindex", actions = { lists.groupindex, context }, arguments = { "string", "string" } }

implement {
    name    = "currentsectiontolist",
    actions = { sections.current, lists.addto, context }
}

local function userdata(name,r,tag)
    local str, metadata = lists.userdata(name,r,tag)
    if str then
     -- local catcodes = metadata and metadata.catcodes
     -- if catcodes then
     --     context.sprint(catcodes,str)
     -- else
     --     context(str)
     -- end
        helpers.title(str,metadata)
    end
end

implement {
    name      = "listuserdata",
    actions   = userdata,
    arguments = { "string", "integer", "string" }
}

-- we could also set variables .. names will change (when this module is done)
-- maybe strc_lists_savedtitle etc

implement { name = "doifelselisthastitle",  actions = { lists.hastitledata,  commands.doifelse }, arguments = { "string", "integer" } }
implement { name = "doifelselisthaspage",   actions = { lists.haspagedata,   commands.doifelse }, arguments = { "string", "integer" } }
implement { name = "doifelselisthasnumber", actions = { lists.hasnumberdata, commands.doifelse }, arguments = { "string", "integer" } }
implement { name = "doifelselisthasentry",  actions = { lists.iscached,      commands.doifelse }, arguments = { "integer" } }

local function savedlisttitle(name,n,tag)
    local data = cached[tonumber(n)]
    if data then
        local titledata = data.titledata
        if titledata then
            helpers.title(titledata[tag] or titledata.title or "",data.metadata)
        end
    end
end

local function savedlistnumber(name,n)
    local data = cached[tonumber(n)]
    if data then
        local numberdata = data.numberdata
        if numberdata then
            typesetnumber(numberdata,"number",numberdata or false)
        end
    end
end

local function savedlistprefixednumber(name,n)
    local data = cached[tonumber(n)]
    if data then
        local numberdata = lists.reordered(data)
        if numberdata then
            helpers.prefix(data,data.prefixdata)
            typesetnumber(numberdata,"number",numberdata or false)
        end
    end
end

lists.savedlisttitle          = savedlisttitle
lists.savedlistnumber         = savedlistnumber
lists.savedlistprefixednumber = savedlistprefixednumber

implement {
    name      = "savedlistnumber",
    actions   = savedlistnumber,
    arguments = { "string", "integer" }
}

implement {
    name      = "savedlisttitle",
    actions   = savedlisttitle,
    arguments = { "string", "integer" }
}

implement {
    name      = "savedlistprefixednumber",
    actions   = savedlistprefixednumber,
    arguments = { "string", "integer" }
}

implement {
    name      = "discardfromlist",
    actions   = lists.discard,
    arguments = { "integer" }
}

-- new and experimental and therefore off by default

lists.autoreorder = false -- true

local function addlevel(t,k)
    local v = { }
    setmetatableindex(v,function(t,k)
        local v = { }
        t[k] = v
        return v
    end)
    t[k] = v
    return v
end

local internals = setmetatableindex({ }, function(t,k)

    local sublists = setmetatableindex({ },addlevel)

    local collected = lists.collected or { }

    for i=1,#collected do
        local entry = collected[i]
        local numberdata = entry.numberdata
        if numberdata then
            local metadata = entry.metadata
            if metadata then
                local references = entry.references
                if references then
                    local kind = metadata.kind
                    local name = numberdata.counter or metadata.name
                    local internal = references.internal
                    if kind and name and internal then
                        local sublist = sublists[kind][name]
                        sublist[#sublist + 1] = { internal, numberdata }
                    end
                end
            end
        end
    end

    for k, v in next, sublists do
        for k, v in next, v do
            local tmp = { }
            for i=1,#v do
                tmp[i] = v[i]
            end
            sort(v,function(a,b) return a[1] < b[1] end)
            for i=1,#v do
                t[v[i][1]] = tmp[i][2]
            end
        end
    end

    setmetatableindex(t,nil)

    return t[k]

end)

function lists.reordered(entry)
    local numberdata = entry.numberdata
    if lists.autoreorder then
        if numberdata then
            local metadata = entry.metadata
            if metadata then
                local references = entry.references
                if references then
                    local kind = metadata.kind
                    local name = numberdata.counter or metadata.name
                    local internal = references.internal
                    if kind and name and internal then
                        return internals[internal] or numberdata
                    end
                end
            end
        end
    else
        function lists.reordered(entry)
            return entry.numberdata
        end
    end
    return numberdata
end