API Overview API Index Package Overview Direct link to this page
JDK 1.6
  javax.swing.text.html.parser. Parser View Javadoc
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
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293

/*
 * @(#)Parser.java	1.47 06/02/26
 *
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package javax.swing.text.html.parser;

import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.ChangedCharSetException;
import java.io.*;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
import java.util.Enumeration;
import java.net.URL;

import sun.misc.MessageUtils;

/**
 * A simple DTD-driven HTML parser. The parser reads an
 * HTML file from an InputStream and calls various methods
 * (which should be overridden in a subclass) when tags and
 * data are encountered.
 * <p>
 * Unfortunately there are many badly implemented HTML parsers
 * out there, and as a result there are many badly formatted
 * HTML files. This parser attempts to parse most HTML files.
 * This means that the implementation sometimes deviates from
 * the SGML specification in favor of HTML.
 * <p>
 * The parser treats \r and \r\n as \n. Newlines after starttags
 * and before end tags are ignored just as specified in the SGML/HTML
 * specification.
 * <p>
 * The html spec does not specify how spaces are to be coalesced very well.
 * Specifically, the following scenarios are not discussed (note that a
 * space should be used here, but I am using &amp;nbsp to force the space to
 * be displayed):
 * <p>
 * '&lt;b>blah&nbsp;&lt;i>&nbsp;&lt;strike>&nbsp;foo' which can be treated as:
 * '&lt;b>blah&nbsp;&lt;i>&lt;strike>foo' 
 * <p>as well as:
 * '&lt;p>&lt;a href="xx">&nbsp;&lt;em>Using&lt;/em>&lt;/a>&lt;/p>'
 * which appears to be treated as:
 * '&lt;p>&lt;a href="xx">&lt;em>Using&lt;/em>&lt;/a>&lt;/p>'
 * <p>
 * If <code>strict</code> is false, when a tag that breaks flow,
 * (<code>TagElement.breaksFlows</code>) or trailing whitespace is
 * encountered, all whitespace will be ignored until a non whitespace
 * character is encountered. This appears to give behavior closer to
 * the popular browsers.
 *
 * @see DTD
 * @see TagElement
 * @see SimpleAttributeSet
 * @version 1.47, 02/26/06
 * @author Arthur van Hoff
 * @author Sunita Mani
 */
public
class Parser implements DTDConstants {

    private char text[] = new char[1024];
    private int textpos = 0;
    private TagElement last;
    private boolean space;

    private char str[] = new char[128];
    private int strpos = 0;

    protected DTD dtd = null;

    private int ch;
    private int ln;
    private Reader in;

    private Element recent;
    private TagStack stack;
    private boolean skipTag = false;
    private TagElement lastFormSent = null;
    private SimpleAttributeSet attributes = new SimpleAttributeSet();

    // State for <html>, <head> and <body>.  Since people like to slap
    // together HTML documents without thinking, occasionally they
    // have multiple instances of these tags.  These booleans track
    // the first sightings of these tags so they can be safely ignored
    // by the parser if repeated.
    private boolean seenHtml = false;
    private boolean seenHead = false;
    private boolean seenBody = false;

    /**
     * The html spec does not specify how spaces are coalesced very well.
     * If strict == false, ignoreSpace is used to try and mimic the behavior
     * of the popular browsers.
     * <p>
     * The problematic scenarios are:
     * '&lt;b>blah &lt;i> &lt;strike> foo' which can be treated as:
     * '&lt;b>blah &lt;i>&lt;strike>foo'
     * as well as:
     * '&lt;p>&lt;a href="xx"> &lt;em>Using&lt;/em>&lt;/a>&lt;/p>'
     * which appears to be treated as:
     * '&lt;p>&lt;a href="xx">&lt;em>Using&lt;/em>&lt;/a>&lt;/p>'
     * <p>
     * When a tag that breaks flow, or trailing whitespace is encountered
     * ignoreSpace is set to true. From then on, all whitespace will be
     * ignored.
     * ignoreSpace will be set back to false the first time a
     * non whitespace character is encountered. This appears to give
     * behavior closer to the popular browsers.
     */
    private boolean ignoreSpace;

    /**
     * This flag determines whether or not the Parser will be strict
     * in enforcing SGML compatibility.  If false, it will be lenient
     * with certain common classes of erroneous HTML constructs.
     * Strict or not, in either case an error will be recorded.
     *
     */
    protected boolean strict = false;


    /** Number of \r\n's encountered. */
    private int crlfCount;
    /** Number of \r's encountered. A \r\n will not increment this. */
    private int crCount;
    /** Number of \n's encountered. A \r\n will not increment this. */
    private int lfCount;

    //
    // To correctly identify the start of a tag/comment/text we need two
    // ivars. Two are needed as handleText isn't invoked until the tag
    // after the text has been parsed, that is the parser parses the text,
    // then a tag, then invokes handleText followed by handleStart.
    //
    /** The start position of the current block. Block is overloaded here,
     * it really means the current start position for the current comment,
     * tag, text. Use getBlockStartPosition to access this. */
    private int currentBlockStartPos;
    /** Start position of the last block. */
    private int lastBlockStartPos;

    /**
     * array for mapping numeric references in range
     * 130-159 to displayable Unicode characters.
     */
    private static final char[] cp1252Map = {
        8218,  // &#130;
        402,   // &#131;
        8222,  // &#132;
        8230,  // &#133;
        8224,  // &#134;
        8225,  // &#135;
        710,   // &#136;
        8240,  // &#137;
        352,   // &#138;
        8249,  // &#139;
        338,   // &#140;
        141,   // &#141;
        142,   // &#142;
        143,   // &#143;
        144,   // &#144;
        8216,  // &#145;
        8217,  // &#146;
        8220,  // &#147;
        8221,  // &#148;
        8226,  // &#149;
        8211,  // &#150;
        8212,  // &#151;
        732,   // &#152;
        8482,  // &#153;
        353,   // &#154;
        8250,  // &#155;
        339,   // &#156;
        157,   // &#157;
        158,   // &#158;
        376    // &#159;
    };

    public Parser(DTD dtd) {
	this.dtd = dtd;
    }


    /**
     * @return the line number of the line currently being parsed
     */
    protected int getCurrentLine() {
	return ln;
    }

    /**
     * Returns the start position of the current block. Block is
     * overloaded here, it really means the current start position for
     * the current comment tag, text, block.... This is provided for
     * subclassers that wish to know the start of the current block when
     * called with one of the handleXXX methods.
     */
    int getBlockStartPosition() {
	return Math.max(0, lastBlockStartPos - 1);
    }

    /**
     * Makes a TagElement.
     */
    protected TagElement makeTag(Element elem, boolean fictional) {
	return new TagElement(elem, fictional);
    }

    protected TagElement makeTag(Element elem) {
	return makeTag(elem, false);
    }

    protected SimpleAttributeSet getAttributes() {
	return attributes;
    }

    protected void flushAttributes() {
	attributes.removeAttributes(attributes);
    }

    /**
     * Called when PCDATA is encountered.
     */
    protected void handleText(char text[]) {
    }

    /**
     * Called when an HTML title tag is encountered.
     */
    protected void handleTitle(char text[]) {
	// default behavior is to call handleText. Subclasses
	// can override if necessary.
	handleText(text);
    }

    /**
     * Called when an HTML comment is encountered.
     */
    protected void handleComment(char text[]) {
    }

    protected void handleEOFInComment() {
	// We've reached EOF.  Our recovery strategy is to
	// see if we have more than one line in the comment;
	// if so, we pretend that the comment was an unterminated
	// single line comment, and reparse the lines after the
	// first line as normal HTML content.

	int commentEndPos = strIndexOf('\n');
	if (commentEndPos >= 0) {
	    handleComment(getChars(0, commentEndPos));
	    try {
		in.close();
		in = new CharArrayReader(getChars(commentEndPos + 1));
		ch = '>';
	    } catch (IOException e) {
		error("ioexception");
	    }

	    resetStrBuffer();
	} else {
	    // no newline, so signal an error
	    error("eof.comment");
	}
    }

    /**
     * Called when an empty tag is encountered.
     */
    protected void handleEmptyTag(TagElement tag) throws ChangedCharSetException {
    }

    /**
     * Called when a start tag is encountered.
     */
    protected void handleStartTag(TagElement tag) {
    }

    /**
     * Called when an end tag is encountered.
     */
    protected void handleEndTag(TagElement tag) {
    }

    /**
     * An error has occurred.
     */
    protected void handleError(int ln, String msg) {
	/*
	Thread.dumpStack();
	System.out.println("**** " + stack);
	System.out.println("line " + ln + ": error: " + msg);
	System.out.println();
	*/
    }

    /**
     * Output text.
     */
    void handleText(TagElement tag) {
	if (tag.breaksFlow()) {
	    space = false;
            if (!strict) {
                ignoreSpace = true;
            }
	}
	if (textpos == 0) {
	    if ((!space) || (stack == null) || last.breaksFlow() ||
		!stack.advance(dtd.pcdata)) {
		last = tag;
		space = false;
		lastBlockStartPos = currentBlockStartPos;
		return;
	    }
	}
	if (space) {
            if (!ignoreSpace) {
                // enlarge buffer if needed
                if (textpos + 1 > text.length) {
                    char newtext[] = new char[text.length + 200];
                    System.arraycopy(text, 0, newtext, 0, text.length);
                    text = newtext;
                }

                // output pending space
                text[textpos++] = ' ';
                if (!strict && !tag.getElement().isEmpty()) {
                    ignoreSpace = true;
                }
            }
            space = false;
	}
	char newtext[] = new char[textpos];
	System.arraycopy(text, 0, newtext, 0, textpos);
	// Handles cases of bad html where the title tag
	// was getting lost when we did error recovery.
	if (tag.getElement().getName().equals("title")) {
	    handleTitle(newtext);
        } else {
	    handleText(newtext);
	}
	lastBlockStartPos = currentBlockStartPos;
	textpos = 0;
	last = tag;
	space = false;
    }

    /**
     * Invoke the error handler.
     */
    protected void error(String err, String arg1, String arg2,
	String arg3) {
        handleError(ln, err + " " + arg1 + " " + arg2 + " " + arg3);
    }

    protected void error(String err, String arg1, String arg2) {
	error(err, arg1, arg2, "?");
    }
    protected void error(String err, String arg1) {
	error(err, arg1, "?", "?");
    }
    protected void error(String err) {
	error(err, "?", "?", "?");
    }


    /**
     * Handle a start tag. The new tag is pushed
     * onto the tag stack. The attribute list is
     * checked for required attributes.
     */
    protected void startTag(TagElement tag) throws ChangedCharSetException {
	Element elem = tag.getElement();

	// If the tag is an empty tag and texpos != 0
	// this implies that there is text before the
	// start tag that needs to be processed before
	// handling the tag.
	//
	if (!elem.isEmpty() || textpos != 0) {
	    handleText(tag);
	} else {
	    // this variable gets updated in handleText().
	    // Since in this case we do not call handleText()
	    // we need to update it here.
	    //
	    last = tag;
	    // Note that we should really check last.breakFlows before
	    // assuming this should be false.
	    space = false;
	}
	lastBlockStartPos = currentBlockStartPos;

	// check required attributes
	for (AttributeList a = elem.atts ; a != null ; a = a.next) {
	    if ((a.modifier == REQUIRED) && 
		((attributes.isEmpty()) || 
		 ((!attributes.isDefined(a.name)) && 
		  (!attributes.isDefined(HTML.getAttributeKey(a.name)))))) {
		error("req.att ", a.getName(), elem.getName());
	    }
	}

	if (elem.isEmpty()) {
	    handleEmptyTag(tag);
            /*
	} else if (elem.getName().equals("form")) {
	    handleStartTag(tag);
            */
	} else {
	    recent = elem;
	    stack = new TagStack(tag, stack);
	    handleStartTag(tag);
	}
    }

    /**
     * Handle an end tag. The end tag is popped
     * from the tag stack.
     */
    protected void endTag(boolean omitted) {
	handleText(stack.tag);

	if (omitted && !stack.elem.omitEnd()) {
	    error("end.missing", stack.elem.getName());
	} else if (!stack.terminate()) {
	    error("end.unexpected", stack.elem.getName());
	}

	// handle the tag
	handleEndTag(stack.tag);
	stack = stack.next;
	recent = (stack != null) ? stack.elem : null;
    }


    boolean ignoreElement(Element elem) {

        String stackElement = stack.elem.getName();
	String elemName = elem.getName();
	/* We ignore all elements that are not valid in the context of
	   a table except <td>, <th> (these we handle in
	   legalElementContext()) and #pcdata.  We also ignore the
	   <font> tag in the context of <ul> and <ol> We additonally
	   ignore the <meta> and the <style> tag if the body tag has
	   been seen. **/
	if ((elemName.equals("html") && seenHtml) ||
	    (elemName.equals("head") && seenHead) ||
	    (elemName.equals("body") && seenBody)) {
	    return true;
	}
	if (elemName.equals("dt") || elemName.equals("dd")) {
	    TagStack s = stack;
	    while (s != null && !s.elem.getName().equals("dl")) {
		s = s.next;
	    }
	    if (s == null) {
		return true;
	    }
	}

	if (((stackElement.equals("table")) &&
	     (!elemName.equals("#pcdata")) && (!elemName.equals("input"))) ||
	    ((elemName.equals("font")) &&
	     (stackElement.equals("ul") || stackElement.equals("ol"))) ||
	    (elemName.equals("meta") && stack != null) ||
	    (elemName.equals("style") && seenBody) ||
	    (stackElement.equals("table") && elemName.equals("a"))) {
	    return true;
	}
	return false;
    }


    /**
     * Marks the first time a tag has been seen in a document
     */

    protected void markFirstTime(Element elem) {
	String elemName = elem.getName();
	if (elemName.equals("html")) {
	    seenHtml = true;
	} else if (elemName.equals("head")) {
	    seenHead = true;
	} else if (elemName.equals("body")) {
            if (buf.length == 1) {
                // Refer to note in definition of buf for details on this.
                char[] newBuf = new char[256];

                newBuf[0] = buf[0];
                buf = newBuf;
            }
	    seenBody = true;
	}
    }

    /**
     * Create a legal content for an element.
     */
    boolean legalElementContext(Element elem) throws ChangedCharSetException {

	// System.out.println("-- legalContext -- " + elem);

	// Deal with the empty stack
	if (stack == null) {
	    // System.out.println("-- stack is empty");
	    if (elem != dtd.html) {
		// System.out.println("-- pushing html");
		startTag(makeTag(dtd.html, true));
		return legalElementContext(elem);
	    }
	    return true;
	}

	// Is it allowed in the current context
	if (stack.advance(elem)) {
	    // System.out.println("-- legal context");
	    markFirstTime(elem);
	    return true;
	}
	boolean insertTag = false;

	// The use of all error recovery strategies are contingent
	// on the value of the strict property.
	//
	// These are commonly occuring errors.  if insertTag is true,
	// then we want to adopt an error recovery strategy that
	// involves attempting to insert an additional tag to
	// legalize the context.  The two errors addressed here
	// are:
	// 1) when a <td> or <th> is seen soon after a <table> tag.
	//    In this case we insert a <tr>.
	// 2) when any other tag apart from a <tr> is seen
	//    in the context of a <tr>.  In this case we would
	//    like to add a <td>.  If a <tr> is seen within a
	//    <tr> context, then we will close out the current
	//    <tr>.
	//
	// This insertion strategy is handled later in the method.
	// The reason for checking this now, is that in other cases
	// we would like to apply other error recovery strategies for example
	// ignoring tags.
	//
	// In certain cases it is better to ignore a tag than try to
	// fix the situation.  So the first test is to see if this
	// is what we need to do.
	//
	String stackElemName = stack.elem.getName();
	String elemName = elem.getName();


	if (!strict &&
	    ((stackElemName.equals("table") && elemName.equals("td")) ||
	     (stackElemName.equals("table") && elemName.equals("th")) ||
	     (stackElemName.equals("tr") && !elemName.equals("tr")))){
	     insertTag = true;
	}


	if (!strict && !insertTag && (stack.elem.getName() != elem.getName() ||
				      elem.getName().equals("body"))) {
	    if (skipTag = ignoreElement(elem)) {
	        error("tag.ignore", elem.getName());
		return skipTag;
	    }
	}

	// Check for anything after the start of the table besides tr, td, th
	// or caption, and if those aren't there, insert the <tr> and call
	// legalElementContext again.
	if (!strict && stackElemName.equals("table") &&
	    !elemName.equals("tr") && !elemName.equals("td") &&
	    !elemName.equals("th") && !elemName.equals("caption")) {
	    Element e = dtd.getElement("tr");
	    TagElement t = makeTag(e, true);
	    legalTagContext(t);
	    startTag(t);
	    error("start.missing", elem.getName());
	    return legalElementContext(elem);
	}

	// They try to find a legal context by checking if the current
	// tag is valid in an enclosing context.  If so
	// close out the tags by outputing end tags and then
	// insert the curent tag.  If the tags that are
	// being closed out do not have an optional end tag
	// specification in the DTD then an html error is
	// reported.
	//
	if (!insertTag && stack.terminate() && (!strict || stack.elem.omitEnd())) {
	    for (TagStack s = stack.next ; s != null ; s = s.next) {
		if (s.advance(elem)) {
		    while (stack != s) {
			endTag(true);
		    }
		    return true;
		}
		if (!s.terminate() || (strict && !s.elem.omitEnd())) {
		    break;
		}
	    }
	}

	// Check if we know what tag is expected next.
	// If so insert the tag.  Report an error if the
	// tag does not have its start tag spec in the DTD as optional.
	//
	Element next = stack.first();
	if (next != null && (!strict || next.omitStart()) &&
	   !(next==dtd.head && elem==dtd.pcdata) ) {
	    // System.out.println("-- omitting start tag: " + next);
	    TagElement t = makeTag(next, true);
	    legalTagContext(t);
	    startTag(t);
	    if (!next.omitStart()) {
		error("start.missing", elem.getName());
	    }
	    return legalElementContext(elem);
	}


	// Traverse the list of expected elements and determine if adding
	// any of these elements would make for a legal context.
	//

	if (!strict) {
	    ContentModel content = stack.contentModel();
	    Vector elemVec = new Vector();
	    if (content != null) {
		content.getElements(elemVec);
		for (Enumeration v = elemVec.elements(); v.hasMoreElements();) {
		    Element e = (Element)v.nextElement();

		    // Ensure that this element has not been included as
		    // part of the exclusions in the DTD.
		    //
		    if (stack.excluded(e.getIndex())) {
			continue;
		    }

		    boolean reqAtts = false;

		    for (AttributeList a = e.getAttributes(); a != null ; a = a.next) {
		        if (a.modifier == REQUIRED) {
			    reqAtts = true;
			    break;
		        }
		    }
		    // Ensure that no tag that has required attributes
		    // gets inserted.
	            //
		    if (reqAtts) {
		        continue;
		    }

		    ContentModel m = e.getContent();
		    if (m != null && m.first(elem)) {
			// System.out.println("-- adding a legal tag: " + e);
			TagElement t = makeTag(e, true);
			legalTagContext(t);
			startTag(t);
			error("start.missing", e.getName());
			return legalElementContext(elem);
		    }
		}
	    }
	}

	// Check if the stack can be terminated.  If so add the appropriate
	// end tag.  Report an error if the tag being ended does not have its
	// end tag spec in the DTD as optional.
	//
	if (stack.terminate() && (stack.elem != dtd.body) && (!strict || stack.elem.omitEnd())) {
	    // System.out.println("-- omitting end tag: " + stack.elem);
	    if (!stack.elem.omitEnd()) {
		error("end.missing", elem.getName());
	    }

	    endTag(true);
	    return legalElementContext(elem);
	}

	// At this point we know that something is screwed up.
	return false;
    }

    /**
     * Create a legal context for a tag.
     */
    void legalTagContext(TagElement tag) throws ChangedCharSetException {
	if (legalElementContext(tag.getElement())) {
	    markFirstTime(tag.getElement());
	    return;
	}

	// Avoid putting a block tag in a flow tag.
	if (tag.breaksFlow() && (stack != null) && !stack.tag.breaksFlow()) {
	    endTag(true);
	    legalTagContext(tag);
	    return;
	}

	// Avoid putting something wierd in the head of the document.
	for (TagStack s = stack ; s != null ; s = s.next) {
	    if (s.tag.getElement() == dtd.head) {
		while (stack != s) {
		    endTag(true);
		}
		endTag(true);
		legalTagContext(tag);
		return;
	    }
	}

	// Everything failed
	error("tag.unexpected", tag.getElement().getName());
    }

    /**
     * Error context. Something went wrong, make sure we are in
     * the document's body context
     */
    void errorContext() throws ChangedCharSetException {
	for (; (stack != null) && (stack.tag.getElement() != dtd.body) ; stack = stack.next) {
	    handleEndTag(stack.tag);
	}
	if (stack == null) {
	    legalElementContext(dtd.body);
	    startTag(makeTag(dtd.body, true));
	}
    }

    /**
     * Add a char to the string buffer.
     */
    void addString(int c) {
	if (strpos  == str.length) {
	    char newstr[] = new char[str.length + 128];
	    System.arraycopy(str, 0, newstr, 0, str.length);
	    str = newstr;
	}
	str[strpos++] = (char)c;
    }

    /**
     * Get the string that's been accumulated.
     */
    String getString(int pos) {
	char newStr[] = new char[strpos - pos];
	System.arraycopy(str, pos, newStr, 0, strpos - pos);
	strpos = pos;
	return new String(newStr);
    }

    char[] getChars(int pos) {
	char newStr[] = new char[strpos - pos];
	System.arraycopy(str, pos, newStr, 0, strpos - pos);
	strpos = pos;
	return newStr;
    }

    char[] getChars(int pos, int endPos) {
	char newStr[] = new char[endPos - pos];
	System.arraycopy(str, pos, newStr, 0, endPos - pos);
	// REMIND: it's not clear whether this version should set strpos or not
	// strpos = pos;
	return newStr;
    }

    void resetStrBuffer() {
	strpos = 0;
    }

    int strIndexOf(char target) {
	for (int i = 0; i < strpos; i++) {
	    if (str[i] == target) {
		return i;
	    }
	}

	return -1;
    }

    /**
     * Skip space.
     * [5] 297:5
     */
    void skipSpace() throws IOException {
	while (true) {
	    switch (ch) {
	      case '\n':
		ln++;
		ch = readCh();
		lfCount++;
		break;

	      case '\r':
		ln++;
		if ((ch = readCh()) == '\n') {
		    ch = readCh();
		    crlfCount++;
		}
		else {
		    crCount++;
		}
		break;
	      case ' ':
	      case '\t':
		ch = readCh();
		break;

	      default:
		return;
	    }
	}
    }

    /**
     * Parse identifier. Uppercase characters are folded
     * to lowercase when lower is true. Returns falsed if
     * no identifier is found. [55] 346:17
     */
    boolean parseIdentifier(boolean lower) throws IOException {
	switch (ch) {
	  case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
	  case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
	  case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
	  case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
	  case 'Y': case 'Z':
	    if (lower) {
		ch = 'a' + (ch - 'A');
	    }

	  case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
	  case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
	  case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
	  case 's': case 't': case 'u': case 'v': case 'w': case 'x':
	  case 'y': case 'z':
	    break;

	  default:
	    return false;
	}

	while (true) {
	    addString(ch);

	    switch (ch = readCh()) {
	      case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
	      case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
	      case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
	      case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
	      case 'Y': case 'Z':
		if (lower) {
		    ch = 'a' + (ch - 'A');
		}

	      case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
	      case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
	      case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
	      case 's': case 't': case 'u': case 'v': case 'w': case 'x':
	      case 'y': case 'z':

	      case '0': case '1': case '2': case '3': case '4':
	      case '5': case '6': case '7': case '8': case '9':

	      case '.': case '-':

	      case '_': // not officially allowed
		break;

	      default:
		return true;
	    }
	}
    }

    /**
     * Parse an entity reference. [59] 350:17
     */
    private char[] parseEntityReference() throws IOException {
	int pos = strpos;

	if ((ch = readCh()) == '#') {
            int n = 0;
            ch = readCh();
            if ((ch >= '0') && (ch <= '9') ||
                    ch == 'x' || ch == 'X') {

                if ((ch >= '0') && (ch <= '9')) {
                    // parse decimal reference
                    while ((ch >= '0') && (ch <= '9')) {
                        n = (n * 10) + ch - '0';
                        ch = readCh();
                    }
                } else {
                    // parse hexadecimal reference
                    ch = readCh();
                    char lch = (char) Character.toLowerCase(ch);
                    while ((lch >= '0') && (lch <= '9') ||
                            (lch >= 'a') && (lch <= 'f')) {
                        if (lch >= '0' && lch <= '9') {
                            n = (n * 16) + lch - '0';
                        } else {
                            n = (n * 16) + lch - 'a' + 10;
                        }
                        ch = readCh();
                        lch = (char) Character.toLowerCase(ch);
                    }
                }
                switch (ch) {
                    case '\n':
                        ln++;
                        ch = readCh();
                        lfCount++;
                        break;

                    case '\r':
                        ln++;
                        if ((ch = readCh()) == '\n') {
                            ch = readCh();
                            crlfCount++;
                        } 
                        else {
                            crCount++;
                        }
                        break;

                    case ';':
                        ch = readCh();
                        break;
                }
                char data[] = {mapNumericReference((char) n)};
                return data;
            }
            addString('#');
            if (!parseIdentifier(false)) {
                error("ident.expected");
                strpos = pos;
                char data[] = {'&', '#'};
                return data;
            }
	} else if (!parseIdentifier(false)) {
	    char data[] = {'&'};
	    return data;
	}
	switch (ch) {
	  case '\n':
	    ln++;
	    ch = readCh();
	    lfCount++;
	    break;

	  case '\r':
	    ln++;
	    if ((ch = readCh()) == '\n') {
		ch = readCh();
		crlfCount++;
	    }
	    else {
		crCount++;
	    }
	    break;

	  case ';':
	    ch = readCh();
	    break;
	}

	String nm = getString(pos);
	Entity ent = dtd.getEntity(nm);

	// entities are case sensitive - however if strict
	// is false then we will try to make a match by
	// converting the string to all lowercase.
	//
	if (!strict && (ent == null)) {
	    ent = dtd.getEntity(nm.toLowerCase());
	}
	if ((ent == null) || !ent.isGeneral()) {

	    if (nm.length() == 0) {
		error("invalid.entref", nm);
		return new char[0];
	    }
	    /* given that there is not a match restore the entity reference */
	    String str = "&" + nm;

	    char b[] = new char[str.length()];
	    str.getChars(0, b.length, b, 0);
	    return b;
	}
	return ent.getData();
    }

    /**
     * Converts numeric character reference to Unicode character.
     *
     * Normally the code in a reference should be always converted
     * to the Unicode character with the same code, but due to
     * wide usage of Cp1252 charset most browsers map numeric references
     * in the range 130-159 (which are control chars in Unicode set)
     * to displayable characters with other codes.
     *
     * @param c the code of numeric character reference.
     * @return the character corresponding to the reference code.
     */
    private char mapNumericReference(char c) {
        if (c < 130 || c > 159) {
            return c;
        }
        return cp1252Map[c - 130];
    }

    /**
     * Parse a comment. [92] 391:7
     */
    void parseComment() throws IOException {

	while (true) {
	    int c = ch;
	    switch (c) {
	      case '-':
		  /** Presuming that the start string of a comment "<!--" has
		      already been parsed, the '-' character is valid only as
		      part of a comment termination and further more it must
		      be present in even numbers. Hence if strict is true, we
		      presume the comment has been terminated and return.
		      However if strict is false, then there is no even number
		      requirement and this character can appear anywhere in the
		      comment.  The parser reads on until it sees the following
		      pattern: "-->" or "--!>".
		   **/
		if (!strict && (strpos != 0) && (str[strpos - 1] == '-')) {
		    if ((ch = readCh()) == '>') {
			return;
		    }
		    if (ch == '!') {
			if ((ch = readCh()) == '>') {
			    return;
			} else {
			    /* to account for extra read()'s that happened */
			    addString('-');
			    addString('!');
			    continue;
			}
		    }
		    break;
		}

		if ((ch = readCh()) == '-') {
		    ch = readCh();
		    if (strict || ch == '>') {
			return;
		    }
		    if (ch == '!') {
			if ((ch = readCh()) == '>') {
			    return;
			} else {
			    /* to account for extra read()'s that happened */
			    addString('-');
			    addString('!');
			    continue;
			}
		    }
		    /* to account for the extra read() */
		    addString('-');
		}
		break;

	      case -1:
		  handleEOFInComment();
		  return;

	      case '\n':
		ln++;
		ch = readCh();
		lfCount++;
		break;

	      case '>':
		ch = readCh();
		break;

	      case '\r':
		ln++;
		if ((ch = readCh()) == '\n') {
		    ch = readCh();
		    crlfCount++;
		}
		else {
		    crCount++;
		}
		c = '\n';
		break;
	      default:
		ch = readCh();
		break;
	    }

	    addString(c);
	}
    }

    /**
     * Parse literal content. [46] 343:1 and [47] 344:1
     */
    void parseLiteral(boolean replace) throws IOException {
	while (true) {
	    int c = ch;
	    switch (c) {
	      case -1:
		error("eof.literal", stack.elem.getName());
		endTag(true);
		return;

	      case '>':
		ch = readCh();
		int i = textpos - (stack.elem.name.length() + 2), j = 0;

		// match end tag
		if ((i >= 0) && (text[i++] == '<') && (text[i] == '/')) {
		    while ((++i < textpos) &&
			   (Character.toLowerCase(text[i]) == stack.elem.name.charAt(j++)));
		    if (i == textpos) {
			textpos -= (stack.elem.name.length() + 2);
			if ((textpos > 0) && (text[textpos-1] == '\n')) {
			    textpos--;
			}
			endTag(false);
			return;
		    }
		}
		break;

	      case '&':
		char data[] = parseEntityReference();
		if (textpos + data.length > text.length) {
		    char newtext[] = new char[Math.max(textpos + data.length + 128, text.length * 2)];
		    System.arraycopy(text, 0, newtext, 0, text.length);
		    text = newtext;
		}
		System.arraycopy(data, 0, text, textpos, data.length);
		textpos += data.length;
		continue;

	      case '\n':
		ln++;
		ch = readCh();
		lfCount++;
		break;

	      case '\r':
		ln++;
		if ((ch = readCh()) == '\n') {
		    ch = readCh();
		    crlfCount++;
		}
		else {
		    crCount++;
		}
                c = '\n';
		break;
	      default:
		ch = readCh();
		break;
	    }

	    // output character
	    if (textpos == text.length) {
		char newtext[] = new char[text.length + 128];
		System.arraycopy(text, 0, newtext, 0, text.length);
		text = newtext;
	    }
	    text[textpos++] = (char)c;
	}
    }

    /**
     * Parse attribute value. [33] 331:1
     */
    String parseAttributeValue(boolean lower) throws IOException {
	int delim = -1;

	// Check for a delimiter
	switch(ch) {
	  case '\'':
	  case '"':
	    delim = ch;
	    ch = readCh();
	    break;
	}

	// Parse the rest of the value
	while (true) {
	    int c = ch;

	    switch (c) {
	      case '\n':
		ln++;
		ch = readCh();
		lfCount++;
		if (delim < 0) {
		    return getString(0);
		}
		break;

	      case '\r':
		ln++;

		if ((ch = readCh()) == '\n') {
		    ch = readCh();
		    crlfCount++;
		}
		else {
		    crCount++;
		}
		if (delim < 0) {
		    return getString(0);
		}
		break;

	      case '\t':
		  if (delim < 0)
		      c = ' ';
	      case ' ':
		ch = readCh();
		if (delim < 0) {
		    return getString(0);
		}
		break;

	      case '>':
	      case '<':
		if (delim < 0) {
		    return getString(0);
		}
		ch = readCh();
		break;

	      case '\'':
	      case '"':
		ch = readCh();
		if (c == delim) {
		    return getString(0);
		} else if (delim == -1) {
		    error("attvalerr");
		    if (strict || ch == ' ') {
			return getString(0);
		    } else {
			continue;
		    }
		}
		break;

	    case '=':
		if (delim < 0) {
		    /* In SGML a construct like <img src=/cgi-bin/foo?x=1>
		       is considered invalid since an = sign can only be contained
		       in an attributes value if the string is quoted.
		       */
		    error("attvalerr");
		    /* If strict is true then we return with the string we have thus far.
		       Otherwise we accept the = sign as part of the attribute's value and
		       process the rest of the img tag. */
		    if (strict) {
			return getString(0);
		    }
		}
		ch = readCh();
		break;

	      case '&':
		if (strict && delim < 0) {
		    ch = readCh();
		    break;
		}

		char data[] = parseEntityReference();
		for (int i = 0 ; i < data.length ; i++) {
		    c = data[i];
		    addString((lower && (c >= 'A') && (c <= 'Z')) ? 'a' + c - 'A' : c);
		}
		continue;

	      case -1:
		return getString(0);

	      default:
		if (lower && (c >= 'A') && (c <= 'Z')) {
		    c = 'a' + c - 'A';
		}
		ch = readCh();
		break;
	    }
	    addString(c);
	}
    }


    /**
     * Parse attribute specification List. [31] 327:17
     */
    void parseAttributeSpecificationList(Element elem) throws IOException {

	while (true) {
	    skipSpace();

	    switch (ch) {
	      case '/':
	      case '>':
	      case '<':
	      case -1:
		return;

	      case '-':
		if ((ch = readCh()) == '-') {
		    ch = readCh();
		    parseComment();
		    strpos = 0;
		} else {
		    error("invalid.tagchar", "-", elem.getName());
		    ch = readCh();
		}
		continue;
	    }

	    AttributeList att = null;
	    String attname = null;
	    String attvalue = null;

	    if (parseIdentifier(true)) {
		attname = getString(0);
		skipSpace();
		if (ch == '=') {
		    ch = readCh();
		    skipSpace();
		    att = elem.getAttribute(attname);
//  Bug ID 4102750
//  Load the NAME of an Attribute Case Sensitive
//  The case of the NAME  must be intact
//  MG 021898
		    attvalue = parseAttributeValue((att != null) && (att.type != CDATA) && (att.type != NOTATION) && (att.type != NAME));
//		    attvalue = parseAttributeValue((att != null) && (att.type != CDATA) && (att.type != NOTATION));
		} else {
		    attvalue = attname;
		    att = elem.getAttributeByValue(attvalue);
		    if (att == null) {
			att = elem.getAttribute(attname);
			if (att != null) {
			    attvalue = att.getValue();
			}
			else {
			    // Make it null so that NULL_ATTRIBUTE_VALUE is
			    // used
			    attvalue = null;
			}
		    }
		}
	    } else if (!strict && ch == ',') { // allows for comma separated attribute-value pairs
		ch = readCh();
		continue;
	    } else if (!strict && ch == '"') { // allows for quoted attributes
		ch = readCh();
		skipSpace();
		if (parseIdentifier(true)) {
		    attname = getString(0);
		    if (ch == '"') {
			ch = readCh();
		    }
		    skipSpace();
		    if (ch == '=') {
			ch = readCh();
			skipSpace();
			att = elem.getAttribute(attname);
			attvalue = parseAttributeValue((att != null) &&
						(att.type != CDATA) &&
						(att.type != NOTATION));
		    } else {
			attvalue = attname;
			att = elem.getAttributeByValue(attvalue);
			if (att == null) {
			    att = elem.getAttribute(attname);
			    if (att != null) {
				attvalue = att.getValue();
			    }
			}
		    }
		} else {
		    char str[] = {(char)ch};
		    error("invalid.tagchar", new String(str), elem.getName());
		    ch = readCh();
		    continue;
		}
	    } else if (!strict && (attributes.isEmpty()) && (ch == '=')) {
		ch = readCh();
		skipSpace();
		attname = elem.getName();
		att = elem.getAttribute(attname);
		attvalue = parseAttributeValue((att != null) &&
					       (att.type != CDATA) &&
					       (att.type != NOTATION));
	    } else if (!strict && (ch == '=')) {
		ch = readCh();
		skipSpace();
		attvalue = parseAttributeValue(true);
		error("attvalerr");
		return;
	    } else {
		char str[] = {(char)ch};
		error("invalid.tagchar", new String(str), elem.getName());
		if (!strict) {
		    ch = readCh();
		    continue;
		} else {
		    return;
		}
	    }

	    if (att != null) {
		attname = att.getName();
	    } else {
		error("invalid.tagatt", attname, elem.getName());
	    }

	    // Check out the value
	    if (attributes.isDefined(attname)) {
		error("multi.tagatt", attname, elem.getName());
	    }
	    if (attvalue == null) {
		attvalue = ((att != null) && (att.value != null)) ? att.value :
		    HTML.NULL_ATTRIBUTE_VALUE;
	    } else if ((att != null) && (att.values != null) && !att.values.contains(attvalue)) {
		error("invalid.tagattval", attname, elem.getName());
	    }
	    HTML.Attribute attkey = HTML.getAttributeKey(attname);
	    if (attkey == null) {
		attributes.addAttribute(attname, attvalue);
	    } else {
		attributes.addAttribute(attkey, attvalue);
	    }
	}
    }

    /**
     * Parses th Document Declaration Type markup declaration.
     * Currently ignores it.
     */
    public String parseDTDMarkup() throws IOException {

	StringBuffer strBuff = new StringBuffer();
	ch = readCh();
	while(true) {
	    switch (ch) {
	    case '>':
		ch = readCh();
		return strBuff.toString();
	    case -1:
		error("invalid.markup");
		return strBuff.toString();
	    case '\n':
		ln++;
		ch = readCh();
		lfCount++;
		break;
	    case '"':
		ch = readCh();
		break;
	    case '\r':
		ln++;
		if ((ch = readCh()) == '\n') {
		    ch = readCh();
		    crlfCount++;
		}
		else {
		    crCount++;
		}
		break;
	    default:
		strBuff.append((char)(ch & 0xFF));
		ch = readCh();
		break;
	    }
	}
    }

    /**
     * Parse markup declarations.
     * Currently only handles the Document Type Declaration markup.
     * Returns true if it is a markup declaration false otherwise.
     */
    protected boolean parseMarkupDeclarations(StringBuffer strBuff) throws IOException {

	/* Currently handles only the DOCTYPE */
	if ((strBuff.length() == "DOCTYPE".length()) &&
	    (strBuff.toString().toUpperCase().equals("DOCTYPE"))) {
	    parseDTDMarkup();
	    return true;
	}
	return false;
    }

    /**
     * Parse an invalid tag.
     */
    void parseInvalidTag() throws IOException {
	// ignore all data upto the close bracket '>'
	while (true) {
	    skipSpace();
	    switch (ch) {
	      case '>':
	      case -1:
		  ch = readCh();
	        return;
	      case '<':
		  return;
	      default:
		  ch = readCh();

	    }
	}
    }

    /**
     * Parse a start or end tag.
     */
    void parseTag() throws IOException {
	Element elem = null;
	boolean net = false;
	boolean warned = false;
	boolean unknown = false;

	switch (ch = readCh()) {
	  case '!':
	    switch (ch = readCh()) {
	      case '-':
		// Parse comment. [92] 391:7
		while (true) {
		    if (ch == '-') {
			if (!strict || ((ch = readCh()) == '-')) {
			    ch = readCh();
			    if (!strict && ch == '-') {
				ch = readCh();
			    }
			    // send over any text you might see
			    // before parsing and sending the
			    // comment
			    if (textpos != 0) {
				char newtext[] = new char[textpos];
				System.arraycopy(text, 0, newtext, 0, textpos);
				handleText(newtext);
				lastBlockStartPos = currentBlockStartPos;
				textpos = 0;
			    }
			    parseComment();
			    last = makeTag(dtd.getElement("comment"), true);
			    handleComment(getChars(0));
			    continue;
			} else if (!warned) {
			    warned = true;
			    error("invalid.commentchar", "-");
			}
		    }
		    skipSpace();
		    switch (ch) {
		      case '-':
			continue;
		      case '>':
			ch = readCh();
		      case -1:
			return;
		      default:
			ch = readCh();
			if (!warned) {
			    warned = true;
			    error("invalid.commentchar",
				  String.valueOf((char)ch));
			}
			break;
		    }
		}

	      default:
 		// deal with marked sections
		StringBuffer strBuff = new StringBuffer();
		while (true) {
		    strBuff.append((char)ch);
		    if (parseMarkupDeclarations(strBuff)) {
			return;
		    }
		    switch(ch) {
		      case '>':
			ch = readCh();
		      case -1:
			error("invalid.markup");
			return;
		      case '\n':
			ln++;
			ch = readCh();
			lfCount++;
			break;
		      case '\r':
			ln++;
			if ((ch = readCh()) == '\n') {
			    ch = readCh();
			    crlfCount++;
			}
			else {
			    crCount++;
			}
			break;

		      default:
			ch = readCh();
			break;
		    }
		}
	    }

	  case '/':
	    // parse end tag [19] 317:4
	    switch (ch = readCh()) {
	      case '>':
		ch = readCh();
	      case '<':
		// empty end tag. either </> or </<
		if (recent == null) {
		    error("invalid.shortend");
		    return;
		}
		elem = recent;
		break;

	      default:
		if (!parseIdentifier(true)) {
		    error("expected.endtagname");
		    return;
		}
		skipSpace();
		switch (ch) {
		  case '>':
		    ch = readCh();
		  case '<':
		    break;

		  default:
		    error("expected", "'>'");
		    while ((ch != -1) && (ch != '\n') && (ch != '>')) {
			ch = readCh();
		    }
		    if (ch == '>') {
			ch = readCh();
		    }
		    break;
		}
		String elemStr = getString(0);
		if (!dtd.elementExists(elemStr)) {
		    error("end.unrecognized", elemStr);
		    // Ignore RE before end tag
		    if ((textpos > 0) && (text[textpos-1] == '\n')) {
			textpos--;
		    }
		    elem = dtd.getElement("unknown");
		    elem.name = elemStr;
		    unknown = true;
		} else {
		    elem = dtd.getElement(elemStr);
		}
		break;
	    }


	    // If the stack is null, we're seeing end tags without any begin
	    // tags.  Ignore them.

	    if (stack == null) {
		error("end.extra.tag", elem.getName());
		return;
	    }

	    // Ignore RE before end tag
            if ((textpos > 0) && (text[textpos-1] == '\n')) {
		// In a pre tag, if there are blank lines
		// we do not want to remove the newline
		// before the end tag.  Hence this code.
		//
		if (stack.pre) {
		    if ((textpos > 1) && (text[textpos-2] != '\n')) {
			textpos--;
		    }
		} else {
		    textpos--;
		}
	    }

	    // If the end tag is a form, since we did not put it
	    // on the tag stack, there is no corresponding start
	    // start tag to find. Hence do not touch the tag stack.
	    //

            /*
	    if (!strict && elem.getName().equals("form")) {
		if (lastFormSent != null) {
		    handleEndTag(lastFormSent);
		    return;
		} else {
		    // do nothing.
		    return;
		}
	    }
            */

	    if (unknown) {
		// we will not see a corresponding start tag
		// on the the stack.  If we are seeing an
		// end tag, lets send this on as an empty
		// tag with the end tag attribute set to
		// true.
		TagElement t = makeTag(elem);
		handleText(t);
		attributes.addAttribute(HTML.Attribute.ENDTAG, "true");
		handleEmptyTag(makeTag(elem));
		unknown = false;
		return;
	    }

	    // find the corresponding start tag

	    // A commonly occuring error appears to be the insertion
	    // of extra end tags in a table.  The intent here is ignore
	    // such extra end tags.
	    //
	    if (!strict) {
		String stackElem = stack.elem.getName();

		if (stackElem.equals("table")) {
		    // If it isnt a valid end tag ignore it and return
		    //
		    if (!elem.getName().equals(stackElem)) {
			error("tag.ignore", elem.getName());
			return;
		    }
		}



		if (stackElem.equals("tr") ||
		    stackElem.equals("td")) {
		    if ((!elem.getName().equals("table")) &&
			(!elem.getName().equals(stackElem))) {
			error("tag.ignore", elem.getName());
			return;
		    }
		}
	    }
	    TagStack sp = stack;

	    while ((sp != null) && (elem != sp.elem)) {
		sp = sp.next;
	    }
	    if (sp == null) {
		error("unmatched.endtag", elem.getName());
		return;
	    }

 	    // People put font ending tags in the darndest places.
 	    // Don't close other contexts based on them being between
 	    // a font tag and the corresponding end tag.  Instead,
 	    // ignore the end tag like it doesn't exist and allow the end
	    // of the document to close us out.
	    String elemName = elem.getName();
 	    if (stack != sp &&
		(elemName.equals("font") ||
		 elemName.equals("center"))) {

		// Since closing out a center tag can have real wierd
		// effects on the formatting,  make sure that tags
		// for which omitting an end tag is legimitate
		// get closed out.
		//
		if (elemName.equals("center")) {
		    while(stack.elem.omitEnd() && stack != sp) {
			endTag(true);
		    }
		    if (stack.elem == elem) {
			endTag(false);
		    }
		}
		return;
	    }
	    // People do the same thing with center tags.  In this
	    // case we would like to close off the center tag but
	    // not necessarily all enclosing tags.



	    // end tags
	    while (stack != sp) {
		endTag(true);
	    }

	    endTag(false);
	    return;

	  case -1:
	    error("eof");
	    return;
	}

	// start tag [14] 314:1
	if (!parseIdentifier(true)) {
	    elem = recent;
	    if ((ch != '>') || (elem == null)) {
		error("expected.tagname");
		return;
	    }
	} else {
	    String elemStr = getString(0);

	    if (elemStr.equals("image")) {
		elemStr = new String("img");
	    }

	    /* determine if this element is part of the dtd. */

	    if (!dtd.elementExists(elemStr)) {
		//		parseInvalidTag();
		error("tag.unrecognized ", elemStr);
		elem = dtd.getElement("unknown");
		elem.name = elemStr;
		unknown = true;
	    } else {
		elem = dtd.getElement(elemStr);
	    }
	}

	// Parse attributes
	parseAttributeSpecificationList(elem);

	switch (ch) {
	  case '/':
	    net = true;
	  case '>':
	    ch = readCh();
            if (ch == '>' && net) {
                ch = readCh();
            }
	  case '<':
	    break;

	  default:
	    error("expected", "'>'");
	    break;
	}

	if (!strict) {
	  if (elem.getName().equals("script")) {
	    error("javascript.unsupported");
	  }
	}

	// ignore RE after start tag
	//
	if (!elem.isEmpty())  {
	    if (ch == '\n') {
		ln++;
		lfCount++;
		ch = readCh();
	    } else if (ch == '\r') {
		ln++;
		if ((ch = readCh()) == '\n') {
		    ch = readCh();
		    crlfCount++;
		}
		else {
		    crCount++;
		}
	    }
	}

	// ensure a legal context for the tag
	TagElement tag = makeTag(elem, false);


	/** In dealing with forms, we have decided to treat
	    them as legal in any context.  Also, even though
	    they do have a start and an end tag, we will
	    not put this tag on the stack.  This is to deal
	    several pages in the web oasis that choose to
	    start and end forms in any possible location. **/

        /*
	if (!strict && elem.getName().equals("form")) {
	    if (lastFormSent == null) {
		lastFormSent = tag;
	    } else {
		handleEndTag(lastFormSent);
		lastFormSent = tag;
	    }
	} else {
        */
	    // Smlly, if a tag is unknown, we will apply
	    // no legalTagContext logic to it.
	    //
	    if (!unknown) {
		legalTagContext(tag);

		// If skip tag is true,  this implies that
		// the tag was illegal and that the error
		// recovery strategy adopted is to ignore
		// the tag.
		if (!strict && skipTag) {
		    skipTag = false;
		    return;
		}
	    }
            /*
	}
            */

	startTag(tag);

	if (!elem.isEmpty()) {
	    switch (elem.getType()) {
	      case CDATA:
		parseLiteral(false);
		break;
	      case RCDATA:
		parseLiteral(true);
		break;
	      default:
		if (stack != null) {
		    stack.net = net;
		}
		break;
	    }
	}
    }

    private static final String START_COMMENT = "<!--";
    private static final String END_COMMENT = "-->";
    private static final char[] SCRIPT_END_TAG = "</script>".toCharArray();
    private static final char[] SCRIPT_END_TAG_UPPER_CASE = 
                                        "</SCRIPT>".toCharArray();
    
    void parseScript() throws IOException {
        char[] charsToAdd = new char[SCRIPT_END_TAG.length];
        
        /* Here, ch should be the first character after <script> */
        while (true) {
            int i = 0;
            while (i < SCRIPT_END_TAG.length 
                       && (SCRIPT_END_TAG[i] == ch 
                           || SCRIPT_END_TAG_UPPER_CASE[i] == ch)) {
                charsToAdd[i] = (char) ch;
                ch = readCh();
                i++;
            }
            if (i == SCRIPT_END_TAG.length) {
                
                /*  '</script>' tag detected */
                /* Here, ch == '>' */
                ch = readCh();
                /* Here, ch == the first character after </script> */
                return;
            } else {
                
                /* To account for extra read()'s that happened */
                for (int j = 0; j < i; j++) {
                    addString(charsToAdd[j]);
                }
                
                switch (ch) {
                case -1:
                    error("eof.script");
                    return;
                case '\n':
                    ln++;
                    ch = readCh();
                    lfCount++;
                    addString('\n');
                    break;
                case '\r':
                    ln++;
                    if ((ch = readCh()) == '\n') {
                        ch = readCh();
                        crlfCount++;
                    } else {
                        crCount++;
                    }
                    addString('\n');
                    break;
                default:
                    addString(ch);
                    ch = readCh();
                    break;
                } // switch
            }
        } // while
    }
    
    /**
     * Parse Content. [24] 320:1
     */
    void parseContent() throws IOException {
	Thread curThread = Thread.currentThread();

	for (;;) {
	    if (curThread.isInterrupted()) {
                curThread.interrupt(); // resignal the interrupt
                break;
            }

            int c = ch;
	    currentBlockStartPos = currentPosition;
            
            if (recent == dtd.script) { // means: if after starting <script> tag

                /* Here, ch has to be the first character after <script> */
                parseScript();
                last = makeTag(dtd.getElement("comment"), true);
                
                /* Remove leading and trailing HTML comment declarations */
                String str = new String(getChars(0)).trim();
                int minLength = START_COMMENT.length() + END_COMMENT.length();
                if (str.startsWith(START_COMMENT) && str.endsWith(END_COMMENT) 
                       && str.length() >= (minLength)) {
                    str = str.substring(START_COMMENT.length(), 
                                      str.length() - END_COMMENT.length());
                }
                
                /* Handle resulting chars as comment */
                handleComment(str.toCharArray());
                endTag(false);
                lastBlockStartPos = currentPosition;
            } else {
                switch (c) {
                  case '<':
                    parseTag();
                    lastBlockStartPos = currentPosition;
                    continue;

                  case '/':
                    ch = readCh();
                    if ((stack != null) && stack.net) {
                        // null end tag.
                        endTag(false);
                        continue;
                    }
                    break;

                  case -1:
                    return;

                  case '&':
                    if (textpos == 0) {
                        if (!legalElementContext(dtd.pcdata)) {
                            error("unexpected.pcdata");
                        }
                        if (last.breaksFlow()) {
                            space = false;
                        }
                    }
                    char data[] = parseEntityReference();
                    if (textpos + data.length + 1 > text.length) {
                        char newtext[] = new char[Math.max(textpos + data.length + 128, text.length * 2)];
                        System.arraycopy(text, 0, newtext, 0, text.length);
                        text = newtext;
                    }
                    if (space) {
                        space = false;
                        text[textpos++] = ' ';
                    }
                    System.arraycopy(data, 0, text, textpos, data.length);
                    textpos += data.length;
                    ignoreSpace = false;
                    continue;

                  case '\n':
                    ln++;
                    lfCount++;
                    ch = readCh();
                    if ((stack != null) && stack.pre) {
                        break;
                    }
                    if (textpos == 0) {
                        lastBlockStartPos = currentPosition;
                    }
                    if (!ignoreSpace) {
                        space = true;
                    }
                    continue;

                  case '\r':
                    ln++;
                    c = '\n';
                    if ((ch = readCh()) == '\n') {
                        ch = readCh();
                        crlfCount++;
                    }
                    else {
                        crCount++;
                    }
                    if ((stack != null) && stack.pre) {
                        break;
                    }
                    if (textpos == 0) {
                        lastBlockStartPos = currentPosition;
                    }
                    if (!ignoreSpace) {
                        space = true;
                    }
                    continue;


                  case '\t':
                  case ' ':
                    ch = readCh();
                    if ((stack != null) && stack.pre) {
                        break;
                    }
                    if (textpos == 0) {
                        lastBlockStartPos = currentPosition;
                    }
                    if (!ignoreSpace) {
                        space = true;
                    }
                    continue;

                  default:
                    if (textpos == 0) {
                        if (!legalElementContext(dtd.pcdata)) {
                            error("unexpected.pcdata");
                        }
                        if (last.breaksFlow()) {
                            space = false;
                        }
                    }
                    ch = readCh();
                    break;
                }
            } 
                
	    // enlarge buffer if needed
	    if (textpos + 2 > text.length) {
		char newtext[] = new char[text.length + 128];
		System.arraycopy(text, 0, newtext, 0, text.length);
		text = newtext;
	    }

	    // output pending space
	    if (space) {
		if (textpos == 0) {
		    lastBlockStartPos--;
		}
		text[textpos++] = ' ';
		space = false;
	    }
	    text[textpos++] = (char)c;
            ignoreSpace = false;
	}
    }

    /**
     * Returns the end of line string. This will return the end of line
     * string that has been encountered the most, one of \r, \n or \r\n.
     */
    String getEndOfLineString() {
	if (crlfCount >= crCount) {
	    if (lfCount >= crlfCount) {
		return "\n";
	    }
	    else {
		return "\r\n";
	    }
	}
	else {
	    if (crCount > lfCount) {
		return "\r";
	    }
	    else {
		return "\n";
	    }
	}
    }

    /**
     * Parse an HTML stream, given a DTD.
     */
    public synchronized void parse(Reader in) throws IOException {
	this.in = in;

	this.ln = 1;

	seenHtml = false;
	seenHead = false;
	seenBody = false;

	crCount = lfCount = crlfCount = 0;

	try {
            ch = readCh();
            text = new char[1024];
            str = new char[128];
            
            parseContent();
            // NOTE: interruption may have occurred.  Control flows out
            // of here normally.
            while (stack != null) {
                endTag(true);
            }
            in.close();
	} catch (IOException e) {
	    errorContext();
	    error("ioexception");
	    throw e;
	} catch (Exception e) {
	    errorContext();
	    error("exception", e.getClass().getName(), e.getMessage());
	    e.printStackTrace();
	} catch (ThreadDeath e) {
	    errorContext();
	    error("terminated");
	    e.printStackTrace();
	    throw e;
	} finally {
	    for (; stack != null ; stack = stack.next) {
		handleEndTag(stack.tag);
	    }

	    text = null;
	    str = null;
	}

    }


    /*
     * Input cache.  This is much faster than calling down to a synchronized
     * method of BufferedReader for each byte.  Measurements done 5/30/97
     * show that there's no point in having a bigger buffer:  Increasing
     * the buffer to 8192 had no measurable impact for a program discarding
     * one character at a time (reading from an http URL to a local machine).
     * NOTE: If the current encoding is bogus, and we read too much
     * (past the content-type) we may suffer a MalformedInputException. For
     * this reason the initial size is 1 and when the body is encountered the
     * size is adjusted to 256.
     */
    private char buf[] = new char[1];
    private int pos;
    private int len;
    /*
	tracks position relative to the beginning of the
	document.
    */
    private int currentPosition;


    private final int readCh() throws IOException {

	if (pos >= len) {

	    // This loop allows us to ignore interrupts if the flag
	    // says so
	    for (;;) {
		try {
		    len = in.read(buf);
		    break;
		} catch (InterruptedIOException ex) {
		    throw ex;
		}
	    }

	    if (len <= 0) {
		return -1;	// eof
	    }
	    pos = 0;
	}
	++currentPosition;

	return buf[pos++];
    }


    protected int getCurrentPos() {
	return currentPosition;
    }
}

Generated By: JavaOnTracks Doclet 0.1.4     ©Thibaut Colar