summaryrefslogtreecommitdiff
path: root/tex/context/base/publ-ini.lua
blob: 4d4c9ef09e34f18584d2f8bee7c71a4eec0c7113 (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
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
if not modules then modules = { } end modules ['publ-ini'] = {
    version   = 1.001,
    comment   = "this module part of publication support",
    author    = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
    copyright = "PRAGMA ADE / ConTeXt Development Team",
    license   = "see context related readme files"
}

-- If we define two datasets with the same bib file we can consider
-- sharing the data but that means that we need to have a parent which
-- in turn makes things messy if we start manipulating entries in
-- different ways (future) .. not worth the trouble as we will seldom
-- load big bib files many times and even then ... fonts are larger.

local next, rawget, type, tostring, tonumber = next, rawget, type, tostring, tonumber
local match, gmatch, format, gsub, find = string.match, string.gmatch, string.format, string.gsub, string.find
local concat, sort, tohash = table.concat, table.sort, table.tohash
local utfsub = utf.sub
local mod = math.mod
local formatters = string.formatters
local allocate = utilities.storage.allocate
local settings_to_array, settings_to_set = utilities.parsers.settings_to_array, utilities.parsers.settings_to_set
local sortedkeys, sortedhash = table.sortedkeys, table.sortedhash
local setmetatableindex = table.setmetatableindex
local lpegmatch = lpeg.match
local P, C, Ct, R, Carg = lpeg.P, lpeg.C, lpeg.Ct, lpeg.R, lpeg.Carg

local report           = logs.reporter("publications")
local report_cite      = logs.reporter("publications","cite")
local report_reference = logs.reporter("publications","reference")

local trace            = false  trackers.register("publications",                 function(v) trace            = v end)
local trace_cite       = false  trackers.register("publications.cite",            function(v) trace_cite       = v end)
local trace_missing    = false  trackers.register("publications.cite.missing",    function(v) trace_missing    = v end)
local trace_references = false  trackers.register("publications.cite.references", function(v) trace_references = v end)

local datasets       = publications.datasets

local variables      = interfaces.variables

local v_local        = variables["local"]
local v_global       = variables["global"]

local v_force        = variables.force
local v_standard     = variables.standard
local v_start        = variables.start
local v_none         = variables.none
local v_left         = variables.left
local v_right        = variables.right
local v_middle       = variables.middle
local v_inbetween    = variables.inbetween
local v_yes          = variables.yes
local v_all          = variables.all
local v_short        = variables.short
local v_cite         = variables.cite
local v_default      = variables.default
local v_reference    = variables.reference
local v_dataset      = variables.dataset
local v_author       = variables.author or "author"
local v_editor       = variables.editor or "editor"

local numbertochar   = converters.characters

local logsnewline    = logs.newline
local logspushtarget = logs.pushtarget
local logspoptarget  = logs.poptarget
local csname_id      = token.csname_id

local basicsorter    = sorters.basicsorter -- (a,b)
local sortcomparer   = sorters.comparers.basic -- (a,b)
local sortstripper   = sorters.strip
local sortsplitter   = sorters.splitters.utf

local manipulators       = typesetters.manipulators
local splitmanipulation  = manipulators.splitspecification
local applymanipulation  = manipulators.applyspecification
local manipulatormethods = manipulators.methods

-- this might move elsewhere

manipulatormethods.Word  = converters.Word
manipulatormethods.WORD  = converters.WORD
manipulatormethods.Words = converters.Words
manipulatormethods.WORDS = converters.WORDS

local context                     = context

local ctx_setvalue                = context.setvalue
local ctx_firstoftwoarguments     = context.firstoftwoarguments
local ctx_secondoftwoarguments    = context.secondoftwoarguments
local ctx_firstofoneargument      = context.firstofoneargument
local ctx_gobbleoneargument       = context.gobbleoneargument

local ctx_btxlistparameter        = context.btxlistparameter
local ctx_btxcitevariantparameter = context.btxcitevariantparameter
local ctx_btxlistvariantparameter = context.btxlistvariantparameter
local ctx_btxdirectlink           = context.btxdirectlink
local ctx_btxhandlelistentry      = context.btxhandlelistentry
local ctx_btxchecklistentry       = context.btxchecklistentry
local ctx_btxchecklistcombi       = context.btxchecklistcombi
local ctx_btxsetcitereference     = context.btxsetcitereference
local ctx_btxsetlistreference     = context.btxsetlistreference
local ctx_btxmissing              = context.btxmissing

local ctx_btxsetdataset           = context.btxsetdataset
local ctx_btxsettag               = context.btxsettag
local ctx_btxsetlanguage          = context.btxsetlanguage
local ctx_btxsetcombis            = context.btxsetcombis
local ctx_btxsetcategory          = context.btxsetcategory
local ctx_btxcitesetup            = context.btxcitesetup
local ctx_btxsetfirst             = context.btxsetfirst
local ctx_btxsetsecond            = context.btxsetsecond
local ctx_btxsetinternal          = context.btxsetinternal
local ctx_btxsetbacklink          = context.btxsetbacklink
local ctx_btxsetbacktrace         = context.btxsetbacktrace
local ctx_btxsetcount             = context.btxsetcount
local ctx_btxsetconcat            = context.btxsetconcat
local ctx_btxsetoveflow           = context.btxsetoverflow
local ctx_btxstartcite            = context.btxstartcite
local ctx_btxstopcite             = context.btxstopcite
local ctx_btxstartciteauthor      = context.btxstartciteauthor
local ctx_btxstopciteauthor       = context.btxstopciteauthor
local ctx_btxstartsubcite         = context.btxstartsubcite
local ctx_btxstopsubcite          = context.btxstopsubcite
local ctx_btxlistsetup            = context.btxlistsetup

statistics.register("publications load time", function()
    local publicationsstats = publications.statistics
    local nofbytes = publicationsstats.nofbytes
    if nofbytes > 0 then
        return string.format("%s seconds, %s bytes, %s definitions, %s shortcuts",
            statistics.elapsedtime(publications),nofbytes,publicationsstats.nofdefinitions,publicationsstats.nofshortcuts)
    else
        return nil
    end
end)

luatex.registerstopactions(function()
    local done = false
    local undefined = csname_id("undefined*crap")
    for name, dataset in sortedhash(datasets) do
        for command, n in sortedhash(dataset.commands) do
            if not done then
                logspushtarget("logfile")
                logsnewline()
                report("start used btx commands")
                logsnewline()
                done = true
            end
            local c = csname_id(command)
            if c and c ~= undefined then
                report("%-20s %-20s % 5i %s",name,command,n,"known")
            else
                local u = csname_id(utf.upper(command))
                if u and u ~= undefined then
                    report("%-20s %-20s % 5i %s",name,command,n,"KNOWN")
                else
                    report("%-20s %-20s % 5i %s",name,command,n,"unknown")
                end
            end
        end
    end
    if done then
        logsnewline()
        report("stop used btx commands")
        logsnewline()
        logspoptarget()
    end
end)

-- multipass, we need to sort because hashing is random per run and not per
-- version (not the best changed feature of lua)

local collected = allocate()
local tobesaved = allocate()

-- we use a a dedicated (and efficient as it know what it deals with) serializer,
-- also because we need to ignore the 'details' field

local function serialize(t)
    local f_key_table  = formatters[" [%q] = {"]
    local f_key_string = formatters["  %s = %q,"]
    local r = { "return {" }
    local m = 1
    for tag, entry in sortedhash(t) do
        m = m + 1
        r[m] = f_key_table(tag)
        local s = sortedkeys(entry)
        for i=1,#s do
            local k = s[i]
            m = m + 1
            r[m] = f_key_string(k,entry[k])
        end
        m = m + 1
        r[m] = " },"
    end
    r[m] = "}"
    return concat(r,"\n")
end

local function finalizer()
    local prefix = tex.jobname -- or environment.jobname
    local setnames = sortedkeys(datasets)
    for i=1,#setnames do
        local name     = setnames[i]
        local dataset  = datasets[name]
        local userdata = dataset.userdata
        local checksum = nil
        local username = file.addsuffix(file.robustname(formatters["%s-btx-%s"](prefix,name)),"lua")
        if userdata and next(userdata) then
            if job.passes.first then
                local newdata = serialize(userdata)
                checksum = md5.HEX(newdata)
                io.savedata(username,newdata)
            end
        else
            os.remove(username)
            username = nil
        end
        local loaded = dataset.loaded
        local sources = dataset.sources
        local used   = { }
        for i=1,#sources do
            local source = sources[i]
         -- if loaded[source.filename] ~= "previous" then -- needs checking
            if loaded[source.filename] ~= "previous" or loaded[source.filename] == "current" then
                used[#used+1] = source
            end
        end
        tobesaved[name] = {
            usersource = {
                filename = username,
                checksum = checksum,
            },
            datasources = used,
        }
    end
end

local function initializer()
    statistics.starttiming(publications)
    for name, state in next, collected do
        local dataset     = datasets[name]
        local datasources = state.datasources
        local usersource  = state.usersource
        if datasources then
            for i=1,#datasources do
                local filename = datasources[i].filename
                publications.load(dataset,filename,"previous")
            end
        end
        if usersource then
            dataset.userdata = table.load(usersource.filename) or { }
        end
    end
    statistics.stoptiming(publications)
    function initializer() end -- will go, for now, runtime loaded
end

job.register('publications.collected',tobesaved,initializer,finalizer)

if not publications.authors then
    initializer() -- for now, runtime loaded
end

-- we want to minimize references as there can be many (at least
-- when testing)

local initialized  = false
local usedentries  = { }
local citetolist   = { }
local listtocite   = { }
local nofcitations = 0

setmetatableindex(usedentries,function(t,k)
    if not initialized then
        usedentries = { }
        citetolist  = { }
        listtocite  = { }
        local internals = structures.references.internals
        local p_collect = (C(R("09")^1) * Carg(1) / function(s,entry) listtocite[tonumber(s)] = entry end + P(1))^0
        for i=1,#internals do
            local entry = internals[i]
            if entry then
                local metadata = entry.metadata
                if metadata then
                    local kind = metadata.kind
                    if kind == "full" then
                        -- reference (in list)
                        local userdata = entry.userdata
                        if userdata then
                            local set = userdata.btxset
                            if set then
                                local tag = userdata.btxref
                                local s = usedentries[set]
                                if s then
                                    local u = s[tag]
                                    if u then
                                        u[#u+1] = entry
                                    else
                                        s[tag] = { entry }
                                    end
                                else
                                    usedentries[set] = { [tag] = { entry } }
                                end
                                -- alternative: collect prev in group
                                local bck = userdata.btxbck
                                if bck then
                                    lpegmatch(p_collect,bck,1,entry) -- for s in string.gmatch(bck,"[^ ]+") do listtocite[tonumber(s)] = entry end
                                else
                                    local int = tonumber(userdata.btxint)
                                    if int then
                                        listtocite[int] = entry
                                    end
                                end
                            end
                        end
                    elseif kind == "userdata" then
                        -- list entry (each cite)
                        local userdata = entry.userdata
                        if userdata then
                            local int = tonumber(userdata.btxint)
                            if int then
                                citetolist[int] = entry
-- xx[dataset][tag] = { entry, ...  }
                            end
                        end
                    end
                end
            else
                -- weird
            end
        end
        return usedentries[k]
    end
end)

-- match:
--
-- [current|previous|following] section
-- [current|previous|following] block
-- [current|previous|following] component
--
-- by prefix
-- by dataset

local reported = { }
local finder   = publications.finder

local function findallused(dataset,reference,internal)
    local finder  = publications.finder -- for the moment, not yet in all betas
    local find    = finder and finder(reference)
    local tags    = not find and settings_to_array(reference)
    local todo    = { }
    local okay    = { } -- only if mark
    local set     = usedentries[dataset]
    local valid   = datasets[dataset].luadata
    local ordered = datasets[dataset].ordered
    if set then
        local function register(tag)
            local entry = set[tag]
            if entry then
                -- only once in a list but at some point we can have more (if we
                -- decide to duplicate)
                if #entry == 1 then
                    entry = entry[1]
                else
                    -- same block and section
                    local done = false
                    if internal and internal > 0 then
                        -- first following in list
                        for i=1,#entry do
                            local e = entry[i]
                            if e.references.internal > internal then
                                done = e
                                break
                            end
                        end
                        if not done then
                            -- last preceding in list
                            for i=1,#entry do
                                local e = entry[i]
                                if e.references.internal < internal then
                                    done = e
                                else
                                    break
                                end
                            end
                        end
                    end
                    if done then
                        entry = done
                    else
                        entry = entry[1]
                    end
                end
                okay[#okay+1] = entry
            end
            todo[tag] = true
        end
        if find then
            tags = { }
            for i=1,#ordered do
                local entry = ordered[i]
                if find(entry) then
                    local tag = entry.tag
                    register(tag)
                    tags[#tags+1] = tag
                end
            end
        else
            for i=1,#tags do
                local tag  = tags[i]
                if valid[tag] then
                    register(tag)
                elseif not reported[tag] then
                    reported[tag] = true
                    report_cite("non-existent entry %a in %a",tag,dataset)
                end
            end
        end
    else
        if find then
            tags = { }
            for i=1,#ordered do
                local entry = ordered[i]
                if find(entry) then
                    tags[#tags+1] = entry.tag
                end
            end
        else
            for i=1,#tags do
                local tag = tags[i]
                if valid[tag] then
                    todo[tag] = true
                elseif not reported[tag] then
                    reported[tag] = true
                    report_cite("non-existent entry %a in %a",tag,dataset)
                end
            end
        end
    end
    return okay, todo, tags
end

local function unknowncite(reference)
    ctx_btxsettag(reference)
    ctx_btxcitesetup("unknown")
end

local concatstate = publications.concatstate

local tobemarked = nil

function marknocite(dataset,tag,nofcitations) -- or just: ctx_btxdomarkcitation
    ctx_btxstartcite()
    ctx_btxsetdataset(dataset)
    ctx_btxsettag(tag)
    ctx_btxsetbacklink(nofcitations)
    ctx_btxcitesetup("nocite")
    ctx_btxstopcite()
end

local function markcite(dataset,tag,flush)
    if not tobemarked then
        return 0
    end
    local citation = tobemarked[tag]
    if not citation then
        return 0
    end
    if citation == true then
        nofcitations = nofcitations + 1
        if trace_cite then
            report_cite("mark, dataset: %s, tag: %s, number: %s, state: %s",dataset,tag,nofcitations,"cited")
        end
        if flush then
            marknocite(dataset,tag,nofcitations)
        end
        tobemarked[tag] = nofcitations
        return nofcitations
    else
        return citation
    end
end

local marked_dataset = nil
local marked_list    = nil

local function flushmarked(dataset,list,todo)
    marked_dataset = dataset
    marked_list    = list
end

function commands.flushmarked()
    if marked_list and tobemarked then
        for i=1,#marked_list do
            -- keep order
            local tag = marked_list[i]
            local tbm = tobemarked[tag]
            if not tbm or tbm == true then
                nofcitations = nofcitations + 1
                marknocite(marked_dataset,tag,nofcitations)
                if trace_cite then
                    report_cite("mark, dataset: %s, tag: %s, number: %s, state: %s",dataset,tag,nofcitations,"unset")
                end
            else
            end
        end
    end
    tobemarked     = nil
    marked_dataset = nil
    marked_list    = nil
end

-- basic access

local function getfield(dataset,tag,name)
    local d = datasets[dataset].luadata[tag]
    return d and d[name]
end

local function getdetail(dataset,tag,name)
    local d = datasets[dataset].details[tag]
    return d and d[name]
end

function commands.btxsingularorplural(dataset,tag,name)
    local d = datasets[dataset].details[tag]
    if d then
        d = d[name]
    end
    if type(d) == "table" then
        d = #d <= 1
    else
        d = false
    end
    commands.doifelse(d)
end

function commands.oneorrange(dataset,tag,name)
    local d = datasets[dataset].luadata[tag] -- details ?
    if d then
        d = d[name]
    end
    if type(d) == "string" then
        d = find(d,"%-")
    else
        d = false

    end
    commands.doifelse(not d) -- so singular is default
end

function commands.firstinrange(dataset,tag,name)
    local d = datasets[dataset].luadata[tag] -- details ?
    if d then
        d = d[name]
    end
    if type(d) == "string" then
        context(match(d,"([^%-]+)"))
    end
end

-- basic loading

function commands.usebtxdataset(name,filename)
    publications.load(datasets[name],filename,"current")
end

function commands.convertbtxdatasettoxml(name,nice)
    publications.converttoxml(datasets[name],nice)
end

-- enhancing

local splitauthorstring = publications.authors.splitstring

local pagessplitter = lpeg.splitat(P("-")^1)

-- maybe not redo when already done

function publications.enhance(dataset) -- for the moment split runs (maybe publications.enhancers)
    statistics.starttiming(publications)
    if type(dataset) == "string" then
        dataset = datasets[dataset]
    end
    local luadata = dataset.luadata
    local details = dataset.details
    local ordered = dataset.ordered
    -- author, editor
    for tag, entry in next, luadata do
        local author = entry.author
        local editor = entry.editor
        details[tag] = {
            author = author and splitauthorstring(author),
            editor = editor and splitauthorstring(editor),
        }
    end
    -- short
    local shorts = { }
    for i=1,#ordered do
        local entry = ordered[i]
        if entry then
            local tag = entry.tag
            if tag then
                local detail = details[tag]
                if detail then
                    local author = detail.author
                    if author then
                        -- number depends on sort order
                        local t = { }
                        if #author == 0 then
                            -- what
                        else
                            local n = #author == 1 and 3 or 1
                            for i=1,#author do
                                local surnames = author[i].surnames
                                if not surnames or #surnames == 0 then
                                    -- error
                                else
                                    t[#t+1] = utfsub(surnames[1],1,n)
                                end
                            end
                        end
                        local year = tonumber(entry.year) or 0
                        local short = formatters["%t%02i"](t,mod(year,100))
                        local s = shorts[short]
                        if not s then
                            shorts[short] = tag
                        elseif type(s) == "string" then
                            shorts[short] = { s, tag }
                        else
                            s[#s+1] = tag
                        end
                    else
                        --
                    end
                else
                    report("internal error, no detail for tag %s",tag)
                end
                --
                local pages = entry.pages
                if pages then
                    local first, last = lpegmatch(pagessplitter,pages)
                    details[tag].pages = first and last and { first, last } or pages
                end
                --
                local keyword = entry.keyword
                if keyword then
                    details[tag].keyword = settings_to_set(keyword)
                end
            else
                report("internal error, no tag at index %s",i)
            end
        else
            report("internal error, no entry at index %s",i)
        end
    end
    for short, tags in next, shorts do -- ordered ?
        if type(tags) == "table" then
            sort(tags)
            for i=1,#tags do
             -- details[tags[i]].short = short .. numbertochar(i)
                local detail = details[tags[i]]
                detail.short  = short
                detail.suffix = numbertochar(i)
            end
        else
            details[tags].short = short
        end
    end
    statistics.stoptiming(publications)
end

function commands.addbtxentry(name,settings,content)
    local dataset = datasets[name]
    if dataset then
        publications.addtexentry(dataset,settings,content)
    end
end

function commands.setbtxdataset(name,default)
    local dataset = rawget(datasets,name)
    if dataset then
        context(name)
    elseif default and default ~= "" then
        context(name)
    else
        report("unknown dataset %a",name)
    end
end

function commands.setbtxentry(name,tag)
    local dataset = rawget(datasets,name)
    if dataset then
        if dataset.luadata[tag] then
            context(tag)
        else
            report("unknown tag %a in dataset %a",tag,name)
        end
    else
        report("unknown dataset %a",name)
    end
end

-- rendering of fields

function commands.btxflush(name,tag,field)
    local dataset = rawget(datasets,name)
    if dataset then
        local fields = dataset.luadata[tag]
        if fields then
            local manipulator, field = splitmanipulation(field)
            local value = fields[field]
            if type(value) == "string" then
                local suffixes = dataset.suffixes[tag]
                if suffixes then
                    local suffix = suffixes[field]
                    if suffix then
                        value = value .. converters.characters(suffix)
                    end
                end
                context(manipulator and applymanipulation(manipulator,value) or value)
                return
            end
            local details = dataset.details[tag]
            if details then
                local value = details[field]
                if type(value) == "string" then
                    local suffixes = dataset.suffixes[tag]
                    if suffixes then
                        local suffix = suffixes[field]
                        if suffix then
                            value = value .. converters.characters(suffix)
                        end
                    end
                    context(manipulator and applymanipulation(manipulator,value) or value)
                    return
                end
            end
            report("unknown field %a of tag %a in dataset %a",field,tag,name)
        else
            report("unknown tag %a in dataset %a",tag,name)
        end
    else
        report("unknown dataset %a",name)
    end
end

function commands.btxdetail(name,tag,field)
    local dataset = rawget(datasets,name)
    if dataset then
        local details = dataset.details[tag]
        if details then
            local manipulator, field = splitmanipulation(field)
            local value = details[field]
            if type(value) == "string" then
                local suffixes = dataset.suffixes[tag]
                if suffixes then
                    local suffix = suffixes[field]
                    if suffix then
                        value = value .. converters.characters(suffix)
                    end
                end
                context(manipulator and applymanipulation(manipulator,value) or value)
            else
                report("unknown detail %a of tag %a in dataset %a",field,tag,name)
            end
        else
            report("unknown tag %a in dataset %a",tag,name)
        end
    else
        report("unknown dataset %a",name)
    end
end

function commands.btxfield(name,tag,field)
    local dataset = rawget(datasets,name)
    if dataset then
        local fields = dataset.luadata[tag]
        if fields then
            local manipulator, field = splitmanipulation(field)
            local value = fields[field]
            if type(value) == "string" then
                local suffixes = dataset.suffixes[tag]
                if suffixes then
                    local suffix = suffixes[field]
                    if suffix then
                        value = value .. converters.characters(suffix)
                    end
                end
                context(manipulator and applymanipulation(manipulator,value) or value)
            else
                report("unknown field %a of tag %a in dataset %a",field,tag,name)
            end
        else
            report("unknown tag %a in dataset %a",tag,name)
        end
    else
        report("unknown dataset %a",name)
    end
end

-- testing: to be speed up with testcase

function commands.btxdoifelse(name,tag,field)
    local dataset = rawget(datasets,name)
    if dataset then
        local data  = dataset.luadata[tag]
        local value = data and data[field]
        if value and value ~= "" then
            ctx_firstoftwoarguments()
            return
        end
    end
    ctx_secondoftwoarguments()
end

function commands.btxdoif(name,tag,field)
    local dataset = rawget(datasets,name)
    if dataset then
        local data  = dataset.luadata[tag]
        local value = data and data[field]
        if value and value ~= "" then
            ctx_firstofoneargument()
            return
        end
    end
    ctx_gobbleoneargument()
end

function commands.btxdoifnot(name,tag,field)
    local dataset = rawget(datasets,name)
    if dataset then
        local data  = dataset.luadata[tag]
        local value = data and data[field]
        if value and value ~= "" then
            ctx_gobbleoneargument()
            return
        end
    end
    ctx_firstofoneargument()
end

-- -- alternative approach: keep data at the tex end

function publications.singularorplural(singular,plural)
    if lastconcatsize and lastconcatsize > 1 then
        context(plural)
    else
        context(singular)
    end
end

local patterns = { "publ-imp-%s.mkvi", "publ-imp-%s.mkiv", "publ-imp-%s.tex" }

local function failure(name)
    report("unknown library %a",name)
end

local function action(name,foundname)
    context.input(foundname)
end

function commands.loadbtxdefinitionfile(name) -- a more specific name
    commands.uselibrary {
        name     = gsub(name,"^publ%-",""),
        patterns = patterns,
        action   = action,
        failure  = failure,
        onlyonce = true,
    }
end

-- lists:

publications.lists = publications.lists or { }
local lists        = publications.lists

local context     = context
local structures  = structures

local references  = structures.references
local sections    = structures.sections

-- per rendering

local renderings = { } --- per dataset

setmetatableindex(renderings,function(t,k)
    local v = {
        list         = { },
        done         = { },
        alldone      = { },
        used         = { },
        registered   = { },
        ordered      = { },
        shorts       = { },
        method       = v_none,
        currentindex = 0,
    }
    t[k] = v
    return v
end)

-- why shorts vs tags: only for sorting

function lists.register(dataset,tag,short) -- needs checking now that we split
    local r = renderings[dataset]
    if not short or short == "" then
        short = tag
    end
    if trace then
        report("registering publication entry %a with shortcut %a",tag,short)
    end
    local top = #r.registered + 1
    -- do we really need these
    r.registered[top] = tag
    r.ordered   [tag] = top
    r.shorts    [tag] = short
end

function lists.nofregistered(dataset)
    return #renderings[dataset].registered
end

local function validkeyword(dataset,tag,keyword)
    local ds = datasets[dataset]
    if not ds then
        report("unknown dataset %a",dataset)
        return
    end
    local dt = ds.details[tag]
    if not dt then
        report("no details for tag %a",tag)
        return
    end
    local kw = dt.keyword
    if kw then
        for k in next, keyword do
            if kw[k] then
                return true
            end
        end
    end
end

local methods = { }
lists.methods = methods

methods[v_dataset] = function(dataset,rendering,keyword)
    -- why only once inless criterium=all?
    local luadata = datasets[dataset].luadata
    local list = rendering.list
    for tag, data in sortedhash(luadata) do
        if not keyword or validkeyword(dataset,tag,keyword) then
            list[#list+1] = { tag }
        end
    end
end

methods[v_force] = function (dataset,rendering,keyword)
    -- only for checking, can have duplicates, todo: collapse page numbers, although
    -- we then also needs deferred writes
    local result = structures.lists.filter(rendering.specification) or { }
    local list   = rendering.list
    for listindex=1,#result do
        local r = result[listindex]
        local u = r.userdata
        if u and u.btxset == dataset then
            local tag = u.btxref
            if tag and (not keyword or validkeyword(dataset,tag,keyword)) then
                list[#list+1] = { tag, listindex, u.btxint }
            end
        end
    end
    lists.result = result
end

-- local  : if tag and                      done[tag] ~= section then ...
-- global : if tag and not alldone[tag] and done[tag] ~= section then ...

methods[v_local] = function(dataset,rendering,keyword)
    local result   = structures.lists.filter(rendering.specification) or { }
    local section  = sections.currentid()
    local list     = rendering.list
    local done     = rendering.done
    local alldone  = rendering.alldone
    local doglobal = rendering.method == v_global
    local traced   = { } -- todo: only if interactive (backlinks) or when tracing
    for listindex=1,#result do
        local r = result[listindex]
        local u = r.userdata
        if u and u.btxset == dataset then
            local tag = u.btxref
            if not tag then
                -- problem
            elseif done[tag] == section then
                -- skip
            elseif doglobal and alldone[tag] then
                -- skip
            elseif not keyword or validkeyword(dataset,tag,keyword) then
                if traced then
                    local l = traced[tag]
                    if l then
                        l[#l+1] = u.btxint
                    else
                        local l = { tag, listindex, u.btxint }
                        list[#list+1] = l
                        traced[tag] = l
                    end
                else
                    done[tag]    = section
                    alldone[tag] = true
                    list[#list+1] = { tag, listindex, u.btxint }
                end
            end
        end
    end
    if traced then
        for tag in next, traced do
            done[tag]    = section
            alldone[tag] = true
        end
    end
    lists.result = result
end

methods[v_global] = methods[v_local]

function lists.collectentries(specification)
    local dataset = specification.btxdataset
    if not dataset then
        return
    end
    local rendering  = renderings[dataset]
    if not rendering then
        return
    end
    local method            = specification.method or v_none
    rendering.method        = method
    rendering.list          = { }
    rendering.done          = { }
    rendering.sorttype      = specification.sorttype  or v_default
    rendering.criterium     = specification.criterium or v_none
    rendering.repeated      = specification.repeated  or v_no
    rendering.specification = specification
    local filtermethod      = methods[method]
    if not filtermethod then
        return
    end
    lists.result  = { } -- kind of reset
    local keyword = specification.keyword
    if keyword and keyword ~= "" then
        keyword = settings_to_set(keyword)
    else
        keyword = nil
    end
    filtermethod(dataset,rendering,keyword)
end

lists.sorters = {
    [v_short] = function(dataset,rendering,list)
        local shorts = rendering.shorts
        local function compare(a,b)
            local aa, bb = a and a[1], b and b[1]
            if aa and bb then
                aa, bb = shorts[aa], shorts[bb]
                return aa and bb and aa < bb
            end
            return false
        end
        sort(list,compare)
    end,
    [v_reference] = function(dataset,rendering,list)
        local function compare(a,b)
            local aa, bb = a and a[1], b and b[1]
            if aa and bb then
                return aa and bb and aa < bb
            end
            return false
        end
        sort(list,compare)
    end,
    [v_dataset] = function(dataset,rendering,list)
        local function compare(a,b)
            local aa, bb = a and a[1], b and b[1]
            if aa and bb then
                aa, bb = list[aa].index or 0, list[bb].index or 0
                return aa and bb and aa < bb
            end
            return false
        end
        sort(list,compare)
    end,
 -- [v_default] = function(dataset,rendering,list) -- not really needed
 --     local ordered = rendering.ordered
 --     local function compare(a,b)
 --         local aa, bb = a and a[1], b and b[1]
 --         if aa and bb then
 --             aa, bb = ordered[aa], ordered[bb]
 --             return aa and bb and aa < bb
 --         end
 --         return false
 --     end
 --     sort(list,compare)
 -- end,
    [v_author] = function(dataset,rendering,list)
        local valid = publications.authors.sorters.author(dataset,list)
        if #valid == 0 or #valid ~= #list then
            -- nothing to sort
        else
            -- if needed we can wrap compare and use the list directly but this is cleaner
            sorters.sort(valid,sortcomparer)
            for i=1,#valid do
                local v = valid[i]
                valid[i] = list[v.index]
            end
            return valid
        end
    end,
}

-- for determining width

function lists.fetchentries(dataset)
    local rendering = renderings[dataset]
    local list      = rendering.list
    local used      = rendering.used
    local forceall  = rendering.criterium == v_all
    local repeated  = rendering.repeated == v_yes
    local luadata   = datasets[dataset].luadata
    for i=1,#list do
        local tag = list[i][1]
        if luadata[tag] and (forceall or repeated or not used[tag]) then
            ctx_btxsettag(tag)
            ctx_btxchecklistentry()
        end
    end
end

-- for rendering

function lists.flushentries(dataset,sorttype)
    local rendering = renderings[dataset]
    local list      = rendering.list
    local sorttype  = rendering.sorttype or sorttype
    local sorter    = lists.sorters[sorttype] or lists.sorters[v_default]
    local used      = rendering.used
    local forceall  = rendering.criterium == v_all
    local repeated  = rendering.repeated == v_yes
    local luadata = datasets[dataset].luadata
    if type(sorter) == "function" then
        list = sorter(dataset,rendering,list) or list
    end
 -- local details = datasets[dataset].details
    for i=1,#list do
     -- we can pass i here too ... more efficient to avoid the setvalue
        local li    = list[i]
        local tag   = li[1]
        local entry = luadata[tag]
        if entry and (forceall or repeated or not used[tag]) then
            local combined = entry.combined
            if combined then
                ctx_btxsetcombis(concat(combined,","))
            end
            ctx_btxsetcategory(entry.category or "unknown")
            ctx_btxsettag(tag)
            local language = entry.language
            if language then
                ctx_btxsetlanguage(language)
            end
            local bl = li[3]
            if bl and bl ~= "" then
                ctx_btxsetbacklink(bl)
                ctx_btxsetbacktrace(concat(li," ",3))
                local uc = citetolist[tonumber(bl)]
                if uc then
                    ctx_btxsetinternal(uc.references.internal or "")
                end
            else
                -- nothing
            end
            ctx_btxhandlelistentry()
            if not repeated then
                used[tag] = true -- beware we keep the old state (one can always use criterium=all)
            end
        end
     end
end

function lists.filterall(dataset)
    local r = renderings[dataset]
    local list = r.list
    local registered = r.registered
    for i=1,#registered do
        list[i] = { registered[i], i }
    end
end

commands.btxresolvelistreference = lists.resolve
commands.btxaddtolist            = lists.addentry
commands.btxcollectlistentries   = lists.collectentries
commands.btxfetchlistentries     = lists.fetchentries
commands.btxflushlistentries     = lists.flushentries

local citevariants        = { }
publications.citevariants = citevariants

-- helper

local function sortedtags(dataset,list,sorttype)
    local luadata = datasets[dataset].luadata
    local valid = { }
    for i=1,#list do
        local tag = list[i]
        local entry = luadata[tag]
        if entry then
            local key = entry[sorttype]
            if key then
                valid[#valid+1] = {
                    tag   = tag,
                    split = sortsplitter(sortstripper(key))
                }
            end
        end
    end
    if #valid == 0 or #valid ~= #list then
        return list
    else
        sorters.sort(valid,basicsorter)
        for i=1,#valid do
            valid[i] = valid[i].tag
        end
        return valid
    end
end

--     if sorttype and sorttype ~= "" then
--         tags = sortedtags(dataset,tags,sorttype)
--     end

local optionalspace  = lpeg.patterns.whitespace^0
local prefixsplitter = optionalspace * lpeg.splitat(optionalspace * P("::") * optionalspace)

function commands.btxhandlecite(specification)
    local tag = specification.reference
    if not tag or tag == "" then
        return
    end
    --
    local dataset  = specification.dataset or "" -- standard
    local mark     = specification.markentry ~= false
    local variant  = specification.variant or "num"
    local sorttype = specification.sorttype
    local compress = specification.compress == v_yes
    local internal = specification.internal
    --
    local prefix, rest = lpegmatch(prefixsplitter,tag)
    if rest then
        dataset = prefix
    else
        rest = tag
    end
    local action = citevariants[variant] -- there is always fallback on default
    if trace_cite then
        report_cite("inject, dataset: %s, tag: %s, variant: %s, compressed",dataset or "-",rest,variant)
    end
    ctx_setvalue("currentbtxdataset",dataset)
    action(dataset,rest,mark,compress,variant,internal) -- maybe pass a table
end


function commands.btxhandlenocite(specification)
    local tag = specification.reference
    if not tag or tag == "" then
        return
    end
    --
    local dataset  = specification.dataset or "" -- standard
    local mark     = specification.markentry ~= false
    local internal = specification.internal or ""
    --
    local prefix, rest = lpegmatch(prefixsplitter,tag)
    if rest then
        dataset = prefix
    else
        rest = tag
    end
    --
    if trace_cite then
        report_cite("mark, dataset: %s, tags: %s",dataset or "-",rest)
    end
    --
    local reference = publications.parenttag(dataset,rest)
    local found, todo, list = findallused(dataset,reference,internal)
    tobemarked = mark and todo
    if found and tobemarked then
        flushmarked(dataset,list)
        commands.flushmarked() -- here (could also be done in caller)
    end
end

-- function commands.btxcitevariant(dataset,block,tags,variant) -- uses? specification ?
--     local action = citevariants[variant]
--     if action then
--         action(dataset,tags,variant)
--     end
-- end

-- sorter

local keysorter = function(a,b) return a.sortkey < b.sortkey end

local function compresslist(source)
    for i=1,#source do
        if type(source[i].sortkey) ~= "number" then
            return source
        end
    end
    local first, last, firstr, lastr
    local target, noftarget, tags = { }, 0, { }
    sort(source,keysorter)
    -- suffixes
    local oldvalue = nil
    local suffix   = 0
    local function setsuffix(entry,suffix,sortfld)
        entry.suffix  = suffix
        local dataset = datasets[entry.dataset]
        if dataset then
            local suffixes = dataset.suffixes[entry.tag]
            if suffixes then
                suffixes[sortfld] = suffix
            else
                dataset.suffixes[entry.tag] = { [sortfld] = suffix }
            end
        end
    end
    for i=1,#source do
        local entry   = source[i]
        local sortfld = entry.sortfld
        if sortfld then
            local value = entry.sortkey
            if value == oldvalue then
                if suffix == 0 then
                    suffix = 1
                    local entry = source[i-1]
                    setsuffix(entry,suffix,sortfld)
                end
                suffix = suffix + 1
                setsuffix(entry,suffix,sortfld)
            else
                oldvalue = value
                suffix   = 0
            end
        else
            break
        end
    end
    --
    local function flushrange()
        noftarget = noftarget + 1
        if last > first + 1 then
            target[noftarget] = {
                first = firstr,
                last  = lastr,
                tags  = tags,
            }
        else
            target[noftarget] = firstr
            if last > first then
                noftarget = noftarget + 1
                target[noftarget] = lastr
            end
        end
        tags = { }
    end
    for i=1,#source do
        local entry = source[i]
        local current = entry.sortkey
        if not first then
            first, last, firstr, lastr = current, current, entry, entry
        elseif current == last + 1 then
            last, lastr = current, entry
        else
            flushrange()
            first, last, firstr, lastr = current, current, entry, entry
        end
        tags[#tags+1] = entry.tag
    end
    if first and last then
        flushrange()
    end
    return target
end

-- local source = {
--     { tag = "one",   internal = 1, value = "foo", page = 1 },
--     { tag = "two",   internal = 2, value = "bar", page = 2 },
--     { tag = "three", internal = 3, value = "gnu", page = 3 },
-- }
--
-- local target = compresslist(source)

local numberonly = R("09")^1 / tonumber + P(1)^0
local f_missing  = formatters["<%s>"]

-- maybe also sparse (e.g. pages)

local function processcite(dataset,reference,mark,compress,setup,internal,getter,setter,compressor)
    reference = publications.parenttag(dataset,reference)
    local found, todo, list = findallused(dataset,reference,internal)
    tobemarked = mark and todo
--     if type(tobemarked) ~= "table" then
--         tobemarked = { }
--     end
    if found and setup then
        local source = { }
        local badkey = false
        for i=1,#found do
            local entry    = found[i]
            local tag      = entry.userdata.btxref
            local internal = entry.references.internal
            local data     = getter(dataset,tag,entry,internal)
            if compress and not compressor then
                local sortkey = data.sortkey
                if sortkey then
                    local key = lpegmatch(numberonly,sortkey)
                    if key then
                        data.sortkey = key
                    else
                        badkey = true
                    end
                else
                    badkey = true
                end
            end
            source[i] = data
        end

        local function flush(i,n,entry,tag)
            local tag = tag or entry.tag
            local currentcitation = markcite(dataset,tag)
            ctx_btxstartcite()
            ctx_btxsettag(tag)
            ctx_btxsetbacklink(currentcitation)
            local bl = listtocite[currentcitation]
            if bl then
                -- we refer to a coming list entry
                ctx_btxsetinternal(bl.references.internal or "")
            else
                -- we refer to a previous list entry
                ctx_btxsetinternal(entry.internal or "")
            end
            local language = entry.language
            if language then
                ctx_btxsetlanguage(language)
            end
            if not setter(entry,entry.last) then
                ctx_btxsetfirst(f_missing(tag))
            end
            ctx_btxsetconcat(concatstate(i,n))
            ctx_btxcitesetup(setup)
            ctx_btxstopcite()
        end

        if compress and not badkey then
            local target = (compressor or compresslist)(source)
            local nofcollected = #target
            if nofcollected == 0 then
                unknowncite(reference)
            else
                for i=1,nofcollected do
                    local entry = target[i]
                    local first = entry.first
                    if first then
                        flush(i,nofcollected,first,list[1]) -- somewhat messy as we can be sorted so this needs checking! might be wrong
                    else
                        flush(i,nofcollected,entry)
                    end
                end
            end
        else
            local nofcollected = #source
            if nofcollected == 0 then
                unknowncite(reference)
            else
                for i=1,nofcollected do
                    flush(i,nofcollected,source[i])
                end
            end
        end
    end
    if tobemarked then
        flushmarked(dataset,list)
    end
end

local function simplegetter(first,last,field)
    local value = first[field]
    if value then
        ctx_btxsetfirst(value)
        if last then
            ctx_btxsetsecond(last[field])
        end
        return true
    end
end

local setters = setmetatableindex({},function(t,k)
    local v = function(dataset,tag,entry,internal)
        local value = getfield(dataset,tag,k)
        return {
            tag      = tag,
            internal = internal,
            [k]      = value,
            sortkey  = value,
            sortfld  = k,
        }
    end
    t[k] = v
    return v
end)

local getters = setmetatableindex({},function(t,k)
    local v = function(first,last)
        return simplegetter(first,last,k)
    end
    t[k] = v
    return v
end)

-- default

setmetatableindex(citevariants,function(t,k)
    local v = t.default
    t[k] = v
    return v
end)

function citevariants.default(dataset,reference,mark,compress,variant,internal)
    processcite(dataset,reference,mark,compress,variant,internal,setters[variant],getters[variant])
end

-- short

local function setter(dataset,tag,entry,internal)
    return {
        tag      = tag,
        internal = internal,
        short    = getfield(dataset,tag,"short"),
        suffix   = getfield(dataset,tag,"suffix"),
    }
end

local function getter(first,last) -- last not used
    local short = first.short
    if short then
        local suffix = first.suffix
        if suffix then
            ctx_btxsetfirst(short .. suffix)
        else
            ctx_btxsetfirst(short)
        end
        return true
    end
end

function citevariants.short(dataset,reference,mark,compress,variant,internal)
    processcite(dataset,reference,mark,false,"short",internal,setter,getter)
end

-- pages (no compress)

local function setter(dataset,tag,entry,internal)
    return {
        dataset  = dataset,
        tag      = tag,
        internal = internal,
        pages    = getdetail(dataset,tag,"pages"),
    }
end

local function getter(first,last)
    local pages = first.pages
    if pages then
        if type(pages) == "table" then
            ctx_btxsetfirst(pages[1])
            ctx_btxsetsecond(pages[2])
        else
            ctx_btxsetfirst(pages)
        end
        return true
    end
end

function citevariants.page(dataset,reference,mark,compress,variant,internal)
    processcite(dataset,reference,mark,compress,"page",internal,setter,getter)
end

-- num

local function setter(dataset,tag,entry,internal)
    local entries = entry.entries
    local text = entries and entries.text or "?"
    return {
        dataset  = dataset,
        tag      = tag,
        internal = internal,
        num      = text,
        sortkey  = text,
    }
end

local function getter(first,last)
    return simplegetter(first,last,"num")
end

function citevariants.num(dataset,reference,mark,compress,variant,internal)
    processcite(dataset,reference,mark,compress,"num",internal,setter,getter)
end

-- year

local function setter(dataset,tag,entry,internal)
    local year = getfield(dataset,tag,"year")
    return {
        dataset  = dataset,
        tag      = tag,
        internal = internal,
        year     = year,
        sortkey  = year,
        sortfld  = "year",
    }
end

local function getter(first,last)
    return simplegetter(first,last,"year")
end

function citevariants.year(dataset,reference,mark,compress,variant,internal)
    processcite(dataset,reference,mark,compress,"year",internal,setter,getter)
end

-- index | serial

local function setter(dataset,tag,entry,internal)
    local index = getfield(dataset,tag,"index")
    return {
        dataset  = dataset,
        tag      = tag,
        internal = internal,
        index    = index,
        sortkey  = index,
    }
end

local function getter(first,last)
    return simplegetter(first,last,"index")
end

function citevariants.index(dataset,reference,mark,compress,variant,internal)
    processcite(dataset,reference,mark,compress,"index",internal,setter,getter)
end

function citevariants.serial(dataset,reference,mark,compress,variant,internal)
    processcite(dataset,reference,mark,compress,"serial",internal,setter,getter)
end

-- category | type

local function setter(dataset,tag,entry,internal)
    return {
        dataset  = dataset,
        tag      = tag,
        internal = internal,
        category = getfield(dataset,tag,"category"),
    }
end

local function getter(first,last)
    return simplegetter(first,last,"category")
end

function citevariants.category(dataset,reference,mark,compress,variant,internal)
    processcite(dataset,reference,mark,compress,"category",internal,setter,getter)
end

function citevariants.type(dataset,reference,mark,compress,variant,internal)
    processcite(dataset,reference,mark,compress,"type",internal,setter,getter)
end

-- key | tag

local function setter(dataset,tag,entry,internal)
    return {
        dataset  = dataset,
        tag      = tag,
        internal = internal,
    }
end

local function getter(first,last)
    ctx_btxsetfirst(first.tag)
    return true
end

function citevariants.key(dataset,reference,mark,compress,variant,internal)
    return processcite(dataset,reference,mark,compress,"key",internal,setter,getter)
end

function citevariants.tag(dataset,reference,mark,compress,variant,internal)
    return processcite(dataset,reference,mark,compress,"tag",internal,setter,getter)
end

-- todo : sort
-- todo : choose between publications or commands namespace
-- todo : use details.author
-- todo : sort details.author
-- (name, name and name) .. how names? how sorted?
-- todo: we loop at the tex end .. why not here
-- \cite[{hh,afo},kvm]

-- common

local currentbtxciteauthor = function()
    context.currentbtxciteauthor()
    return true -- needed?
end

local function authorcompressor(found)
    local result  = { }
    local entries = { }
    for i=1,#found do
        local entry    = found[i]
        local author   = entry.author
        local aentries = entries[author]
        if aentries then
            aentries[#aentries+1] = entry
        else
            entries[author] = { entry }
        end
    end
    for i=1,#found do
        local entry    = found[i]
        local author   = entry.author
        local aentries = entries[author]
        if not aentries then
            result[#result+1] = entry
        elseif aentries == true then
            -- already done
        else
            result[#result+1] = entry
            entry.entries = aentries
            entries[author] = true
        end
    end
    -- todo: add letters (should we then tag all?)
    return result
end

local function authorconcat(target,key,setup)
    ctx_btxstartsubcite(setup)
    local nofcollected = #target
    if nofcollected == 0 then
        unknowncite(tag)
    else
        for i=1,nofcollected do
            local entry = target[i]
            local first = entry.first
            local tag   = entry.tag
            local currentcitation = markcite(entry.dataset,tag)
            ctx_btxstartciteauthor()
            ctx_btxsettag(tag)
            ctx_btxsetbacklink(currentcitation)
            local bl = listtocite[currentcitation]
            ctx_btxsetinternal(bl and bl.references.internal or "")
            if first then
                ctx_btxsetfirst(first[key] or f_missing(first.tag))
                local suffix = entry.suffix
                local value  = entry.last[key]
                if suffix then
                    ctx_btxsetsecond(value .. converters.characters(suffix))
                else
                    ctx_btxsetsecond(value)
                end
            else
                local suffix = entry.suffix
                local value  = entry[key] or f_missing(tag)
                if suffix then
                    ctx_btxsetfirst(value .. converters.characters(suffix))
                else
                    ctx_btxsetfirst(value)
                end
            end
            ctx_btxsetconcat(concatstate(i,nofcollected))
            ctx_btxcitesetup(setup)
            ctx_btxstopciteauthor()
        end
    end
    ctx_btxstopsubcite()
end

local function authorsingle(entry,key,setup)
    ctx_btxstartsubcite(setup)
    ctx_btxstartciteauthor()
    local tag = entry.tag
    ctx_btxsettag(tag)
 -- local currentcitation = markcite(entry.dataset,tag)
 -- ctx_btxsetbacklink(currentcitation)
 -- local bl = listtocite[currentcitation]
 -- ctx_btxsetinternal(bl and bl.references.internal or "")
    ctx_btxsetfirst(entry[key] or f_missing(tag))
    ctx_btxcitesetup(setup)
    ctx_btxstopciteauthor()
    ctx_btxstopsubcite()
end

local partialinteractive = false

local function authorgetter(first,last,key,setup) -- only first
 -- ctx_btxsetfirst(first.author)         -- unformatted
    ctx_btxsetfirst(currentbtxciteauthor) -- formatter (much slower)
    local entries = first.entries
    -- alternatively we can use a concat with one ... so that we can only make the
    -- year interactive, as with the concat
    if partialinteractive and not entries then
        entries = { first }
    end
    if entries then
        local c = compresslist(entries)
        local f = function() authorconcat(c,key,setup) return true end -- indeed return true?
        ctx_btxsetcount(#c)
        ctx_btxsetsecond(f)
    else
        local f = function() authorsingle(first,key,setup) return true end -- indeed return true?
        ctx_btxsetcount(0)
        ctx_btxsetsecond(f)
    end
    return true
end

-- author

local function setter(dataset,tag,entry,internal)
    return {
        dataset  = dataset,
        tag      = tag,
        internal = internal,
        author   = getfield(dataset,tag,"author"),
    }
end

local function getter(first,last,_,setup)
 -- ctx_btxsetfirst(first.author)         -- unformatted
    ctx_btxsetfirst(currentbtxciteauthor) -- formatter (much slower)
    return true
end

function citevariants.author(dataset,reference,mark,compress,variant,internal)
    processcite(dataset,reference,mark,false,"author",internal,setter,getter)
end

-- authornum

local function setter(dataset,tag,entry,internal)
    local text = entry.entries.text
    return {
        dataset  = dataset,
        tag      = tag,
        internal = internal,
        author   = getfield(dataset,tag,"author"),
        num      = text,
        sortkey  = text and lpegmatch(numberonly,text),
    }
end

local function getter(first,last)
    authorgetter(first,last,"num","author:num")
    return true
end

local function compressor(found)
    return authorcompressor(found) -- can be just an alias
end

function citevariants.authornum(dataset,reference,mark,compress,variant,internal)
    processcite(dataset,reference,mark,compress,"authornum",internal,setter,getter,compressor)
end

-- authoryear | authoryears

local function setter(dataset,tag,entry,internal)
    local year = getfield(dataset,tag,"year")
    return {
        dataset  = dataset,
        tag      = tag,
        internal = internal,
        author   = getfield(dataset,tag,"author"),
        year     = year,
        sortkey  = year and lpegmatch(numberonly,year),
        sortfld  = "year",
    }
end

local function getter(first,last)
    authorgetter(first,last,"year","author:year")
    return true
end

local function compressor(found)
    return authorcompressor(found)
end

function citevariants.authoryear(dataset,reference,mark,compress,variant,internal)
    processcite(dataset,reference,mark,compress,"authoryear",internal,setter,getter,compressor)
end

local function getter(first,last)
    authorgetter(first,last,"year","author:years")
    return true
end

function citevariants.authoryears(dataset,reference,mark,compress,variant,internal)
    processcite(dataset,reference,mark,compress,"authoryears",internal,setter,getter,compressor)
end

-- List variants

local listvariants        = { }
publications.listvariants = listvariants

function commands.btxlistvariant(dataset,block,tag,variant,listindex)
    local action = listvariants[variant] or listvariants.default
    if action then
        action(dataset,block,tag,variant,tonumber(listindex) or 0)
    end
end

function listvariants.default(dataset,block,tag,variant)
    ctx_btxsetfirst("?")
    ctx_btxlistsetup(variant)
end

function listvariants.num(dataset,block,tag,variant,listindex)
    ctx_btxsetfirst(listindex)
    ctx_btxlistsetup(variant)
end

listvariants[v_yes] = listvariants.num
listvariants.bib    = listvariants.num

function listvariants.short(dataset,block,tag,variant,listindex)
    local short  = getdetail(dataset,tag,"short","short")
    local suffix = getdetail(dataset,tag,"suffix","suffix")
    if short then
        ctx_btxsetfirst(short)
    end
    if suffix then
        ctx_btxsetsecond(suffix)
    end
    ctx_btxlistsetup(variant)
end

function listvariants.page(dataset,block,tag,variant,listindex)
    local rendering     = renderings[dataset]
    local specification = rendering.list[listindex]
    for i=3,#specification do
        local backlink = tonumber(specification[i])
        if backlink then
            local citation = citetolist[backlink]
            if citation then
                local references = citation.references
                if references then
                    local internal = references.internal
                    local realpage = references.realpage
                    if internal and realpage then
                        ctx_btxsetconcat(i-2)
                        ctx_btxsetfirst(realpage)
                        ctx_btxsetsecond(backlink)
                        ctx_btxlistsetup(variant)
                    end
                end
            end
        end
    end
end