summaryrefslogtreecommitdiff
path: root/biblio/citation-style-language/citeproc-output.lua
blob: 0c056fa74802fb89a3f33f0a0b29f0bbd59967eb (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
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
--
-- Copyright (c) 2021-2024 Zeping Lee
-- Released under the MIT license.
-- Repository: https://github.com/zepinglee/citeproc-lua
--

local output_module = {}

local lpeg = require("lpeg")
local uni_utf8
local unicode
local dom
local ir_node
local util

if kpse then
  uni_utf8 = require("unicode").utf8
  unicode = require("citeproc-unicode")
  dom = require("luaxml-domobject")
  ir_node = require("citeproc-ir-node")
  util = require("citeproc-util")
else
  uni_utf8 = require("lua-utf8")
  unicode = require("citeproc.unicode")
  dom = require("citeproc.luaxml.domobject")
  ir_node = require("citeproc.ir-node")
  util = require("citeproc.util")
end

local GroupVar = ir_node.GroupVar


---@class LocalizedQuotes
local LocalizedQuotes = {
  outer_open = util.unicode['left double quotation mark'],
  outer_close = util.unicode['right double quotation mark'],
  inner_open = util.unicode['left single quotation mark'],
  inner_close = util.unicode['right single quotation mark'],
  punctuation_in_quote = false,
}

function LocalizedQuotes:new(outer_open, outer_close, inner_open, inner_close, punctuation_in_quote)
  local o = {
    outer_open = outer_open or util.unicode['left double quotation mark'],
    outer_close = outer_close or util.unicode['right double quotation mark'],
    inner_open = inner_open or util.unicode['left single quotation mark'],
    inner_close = inner_close or util.unicode['right single quotation mark'],
    punctuation_in_quote = punctuation_in_quote,
  }
  setmetatable(o, self)
  self.__index = self
  return o
end

-- Inspired by:
-- https://github.com/zotero/citeproc-rs/blob/master/crates/io/src/output/markup.rs#L67
-- https://hackage.haskell.org/package/pandoc-types-1.22.2.1/docs/Text-Pandoc-Definition.html
---@class InlineElement
---@field _type string
---@field _base_class string
---@field value string?
---@field inlines InlineElement[]?
local InlineElement = {
  _type = "InlineElement",
  _base_class = "InlineElement",
  value = nil,
  inlines = nil,
}



---comment
---@param class_name string
---@return table
function InlineElement:derive(class_name)
  local o = {
    _type  = class_name,
  }
  -- self[class_name] = o
  setmetatable(o, self)
  self.__index = self
  o.__index = o
  return o
end

function InlineElement:new(inlines)
  local o = {
    inlines = inlines,
    _type  = self._type,
  }
  setmetatable(o, self)
  return o
end


function InlineElement:_debug()
  local text = self._type .. "("
  if self.value then
    text = text .. '"' .. self.value .. '"'
  elseif self.inlines then
    local inlines_text = ""
    for _, inline in ipairs(self.inlines) do
      if inlines_text ~= "" then
        inlines_text = inlines_text .. ", "
      end
      inlines_text = inlines_text .. inline:_debug()
    end
    text = text .. inlines_text
  end
  text = text .. ")"
  return text
end


---@class PlainText: InlineElement
local PlainText = InlineElement:derive("PlainText")

---@param value string
---@return PlainText
function PlainText:new(value)
  local o = InlineElement.new(self)
  o.value = value
  setmetatable(o, self)
  return o
end


---@class Formatted: InlineElement
---@field formatting table?
local Formatted = InlineElement:derive("Formatted")

---@param inlines InlineElement[]
---@param formatting table?
---@return Formatted
function Formatted:new(inlines, formatting)
  local o = InlineElement.new(self)
  o.inlines = inlines
  o.formatting = formatting
  setmetatable(o, self)
  return o
end


---@class Micro: InlineElement
local Micro = InlineElement:derive("Micro")

-- This is how we can flip-flop only user-supplied styling.
-- Inside this is parsed micro html
---@param inlines InlineElement[]
---@return Micro
function Micro:new(inlines)
  local o = InlineElement.new(self)
  o.inlines = inlines
  setmetatable(o, self)
  return o
end


---@class Quoted: InlineElement
---@field is_inner boolean
---@field quotes table
local Quoted = InlineElement:derive("Quoted")

---@param inlines InlineElement[]
---@param localized_quotes table?
---@return Quoted
function Quoted:new(inlines, localized_quotes)
  local o = InlineElement.new(self)
  o.inlines = inlines
  o.is_inner = false
  if localized_quotes then
    o.quotes = localized_quotes
  else
    o.quotes = LocalizedQuotes:new()
  end

  setmetatable(o, self)
  return o
end


---@class Code: InlineElement
local Code = InlineElement:derive("Code")

---@param value string
---@return Code
function Code:new(value)
  local o = InlineElement.new(self)
  o.value = value
  setmetatable(o, self)
  return o
end


---@class MathML: InlineElement
local MathML = InlineElement:derive("MathML")

---@param value string
---@return MathML
function MathML:new(value)
  local o = InlineElement.new(self)
  o.value = value
  setmetatable(o, self)
  return o
end


---@class MathTeX: InlineElement
local MathTeX = InlineElement:derive("MathTeX")

---@param value string
---@return MathTeX
function MathTeX:new(value)
  local o = InlineElement.new(self)
  o.value = value
  setmetatable(o, self)
  return o
end


---@class NoCase: InlineElement
local NoCase = InlineElement:derive("NoCase")

---@param inlines InlineElement[]
---@return NoCase
function NoCase:new(inlines)
  local o = InlineElement.new(self)
  o.inlines = inlines
  setmetatable(o, self)
  return o
end


---@class NoDecor: InlineElement
local NoDecor = InlineElement:derive("NoDecor")

---@param inlines InlineElement[]
---@return NoDecor
function NoDecor:new(inlines)
  local o = InlineElement.new(self)
  o.inlines = inlines
  setmetatable(o, self)
  return o
end


---@class Linked: InlineElement
---@field href string
local Linked = InlineElement:derive("Linked")

---@param value string
---@param href string
---@return Linked
function Linked:new(value, href)
  local o = InlineElement.new(self)
  o.value = value
  o.href = href
  setmetatable(o, self)
  return o
end


---@class Div: InlineElement
---@field div table?
local Div = InlineElement:derive("Div")

---@param inlines InlineElement[]
---@param display table?
---@return Div
function Div:new(inlines, display)
  local o = InlineElement.new(self)
  o.inlines = inlines
  o.div = display
  setmetatable(o, self)
  return o
end


---@class CiteInline: InlineElement
---@field cite_item CitationItem
local CiteInline = InlineElement:derive("CiteInline")

---@param inlines InlineElement[]
---@param cite_item CitationItem
---@return CiteInline
function CiteInline:new(inlines, cite_item)
  local o = InlineElement.new(self)
  o.inlines = inlines
  o.cite_item = cite_item
  setmetatable(o, self)
  return o
end


---@param text string
---@param context Context?
---@param is_external boolean?
---@return InlineElement[]
function InlineElement:parse(text, context, is_external)
  local text_type = type(text)
  local inlines
  if text_type == "table" then
    -- CSL rich text
    inlines = self:parse_csl_rich_text(text)
  elseif text_type == "string" then
    -- String with HTML-like formatting tags
    -- util.debug(text)
    inlines = self:parse_html_tags(text, context, is_external)
    -- util.debug(inlines)
  elseif text_type == "number" then
    inlines = {PlainText:new(tostring(text))}
  else
    util.error("Invalid text type")
  end
  return inlines
end

---@param text string | (string | table)[]
---@return InlineElement[]
function InlineElement:parse_csl_rich_text(text)
  -- Example: [
  --   "A title with a",
  --   {
  --     "quote": "quoted string."
  --   }
  -- ]
  local inlines = {}

  local text_type = type(text)
  if text_type == "string" then
    table.insert(inlines, PlainText:new(text))
  elseif text_type == "table" then
    for _, subtext in ipairs(text) do
      local subtext_type = type(subtext)
      local inline
      if subtext_type == "string" then
        inline = PlainText:new(subtext)
      elseif subtext_type == "table" then
        local format
        local content
        for format_, content_ in pairs(subtext) do
          format = format_
          content = content_
        end
        if format == "bold" then
          inline = Formatted:new(self:parse_csl_rich_text(content), {["font-weight"] = "bold"})
        elseif format == "code" then
          if type(content) ~= "string" then
            util.error("Invalid rich text content.")
          end
          inline = Code:new(content)
        elseif format == "italic" then
          inline = Formatted:new(self:parse_csl_rich_text(content), {["font-style"] = "italic"})
        elseif format == "math-ml" then
          if type(content) ~= "string" then
            util.error("Invalid rich text content.")
          end
          inline = Code:new(content)
        elseif format == "math-tex" then
          if type(content) ~= "string" then
            util.error("Invalid rich text content.")
          end
          inline = Code:new(content)
        elseif format == "preserve" then
          inline = NoCase:new(self:parse_csl_rich_text(content))
        elseif format == "quote" then
          inline = Quoted:new(self:parse_csl_rich_text(content))
        elseif format == "sc" then
          inline = Formatted:new(self:parse_csl_rich_text(content), {["font-variant"] = "small-caps"})
        elseif format == "strike" then
          inline = Formatted:new(self:parse_csl_rich_text(content), {["strike-through"] = true})
        elseif format == "sub" then
          inline = Formatted:new(self:parse_csl_rich_text(content), {["font-variant"] = "small-caps"})
        elseif format == "sup" then
          inline = Formatted:new(self:parse_csl_rich_text(content), {["font-variant"] = "small-caps"})
        end
      end
      table.insert(inlines, inline)
    end
  else
    util.error("Invalid text type")
  end

  return inlines
end

local function tokens2inlines(tokens)
  local inlines = {}
  local i = 1
  while i <= #tokens do
    local token = tokens[i]
    if type(token) == "string" then
      local text = token
      local j = i + 1
      while j <= #tokens and type(tokens[j]) == "string" do
        text = text .. tokens[j]
        j = j + 1
      end
      i = j
      table.insert(inlines, PlainText:new(text))
    else
      table.insert(inlines, token)
      i = i + 1
    end
  end
  return inlines
end

local function get_inline_element_grammar()
  local P = lpeg.P
  local C = lpeg.C
  local Ct = lpeg.Ct
  local S = lpeg.S
  local V = lpeg.V
  local spaces = P(" ")^1
  local grammar = P{
    "content";
    token = V"italic" + V"bold" + V"sup" + V"sub" + V"sc" + V"small_caps" + V"span_nocase" + V"nodecor" + V"mathtex" + V"mathml" + V"code" + V"script" + C(1),
    content = Ct((V"token")^0) / tokens2inlines,
    italic = P"<i>" * Ct((V"token" - P"</i>")^0) * P"</i>" / function (tokens)
      return Formatted:new(tokens2inlines(tokens), {["font-style"] = "italic"})
    end,
    bold = P"<b>" * Ct((V"token" - P"</b>")^0) * P"</b>" / function (tokens)
      return Formatted:new(tokens2inlines(tokens), {["font-weight"] = "bold"})
    end,
    sup = P"<sup>" * Ct((V"token" - P"</sup>")^0) * P"</sup>" / function (tokens)
      return Formatted:new(tokens2inlines(tokens), {["vertical-align"] = "sup"})
    end,
    sub = P"<sub>" * Ct((V"token" - P"</sub>")^0) * P"</sub>" / function (tokens)
      return Formatted:new(tokens2inlines(tokens), {["vertical-align"] = "sub"})
    end,
    sc = P"<sc>" * Ct((V"token" - P"</sc>")^0) * P"</sc>" / function (tokens)
      return Formatted:new(tokens2inlines(tokens), {["font-variant"] = "small-caps"})
    end,
    quoted = (
          C(P'"') * Ct((V"token" - P'"')^0) * C(P'"')
          + C(P"'") * Ct((V"token" - P"'")^0) * C(P"'")
          + C(P'“') * Ct((V"token" - P'”')^0) * C(P'”')
          + C(P"‘") * Ct((V"token" - P"’")^0) * C(P"’")
          + C(P"«") * Ct((V"token" - P"»")^0) * C(P"»")
        ) / function (open, tokens, close)
      return Quoted:new(tokens2inlines(tokens), LocalizedQuotes:new(open, close))
    end,
    small_caps = P"<span" * spaces * P'style="font-variant:' * spaces^0 * P'small-caps;">' * Ct((V"token" - P"</span>")^0) * P"</span>" / function (tokens)
      return Formatted:new(tokens2inlines(tokens), {["font-variant"] = "small-caps"})
    end,
    -- nocase = P"<nocase>" * Ct((V"token" - P"</nocase>")^0) * P"</nocase>" / function (tokens)
    --   return NoCase:new(tokens2inlines(tokens))
    -- end,
    span_nocase = P"<span" * spaces * P'class="nocase">' * Ct((V"token" - P"</span>")^0) * P"</span>" / function (tokens)
      return NoCase:new(tokens2inlines(tokens))
    end,
    nodecor = P"<span" * spaces * P'class="nodecor">' * Ct((V"token" - P"</span>")^0) * P"</span>" / function (tokens)
      return NoDecor:new(tokens2inlines(tokens))
    end,
    mathtex = P"<mathtex>" * Ct((1- P"</mathtex>")^0) * P"</mathtex>" / function (text)
      return MathML:new(text)
    end,
    mathml = P"<math>" * C((1- P"</math>")^0) * P"</math>" / function (text)
      return MathML:new(text)
    end,
    code = P"<code>" * C((1 - P"</code>")^0) * P"</code>" / function (text)
      return Code:new(text)
    end,
    script = P"<script>" * C((1- P"</script>")^0) * P"</script>" / function (text)
      return Code:new(text)
    end,
  }
  return grammar
end

local inline_element_grammar = get_inline_element_grammar()

---@param str string
---@param context Context?
---@param is_external boolean?
---@return InlineElement[]
function InlineElement:parse_html_tags(str, context, is_external)
  local inlines = inline_element_grammar:match(str)
  inlines = InlineElement:parse_quotes(inlines, context, is_external)
  return inlines
end

-- TODO: Rewrite with lpeg
---@param inlines InlineElement[]
---@param context Context
---@param is_external boolean?
---@return table
function InlineElement:parse_quotes(inlines, context, is_external)
  local quote_fragments = InlineElement:get_quote_fragments(inlines)
  -- util.debug(quote_fragments)

  local quote_stack = {}
  local text_stack = {{}}

  local localized_quotes
  if context then
    localized_quotes = context:get_localized_quotes()
  else
    localized_quotes = LocalizedQuotes:new()
  end

  for _, fragment in ipairs(quote_fragments) do
    local top_text_list = text_stack[#text_stack]

    if type(fragment) == "table" then
      if fragment.inlines then
        fragment.inlines = self:parse_quotes(fragment.inlines, context, is_external)
      end
      table.insert(top_text_list, fragment)

    elseif type(fragment) == "string" then
      local quote = fragment
      local top_quote = quote_stack[#quote_stack]

      if quote == "'" then
        if top_quote == "'" and #top_text_list > 0 then
          table.remove(quote_stack)
          local quoted = Quoted:new(top_text_list, localized_quotes)
          table.remove(text_stack)
          table.insert(text_stack[#text_stack], quoted)
        else
          table.insert(quote_stack, quote)
          table.insert(text_stack, {})
        end

      elseif quote == '"' then
        if top_quote == '"' then
          table.remove(quote_stack)
          local quoted = Quoted:new(top_text_list, localized_quotes)
          table.remove(text_stack)
          table.insert(text_stack[#text_stack], quoted)
        else
          table.insert(quote_stack, quote)
          table.insert(text_stack, {})
        end

      elseif quote == util.unicode["left single quotation mark"] or
             quote == util.unicode["left double quotation mark"] or
             quote == util.unicode["left-pointing double angle quotation mark"] then
        table.insert(quote_stack, quote)
        table.insert(text_stack, {})

      elseif (quote == util.unicode["right single quotation mark"] and
              top_quote == util.unicode["left single quotation mark"]) or
             (quote == util.unicode["right double quotation mark"] and
              top_quote == util.unicode["left double quotation mark"]) or
             (quote == util.unicode["right-pointing double angle quotation mark"] and
              top_quote == util.unicode["left-pointing double angle quotation mark"]) then
          table.remove(quote_stack)
          if is_external then
            -- The text is from prefix or suffix of citationItem.
            -- See flipflop_LeadingMarkupWithApostrophe.txt
            localized_quotes.outer_open = top_quote
            localized_quotes.outer_close = quote
            localized_quotes.inner_open = top_quote
            localized_quotes.inner_close = quote
          end
          local quoted = Quoted:new(top_text_list, localized_quotes)
          table.remove(text_stack)
          table.insert(text_stack[#text_stack], quoted)

      else
        local last_inline = top_text_list[#top_text_list]
        if last_inline and last_inline._type == "PlainText" then
          last_inline.value = last_inline.value .. fragment
        else
          table.insert(top_text_list, PlainText:new(fragment))
        end
      end

    end
  end

  local elements = text_stack[1]
  if #text_stack > 1 then
    -- assert(#text_stack == #quote_stack + 1)
    for i, quote in ipairs(quote_stack) do
      if quote == "'" then
        quote = util.unicode["apostrophe"]
      end
      local last_inline = elements[#elements]
      if last_inline and last_inline._type == "PlainText" then
        last_inline.value = last_inline.value .. quote
      else
        table.insert(elements, PlainText:new(quote))
      end

      for _, inline in ipairs(text_stack[i + 1]) do
        if inline._type == "PlainText" then
          local last_inline = elements[#elements]
          if last_inline and last_inline._type == "PlainText" then
            last_inline.value = last_inline.value .. inline.value
          else
            table.insert(elements, inline)
          end
        else
          table.insert(elements, inline)
        end
      end
    end
  end

  return elements
end

local function merge_fragments_at(fragments, i)
  if type(fragments[i+1]) == "string" then
    fragments[i] = fragments[i] .. fragments[i+1]
    table.remove(fragments, i+1)
  end
  if type(fragments[i-1]) == "string" then
    fragments[i-1] = fragments[i-1] .. fragments[i]
    table.remove(fragments, i)
  end
end

-- Return a list of strings and InlineElement
function InlineElement:get_quote_fragments(inlines)
  local fragments = {}
  for _, inline in ipairs(inlines) do
    if inline._type == "PlainText" then
      local quote_tuples = {}
      for _, quote in ipairs({
        "'",
        '"',
        util.unicode["left single quotation mark"],
        util.unicode["right single quotation mark"],
        util.unicode["left double quotation mark"],
        util.unicode["right double quotation mark"],
        util.unicode["left-pointing double angle quotation mark"],
        util.unicode["right-pointing double angle quotation mark"],
      }) do
        string.gsub(inline.value, "()(" .. quote .. ")()", function (idx, qt, next_idx)
          table.insert(quote_tuples, {idx, qt, next_idx})
        end)
      end
      table.sort(quote_tuples, function (a, b)
        return a[1] < b[1]
      end)
      local start_idx = 1
      for _, quote_tuple in ipairs(quote_tuples) do
        local idx, qt, next_idx = table.unpack(quote_tuple)
        local fragment = string.sub(inline.value, start_idx, idx-1)
        if fragment ~= "" then
          table.insert(fragments, fragment)
        end
        table.insert(fragments, qt)
        start_idx = next_idx
      end
      -- Insert last fragment
      local fragment = string.sub(inline.value, start_idx, #inline.value)
      if fragment ~= "" then
        table.insert(fragments, fragment)
      end
    else
      table.insert(fragments, inline)
    end

    for i = #fragments, 1, -1 do
      local fragment = fragments[i]
      if fragment == "'" or fragment == '"' then
        local left, right
        if i > 1 then
          left = fragments[i - 1]
          if type(left) == "table" then
            left = left:get_right_most_string()
          end
        end
        if i < #fragments then
          right = fragments[i + 1]
          if type(right) == "table" then
            right = right:get_left_most_string()
          end
        end
        -- TODO: consider utf-8
        if left and right then
          if string.match(left, "%s$") and string.match(right, "^%s") then
            -- Orphan quote: bugreports_SingleQuote.txt
            if fragment == "'" then
              fragments[i] = util.unicode['apostrophe']
            end
            merge_fragments_at(fragments, i)
          end
          if not string.match(left, "[%s%p]$") and not string.match(right, "^[%s%p]") then
            if fragment == "'" then
              fragments[i] = util.unicode['apostrophe']
            end
            merge_fragments_at(fragments, i)
          end
        end
      end
    end
  end
  return fragments
end

function InlineElement:get_left_most_string()
  if self.value then
    return self.value
  elseif self.inlines then
    return self.inlines[1]:get_left_most_string()
  end
end

function InlineElement:get_right_most_string()
  if self.value then
    return self.value
  elseif self.inlines then
    return self.inlines[#self.inlines]:get_left_most_string()
  end
end

function InlineElement:capitalize_first_term()
  -- util.debug(self)
  if self._type == "PlainText" then
    self.value = unicode.capitalize(self.value)
  elseif self._type ~= "Code" and self._type ~= "MathML" and self._type ~= "MathTeX" then
    if self.inlines[1] then
    self.inlines[1]:capitalize_first_term()
    end
  end
end

--[[
Class inheritance hierarchical

OutputFormat
├── SortStringFormat
├── DisamStringFormat
└── Markup
    ├── LatexWriter
    ├── HtmlWriter
    └── PlainTextWriter
--]]

---@class OutputFormat
---@field name string
---@field markups table<string, string>
local OutputFormat = {

}

function OutputFormat:new(format_name)
  local o = {
    name = format_name,
    -- markups = {},
  }
  setmetatable(o, self)
  self.__index = self
  return o
end

function OutputFormat:flatten_ir(ir, override_delim)
  if self.group_var == GroupVar.Missing or self.collapse_suppressed then
    return {}
  end
  local inlines = {}
  if ir._type == "SeqIr" or ir._type == "NameIr" then
    inlines = self:flatten_seq_ir(ir, override_delim)
  else
    inlines = self:with_format(ir.inlines, ir.formatting)
    inlines = self:affixed_quoted(inlines, ir.affixes, ir.quotes);
    inlines = self:with_display(inlines, ir.display);
  end
  return inlines
end

function OutputFormat:flatten_seq_ir(ir, override_delim)
  -- if not ir.children then
  --   print(debug.traceback())
  -- end
  if #ir.children == 0 then
    return {}
  end
  local inlines_list = {}
  local delimiter = ir.delimiter
  if not delimiter and ir.should_inherit_delim then
    delimiter = override_delim
  end

  for _, child in ipairs(ir.children) do
    if child.group_var ~= GroupVar.Missing and not child.collapse_suppressed then
      local child_inlines = self:flatten_ir(child, delimiter)
      if #child_inlines > 0 then
        table.insert(inlines_list, child_inlines)
      end
    end
  end

  if #inlines_list == 0 then
    return {}
  end

  local inlines = self:group(inlines_list, delimiter, ir.formatting)
  -- assert ir.quotes == localized quotes
  inlines = self:affixed_quoted(inlines, ir.affixes, ir.quotes);
  inlines = self:with_display(inlines, ir.display);
  return inlines
end

function OutputFormat:group(inlines_list, delimiter, formatting)
  -- Each node is list of InlineElements
  if #inlines_list == 1 then
    return self:format_list(inlines_list[1], formatting)
  else
    local inlines = OutputFormat:join_many(inlines_list, delimiter)
    return self:format_list(inlines, formatting)
  end
end

function OutputFormat:format_list(inlines, formatting)
  if formatting then
    return {Formatted:new(inlines, formatting)}
  else
    return inlines
  end
end

function OutputFormat:join_many(lists, delimiter)
  local res = {}
  for i, list in ipairs(lists) do
    if delimiter and i > 1 then
      table.insert(res, PlainText:new(delimiter))
    end
    for _, el in ipairs(list) do
      table.insert(res, el)
    end
  end
  return res
end

function OutputFormat:with_format(inlines, formatting)
  return self:format_list(inlines, formatting)
end


---Check if there is a lowercase word not in CSL's stop words
---@param str string
---@return boolean
local function is_str_sentence_case(str)
  local words = unicode.words(str)
  for _, word in ipairs(words) do
    if unicode.islower(word) and not util.stop_words[word] then
      -- util.debug(word)
      return true
    end
  end
  return false
end

---Returns true if the inlines contain a lowercase word which is not CSL's stop words.
---@param inlines table[]
---@return boolean
function OutputFormat:is_sentence_case(inlines)
  for _, inline in ipairs(inlines) do
    if util.is_instance(inline, PlainText) then
      if is_str_sentence_case(inline.value) then
        -- util.debug(inline.value)
        return true
      end

    elseif util.is_instance(inline, Quoted)
        or util.is_instance(inline, NoCase)
        or util.is_instance(inline, NoDecor)
        or util.is_instance(inline, CiteInline)
        or (util.is_instance(inline, Formatted)
            and inline.formatting["font-variant"] ~= "small-caps"
            and inline.formatting["vertical-align"] ~= "sup"
            and inline.formatting["vertical-align"] ~= "sub") then
      if self:is_sentence_case(inline.inlines) then
        return true
      end
    end
  end
  return false
end

---1. For uppercase strings, the first character of the string remains capitalized.
---   All other letters are lowercased.
---2. For lower or mixed case strings, the first character of the first word is
---   capitalized if the word is lowercase.
---3. All other words are lowercased if capitalized.
---@param inlines table[]
---@param check_sentence_case boolean
function OutputFormat:convert_sentence_case(inlines, check_sentence_case)
  if not inlines or #inlines == 0  then
    return
  end
  local is_uppercase = false  -- TODO
  -- util.debug(check_sentence_case)
  -- util.debug(self:is_sentence_case(inlines))
  if check_sentence_case then
    if self:is_sentence_case(inlines) then
      self:apply_text_case_inner(inlines, "capitalize-first", false, is_uppercase)
    else
      self:apply_text_case_inner(inlines, "sentence-strong", false, is_uppercase)
    end
  else
    self:apply_text_case_inner(inlines, "sentence-strong", false, is_uppercase)
  end
end

function OutputFormat:apply_text_case(inlines, text_case, is_english)
  if not inlines or #inlines == 0 or not text_case then
    return
  end
  -- Title case conversion only affects English-language items.
  if text_case == "title" and not is_english then
    return
  end
  local is_uppercase = false  -- TODO
  self:apply_text_case_inner(inlines, text_case, false, is_uppercase)
end

local function string_contains_word(str)
  return string.match(str, "%w") ~= nil
end

local function inline_contains_word(inline)
  if inline._type == "PlainText" then
    return string_contains_word(inline.value)
  elseif inline.inlines then
    for _, el in ipairs(inline.inlines) do
      if inline_contains_word(el) then
        return true
      end
    end
  end
  return false
end

function OutputFormat:apply_text_case_inner(inlines, text_case, seen_one, is_uppercase)
  for i, inline in ipairs(inlines) do
    if seen_one and text_case == "capitalize-first" then
      break
    end
    local is_last = (i == #inlines)
    if inline._type == "PlainText" then
      -- util.debug(inline.value)
      -- util.debug(text_case)
      inline.value = self:transform_case(inline.value, text_case, seen_one, is_last, is_uppercase);
      -- util.debug(inline.value)
      seen_one = seen_one or string_contains_word(inline.value)

    elseif inline._type == "NoCase" or
           inline._type == "NoDecor" or
           inline._type == "Code" or
           inline._type == "MathML" or
           inline._type == "MathTeX" or
           (inline._type == "Formatted" and inline.formatting["font-variant"] == "small-caps") or
           (inline._type == "Formatted" and inline.formatting["vertical-align"] == "sup") or
           (inline._type == "Formatted" and inline.formatting["vertical-align"] == "sub") then
      seen_one = seen_one or inline_contains_word(inline)

    elseif inline._type == "Formatted" or inline._type == "Quoted" or inline._type == "CiteInline" then
      seen_one = self:apply_text_case_inner(inline.inlines, text_case, seen_one, is_uppercase) or seen_one

    end
  end
  return seen_one
end

local function transform_lowercase(str)
  return unicode.lower(str)
end

local function transform_uppercase(str)
  -- TODO: locale specific uppercase: textcase_LocaleUnicode.txt
  return unicode.upper(str)
end

---comment
---@param str string
---@param is_first boolean
---@param transform function
---@return string
local function transform_first_word(str, is_first, transform)
  if is_first then
    local segments = unicode.split_word_bounds(str)
    for i, segment in ipairs(segments) do
      -- bugreports_ThesisUniversityAppearsTwice.txt: "Ph.D"
      if uni_utf8.match(segment, "%a") then
        -- util.debug(segment)
        segments[i] = transform(segment)
        break
      end
    end
    str = table.concat(segments)
  end
  return str
end


local SegmentType = {
  Word = 1,
  Puctuation = 2,
  EndingPunctuation = 3,  -- "?" and "!" excluding "." Do we need a sentence break?
  Colon = 4,  -- Including em-dash
  Other = 0,
}

---comment
---@param str string
---@param seen_one boolean
---@param is_last_inline boolean
---@param transform function
---@return string
local function transform_each_word(str, seen_one, is_last_inline, transform)
  local segments = unicode.split_word_bounds(str)
  -- util.debug(segments)

  local segment_type_list = {}
  local last_word_idx
  for i, segment in ipairs(segments) do
    segment_type_list[i] = SegmentType.Other

    -- Do not use isalnum(): "can't"
    if uni_utf8.match(segment, "%w") then
      segment_type_list[i] = SegmentType.Word
      last_word_idx = i

    elseif uni_utf8.match(segment, "%p") then
      segment_type_list[i] = SegmentType.Puctuation
      if segment == "!" or segment == "?" then
        segment_type_list[i] = SegmentType.EndingPunctuation
      -- elseif segment == ":" or segment == "—" then
      elseif segment == ":" then
        -- Em dash is not taken into consideration, see "Stability—with Job" in `textcase_TitleWithEmDash.txt`
        segment_type_list[i] = SegmentType.Colon
      end
    end
  end

  local sentence_begin = not seen_one
  local after_colon = false

  for i, segment in ipairs(segments) do
    if segment_type_list[i] == SegmentType.Word then
      local is_first_word = sentence_begin
      local is_last_word = segment_type_list[i+1] == SegmentType.EndingPunctuation
        or (is_last_inline and i == last_word_idx)
      -- See "Pro-Environmental" in `textcase_StopWordBeforeHyphen.txt`
      -- but not "Out-of-Fashion" in `textcase_TitleCaseWithHyphens.txt`.
      local ignore_stop_word = segments[i+1] == "-" and segments[i-1] ~= "-"

      -- util.debug(segment)
      -- util.debug(after_colon)
      -- See "07-x" in `textcase_LastChar.txt`
      if not (segments[i-1] == "-" and unicode.len(segment) == 1) then
        segments[i] = transform(segment, is_first_word, after_colon, is_last_word, ignore_stop_word)

      end
      -- util.debug(segments[i])

      sentence_begin = false
      after_colon = false

    elseif segment_type_list[i] == SegmentType.EndingPunctuation then
      sentence_begin = true

    elseif segment_type_list[i] == SegmentType.Colon then
      after_colon = true

    end
  end
  return table.concat(segments)
end

---comment
---@param word string
---@return string
local function transform_capitalize_word_if_lower(word)
  if unicode.islower(word) then
    local res = unicode.capitalize(word)
    return res
  else
    return word
  end
end

local function title_case_word(word, is_first, after_end_punct, is_last, ignore_stop_word)
  -- Entirely non-English
  -- e.g. "β" in "β-Carotine"
  -- TODO: two-word cases like "due to"
  -- util.debug(word)
  -- util.debug(ignore_stop_word)
  local res
  if (is_first or is_last or after_end_punct or ignore_stop_word or not util.stop_words[word])
      and string.match(word, "%a") and unicode.islower(word) then
    res = unicode.capitalize(word)
  else
    res = word
  end
  -- util.debug(res)
  return res
end

local function transform_lowercase_if_capitalize(word, is_first, after_end_punct, is_last, is_stop_word)
  -- util.debug(word)
  if not (is_first or after_end_punct) then
    local is_capitalize_word = false
    local lower_first = string.gsub(word, utf8.charpattern, unicode.lower, 1)
    if unicode.islower(lower_first) then
      return lower_first
    else
      return word
    end
  else
    return word
  end
end

function OutputFormat:transform_case(str, text_case, seen_one, is_last, is_uppercase)
  local res = str
  if text_case == "lowercase" then
    res = transform_lowercase(str)
  elseif text_case == "uppercase" then
    res = transform_uppercase(str)
  elseif text_case == "capitalize-first" then
    res = transform_first_word(str, not seen_one, transform_capitalize_word_if_lower)
  elseif text_case == "capitalize-all" then
    res = transform_each_word(str, false, true, transform_capitalize_word_if_lower)
  elseif text_case == "sentence" then
    -- TODO: if uppercase convert all to lowercase
    res = transform_first_word(str, not seen_one, transform_capitalize_word_if_lower)
  elseif text_case == "title" then
    -- TODO: if uppercase convert all to lowercase
    res = transform_each_word(str, seen_one, is_last, title_case_word)
  elseif text_case == "sentence-strong" then
    -- Conversion for BibTeX title fields to sentence case
    -- TODO: if uppercase convert all to lowercase
    res = transform_each_word(str, seen_one, is_last, transform_lowercase_if_capitalize)
    res = transform_first_word(res, not seen_one, transform_capitalize_word_if_lower)
  end
  return res
end

function OutputFormat:affixed(inlines, affixes)
  if affixes and affixes.prefix then
    table.insert(inlines, 1, PlainText:new(affixes.prefix))
  end
  if affixes and affixes.suffix then
    table.insert(inlines, PlainText:new(affixes.suffix))
  end
  return inlines
end

function OutputFormat:affixed_quoted(inlines, affixes, localized_quotes)
  inlines = util.clone(inlines)
  if localized_quotes then
    inlines = self:quoted(inlines, localized_quotes)
  end
  if affixes and affixes.prefix and affixes.prefix ~= "" then
    table.insert(inlines, 1, PlainText:new(affixes.prefix))
  end
  if affixes and affixes.suffix and affixes.suffix ~= "" then
    table.insert(inlines, PlainText:new(affixes.suffix))
  end
  return inlines
end

function OutputFormat:quoted(inlines, localized_quotes)
  return {Quoted:new(inlines, localized_quotes)}
end

function OutputFormat:with_display(nodes, display)
  if display then
    return {Div:new(nodes, display)}
  else
    return nodes
  end
end

---@param inlines InlineElement[]
---@param context Context
function OutputFormat:output(inlines, context)
  self:flip_flop_inlines(inlines)

  self:move_punctuation(inlines)

  -- util.debug(inlines)

  return self:write_inlines(inlines, context)
end

---@param inlines InlineElement[]
---@param context Context
---@return string?
function OutputFormat:output_bibliography_entry(inlines, context)
  self:flip_flop_inlines(inlines)
  -- util.debug(inlines)
  self:move_punctuation(inlines)
  -- TODO:
  -- if self.format == "html" then
  -- elseif self.format == "latex" then
  -- end
  local res = self:write_inlines(inlines, context)
  local markup = self.markups["@bibliography/entry"]
  if type(markup) == "string" then
    res = string.format(markup, res)
  elseif type(markup) == "function" then
    res = markup(res, context)
  end
  return res
end

---@param inlines InlineElement[]
function OutputFormat:flip_flop_inlines(inlines)
  ---@class FlipFlopState
  local flip_flop_state = {
    ["font-style"] = "normal",
    ["font-variant"] = "normal",
    ["font-weight"] = "normal",
    ["text-decoration"] = "none",
    ["vertical-alignment"] = "baseline",
    in_inner_quotes = false,
  }
  self:flip_flop(inlines, flip_flop_state)
end

---@param inlines InlineElement[]
---@param state FlipFlopState
function OutputFormat:flip_flop(inlines, state)
  for i, inline in ipairs(inlines) do
    if inline._type == "Micro" then
      self:flip_flop_micro_inlines(inline.inlines, state)

    elseif inline._type == "Formatted" then
      local new_state = util.clone(state)
      local formatting = inline.formatting

      for _, attribute in ipairs({"font-style", "font-variant", "font-weight"}) do
        local value = formatting[attribute]
        if value then
          if value == state[attribute] then
            if value == "normal" then
              formatting[attribute] = nil
            -- Formatting outside Micro is not reset to "normal".
            -- else
            --   formatting[attribute] = "normal"
            end
          end
          new_state[attribute] = value
        end
      end
      self:flip_flop(inline.inlines, new_state)

    elseif inline._type == "Quoted" then
      inline.is_inner = state.in_inner_quotes
      local new_state = util.clone(state)
      new_state.in_inner_quotes = not new_state.in_inner_quotes
      self:flip_flop(inline.inlines, new_state)

    elseif inline._type == "NoDecor" then
      local new_state = {
        ["font-style"] = "normal",
        ["font-variant"] = "normal",
        ["font-weight"] = "normal",
        ["text-decoration"] = "none",
      }
      self:flip_flop(inline.inlines, new_state)
      for attr, value in pairs(new_state) do
        if value and state[attr] ~= value then
          if not inline.formatting then
            inline._type = "Formatted"
            inline.formatting = {}
          end
          inline.formatting[attr] = value
        end
      end

    elseif inline._type == "Code" or
        inline._type == "MathML" or
        inline._type == "MathTeX" then
      return

    elseif inline.inlines then  -- Div, ...
      self:flip_flop(inline.inlines, state)
    end
  end
end

---@param inlines InlineElement[]
---@param state FlipFlopState
function OutputFormat:flip_flop_micro_inlines(inlines, state)
  for i, inline in ipairs(inlines) do
    if inline._type == "Micro" then
      self:flip_flop_micro_inlines(inline.inlines, state)

    elseif inline._type == "Formatted" then
      local new_state = util.clone(state)
      local formatting = inline.formatting

      for _, attribute in ipairs({"font-style", "font-variant", "font-weight"}) do
        local value = formatting[attribute]
        if value then
          if value == state[attribute] then
            if value == "normal" then
              formatting[attribute] = nil
            else
              -- Formatting inside Micro is reset to "normal".
              formatting[attribute] = "normal"
              value = "normal"
            end
          end
          new_state[attribute] = value
        end
      end
      self:flip_flop_micro_inlines(inline.inlines, new_state)

    elseif inline._type == "Quoted" then
      inline.is_inner = state.in_inner_quotes
      local new_state = util.clone(state)
      new_state.in_inner_quotes = not new_state.in_inner_quotes
      self:flip_flop_micro_inlines(inline.inlines, new_state)

    elseif inline._type == "NoDecor" then
      local new_state = {
        ["font-style"] = "normal",
        ["font-variant"] = "normal",
        ["font-weight"] = "normal",
        ["text-decoration"] = "none",
      }
      self:flip_flop_micro_inlines(inline.inlines, new_state)
      for attr, value in pairs(new_state) do
        if value and state[attr] ~= value then
          if not inline.formatting then
            inline._type = "Formatted"
            inline.formatting = {}
          end
          inline.formatting[attr] = value
        end
      end

    elseif inline._type == "Code" or
        inline._type == "MathML" or
        inline._type == "MathTeX" then
      return

    elseif inline.inlines then  -- Div, ...
      self:flip_flop_micro_inlines(inline.inlines, state)
    end
  end
end

---@param inline InlineElement
---@return InlineElement?
local function find_left(inline)
  if inline._type == "PlainText" then
    return inline
  -- elseif inline._type == "Micro" then
  --   return nil
  elseif inline.inlines and #inline.inlines > 0 and inline._type~="Quoted" then
    return find_left(inline.inlines[1])
  else
    return nil
  end
end

local function find_right(inline)
  if inline._type == "PlainText" then
    return inline
  -- elseif inline._type == "Micro" then
  --   return nil
  elseif inline.inlines and #inline.inlines > 0 and inline._type ~= "Quoted" then
    return find_right(inline.inlines[#inline.inlines])
  else
    return nil
  end
end

local function find_right_in_quoted(inline)
  if inline._type == "PlainText" then
    return inline
  -- elseif inline._type == "Micro" then
  --   return nil
  elseif inline.inlines and #inline.inlines > 0 then
    return find_right_in_quoted(inline.inlines[#inline.inlines])
  else
    return nil
  end
end

--- "'Foo,' bar" => ,
---@param inline InlineElement
local function find_right_quoted(inline)
  if inline._type == "Quoted" and #inline.inlines > 0 then
    ---@cast inline Quoted
    return find_right_in_quoted(inline.inlines[#inline.inlines]), inline.quotes.punctuation_in_quote
  -- elseif inline._type == "Micro" then
  --   return nil
  elseif inline.inlines and #inline.inlines > 0 then
    return find_right_quoted(inline.inlines[#inline.inlines])
  else
    return nil, false
  end
end

local function smash_string_push(first, second)
  local first_char = string.sub(first.value, -1)
  local second_char = string.sub(second.value, 1, 1)
  -- util.debug(first_char)
  -- util.debug(second_char)

  local punct_map = output_module.quote_punctuation_map
  if second_char == " " and (first_char == " " or
      util.endswith(first.value, util.unicode["no-break space"])) then
    second.value = string.sub(second.value, 2)
  elseif punct_map[first_char] then
    if first_char == second_char then
      second.value = string.sub(second.value, 2)
    else
      local combined = punct_map[first_char][second_char]
      if combined and #combined == 1 then
        second.value = string.sub(second.value, 2)
        first.value = string.sub(first.value, 1, -2) .. combined
      end
    end
  end
end

local function smash_just_punc(first, second)
  first = find_right(first)  -- PlainText
  second = find_left(second)  -- PlainText
  if first and second then
    local first_char = string.sub(first.value, -1)
    local second_char = string.sub(second.value, 1, 1)
    -- util.debug(first_char)
    -- util.debug(second_char)

    local punct_map = output_module.quote_punctuation_map
    if second_char == " " and (first_char == " " or
        util.endswith(first.value, util.unicode["no-break space"])) then
      second.value = string.sub(second.value, 2)
      return true
    elseif punct_map[first_char] then
      if first_char == second_char then
        second.value = string.sub(second.value, 2)
        return true
      else
        local combined = punct_map[first_char][second_char]
        if combined and #combined == 1 then
          second.value = string.sub(second.value, 2)
          first.value = string.sub(first.value, 1, -2) .. combined
          return true
        end
      end
    end
  else
    return false
  end
end

local function normalise_text_elements(inlines)
  -- 1. Merge punctuations: "?." => "?"
  -- 2. Merge spaces: "  " => " "
  local idx = 1
  while idx < #inlines do
    local first = inlines[idx]
    local second = inlines[idx+1]

    if first._type == "PlainText" and second._type == "PlainText" then
      smash_string_push(first, second)
      first.value = first.value .. second.value
      table.remove(inlines, idx + 1)

    elseif first._type == "Micro" and second._type == "PlainText" then
      local success = smash_just_punc(first, second)
      if success then
        if second.value == "" then
          table.remove(inlines, idx + 1)
        end
      else
        idx = idx + 1
      end

    elseif (first._type == "Formatted" or first._type == "CiteInline")
        and second._type == "PlainText" then
      local success = smash_just_punc(first, second)
      if success then
        if second.value == "" then
          table.remove(inlines, idx + 1)
        end
      else
        idx = idx + 1
      end

    else
      idx = idx + 1
    end
  end

end

local function move_in_quotes(first, second)
  local first_char = string.sub(first.value, -1)
  local second_char = string.sub(second.value, 1, 1)
  local success = false
  if output_module.move_in_puncts[second_char] then
    if first_char == second_char then
      second.value = string.sub(second.value, 2)
      success = true
    elseif output_module.quote_punctuation_map[first_char] then
      local combined = output_module.quote_punctuation_map[first_char][second_char]
      first.value = string.sub(first.value, 1, -2) .. combined
      second.value = string.sub(second.value, 2)
      success = true
    else
      first.value = first.value .. second_char
      second.value = string.sub(second.value, 2)
      success = true
    end
  end
  return success
end

local function move_out_quotes(first, second)
  local first_char = string.sub(first.value, -1)
  local second_char = string.sub(second.value, 1, 1)
  local success = false
  if output_module.move_out_puncts[first_char] then
    if first_char == second_char then
      first.value = string.sub(first.value, 1, -2)
      success = true
    elseif output_module.quote_punctuation_map[second_char] then
      local combined = output_module.quote_punctuation_map[first_char][second_char]
      first.value = string.sub(first.value, 1, -2)
      second.value = combined .. string.sub(second.value, 2)
      success = true
    else
      first.value = string.sub(first.value, 1, -2)
      second.value = first_char .. second.value
      success = true
    end
  end
  return success
end

---@param inlines InlineElement[]
local function move_around_quote(inlines)
  local idx = 1

  while idx < #inlines do
    -- Move punctuation into quotes as needed
    local first, punctuation_in_quote = find_right_quoted(inlines[idx])

    local second = find_left(inlines[idx+1])
    local success = false
    if first and second then
      if punctuation_in_quote then
        success = move_in_quotes(first, second)
      else
        success = move_out_quotes(first, second)
      end
      if not success then
        idx = idx + 1
      end
    else
      idx = idx + 1
    end
  end
end

---@param inlines InlineElement[]
---@param punctuation_in_quote boolean?
function OutputFormat:move_punctuation(inlines, punctuation_in_quote)
  -- Merge punctuations
  normalise_text_elements(inlines)

  move_around_quote(inlines)

  for _, inline in ipairs(inlines) do
    if inline._type == "Quoted" or inline._type == "Formatted" or
        inline._type == "Div" or inline._type == "CiteInline" then
      self:move_punctuation(inline.inlines)
    end
  end
end

function OutputFormat:write_inlines(inlines, context)
  local res = ""
  for _, inline in ipairs(inlines) do
    res = res .. self:write_inline(inline, context)
  end
  return res
end

function OutputFormat:write_inline(inline, context)
  if inline.value then
    return self:write_escaped(inline.value, context)
  elseif inline.inlines then
    return self:write_inlines(inline.inlines, context)
  end
  return ""
end

function OutputFormat:write_escaped(str, context)
  return str
end


---@class Markup: OutputFormat
local Markup = OutputFormat:new()

function Markup:write_inline(inline, context)
  -- if not context then
  --   print(debug.traceback())
  --   error('stop')
  -- end
  if type(inline) == "string" then
    -- Should not happen
    return self:write_escaped(inline, context)

  elseif type(inline) == "table" then
    -- util.debug(inline._type)
    if inline._type == "PlainText" then
      return self:write_escaped(inline.value, context)

    elseif inline._type == "InlineElement" then
      return self:write_inlines(inline.inlines, context)

    elseif inline._type == "Formatted" then
      return self:write_formatted(inline, context)

    elseif inline._type == "Quoted" then
      return self:write_quoted(inline, context)

    elseif inline._type == "Div" then
      return self:write_display(inline, context)

    elseif inline._type == "Linked" then
      return self:write_link(inline, context)

    elseif inline._type == "CiteInline" then
      return self:write_cite(inline, context)

    elseif inline._type == "Code" then
      return self:write_code(inline, context)

    elseif inline._type == "MathML" then
      return self:write_mathml(inline, context)

    elseif inline._type == "MathTeX" then
      return self:write_math_tex(inline, context)

    elseif inline._type == "NoCase" then
      return self:write_nocase(inline, context)

    elseif inline._type == "NoDecor" then
      return self:write_nodecor(inline, context)

    else
      return self:write_inlines(inline.inlines, context)
    end
  end
  return ""
end

function Markup:write_formatted(inline, context)
  return self:write_inlines(inline.inlines, context)
end

---@param inline Quoted
---@param context Context
---@return string
function Markup:write_quoted(inline, context)
  local res = self:write_inlines(inline.inlines, context)
  local quotes = inline.quotes
  if inline.is_inner then
    return quotes.inner_open .. res .. quotes.inner_close
  else
    return quotes.outer_open .. res .. quotes.outer_close
  end
end

function Markup:write_display(inline, context)
  return self:write_inlines(inline.inlines, context)
end

function Markup:write_link(inline, context)
  return self:write_escaped(inline.value, context)
end

function Markup:write_cite(inline, context)
  return self:write_inlines(inline.inlines, context)
end

function Markup:write_code(inline, context)
  return inline.value
end

function Markup:write_mathml(inline, context)
  return inline.value
end

function Markup:write_math_tex(inline, context)
  return inline.value
end

function Markup:write_nocase(inline, context)
  return self:write_inlines(inline.inlines, context)
end

function Markup:write_nodecor(inline, context)
  return self:write_inlines(inline.inlines, context)
end


local LatexWriter = Markup:new()

LatexWriter.markups = {
  ["bibstart"] = function (engine)
    return string.format("\\begin{thebibliography}{%s}\n", engine.registry.widest_label)
  end,
  ["bibend"] = "\\end{thebibliography}",
  ["@font-style/normal"] = "{\\normalshape %s}",
  ["@font-style/italic"] = "\\textit{%s}",
  ["@font-style/oblique"] = "\\textsl{%s}",
  ["@font-variant/normal"] = "{\\normalshape %s}",
  ["@font-variant/small-caps"] = "\\textsc{%s}",
  ["@font-weight/normal"] = "{\\fontseries{m}\\selectfont %s}",
  ["@font-weight/bold"] = "\\textbf{%s}",
  ["@font-weight/light"] = "{\\fontseries{l}\\selectfont %s}",
  ["@text-decoration/none"] = false,
  ["@text-decoration/underline"] = "\\underline{%s}",
  ["@vertical-align/sup"] = "\\textsuperscript{%s}",
  ["@vertical-align/sub"] = "\\textsubscript{%s}",
  ["@vertical-align/baseline"] = false,
  ["@cite/entry"] = false,
  ["@bibliography/entry"] = function (str, context)
    if string.match(str, "\\bibitem") then
      str =  str .. "\n"
    else
      str =  "\\bibitem{".. context.id .. "}\n" .. str .. "\n"
    end
    return str
  end,
  -- ["@display/block"] = false,
  -- ["@display/left-margin"] = '\n    <div class="csl-left-margin">%s</div>',
  -- ["@display/right-inline"] = '<div class="csl-right-inline">%s</div>',
  -- ["@display/indent"] = '<div class="csl-indent">%s</div>\n  ',
}

local latex_escape_table = {
  ["\\"] = "\\textbackslash{}",
  ["{"] = "\\{",
  ["}"] = "\\}",
  ["$"] = "\\$",
  ["&"] = "\\&",
  ["#"] = "\\#",
  ["^"] = "\\^",
  ["_"] = "\\_",
  ["%"] = "\\%",
  ["~"] = "\\~",
}

---@param str string
---@param context Context
---@return string
function LatexWriter:write_escaped(str, context)
  -- TeXbook, p. 38
  str = str:gsub("[\\{}$&#^_%%~]", latex_escape_table)
  str = str:gsub(util.unicode["em space"], "\\quad ")
  str = str:gsub(util.unicode["no-break space"], "~")
  for char, sub in pairs(util.superscripts) do
    str = string.gsub(str, char, "\\textsuperscript{" .. sub .. "}")
  end
  return str
end

function LatexWriter:write_formatted(inline, context)
  local res = self:write_inlines(inline.inlines, context)
  for _, key in ipairs({"font-style", "font-variant", "font-weight", "text-decoration", "vertical-align"}) do
    local value = inline.formatting[key]
    if value then
      key = "@" .. key .. "/" .. value
      local format_str = self.markups[key]
      if format_str then
        res = string.format(format_str, res)
      end
    end
  end
  return res
end

function LatexWriter:write_display(inline, context)
  if inline.div == "left-margin" then
    local plainter_text_writer = output_module.PlainTextWriter:new()
    local str = plainter_text_writer:write_inline(inline, context)
    local len = utf8.len(str)
    if len > context.engine.registry.maxoffset then
      context.engine.registry.maxoffset = len
      context.engine.registry.widest_label = str
    end
  end

  local res = self:write_inlines(inline.inlines, context)
  if inline.div == "left-margin" then
    if string.match(res, "%]") then
      res = "{" .. res .. "}"
    end
    res = string.format("\\bibitem[%s]{%s}\n", res, context.id)

  elseif inline.div == "right-inline" then
    return res

  elseif inline.div == "block" then
    return ""
  end
  return res
end

function LatexWriter:write_link(inline, context)
  if inline.href == inline.value then
    -- URL
    return string.format("\\url{%s}", inline.value)
  elseif context.engine.opt.wrap_url_and_doi then
    return string.format("\\href{%s}{%s}", inline.href, self:write_escaped(inline.value, context))
  else
    return self:write_escaped(inline.value, context)
  end
end

function LatexWriter:write_cite(inline, context)
  local str = self:write_inlines(inline.inlines, context)
  if context.engine.opt.citation_link then
    str = string.format("\\cslcite{%s}{%s}", inline.cite_item.id, str)
  end
  return str
end

function LatexWriter:write_code(inline, context)
  return inline.value
end

function LatexWriter:write_mathml(inline, context)
  util.error("MathML is not supported in LaTeX output.")
  return ""
end

function LatexWriter:write_math_tex(inline, context)
  return string.format("$%s$", inline.value)
end


local HtmlWriter = Markup:new()

HtmlWriter.markups = {
  ["bibstart"] = "<div class=\"csl-bib-body\">\n",
  ["bibend"] = "</div>",
  ["@font-style/italic"] = "<i>%s</i>",
  ["@font-style/oblique"] = "<em>%s</em>",
  ["@font-style/normal"] = '<span style="font-style:normal;">%s</span>',
  ["@font-variant/small-caps"] = '<span style="font-variant:small-caps;">%s</span>',
  ["@font-variant/normal"] = '<span style="font-variant:normal;">%s</span>',
  ["@font-weight/bold"] = "<b>%s</b>",
  ["@font-weight/normal"] = '<span style="font-weight:normal;">%s</span>',
  ["@font-weight/light"] = false,
  ["@text-decoration/none"] = '<span style="text-decoration:none;">%s</span>',
  ["@text-decoration/underline"] = '<span style="text-decoration:underline;">%s</span>',
  ["@vertical-align/sup"] = "<sup>%s</sup>",
  ["@vertical-align/sub"] = "<sub>%s</sub>",
  ["@vertical-align/baseline"] = '<span style="baseline">%s</span>',
  ["@cite/entry"] = nil,
  ["@bibliography/entry"] = "<div class=\"csl-entry\">%s</div>\n",
  ["@display/block"] = '\n\n    <div class="csl-block">%s</div>\n',
  ["@display/left-margin"] = '\n    <div class="csl-left-margin">%s</div>',
  ["@display/right-inline"] = '<div class="csl-right-inline">%s</div>\n  ',
  ["@display/indent"] = '<div class="csl-indent">%s</div>\n  ',
}

function HtmlWriter:write_escaped(str, context)
  str = string.gsub(str, "%&", "&#38;")
  str = string.gsub(str, "<", "&#60;")
  str = string.gsub(str, ">", "&#62;")
  for char, sub in pairs(util.superscripts) do
    str = string.gsub(str, char, "<sup>" .. sub .. "</sup>")
  end
  return str
end

function HtmlWriter:write_formatted(inline, context)
  local res = self:write_inlines(inline.inlines, context)
  for _, key in ipairs({"font-style", "font-variant", "font-weight", "text-decoration", "vertical-align"}) do
    local value = inline.formatting[key]
    if value then
      key = "@" .. key .. "/" .. value
      local format_str = self.markups[key]
      if format_str then
        res = string.format(format_str, res)
      end
    end
  end
  return res
end

function HtmlWriter:write_display(inline, context)
  if inline.div == "left-margin" then
    local plainter_text_writer = output_module.PlainTextWriter:new()
    local str = plainter_text_writer:write_inline(inline, context)
    --TODO: width of CJK characters
    local len = utf8.len(str)
    if len > context.engine.registry.maxoffset then
      context.engine.registry.maxoffset = len
      context.engine.registry.widest_label = str
    end
  end

  if #inline.inlines == 0 then
    return ""
  end
  local res = self:write_inlines(inline.inlines, context)
  local key = string.format("@display/%s", inline.div)
  if inline.div == "right-inline" then
    -- Strip trailing spaces
    -- variables_ContainerTitleShort.txt
    res = string.gsub(res, "%s+$", "")
  end
  local format_str = self.markups[key]
  if format_str then
    res = string.format(format_str, res)
  end
  return res
end

function HtmlWriter:write_link(inline, context)
  -- if not context then
  --   print(debug.traceback())
  -- end
  local content = self:write_escaped(inline.value, context)
  if context.engine.opt.wrap_url_and_doi then
    local href = self:write_escaped(inline.href, context)
    return string.format('<a href="%s">%s</a>', href, content)
  else
    return content
  end
end

function HtmlWriter:write_code(inline, context)
  return string.format("<code>%s</code>", inline.value)
end

function HtmlWriter:write_mathml(inline, context)
  return string.format('<math xmlns="http://www.w3.org/1998/Math/MathML">%s</math>', inline.value)
end

function HtmlWriter:write_math_tex(inline, context)
  return string.format("<code>$%s$</code>", self:write_escaped(inline.value, context))
end


local PlainTextWriter = Markup:new()

PlainTextWriter.markups = {}

function PlainTextWriter:write_escaped(str, context)
  return str
end

function PlainTextWriter:write_formatted(inline, context)
  return self:write_inlines(inline.inlines, context)
end

function PlainTextWriter:write_display(inline, context)
  return self:write_inlines(inline.inlines, context)
end


-- Omit formatting and quotes
local SortStringFormat = OutputFormat:new()

function SortStringFormat:output(inlines, context)
  -- self:flip_flop_inlines(inlines)
  -- self:move_punctuation(inlines)
  return self:write_inlines(inlines, context)
end

function SortStringFormat:write_escaped(str, context)
  -- sort_Quotes.txt
  str = string.gsub(str, ",", "")
  return str
end


-- Omit formatting and quotes
local DisamStringFormat = OutputFormat:new()

function DisamStringFormat:output(inlines, context)
  -- self:flip_flop_inlines(inlines)
  -- self:move_punctuation(inlines)
  return self:write_inlines(inlines, context)
end

function DisamStringFormat:flatten_ir(ir)
  if self.group_var == GroupVar.Missing then
    return {}
  end
  local inlines
  if ir._type == "SeqIr" or ir._type == "NameIr" then
    if ir._element and ir._element.variable == "accessed" then
      -- Accessed isn't really part of a reference -- it doesn't help disambiguating one from
      -- another. So we will ignore it. Works for, e.g., date_YearSuffixImplicitWithNoDate.txt
      inlines = {}
    else
      inlines = self:flatten_seq_ir(ir)
    end
  elseif ir._type == "YearSuffix" then
    -- Don't include year-suffix in disambiguation
    inlines = {}
  else
    inlines = self:affixed_quoted(ir.inlines, ir.affixes, ir.quotes);
    inlines = self:with_display(inlines, ir.display);
  end
  return inlines
end

function DisamStringFormat:flatten_seq_ir(ir)
  -- if not ir.children then
  --   print(debug.traceback())
  -- end
  if #ir.children == 0 then
    return {}
  end
  local inlines_list = {}
  for _, child in ipairs(ir.children) do
    if child.group_var == GroupVar.Important or child.group_var == GroupVar.Plain then
      -- and not child.collapse_suppressed
      -- Suppressed irs are stil kept in the DisamStringFormat
      table.insert(inlines_list, self:flatten_ir(child))
    end
  end

  local inlines = self:group(inlines_list, ir.delimiter, ir.formatting)
  -- assert ir.quotes == localized quotes
  inlines = self:affixed_quoted(inlines, ir.affixes, ir.quotes);
  inlines = self:with_display(inlines, ir.display);

  -- -- A citation layout
  -- if ir._element_name == "layout" and ir.cite_item then
  --   inlines = {CiteInline:new(inlines, ir.cite_item)}
  -- end

  return inlines
end


local PseudoHtml = HtmlWriter:new()

function PseudoHtml :write_escaped(str, context)
  -- str = string.gsub(str, "%&", "&#38;")
  -- str = string.gsub(str, "<", "&#60;")
  -- str = string.gsub(str, ">", "&#62;")
  -- for char, sub in pairs(util.superscripts) do
  --   str = string.gsub(str, char, "<sup>" .. sub .. "</sup>")
  -- end
  return str
end

function PseudoHtml:write_mathml(inline, context)
  return string.format('<math>%s</math>', inline.value)
end

function PseudoHtml:write_math_tex(inline, context)
  return string.format("<mathtex>%s</mathtex>", inline.value)
end

function PseudoHtml:write_nocase(inline, context)
  local str = self:write_inlines(inline.inlines, context)
  return string.format('<span class="nocase">%s</span>', str)
end


function InlineElement.has_space(inlines)
  local str = DisamStringFormat:output(inlines)
  if not str then
    return false
  end
  if string.match(util.strip(str), "%s") then
    return true
  else
    return false
  end
end

output_module.move_in_puncts = {
  ["."] = true,
  ["!"] = true,
  ["?"] = true,
  [","] = true,
}

output_module.move_out_puncts = {
  [","] = true,
  [";"] = true,
  [":"] = true,
}

-- https://github.com/Juris-M/citeproc-js/blob/aa2683f48fe23be459f4ed3be3960e2bb56203f0/src/queue.js#L724
-- Also merge duplicate punctuations.
output_module.quote_punctuation_map = {
  ["!"] = {
    ["."] = "!",
    ["?"] = "!?",
    [":"] = "!",
    [","] = "!,",
    [";"] = "!;",
  },
  ["?"] = {
    ["!"] = "?!",
    ["."] = "?",
    [":"] = "?",
    [","] = "?,",
    [";"] = "?;",
  },
  ["."] = {
    ["!"] = ".!",
    ["?"] = ".?",
    [":"] = ".:",
    [","] = ".,",
    [";"] = ".;",
  },
  [":"] = {
    ["!"] = "!",
    ["?"] = "?",
    ["."] = ":",
    [","] = ":,",
    [";"] = ":;",
  },
  [","] = {
    ["!"] = ",!",
    ["?"] = ",?",
    [":"] = ",:",
    ["."] = ",.",
    [";"] = ",;",
  },
  [";"] = {
    ["!"] = "!",
    ["?"] = "?",
    [":"] = ";",
    [","] = ";,",
    ["."] = ";",
  }
}


output_module.LocalizedQuotes = LocalizedQuotes

output_module.InlineElement = InlineElement
output_module.PlainText = PlainText
output_module.Formatted = Formatted
output_module.Micro = Micro
output_module.Quoted = Quoted
output_module.Linked = Linked
output_module.Div = Div
output_module.CiteInline = CiteInline
output_module.Code = Code
output_module.MathTeX = MathTeX
output_module.MathTML = MathML
output_module.NoCase = NoCase
output_module.NoDecor = NoDecor

output_module.OutputFormat = OutputFormat

output_module.Markup = Markup
output_module.LatexWriter = LatexWriter
output_module.HtmlWriter = HtmlWriter
output_module.PlainTextWriter = PlainTextWriter
output_module.DisamStringFormat = DisamStringFormat
output_module.SortStringFormat = SortStringFormat
output_module.PseudoHtml = PseudoHtml

return output_module