summaryrefslogtreecommitdiff
path: root/macros/luatex/generic/luaxml/luaxml-mod-html.lua
blob: 69e32b16e22e8a8946e3143d169c5c5ae39eb689 (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
-- Copyright Michal Hoftich, 2022
-- HTML parser inspired by https://browser.engineering/html.html
-- but then redone using https://html.spec.whatwg.org/multipage/parsing.html
--
-- There main purpose of this module is to create an useful DOM for later processing
-- using LuaXML functions. Either for cleanup, or for translation to output formats, 
-- for example LaTeX. 
--
-- It should be possible to serialize DOM back to the original HTML code. 
--
-- We attempt to do some basic fixes, like to close paragraphs or list items that 
-- aren't closed correctly in the original code. We don't fix tables or 
-- formatting elements (see https://html.spec.whatwg.org/multipage/parsing.html#the-list-of-active-formatting-elements)
-- as these features don't seem necessary for the purpose of this module. We may change
-- this policy in the future, if it turns out that they are necessary. 
--
--
local M = {}

-- use local copies of utf8 functions
local ucodepoint = utf8.codepoint
local utfchar      = utf8.char
local function uchar(codepoint)
  if codepoint and codepoint > -1 then
    return utfchar(codepoint)
  end
  return ""
end

-- declare namespaces
local xmlns = {
  HTML = "http://www.w3.org/1999/xhtml",
  MathML = "http://www.w3.org/1998/Math/MathML",
  SVG = "http://www.w3.org/2000/svg",
  XLink = "http://www.w3.org/1999/xlink",
  XML = "http://www.w3.org/XML/1998/namespace",
  XMLNS = "http://www.w3.org/2000/xmlns/", 
}

-- we must make search tree for named entities, as their support 
-- is quite messy
local named_entities
if kpse then
  named_entities = require "luaxml-namedentities"
else
  named_entities = require "luaxml.namedentities"
end

local entity_tree = {children = {}}

local function update_tree(tree, char)
  local children = tree.children or {}
  local current = children[char] or {}
  children[char] = current
  tree.children = children
  return current
end

-- loop over named entities and update tree
for entity, char in pairs(named_entities) do
  local tree = entity_tree
  for char in entity:gmatch(".") do
    tree = update_tree(tree,char)
  end
  tree.entity = entity
  tree.char   = char
end

local function search_entity_tree(tbl) 
  -- get named entity for the list of characters
  local tree = entity_tree
  for _,char in ipairs(tbl) do 
    if tree.children then
      tree = tree.children[char]
      if not tree then return nil end
    else
      return nil
    end
  end
  -- print("tree", tree.char)
  return tree
end


-- declare  basic node types

local Root = {
  _type = "root",
  xmlns = xmlns.HTML
}

function Root:init()
  local o = {}
  setmetatable(o, self)
  self.__index = self
  self.__tostring = function (x) return "_ROOT" end
  o.children = {}
  return o
end

function Root:add_child(node)
  table.insert(self.children, node)
end

local Doctype = {
  _type = "doctype"
}
function Doctype:init(name, parent)
  local o = {}
  setmetatable(o, self)
  self.__index = self
  self.__tostring = function (x) 
    if x.data then
      return "<!DOCTYPE " .. x.name .. " " .. x.data ..  ">" 
    else
      return "<!DOCTYPE " .. x.name .. ">" 
    end
  end
  self.add_child = Root.add_child
  o.parent = parent
  o.name = name
  o.children = {}
  return o
end

function Doctype:add_data(data)
  self.data = data
end


local Text = {
  _type = "text"
}

function Text:init(text, parent)
  local o = {}
  setmetatable(o, self)
  self.__index = self
  o.text = text
  self.__tostring = function (x) return "'" ..  x.text .. "'" end
  self.add_child = Root.add_child
  o.parent = parent
  o.children = {}
  return o
end

local Comment = {
  _type = "comment"
}

function Comment:init(text, parent)
  local o = {}
  setmetatable(o, self)
  self.__index = self
  o.text = text
  self.__tostring = function (x) return "<!--" ..  x.text .. "-->" end
  self.add_child = Root.add_child
  o.parent = parent
  o.children = {}
  return o
end



local Element = {
  _type = "element"
}

function Element:init(tag, parent)
  local o = {}
  setmetatable(o, self)
  self.__index = self
  -- tag can be table with unicode characters
  if type(tag) == "table" then
    o.tag = table.concat(tag)
  else
    o.tag = tag
  end
  self.__tostring = function(x) 
    local attr = {}
    for _, el in ipairs(x.attr) do 
      -- handle attributes
      local value
      if el.value:match('"') then
        value = "'" .. el.value .. "'"
      else
        value = '"' .. el.value .. '"'
      end
      attr[#attr+1] =  el.name .. "=" .. value
    end
    local closing = ">"
    if x.self_closing then
      closing = " />"
    end
    if #attr > 0 then
      return "<" .. x.tag .. " " .. table.concat(attr, " ") .. closing 
    else
      return "<" .. x.tag .. closing
    end
  end
  self.add_child = Root.add_child
  o.children = {}
  o.attr     = {}
  o.parent = parent
  -- default xmlns
  o.xmlns  = xmlns.HTML
  return o
end

-- state machine functions

-- each function takes HtmlParser as an argument
local HtmlStates = {}

-- declare codepoints for more efficient processing
local less_than      = ucodepoint("<")
local greater_than   = ucodepoint(">")
local amperesand     = ucodepoint("&")
local exclam         = ucodepoint("!")
local question       = ucodepoint("?")
local solidus        = ucodepoint("/")
local equals         = ucodepoint("=")
local quoting        = ucodepoint('"')
local apostrophe     = ucodepoint("'")
local semicolon      = ucodepoint(";")
local hyphen         = ucodepoint("-")
local dash           = ucodepoint("-")
local numbersign     = ucodepoint("#")
local smallx         = ucodepoint("x")
local bigx           = ucodepoint("X")
local right_square   = ucodepoint("]")
local EOF            = -1 -- special character, meaning end of stream
local null           = 0

local function is_upper_alpha(codepoint)
  if (64 < codepoint and codepoint < 91) then
    return true
  end
end
local function is_lower_alpha(codepoint)
  if (96 < codepoint and codepoint < 123) then 
    return true
  end
end

local function is_alpha(codepoint)
  -- detect if codepoint is alphanumeric
  if is_upper_alpha(codepoint) or
     is_lower_alpha(codepoint) then
       return true
  end
  return false
end


local function is_numeric(codepoint)
  if 47 < codepoint and codepoint < 58 then
    return true
  end
end

local function is_upper_hex(codepoint)
  if 64 < codepoint and codepoint < 71 then
    return true
  end
end

local function is_lower_hex(codepoint)
  if 96 < codepoint and codepoint < 103 then
    return true
  end
end

local function is_hexadecimal(codepoint) 
  if is_numeric(codepoint) or
     is_lower_hex(codepoint) or
     is_upper_hex(codepoint)
  then 
    return true
  end
end


local function is_alphanumeric(codepoint)
  return is_alpha(codepoint) or is_numeric(codepoint)
end

local function is_space(codepoint) 
  -- detect space characters
  if codepoint==0x0009 or codepoint==0x000A or codepoint==0x000C or codepoint==0x0020 then
    return true
  end
  return false
end

local function is_surrogate(codepoint)
  return  0xD800 <= codepoint and codepoint <= 0xDFFF
end


character_entity_replace_table = {
[0x80] =  0x20AC,  
[0x82] =  0x201A,  
[0x83] =  0x0192,  
[0x84] =  0x201E,  
[0x85] =  0x2026,  
[0x86] =  0x2020,  
[0x87] =  0x2021,  
[0x88] =  0x02C6,  
[0x89] =  0x2030,  
[0x8A] =  0x0160,  
[0x8B] =  0x2039,  
[0x8C] =  0x0152,  
[0x8E] =  0x017D,  
[0x91] =  0x2018,  
[0x92] =  0x2019,  
[0x93] =  0x201C,  
[0x94] =  0x201D,  
[0x95] =  0x2022,  
[0x96] =  0x2013,  
[0x97] =  0x2014,  
[0x98] =  0x02DC,  
[0x99] =  0x2122,  
[0x9A] =  0x0161,  
[0x9B] =  0x203A,  
[0x9C] =  0x0153,  
[0x9E] =  0x017E,  
[0x9F] =  0x0178  
}

local function fix_null(codepoint)
  if codepoint == null then
    return 0xFFFD
  else
    return codepoint
  end
end

HtmlStates.data = function(parser) 
  -- this is the default state
  local codepoint = parser.codepoint
  -- print("codepoint", parser.codepoint)
  if codepoint == less_than then
    -- start of tag
    return "tag_open"
  elseif codepoint  == amperesand then
    -- we must save the current state 
    -- what we will return to after entity
    parser.return_state = "data"
    return "character_reference" 
  elseif codepoint == EOF then
    parser:emit_eof()
  else
    parser:emit_character(uchar(codepoint))
  end
  return "data"
end

HtmlStates.tag_open = function(parser)
  -- parse tag contents
  local codepoint = parser.codepoint
  if codepoint == exclam then
    return "markup_declaration_open"
  elseif codepoint == solidus then
    return "end_tag_open"
  elseif codepoint == question then
    parser:start_token("comment",{data={}})
    return "bogus_comment"
  elseif is_alpha(codepoint) then
    local data = {
      name = {},
      attr = {},
      current_attr_name = {},
      current_attr_value = {},
      self_closing = false
    }
    parser:start_token("start_tag", data)
    return parser:tokenize("tag_name")
  elseif codepoint == EOF then
    parser:emit_character(">")
    parser:emit_eof()
  else
    -- invalid tag
    -- emit "<" and reconsume current character as data
    parser:emit_character("<")
    return parser:tokenize("data")
  end
end

HtmlStates.character_reference = function(parser)
  -- parse HTML entities
  -- initialize temp buffer
  parser.temp_buffer = {"&"}
  local codepoint = parser.codepoint
  if is_alphanumeric(codepoint) then
    return parser:tokenize("named_character_reference")
  elseif codepoint == numbersign then
    table.insert(parser.temp_buffer, uchar(codepoint))
    return "numeric_character_reference"
  else
    parser:flush_temp_buffer()
    return parser:tokenize(parser.return_state)
  end

end

HtmlStates.named_character_reference = function(parser)
  -- named entity parsing is pretty complicated 
  -- https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
  local codepoint = parser.codepoint
  -- test if the current entity name is included in the named entity list
  local search_table = {}
  -- first char in temp buffer is &, which we don't want to lookup in the search tree
  for i=2, #parser.temp_buffer do search_table[#search_table+1] = parser.temp_buffer[i] end
  if codepoint == semicolon then
    -- close named entity
    local entity = search_entity_tree(search_table) 
    if entity and entity.char then
      parser:add_entity(entity.char)
    else
      -- if the current name doesn't correspond to any named entity, flush everything into text
      parser:flush_temp_buffer()
      return parser:tokenize(parser.return_state)
    end
    return parser.return_state
  else
    local char = uchar(codepoint)
    -- try if the current entity name is in the named entity search tree
    table.insert(search_table, char)
    local entity = search_entity_tree(search_table)
    if entity then
      -- keep parsing name entity while we match a name
      table.insert(parser.temp_buffer, char)
      return "named_character_reference"
    else
      -- here this will be more complicated
      if #search_table > 1 then
        local token = parser.current_token
        if token.type == "start_tag" and (codepoint == equals or is_alphanumeric(codepoint)) then
          -- in attribute value, flush characters and retokenize  
          parser:flush_temp_buffer()
          return parser:tokenize(parser.return_state)
        else
          -- try to get entity for characters preceding the current character
          table.remove(search_table)
          local newentity = search_entity_tree(search_table)
          if newentity and newentity.char then
            parser:add_entity(newentity.char)
          else
            -- we need to find if parts of the current substring match a named entity
            -- for example &notit; -> ¬it; but &notin; -> ∉
            local rest = {}
            -- loop over the table with characters, and try to find if it matches entity
            for i = #search_table, 1,-1 do
              local removed_char = table.remove(search_table)
              -- 
              table.insert(rest, 1, removed_char)
              newentity = search_entity_tree(search_table)
              if newentity and newentity.char then
                parser:add_entity(newentity.char)
                parser.temp_buffer = rest
                break
              end
            end
            -- replace temporary buffer witch characters that followed the matched entity
            parser:flush_temp_buffer()
          end
          return parser:tokenize(parser.return_state)
        end
      else
        -- search table contains only the current character
        parser:flush_temp_buffer()
        return parser:tokenize(parser.return_state)
      end
    end
  end

end

HtmlStates.numeric_character_reference = function(parser)
  -- this variable will hold the number
  local codepoint = parser.codepoint
  parser.character_reference_code = 0
  if codepoint == smallx or codepoint == bigx then
    -- hexadecimal entity
    table.insert(parser.temp_buffer, uchar(codepoint))
    return "hexadecimal_character_reference_start"
  else
    -- try decimal entity
    return parser:tokenize("decimal_character_reference_start")
  end

end

HtmlStates.hexadecimal_character_reference_start = function(parser)
  local codepoint = parser.codepoint
  if is_hexadecimal(codepoint) then
    return parser:tokenize("hexadecimal_character_reference")
  else
    parser:flush_temp_buffer()
    return parser:tokenize(parser.return_state)
  end
end

HtmlStates.decimal_character_reference_start = function(parser)
  local codepoint = parser.codepoint
  if is_numeric(codepoint) then
    return parser:tokenize("decimal_character_reference")
  else
    parser:flush_temp_buffer()
    return parser:tokenize(parser.return_state)
  end
end


HtmlStates.decimal_character_reference = function(parser)
  local codepoint = parser.codepoint
  -- helper functions for easier working with the character_reference_code
  local function multiply(number)
    parser.character_reference_code = parser.character_reference_code * number
  end
  local function add(number)
    parser.character_reference_code = parser.character_reference_code + number
  end
  if is_numeric(codepoint) then
    multiply(10)
    add(codepoint - 0x30)
  elseif codepoint == semicolon then
    return "numeric_reference_end_state"
  else
    -- this adds current entity
    parser:tokenize("numeric_reference_end_state")
    -- now tokenize the current character
    return parser:tokenize(parser.return_state)
  end
  return "decimal_character_reference"
end

HtmlStates.hexadecimal_character_reference = function(parser)
  local codepoint = parser.codepoint
  -- helper functions for easier working with the character_reference_code
  local function multiply(number)
    parser.character_reference_code = parser.character_reference_code * number
  end
  local function add(number)
    parser.character_reference_code = parser.character_reference_code + number
  end
  if is_numeric(codepoint) then
    multiply(16)
    add(codepoint - 0x30)
  elseif is_upper_hex(codepoint) then
    multiply(16)
    add(codepoint - 0x37)
  elseif is_lower_hex(codepoint) then
    multiply(16)
    add(codepoint - 0x57)
  elseif codepoint == semicolon then
    return "numeric_reference_end_state"
  else
    -- this adds current entity
    parser:tokenize("numeric_reference_end_state")
    -- now tokenize the current character
    return parser:tokenize(parser.return_state)
  end
  return "hexadecimal_character_reference"
end

HtmlStates.numeric_reference_end_state = function(parser)
  -- in this state, we don't need to 
  local character = parser.character_reference_code
  -- we need to clean invalid character codes
  if character == 0x00 or 
     character >  0x10FFFF or
     is_surrogate(character) 
  then
    character = 0xFFFD
  -- should we add special support for "noncharacter"? I think we can pass them to the output anyway
  elseif character_entity_replace_table[character] then 
    character = character_entity_replace_table[character]
  end
  parser:add_entity(uchar(character))
  return parser.return_state
end


HtmlStates.markup_declaration_open = function(parser)
  -- started by <!
  -- we now need to find the following text, to find if we started comment, doctype, or cdata
  local comment_pattern = "^%-%-"
  local doctype_pattern = "^[Dd][Oo][Cc][Tt][Yy][Pp][Ee]"
  local cdata_pattern   = "^%[CDATA%["
  local start_pos = parser.position
  local text = parser.body
  if text:match(comment_pattern, start_pos) then
    -- local _, newpos = text:find(comment_pattern, start_pos)
    -- we need to ignore next few characters
    parser.ignored_pos = start_pos + 1
    parser:start_token("comment", {data = {}})
    return "comment_start"
  elseif text:match(doctype_pattern, start_pos) then
    parser.ignored_pos = start_pos + 6
    parser:start_token("doctype", {name = {}, data = {}, force_quirks = false})
    return "doctype"
  elseif text:match(cdata_pattern, start_pos) then
    parser.ignored_pos = start_pos + 6
    local current_element = parser:current_node()
    if current_element.xmlns == xmlns.HTML or not current_element.xmlns then
      -- we change CDATA simply to comments
      parser:start_token("comment", {data = {"[CDATA["}})
      return "bogus_comment"
    else
      -- we are in XML mode, this happens for included SVG or MathML
      return "cdata_section"
    end
  else
    parser:start_token("comment", {data = {}})
    return "bogus_comment"
  end
  -- local start, stop = string.find(parser.body, comment_pattern, parser.position)
end


HtmlStates.cdata_section = function(parser)
  local codepoint = parser.codepoint
  if codepoint == right_square then
    return "cdata_section_bracket"
  elseif codepoint == EOF then
    parser:emit_eof()
  else
    parser:emit_character(uchar(codepoint))
    return "cdata_section"
  end
end

HtmlStates.cdata_section_bracket = function(parser)
  local codepoint = parser.codepoint
  if codepoint == right_square then
    return "cdata_section_end"
  else
    parser:emit_character("]")
    return parser:tokenize("cdata_section")
  end
end

HtmlStates.cdata_section_end = function(parser)
  local codepoint = parser.codepoint
  if codepoint == right_square then
    parser:emit_character("]")
    return "cdata_section_end"
  elseif codepoint == greater_than then
    return "data"
  else
    parser:emit_character("]")
    return parser:tokenize("cdata_section")
  end
end


HtmlStates.comment_start = function(parser)
  local codepoint = parser.codepoint
  if codepoint == hyphen then
    return "comment_start_dash"
  elseif codepoint == greater_than then
    parser:emit()
    return "data"
  else
    return parser:tokenize("comment")
  end
end

HtmlStates.comment_start_dash = function(parser)
  local codepoint = parser.codepoint
  if codepoint == hyphen then
    return "comment_end"
  elseif codepoint == greater_than then
    parser:emit()
    return data
  elseif codepoint == EOF then
    parser:emit()
    parser:emit_eof()
  else
    parser:append_token_data("data", "-")
    return parser:tokenize("comment")
  end
end

HtmlStates.comment = function(parser)
  local codepoint = parser.codepoint
  codepoint = fix_null(codepoint)
  if codepoint == less_than then
    parser:append_token_data("data", uchar(codepoint))
    return "comment_less_than"
  elseif codepoint == hyphen then
    return "comment_end_dash"
  elseif codepoint == EOF then
    parser:emit()
    parser:emit_eof()
  else
    parser:append_token_data("data", uchar(codepoint))
  end
  return "comment"
end

HtmlStates.comment_less_than = function(parser)
  local codepoint = parser.codepoint
  if codepoint == exclam then
    parser:append_token_data("data", uchar(codepoint))
    return "comment_less_than_bang"
  elseif codepoint == less_than then
    parser:append_token_data("data", uchar(codepoint))
    return "comment_less_than"
  else
    return parser:tokenize("comment")
  end
end

HtmlStates.comment_less_than_bang = function(parser)
  local codepoint = parser.codepoint
  if codepoint == hyphen then
    return "comment_less_than_bang_dash"
  else
    return parser:tokenize("comment")
  end
end

HtmlStates.comment_less_than_bang_dash = function(parser)
  local codepoint = parser.codepoint
  if codepoint == hyphen then
    return "comment_less_than_bang_dash_dash"
  else
    return parser:tokenize("comment_end_dash")
  end

end

HtmlStates.comment_less_than_bang_dash_dash = function(parser)
  -- these comment states start to be ridiculous
  local codepoint = parser.codepoint
  if codepoint == greater_than or codepoint == EOF then
    return parser:tokenize("comment_end")
  else
    return parser:tokenize("comment_end")
  end
end

HtmlStates.comment_end_dash = function(parser)
  local codepoint = parser.codepoint
  if codepoint == hyphen then
    return "comment_end"
  elseif codepoint == EOF then
    parser:emit()
    parser:emit_eof()
  else
    parser:append_token_data("data", uchar(codepoint))
    return parser:tokenize("comment")
  end
end

HtmlStates.comment_end = function(parser)
  local codepoint = parser.codepoint
  if codepoint == greater_than then
    parser:emit()
    return "data"
  elseif codepoint == exclam then
    return "comment_end_bang"
  elseif codepoint == hyphen then
    parser:append_token_data("data", "-")
    return "comment_end"
  elseif codepoint == EOF then
    parser:emit()
    parser:emit_eof()
  else
    parser:append_token_data("data", "--")
    return parser:tokenize("comment")
  end
end

HtmlStates.comment_end_bang = function(parser)
  local codepoint = parser.codepoint
  if codepoint == hyphen then
    parser:append_token_data("data", "--!")
    return "comment_end_dash"
  elseif codepoint == greater_than then
    parser:emit()
    return "data"
  elseif codepoint == EOF then
    parser:emit()
    parser:emit_eof()
  else
    parser:append_token_data("data", "--!")
    return parser:tokenize("comment")
  end
end

HtmlStates.end_tag_open = function(parser)
  local codepoint = parser.codepoint
  if is_alpha(codepoint) then
    local data = {
      name = {}
    }
    parser:start_token("end_tag", data)
    return parser:tokenize("tag_name")
  elseif codepoint == greater_than then
    return "data"
  elseif codepoint == EOF then
    parser:discard_token()
    parser:emit_character("</")
    parser:emit_eof()
  else
    data = {
      data = {}
    }
    parser:start_token("comment", data)
    return parser:tokenize("bogus_comment")
  end
end

HtmlStates.bogus_comment = function(parser)
  -- started by <?
  local codepoint = parser.codepoint
  codepoint = fix_null(codepoint)
  if codepoint == greater_than then
    parser:emit()
    return "data"
  elseif codepoint == EOF then
    parser:emit()
    parser:emit_eof()
  else
    parser:append_token_data("data", uchar(codepoint))
    return "bogus_comment"
  end
end

local function doctype_eof(parser)
    parser:set_token_data("force_quirks", true)
    parser:emit()
    parser:emit_eof()
end

HtmlStates.doctype = function(parser)
  local codepoint = parser.codepoint
  if is_space(codepoint) then
    return "before_doctype_name"
  elseif codepoint == greater_than then
    return parser:tokenize("before_doctype_name")
  elseif codepoint == EOF then
    doctype_eof(parser)
  else
    return parser:tokenize("before_doctype_name")
  end
end

HtmlStates.before_doctype_name = function(parser)
  local codepoint = parser.codepoint
  codepoint = fix_null(codepoint)
  if is_space(codepoint) then
    return "before_doctype_name"
  elseif codepoint == greater_than then
    parser:set_token_data("force_quirks", true)
    parser:emit()
    return "data"
  elseif codepoint == EOF then
    doctype_eof(parser)
  elseif is_upper_alpha(codepoint) then
    -- add lowercase name
    parser:append_token_data("name", uchar(codepoint + 0x20))
    return "doctype_name"
  else
    parser:append_token_data("name", uchar(codepoint))
    return "doctype_name"
  end
end

HtmlStates.doctype_name = function(parser)

  local codepoint = parser.codepoint
  codepoint = fix_null(codepoint)
  if is_space(codepoint) then
    return "after_doctype_name"
  elseif codepoint == greater_than then
    parser:emit()
    return "data"
  elseif codepoint == EOF then
    doctype_eof(parser)
  elseif is_upper_alpha(codepoint) then
    -- add lowercase name
    parser:append_token_data("name", uchar(codepoint + 0x20))
    return "doctype_name"
  else
    parser:append_token_data("name", uchar(codepoint))
    return "doctype_name"
  end
end

HtmlStates.after_doctype_name = function(parser)
  local codepoint = parser.codepoint
  if is_space(codepoint) then
    return "after_doctype_name"
  elseif codepoint == greater_than then
    parser:emit()
    return "data"
  elseif codepoint == EOF then
    doctype_eof(parser)
  else
    parser:append_token_data("data", uchar(codepoint))
    -- there are lot of complicated rules how to consume doctype, 
    -- but I think that for our purpose they aren't interesting.
    -- so everything until EOF or > is consumed as token.data
    return "consume_doctype_data"
  end
end

HtmlStates.consume_doctype_data = function(parser)
  -- this state just reads everything inside doctype as data
  local codepoint = parser.codepoint
  if codepoint == greater_than then
    parser:emit()
    return "data"
  elseif codepoint == EOF then
    doctype_eof(parser)
  else
    parser:append_token_data("data", uchar(codepoint))
    return "consume_doctype_data"
  end
end

HtmlStates.tag_name = function(parser)
  local codepoint = parser.codepoint
  codepoint = fix_null(codepoint)
  if is_space(codepoint) then 
    return "before_attribute_name"
  elseif codepoint == solidus then
    return "self_closing_tag"
  elseif codepoint == greater_than then
    parser:emit()
    return "data"
  elseif is_upper_alpha(codepoint) then
    local lower = string.lower(uchar(codepoint))
    parser:append_token_data("name", lower)
  elseif codepoint==EOF then
    parser:emit()
    parser:emit_eof()
  else
    local char = uchar(codepoint)
    parser:append_token_data("name", char)
  end
  return "tag_name"

end

HtmlStates.self_closing_tag = function(parser)
  local codepoint = parser.codepoint
  if codepoint == greater_than then
    parser.current_token.self_closing = true
    parser:emit()
    return "data"
  else
    return parser:tokenize("before_attribute_name")
  end
end


HtmlStates.before_attribute_name = function(parser)
  local codepoint = parser.codepoint
  if is_space(codepoint) then
    -- ignore spacing
    return "before_attribute_name"
  elseif codepoint == solidus or codepoint == greater_than then
    -- reconsume in after_attribute_name
    return parser:tokenize("after_attribute_name")
  elseif codepoint == equals then
    -- ToDo: handle https://html.spec.whatwg.org/multipage/parsing.html#parse-error-unexpected-equals-sign-before-attribute-name
  else
    -- start new attribute
    parser:start_attribute()
    return parser:tokenize("attribute_name")
  end
end

HtmlStates.attribute_name = function(parser)
  local codepoint = parser.codepoint
  if is_space(codepoint) 
     or codepoint == solidus
     or codepoint == greater_than 
  then
    return parser:tokenize("after_attribute_name")
  elseif codepoint == equals then
    return "before_attribute_value"
  elseif is_upper_alpha(codepoint) then
    -- lowercase attribute names
    local lower = string.lower(uchar(codepoint))
    parser:append_token_data("current_attr_name", lower)
    return "attribute_name"
  else
    parser:append_token_data("current_attr_name", uchar(codepoint))
    return "attribute_name"
  end
end

HtmlStates.after_attribute_name = function(parser)
  local codepoint = parser.codepoint
  if is_space(codepoint) then
    return "after_attribute_name"
  elseif codepoint == equals then
    return "before_attribute_value"
  elseif codepoint == solidus then
    return "self_closing_tag"
  elseif codepoint == greater_than then
    parser:emit()
    return "data"
  else
    parser:start_attribute()
    return parser:tokenize("attribute_name")
  end
end

HtmlStates.before_attribute_value = function(parser)
  local codepoint = parser.codepoint
  if is_space(codepoint) then
    return "before_attribute_value" 
  elseif codepoint == quoting then
    return "attribute_value_quoting"
  elseif codepoint == apostrophe then
    return "attribute_value_apostrophe"
  elseif codepoint == greater_than then
    parser:emit()
    return "data"
  else
    return  parser:tokenize("attribute_value_unquoted")
  end
end

HtmlStates.attribute_value_quoting = function(parser)
  local codepoint = parser.codepoint
  if codepoint == quoting then
    return "after_attribute_value_quoting"
  elseif codepoint == amperesand then
    parser.return_state = "attribute_value_quoting"
    return "character_reference"
  else
    parser:append_token_data("current_attr_value", uchar(codepoint))
    return "attribute_value_quoting"
  end
end

HtmlStates.attribute_value_apostrophe = function(parser)
  local codepoint = parser.codepoint
  if codepoint == apostrophe then
    return "after_attribute_value_quoting"
  elseif codepoint == amperesand then
    parser.return_state = "attribute_value_apostrophe"
    return "character_reference"
  else
    parser:append_token_data("current_attr_value", uchar(codepoint))
    return "attribute_value_apostrophe"
  end
end

HtmlStates.attribute_value_unquoted = function(parser)
  local codepoint = parser.codepoint
  if is_space(codepoint) then
    return "before_attribute_name"
  elseif codepoint == amperesand then
    parser.return_state = "attribute_value_unquoted"
    return "character_reference"
  elseif codepoint == greater_than then
    parser:emit()
    return "data"
  else
    parser:append_token_data("current_attr_value", uchar(codepoint))
    return "attribute_value_unquoted"
  end
end

HtmlStates.after_attribute_value_quoting = function(parser)
  local codepoint = parser.codepoint
  if is_space(codepoint) then
    return "before_attribute_name"
  elseif codepoint == solidus then
    return "self_closing_tag"
  elseif codepoint == greater_than then
    parser:emit()
    return "data"
  else 
    return parser:tokenize("before_attribute_name")
  end
end

HtmlStates.rcdata = function(parser)
  -- this is the default state
  local codepoint = parser.codepoint
  -- print("codepoint", parser.codepoint)
  codepoint = fix_null(codepoint)
  if codepoint == less_than then
    -- start of tag
    return "rcdata_less_than"
  elseif codepoint  == amperesand then
    -- we must save the current state 
    -- what we will return to after entity
    parser.return_state = "rcdata"
    return "character_reference" 
  elseif codepoint == EOF then
    parser:emit_eof()
  else
    parser:emit_character(uchar(codepoint))
  end
  return "rcdata"
end

local function discard_rcdata_end_tag(parser, text)
    parser:discard_token()
    parser:emit_character(text)
end

HtmlStates.rcdata_less_than = function(parser)
  local codepoint = parser.codepoint
  if codepoint == solidus then
    return "rcdata_end_tag_open"
  else
    discard_rcdata_end_tag(parser, "<")
    return parser:tokenize("rcdata")
  end
end

HtmlStates.rcdata_end_tag_open = function(parser)
  local codepoint = parser.codepoint
  if is_alpha(codepoint) then
    parser:start_token("end_tag", {name={}})
    parser.temp_buffer = {}
    return parser:tokenize("rcdata_end_tag_name")
  else
    discard_rcdata_end_tag(parser, "</")
    return parser:tokenize("rcdata")
  end
end



HtmlStates.rcdata_end_tag_name = function(parser)
  -- we need to find name of the currently opened tag
  local parent = parser:get_parent() or {}
  local opened_tag = parent.tag 
  local current_tag = table.concat(parser.current_token.name or {})
  local codepoint = parser.codepoint
  if is_upper_alpha(codepoint) then
    parser:append_token_data("name", uchar(codepoint + 0x20))
    -- insert current char to temp buffer
    table.insert(parser.temp_buffer, uchar(codepoint))
    return "rcdata_end_tag_name"
  elseif is_lower_alpha(codepoint) then
    parser:append_token_data("name", uchar(codepoint))
    table.insert(parser.temp_buffer, uchar(codepoint))
    return "rcdata_end_tag_name"
  elseif opened_tag == current_tag then
    if is_space(codepoint) then
      return "before_attribute_name"
    elseif codepoint == solidus then
      return "self_closing_tag"
    elseif codepoint == greater_than then
      parser:emit()
      return "data"
    end
  else
    discard_rcdata_end_tag(parser, "</" .. table.concat(parser.temp_buffer))
    parser.temp_buffer = {}
    return parser:tokenize("rcdata")
  end
end

HtmlStates.rawtext = function(parser)
  local codepoint = parser.codepoint
  codepoint = fix_null(codepoint)
  if codepoint == less_than then
    return "rawtext_less_than"
  elseif codepoint == EOF then
    parser:emit_eof()
  else
    parser:emit_character(uchar(codepoint))
    return "rawtext"
  end
end

HtmlStates.rawtext_less_than = function(parser)
  local codepoint = parser.codepoint
  if codepoint == solidus then
    return "rawtext_end_tag_open"
  else
    parser:emit_character("<")
    return parser:tokenize("rawtext")
  end
end

HtmlStates.rawtext_end_tag_open = function(parser)
  local codepoint = parser.codepoint
  if is_alpha(codepoint) then
    parser:start_token("end_tag", {name={}})
    parser.temp_buffer = {}
    return parser:tokenize("rawtext_end_tag_name")
  else
    parser:emit_character("</")
    return parser:tokenize("rawtext")
  end
end

HtmlStates.rawtext_end_tag_name = function(parser)
  -- we need to find name of the currently opened tag
  local parent = parser:get_parent() or {}
  local opened_tag = parent.tag 
  local current_tag = table.concat(parser.current_token.name or {})
  local codepoint = parser.codepoint
  if is_upper_alpha(codepoint) then
    parser:append_token_data("name", uchar(codepoint + 0x20))
    table.insert(parser.temp_buffer, uchar(codepoint))
    return "rawtext_end_tag_name"
  elseif is_lower_alpha(codepoint) then
    parser:append_token_data("name", uchar(codepoint))
    table.insert(parser.temp_buffer, uchar(codepoint))
    return "rawtext_end_tag_name"
  elseif opened_tag == current_tag then
    if is_space(codepoint) then
      return "before_attribute_name"
    elseif codepoint == solidus then
      return "self_closing_tag"
    elseif codepoint == greater_than then
      parser:emit()
      return "data"
    end
  else
    discard_rcdata_end_tag(parser, "</" .. table.concat(parser.temp_buffer))
    parser.temp_buffer = {}
    return parser:tokenize("rawtext")
  end
end

HtmlStates.script_data = function(parser)
  local codepoint = parser.codepoint
  codepoint = fix_null(codepoint)
  if codepoint == less_than then
    return "script_data_less_than"
  elseif codepoint == EOF then
    parser:emit_eof()
  else
    parser:emit_character(uchar(codepoint))
    return "script_data"
  end
end

HtmlStates.script_data_less_than = function(parser)
  local codepoint = parser.codepoint
  if codepoint == solidus then
    parser.temp_buffer = {}
    return "script_data_end_tag_open"
  elseif codepoint == exclam then
    parser:emit_character("<!")
    return "script_data_escape_start"
  else
    parser:emit_character("<")
    return parser:tokenize("script_data")
  end
end

HtmlStates.script_data_end_tag_open = function(parser)
  local codepoint = parser.codepoint
  if is_alpha(codepoint) then
    parser:start_token("end_tag", {name={}})
    return parser:tokenize("script_data_end_tag_name")
  else
    parser:emit_character("</")
    return parser:tokenize("script_data")
  end
end

HtmlStates.script_data_end_tag_name = function(parser)
  -- we need to find name of the currently opened tag
  local parent = parser:get_parent() or {}
  local opened_tag = parent.tag 
  local current_tag = table.concat(parser.current_token.name or {})
  local codepoint = parser.codepoint
  if is_upper_alpha(codepoint) then
    parser:append_token_data("name", uchar(codepoint + 0x20))
    table.insert(parser.temp_buffer, uchar(codepoint))
    return "script_data_end_tag_name"
  elseif is_lower_alpha(codepoint) then
    parser:append_token_data("name", uchar(codepoint))
    table.insert(parser.temp_buffer, uchar(codepoint))
    return "script_data_end_tag_name"
  elseif opened_tag == current_tag then
    if is_space(codepoint) then
      return "before_attribute_name"
    elseif codepoint == solidus then
      return "self_closing_tag"
    elseif codepoint == greater_than then
      parser:emit()
      return "data"
    end
  else
    discard_rcdata_end_tag(parser, "</" .. table.concat(parser.temp_buffer))
    parser.temp_buffer = {}
    return parser:tokenize("script_data")
  end

end

HtmlStates.script_data_escape_start = function(parser)
  local codepoint = parser.codepoint
  if codepoint == hyphen then
    parser:emit_character("-")
    return "script_data_escape_start_dash"
  else
    parser:tokenize("script_data")
  end
end

HtmlStates.script_data_escape_start_dash = function(parser)
  local codepoint = parser.codepoint
  if codepoint == hyphen then
    parser:emit_character("-")
    return "script_data_escaped_dash_dash"
  else
    parser:tokenize("script_data")
  end

end


HtmlStates.script_data_escaped = function(parser)
  local codepoint = parser.codepoint
  codepoint = fix_null(codepoint)
  if codepoint == hyphen then
    parser:emit_character("-")
    return "script_data_escaped_dash"
  elseif codepoint == less_than then
    return "script_data_escaped_less_than_sign"
  elseif codepoint == EOF then
    parser:emit_eof()
  else
    parser:emit_character(uchar(codepoint))
    return "script_data_escaped"
  end
end

HtmlStates.script_data_escaped_dash = function(parser)
  local codepoint = parser.codepoint
  codepoint = fix_null(codepoint)
  if codepoint == hyphen then
    parser:emit_character("-")
    return "script_data_escaped_dash_dash"
  elseif codepoint == less_than then
    return "script_data_escaped_less_than_sign"
  elseif codepoint == EOF then
    parser:emit_eof()
  else
    parser:emit_character(uchar(codepoint))
    return "script_data_escaped"
  end

end

HtmlStates.script_data_escaped_dash_dash = function(parser)
  local codepoint = parser.codepoint
  codepoint = fix_null(codepoint)
  if codepoint == hyphen then
    parser:emit_character("-")
    return "script_data_escaped_dash_dash"
  elseif codepoint == less_than then
    return "script_data_escaped_less_than_sign"
  elseif codepoint == greater_than then
    parser:emit_character(">")
    return "script_data"
  elseif codepoint == EOF then
    parser:emit_eof()
  else
    parser:emit_character(uchar(codepoint))
    return "script_data_escaped"
  end

end

HtmlStates.script_data_escaped_less_than_sign = function(parser)
  local codepoint = parser.codepoint
  if codepoint == solidus then
    parser.temp_buffer = {}
    return "script_data_escaped_end_tag_open"
  elseif is_alpha(codepoint) then
    parser.temp_buffer = {}
    parser:emit_character("<")
    return parser:tokenize("script_data_double_escape_start")
  else
    parser:emit_character("<")
    return parser:tokenize("script_data_escaped")
  end
end

HtmlStates.script_data_escaped_end_tag_open = function(parser) 
  local codepoint = parser.codepoint
  if is_alpha(codepoint) then
    parser:start_token("end_tag", {name={}})
    return parser:tokenize("script_data_escaped_end_tag_name")
  else
    parser:emit_character("</")
    return parser:tokenize("script_data_escaped")
  end
end

HtmlStates.script_data_escaped_end_tag_name = function(parser)
  -- we need to find name of the currently opened tag
  local parent = parser:get_parent() or {}
  local opened_tag = parent.tag 
  local current_tag = table.concat(parser.current_token.name or {})
  local codepoint = parser.codepoint
  if is_upper_alpha(codepoint) then
    parser:append_token_data("name", uchar(codepoint + 0x20))
    table.insert(parser.temp_buffer, uchar(codepoint))
    return "script_data_escaped_end_tag_name"
  elseif is_lower_alpha(codepoint) then
    parser:append_token_data("name", uchar(codepoint))
    table.insert(parser.temp_buffer, uchar(codepoint))
    return "script_data_escaped_end_tag_name"
  elseif opened_tag == current_tag then
    if is_space(codepoint) then
      return "before_attribute_name"
    elseif codepoint == solidus then
      return "self_closing_tag"
    elseif codepoint == greater_than then
      parser:emit()
      return "data"
    end
  else
    discard_rcdata_end_tag(parser, "</" .. table.concat(parser.temp_buffer))
    parser.temp_buffer = {}
    return parser:tokenize("script_data_escaped")
  end
end

HtmlStates.script_data_double_escape_start = function(parser)
  local codepoint = parser.codepoint
  if is_alpha(codepoint) or
     codepoint == solidus or 
     codepoint == greater_than 
  then
    local current_tag = table.concat(parser.current_token.name or {})
    parser:emit_character(uchar(codepoint))
    if current_tag == "script" then
      return "script_data_double_escaped"
    else
      return "script_data_escaped"
    end
  elseif is_upper_alpha(codepoint) then
    parser:emit_character(uchar(codepoint))
    table.insert(parser.temp_buffer, uchar(codepoint) + 0x20)
    return "script_data_double_escape_start"
  elseif is_lower_alpha(codepoint) then
    parser:emit_character(uchar(codepoint))
    table.insert(parser.temp_buffer, uchar(codepoint))
    return "script_data_double_escape_start"
  else
    return parser:tokenize("script_data_escaped")
  end
end

HtmlStates.script_data_double_escaped = function(parser)
  local codepoint = parser.codepoint
  codepoint = fix_null(codepoint)
  if codepoint == hyphen then
    parser:emit_character("-")
    return "script_data_double_escaped_dash"
  elseif codepoint == less_than then
    parser:emit_character("<")
    return "script_data_double_escaped_less_than_sign"
  elseif codepoint == EOF then
    parser:emit_eof()
  else
    parser:emit_character(uchar(codepoint))
    return "script_data_double_escaped"
  end
end

HtmlStates.script_data_double_escaped_dash = function(parser)
  local codepoint = parser.codepoint
  codepoint = fix_null(codepoint)
  if codepoint == hyphen then
    parser:emit_character("-")
    return "script_data_double_escaped_dash"
  elseif codepoint == less_than then
    parser:emit_character("<")
    return "script_data_double_escaped_less_than_sign"
  elseif codepoint == greater_than then
    parser:emit_character(">")
    return "script_data"
  elseif codepoint == EOF then
    parser:emit_eof()
  else
    parser:emit_character(uchar(codepoint))
    return "script_data_double_escaped"
  end
end

HtmlStates.script_data_double_escaped_less_than_sign = function(parser)
  local codepoint = parser.codepoint
  if codepoint == solidus then
    parser:emit("/")
    return "script_data_double_escape_end"
  else
    return parser:tokenize("script_data_double_escaped")
  end
end

HtmlStates.script_data_double_escape_end = function(parser)
  local codepoint = parser.codepoint
  if is_alpha(codepoint) or
     codepoint == solidus or 
     codepoint == greater_than 
  then
    local current_tag = table.concat(parser.current_token.name or {})
    parser:emit_character(uchar(codepoint))
    if current_tag == "script" then
      return "script_data_escaped"
    else
      return "script_data_double_escaped"
    end
  elseif is_upper_alpha(codepoint) then
    parser:emit_character(uchar(codepoint))
    table.insert(parser.temp_buffer, uchar(codepoint) + 0x20)
    return "script_data_double_escape_start"
  elseif is_lower_alpha(codepoint) then
    parser:emit_character(uchar(codepoint))
    table.insert(parser.temp_buffer, uchar(codepoint))
    return "script_data_double_escape_start"
  else
    return parser:tokenize("script_data_double_escaped")
  end

end

-- formatting elements needs special treatment
local formatting_element_names ={
   a = true, b = true, big = true, code = true, em = true, font = true, i = true, nobr = true, s = true, small = true, strike = true, strong = true, tt = true, u = true
}
local function is_formatting_element(name)
  return formatting_element_names[name]
end

local special_elements = {}

local special_elements_list = {"address", "applet", "area", "article", "aside",
"base", "basefont", "bgsound", "blockquote", "body", "br", "button", "caption",
"center", "col", "colgroup", "dd", "details", "dir", "div", "dl", "dt",
"embed", "fieldset", "figcaption", "figure", "footer", "form", "frame",
"frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup",
"hr", "html", "iframe", "img", "input", "keygen", "li", "link", "listing",
"main", "marquee", "menu", "meta", "nav", "noembed", "noframes", "noscript",
"object", "ol", "p", "param", "plaintext", "pre", "script", "section",
"select", "source", "style", "summary", "table", "tbody", "td", "template",
"textarea", "tfoot", "th", "thead", "title", "tr", "track", "ul", "wbr", "xmp",
"mi","mo","mn","ms","mtext", "annotation-xml","foreignObject","desc", "title"
}

for k,v in ipairs(special_elements_list) do
  special_elements[v] = true
end


local function is_special(name)
  return special_elements[name]
end

-- these lists are used in HtmlParser:generate_implied_endtags()
local implied_endtags = {dd=true, dt=true, li = true, optgroup = true, option = true, p = true, rb = true, rp = true, rd = true, trc = true}
local implied_endtags_thoroughly = {dd=true, dt=true, li = true, optgroup = true, option = true, p = true, 
      rb = true, rp = true, rd = true, trc = true, caption = true, colgroup = true, tbody = true, td = true, 
      tfoot = true, th = true, thead = true, tr = true
}

-- find if unfinished tags list contain a tag
-- it fails if any element from element_list is matched before that tag
local function is_in_scope(parser, target, element_list)
  for i = #parser.unfinished, 1, -1 do
    local node = parser.unfinished[i] 
    local tag = node.tag
    if tag == target then 
      return true
    elseif element_list[tag] then
      return false
    end
  end
  return false
end

local particular_scope_elements = { applet = true, caption = true, html = true, table = true, td = true,
      th = true, marquee = true, object = true, template = true, mi = true, mo = true, mn = true,
      ms = true, mtext = true, ["annotation-xml"] = true, foreignObject = true, desc = true, title = true,
}

local function is_in_particular_scope(parser, target)
  return is_in_scope(parser, target, particular_scope_elements)
end

-- derived scope lists
--
-- list_item scope
local list_item_scope_elements = {ol = true, ul = true}
for k,v in pairs(particular_scope_elements) do list_item_scope_elements[k] = v end

local function is_in_list_item_scope(parser, target)
  return is_in_scope(parser, target, list_item_scope_elements)
end

-- button scope
local button_scope_elements = {button = true}
for k,v in pairs(particular_scope_elements) do button_scope_elements[k] = v end

local function is_in_button_scope(parser, target)
  return is_in_scope(parser, target, button_scope_elements)
end

-- table scope
local table_scope_elements = {html = true, table = true, template = true}

local function is_in_table_scope(parser, target)
  return is_in_scope(parser, target, table_scope_elements)
end

-- select scope
local function is_in_select_scope(parser, target)
  -- this scope is specific, because it supports all tags except two
  for i = #parser.unfinished, 1, -1 do
    local node = parser.unfinished[i] 
    local tag = node.tag
    if tag == target then 
      return true
    elseif tag == "optgroup" or tag == "option" then
      -- only these two tags are supported
    else
      return false
    end
  end
  return false
end

-- List of active formatting elements
-- https://html.spec.whatwg.org/multipage/parsing.html#the-list-of-active-formatting-elements
-- we don't implement it yet, but maybe in the future. 


local HtmlTreeStates = {}






local HtmlParser = {}

function HtmlParser:init(body)
  local o ={}
  setmetatable(o, self)
  self.__index        = self
  o.body              = self:normalize_newlines(body) -- HTML string
  o.position          = 0                -- position in the parsed string
  o.unfinished        = {}    -- insert Root node into the list of opened elements
  o.Document          = Root:init()
  o.default_state     = "data"           -- default state machine state
  o.state             = o.default_state  -- working state of the machine
  o.return_state      = o.default_state  -- special state set by entities parsing
  o.temp_buffer       = {}               -- keep temporary data
  o.current_token     = {type="start"}   -- currently processed token
  o.insertion_mode    = "initial"        -- tree construction state
  o.head_pointer      = nil              -- pointer to the Head element
  o.form_pointer      = nil
  o.active_formatting = {}               -- list of active formatting elements
  o.scripting_flag    = false            -- we will not support scripting
  return o
end

function HtmlParser:normalize_newlines(body)
  -- we must normalize newlines
  return body:gsub("\r\n", "\n"):gsub("\r", "\n")
end

-- declare void elements
local self_closing_tags_list = {"area", "base", "br", "col", "embed", "hr", "img", "input",
    "link", "meta", "param", "source", "track", "wbr"}
 
local self_closing_tags = {}
for _,v in ipairs(self_closing_tags_list) do self_closing_tags[v] = true end




function HtmlParser:parse()
  -- we assume utf8 input, you must convert it yourself if the source is 
  -- in a different encoding
  self.text = {}
  self.state = self.default_state
  -- this should enable us to pass over some characters that we want to ignore
  -- for example scripts, css, etc.
  self.ignored_pos = -1
  for pos, ucode in utf8.codes(self.body) do
    -- save buffer info and require the tokenize function
    if pos > self.ignored_pos then
      self.position = pos
      self.codepoint = ucode
      self.character = uchar(ucode)
      self.state = self:tokenize(self.state) or self.state -- if tokenizer don't return new state, assume that it continues in the current state
    end
  end
  return self:finish()
end

function HtmlParser:tokenize(state)
  local state = state or self.state
  local ucode = self.codepoint
  local text = self.text

  self.last_position = self.position
  self.element_state = false
  -- execute state machine object and return new state
  local fn = HtmlStates[state] or function(parser) return self.default_state end
  local newstate =  fn(self)
  -- this should enable changing state from elements that needs special treatment, like <script> or <style>
  if self.element_state then return self.element_state end
  -- print("newstate", newstate, state, uchar(ucode or 32))
  return newstate
end

function HtmlParser:start_token(typ, data)
  -- emit the previous token
  -- self:emit()
  data.type = typ
  self.current_token = data
end

function HtmlParser:discard_token()
  self.current_token = {type="empty"}
end



function HtmlParser:append_token_data(name, data)
  -- append data to the current token
  local token = self.current_token or {}
  if token[name] and type(token[name]) == "table" then
    table.insert(token[name], data)
  end
end

function HtmlParser:set_token_data(name, data)
  local token = self.current_token or {}
  token[name] = data
end

function HtmlParser:flush_temp_buffer()
  -- write stuff from the temp buffer back to the document
  local token = self.current_token
  if token.type == "start_tag" then
    -- in start tag, entities can be only in attribute value
    for _, char in ipairs(self.temp_buffer) do
      table.insert(token.current_attr_value, char)
    end
  elseif self.return_state == "data" then
    -- handle entities in text
    for _, char in ipairs(self.temp_buffer) do
      self:start_token("character", {char=char})
      self:emit()
    end
  end
  self.temp_buffer = {}
end

function HtmlParser:add_entity(char)
  local token = self.current_token
  if token.type == "start_tag" then
    table.insert(token.current_attr_value, char)
  else
    self:start_token("character", {char=char})
    self:emit()
  end
  self.temp_buffer = {}
end

function HtmlParser:emit(token)
  -- state machine functions should use this function to emit tokens
  local token = token or self.current_token
  -- print("Emit", token.type)
  local token_type = token.type
  if token_type     == "character" then
    table.insert(self.text, token.char)
  elseif token_type == "doctype" then
    self:add_text()
    self:add_doctype()
  elseif token_type == "start_tag" then
    self:add_text()
    -- self:start_attribute()
    self:start_tag()
    -- print("Emit start tag", table.concat(token.name))
    -- save last attribute
  elseif token_type == "end_tag" then
    self:add_text()
    self:end_tag()
    -- print("Emit end tag", table.concat(token.name))
  elseif token_type == "comment" then
    self:add_text()
    self:add_comment()
    -- self:start_attribute()
  elseif token_type == "empty" then

  end
  -- self.current_token = {type="empty"}
end

function HtmlParser:emit_character(text)
  self:start_token("character", {char=text})
  self:emit()
end

function HtmlParser:emit_eof()
  self:start_token("end_of_file", {})
  self:emit()
end

function HtmlParser:get_parent()
  -- return parent element
  return self.unfinished[#self.unfinished] or self.Document
end

function HtmlParser:close_element()
  -- return parent element and remove it from the unfinished list
  return table.remove(self.unfinished)
end

function HtmlParser:add_text(text)
  -- process current text node
  local text = text
  if not text then
    text = self.text
  end
  if type(text) == "table" then
    if #text > 0 then
      text = table.concat(text)
    end
  end
  if type(text) == "string" and text~="" then
    local parent = self:get_parent()
    local node = Text:init(text, parent)
    parent:add_child(node)
  end
  self.text = {}
end


function HtmlParser:start_attribute()
  local token = self.current_token or {}
  if token.type == "start_tag" then
    local attr_name = table.concat(token.current_attr_name)
    local attr_value = table.concat(token.current_attr_value) or ""
    if attr_name ~= "" then
      -- token.attr[attr_name] = attr_value
      table.insert(token.attr, {name = attr_name, value = attr_value})
      -- print("saving attribute", attr_name, attr_value)
    end
    self:set_token_data("current_attr_name", {})
    self:set_token_data("current_attr_value", {})
  end
end

function HtmlParser:set_xmlns(node, parent)
  -- handle xmlns
  local in_attr = false
  -- try to find xmlns in node's attributes first
  for _, attr in ipairs(node.attr) do
    if attr.name == "xmlns" then
      node.xmlns = attr.value
      in_attr = true
      break
    end
  end
  if not in_attr then
    -- if we cannot find xmlns attribute, then use 
    --  xmlns from the parent element, or the default xmlns 
    local parent = self:get_parent()
    node.xmlns = parent.xmlns or xmlns.HTML
  end
end

function HtmlParser:start_tag()
  local token = self.current_token
  if token.type == "start_tag" then
    -- close all currently opened attributes
    self:start_attribute()
    -- initiate Element object, pass attributes and info about self_closing
    local name = table.concat(token.name)
    local parent = self:get_parent()
    local node = Element:init(name, parent)
    node.attr = token.attr
    node.self_closing = token.self_closing
    self:set_xmlns(node)
    -- 
    if token.self_closing        -- <img />
      or self_closing_tags[name] -- void elements
    then
      parent:add_child(node)
    else
      -- add to the unfinished list
      table.insert(self.unfinished, node)
    end
    if name == "title" then 
      self.element_state = "rcdata" 
    elseif name == "style" then
      self.element_state = "rawtext" 
    elseif name == "script" then
      self.element_state = "script_data"
    end
  end
end

function HtmlParser:end_tag()
  -- close current opened element
  local token = self.current_token
  if token.type == "end_tag" then
    if #self.unfinished==0 then return nil end
    local node = self:close_element()
    local parent = self:get_parent()
    parent:add_child(node)
  end
end

function HtmlParser:add_comment()
  local token = self.current_token
  if token.type == "comment" then
    self:start_attribute()
    local parent = self:get_parent()
    local text = table.concat(token.data)
    local node = Comment:init(text, parent)
    parent:add_child(node)
  end
end

function HtmlParser:add_doctype()
  local token = self.current_token
  if token.type == "doctype" then
    self:start_attribute()
    local parent = self:get_parent()
    local name = table.concat(token.name)
    local node = Doctype:init(name, parent)
    if #token.data > 0 then
      node:add_data(table.concat(token.data))
    end
    parent:add_child(node)
  end
end

function HtmlParser:switch_insertion(name)
  self.insertion_mode = name
end

function HtmlParser:current_node()
  return self:get_parent()
end

function HtmlParser:adjusted_current_node()
  -- we don't support this feature yet
  -- https://html.spec.whatwg.org/multipage/parsing.html#adjusted-current-node
  return self:current_node()
end


function HtmlParser:reset_insertion_mode()
  -- https://html.spec.whatwg.org/multipage/parsing.html#reset-the-insertion-mode-appropriately
  local last = false
  for position = #self.unfinished, 1, -1 do
    local node = self.unfinished[position]
    if position == 1 then last = true end
    local name = node.tag
    -- switch to insertion mode based on the current element name
    -- there is lot of other cases, but we support only basic ones
    -- we can support other insertion modes in the future
    if name == "head" and last == true then
      self:switch_insertion("in_head")
      return
    elseif name == "body" then
      self:switch_insertion("in_body")
      return
    elseif name == "html" then
      if self.head_pointer then
        self:switch_insertion("before_head")
        return
      else
        self:switch_insertion("after_head")
      end
    elseif last == true then
      self:switch_insertion("in_body")
      return
    end
  end
  -- by default use in_body
  self:switch_insertion("in_body")
end


-- https://html.spec.whatwg.org/multipage/parsing.html#closing-elements-that-have-implied-end-tags
function HtmlParser:generate_implied_endtags(included, ignored)
  local included = included or implied_endtags
  -- parser can pass list of elements that should be removed from the "included" list
  local ignored = ignored or {}
  for _, name in ipairs(ignored) do included[name] = nil end
  local current = self:current_node() or {}
  -- keep removing elements while they are in the "included" list
  if included[current.tag] then
    table.remove(self.unfinished)
    self:generate_implied_endtags(ignored)
  end
end

function HtmlParser:finish()
  -- tokenize without any real character
  self.codepoint = EOF
  self:tokenize(self.state)
  -- self:emit()
  self:add_text()
  -- close all unfinished elements
  if #self.unfinished == 0 then
    -- add implicit html tag
    self:start_tag("html")
  end
  while #self.unfinished > 0 do
    local node = self:close_element()
    local parent = self:get_parent()
    parent:add_child(node)
  end
  -- return root element
  return self.Document -- self:close_element()
end

-- 
M.Text       = Text
M.Element    = Element
M.HtmlParser = HtmlParser
M.HtmlStates = HtmlStates -- table with functions for particular parser states
M.self_closing_tags = self_closing_tags -- list of void elements
M.search_entity_tree = search_entity_tree
M.is_in_particular_scope = is_in_particular_scope
M.is_in_list_item_scope = is_in_list_item_scope
M.is_in_button_scope = is_in_button_scope
M.is_in_table_scope = is_in_table_scope
M.is_in_select_scope = is_in_select_scope

return M