File: clean.c

package info (click to toggle)
tidy-html5 2%3A5.6.0-10
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 5,508 kB
  • sloc: ansic: 40,477; ruby: 841; sh: 293; makefile: 30; cpp: 30
file content (2790 lines) | stat: -rw-r--r-- 76,118 bytes parent folder | download | duplicates (2)
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
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
/*
  clean.c -- clean up misuse of presentation markup

  (c) 1998-2008 (W3C) MIT, ERCIM, Keio University
  See tidy.h for the copyright notice.

  Filters from other formats such as Microsoft Word
  often make excessive use of presentation markup such
  as font tags, B, I, and the align attribute. By applying
  a set of production rules, it is straight forward to
  transform this to use CSS.

  Some rules replace some of the children of an element by
  style properties on the element, e.g.

  <p><b>...</b></p> -> <p style="font-weight: bold">...</p>

  Such rules are applied to the element's content and then
  to the element itself until none of the rules more apply.
  Having applied all the rules to an element, it will have
  a style attribute with one or more properties. 

  Other rules strip the element they apply to, replacing
  it by style properties on the contents, e.g.
  
  <dir><li><p>...</li></dir> -> <p style="margin-left 1em">...
      
  These rules are applied to an element before processing
  its content and replace the current element by the first
  element in the exposed content.

  After applying both sets of rules, you can replace the
  style attribute by a class value and style rule in the
  document head. To support this, an association of styles
  and class names is built.

  A naive approach is to rely on string matching to test
  when two property lists are the same. A better approach
  would be to first sort the properties before matching.

*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "tidy-int.h"
#include "clean.h"
#include "lexer.h"
#include "parser.h"
#include "attrs.h"
#include "message.h"
#include "tmbstr.h"
#include "utf8.h"

static Node* CleanNode( TidyDocImpl* doc, Node *node );

static void RenameElem( TidyDocImpl* doc, Node* node, TidyTagId tid )
{
    const Dict* dict = TY_(LookupTagDef)( tid );
    TidyDocFree( doc, node->element );
    node->element = TY_(tmbstrdup)( doc->allocator, dict->name );
    node->tag = dict;
}

static void FreeStyleProps(TidyDocImpl* doc, StyleProp *props)
{
    StyleProp *next;

    while (props)
    {
        next = props->next;
        TidyDocFree(doc, props->name);
        TidyDocFree(doc, props->value);
        TidyDocFree(doc, props);
        props = next;
    }
}

static StyleProp *InsertProperty( TidyDocImpl* doc, StyleProp* props, ctmbstr name, ctmbstr value )
{
    StyleProp *first, *prev, *prop;
    int cmp;

    prev = NULL;
    first = props;

    while (props)
    {
        cmp = TY_(tmbstrcmp)(props->name, name);

        if (cmp == 0)
        {
            /* this property is already defined, ignore new value */
            return first;
        }

        if (cmp > 0)
        {
            /* insert before this */

            prop = (StyleProp *)TidyDocAlloc(doc, sizeof(StyleProp));
            prop->name = TY_(tmbstrdup)(doc->allocator, name);
            prop->value = TY_(tmbstrdup)(doc->allocator, value);
            prop->next = props;

            if (prev)
                prev->next = prop;
            else
                first = prop;

            return first;
        }

        prev = props;
        props = props->next;
    }

    prop = (StyleProp *)TidyDocAlloc(doc, sizeof(StyleProp));
    prop->name = TY_(tmbstrdup)(doc->allocator, name);
    prop->value = TY_(tmbstrdup)(doc->allocator, value);
    prop->next = NULL;

    if (prev)
        prev->next = prop;
    else
        first = prop;

    return first;
}

/*
 Create sorted linked list of properties from style string
 It temporarily places nulls in place of ':' and ';' to
 delimit the strings for the property name and value.
 Some systems don't allow you to NULL literal strings,
 so to avoid this, a copy is made first.
*/
static StyleProp* CreateProps( TidyDocImpl* doc, StyleProp* prop, ctmbstr style )
{
    tmbstr name, value = NULL, name_end, value_end, line;
    Bool more;

    line = TY_(tmbstrdup)(doc->allocator, style);
    name = line;

    while (*name)
    {
        while (*name == ' ')
            ++name;

        name_end = name;

        while (*name_end)
        {
            if (*name_end == ':')
            {
                value = name_end + 1;
                break;
            }

            ++name_end;
        }

        if (*name_end != ':')
            break;

        while ( value && *value == ' ')
            ++value;

        value_end = value;
        more = no;

        while (*value_end)
        {
            if (*value_end == ';')
            {
                more = yes;
                break;
            }

            ++value_end;
        }

        *name_end = '\0';
        *value_end = '\0';

        prop = InsertProperty(doc, prop, name, value);
        *name_end = ':';

        if (more)
        {
            *value_end = ';';
            name = value_end + 1;
            continue;
        }

        break;
    }

    TidyDocFree(doc, line);  /* free temporary copy */
    return prop;
}

static tmbstr CreatePropString(TidyDocImpl* doc, StyleProp *props)
{
    tmbstr style, p, s;
    uint len;
    StyleProp *prop;

    /* compute length */

    for (len = 0, prop = props; prop; prop = prop->next)
    {
        len += TY_(tmbstrlen)(prop->name) + 2;
        if (prop->value)
            len += TY_(tmbstrlen)(prop->value) + 2;
    }

    style = (tmbstr) TidyDocAlloc(doc, len+1);
    style[0] = '\0';

    for (p = style, prop = props; prop; prop = prop->next)
    {
        s = prop->name;

        while((*p++ = *s++))
            continue;

        if (prop->value)
        {
            *--p = ':';
            *++p = ' ';
            ++p;

            s = prop->value;
            while((*p++ = *s++))
                continue;
        }
        if (prop->next == NULL)
            break;

        *--p = ';';
        *++p = ' ';
        ++p;
    }

    return style;
}

/*
  create string with merged properties
static tmbstr AddProperty( ctmbstr style, ctmbstr property )
{
    tmbstr line;
    StyleProp *prop;

    prop = CreateProps(doc, NULL, style);
    prop = CreateProps(doc, prop, property);
    line = CreatePropString(doc, prop);
    FreeStyleProps(doc, prop);
    return line;
}
*/

void TY_(FreeStyles)( TidyDocImpl* doc )
{
    Lexer* lexer = doc->lexer;
    if ( lexer )
    {
        TagStyle *style, *next;
        for ( style = lexer->styles; style; style = next )
        {
            next = style->next;
            TidyDocFree( doc, style->tag );
            TidyDocFree( doc, style->tag_class );
            TidyDocFree( doc, style->properties );
            TidyDocFree( doc, style );
        }
    }
}

static tmbstr GensymClass( TidyDocImpl* doc )
{
    tmbchar buf[512];  /* CSSPrefix is limited to 256 characters */
    ctmbstr pfx = cfgStr(doc, TidyCSSPrefix);
    if ( pfx == NULL || *pfx == 0 )
      pfx = "c";

    TY_(tmbsnprintf)(buf, sizeof(buf), "%s%u", pfx, ++doc->nClassId );
    return TY_(tmbstrdup)(doc->allocator, buf);
}

static ctmbstr FindStyle( TidyDocImpl* doc, ctmbstr tag, ctmbstr properties )
{
    Lexer* lexer = doc->lexer;
    TagStyle* style;

    for (style = lexer->styles; style; style=style->next)
    {
        if (TY_(tmbstrcmp)(style->tag, tag) == 0 &&
            TY_(tmbstrcmp)(style->properties, properties) == 0)
            return style->tag_class;
    }

    style = (TagStyle *)TidyDocAlloc( doc, sizeof(TagStyle) );
    style->tag = TY_(tmbstrdup)(doc->allocator, tag);
    style->tag_class = GensymClass( doc );
    style->properties = TY_(tmbstrdup)( doc->allocator, properties );
    style->next = lexer->styles;
    lexer->styles = style;
    return style->tag_class;
}

/*
 Add class="foo" to node
*/
static void AddClass( TidyDocImpl* doc, Node* node, ctmbstr classname )
{
    AttVal *classattr = TY_(AttrGetById)(node, TidyAttr_CLASS);;

    /*
     if there already is a class attribute
     then append class name after a space.
    */
    if (classattr)
        TY_(AppendToClassAttr)( doc, classattr, classname );
    else /* create new class attribute */
        TY_(AddAttribute)( doc, node, "class", classname );
}

void TY_(AddStyleAsClass)( TidyDocImpl* doc, Node *node, ctmbstr stylevalue )
{
    ctmbstr classname;

    classname = FindStyle( doc, node->element, stylevalue );
    AddClass( doc, node, classname);
}

/*
 Find style attribute in node, and replace it
 by corresponding class attribute. Search for
 class in style dictionary otherwise gensym
 new class and add to dictionary.

 Assumes that node doesn't have a class attribute
*/
static void Style2Rule( TidyDocImpl* doc, Node *node)
{
    AttVal *styleattr, *classattr;
    ctmbstr classname;

    styleattr = TY_(AttrGetById)(node, TidyAttr_STYLE);

    if (styleattr)
    {
        /* fix for http://tidy.sf.net/bug/850215 */
        if (!styleattr->value)
        {
            TY_(RemoveAttribute)(doc, node, styleattr);
            return;
        }

        classname = FindStyle( doc, node->element, styleattr->value );
        classattr = TY_(AttrGetById)(node, TidyAttr_CLASS);

        /*
         if there already is a class attribute
         then append class name after an underscore
        */
        if (classattr)
        {
            TY_(AppendToClassAttr)( doc, classattr, classname );
            TY_(RemoveAttribute)( doc, node, styleattr );
        }
        else /* reuse style attribute for class attribute */
        {
            TidyDocFree(doc, styleattr->attribute);
            TidyDocFree(doc, styleattr->value);
            styleattr->attribute = TY_(tmbstrdup)(doc->allocator, "class");
            styleattr->value = TY_(tmbstrdup)(doc->allocator, classname);
        }
    }
}

static void AddColorRule( Lexer* lexer, ctmbstr selector, ctmbstr color )
{
    if ( selector && color )
    {
        TY_(AddStringLiteral)(lexer, selector);
        TY_(AddStringLiteral)(lexer, " { color: ");
        TY_(AddStringLiteral)(lexer, color);
        TY_(AddStringLiteral)(lexer, " }\n");
    }
}

/*
 move presentation attribs from body to style element

 background="foo" ->  body { background-image: url(foo) }
 bgcolor="foo"    ->  body { background-color: foo }
 text="foo"       ->  body { color: foo }
 link="foo"       ->  :link { color: foo }
 vlink="foo"      ->  :visited { color: foo }
 alink="foo"      ->  :active { color: foo }
*/
static void CleanBodyAttrs( TidyDocImpl* doc, Node* body )
{
    Lexer* lexer  = doc->lexer;
    tmbstr bgurl   = NULL;
    tmbstr bgcolor = NULL;
    tmbstr color   = NULL;
    AttVal* attr;
    
    if (NULL != (attr = TY_(AttrGetById)(body, TidyAttr_BACKGROUND)))
    {
        bgurl = attr->value;
        attr->value = NULL;
        TY_(RemoveAttribute)( doc, body, attr );
    }

    if (NULL != (attr = TY_(AttrGetById)(body, TidyAttr_BGCOLOR)))
    {
        bgcolor = attr->value;
        attr->value = NULL;
        TY_(RemoveAttribute)( doc, body, attr );
    }

    if (NULL != (attr = TY_(AttrGetById)(body, TidyAttr_TEXT)))
    {
        color = attr->value;
        attr->value = NULL;
        TY_(RemoveAttribute)( doc, body, attr );
    }

    if ( bgurl || bgcolor || color )
    {
        TY_(AddStringLiteral)(lexer, " body {\n");
        if (bgurl)
        {
            TY_(AddStringLiteral)(lexer, "  background-image: url(");
            TY_(AddStringLiteral)(lexer, bgurl);
            TY_(AddStringLiteral)(lexer, ");\n");
            TidyDocFree(doc, bgurl);
        }
        if (bgcolor)
        {
            TY_(AddStringLiteral)(lexer, "  background-color: ");
            TY_(AddStringLiteral)(lexer, bgcolor);
            TY_(AddStringLiteral)(lexer, ";\n");
            TidyDocFree(doc, bgcolor);
        }
        if (color)
        {
            TY_(AddStringLiteral)(lexer, "  color: ");
            TY_(AddStringLiteral)(lexer, color);
            TY_(AddStringLiteral)(lexer, ";\n");
            TidyDocFree(doc, color);
        }

        TY_(AddStringLiteral)(lexer, " }\n");
    }

    if (NULL != (attr = TY_(AttrGetById)(body, TidyAttr_LINK)))
    {
        AddColorRule(lexer, " :link", attr->value);
        TY_(RemoveAttribute)( doc, body, attr );
    }

    if (NULL != (attr = TY_(AttrGetById)(body, TidyAttr_VLINK)))
    {
        AddColorRule(lexer, " :visited", attr->value);
        TY_(RemoveAttribute)( doc, body, attr );
    }

    if (NULL != (attr = TY_(AttrGetById)(body, TidyAttr_ALINK)))
    {
        AddColorRule(lexer, " :active", attr->value);
        TY_(RemoveAttribute)( doc, body, attr );
    }
}

static Bool NiceBody( TidyDocImpl* doc )
{
    Node* node = TY_(FindBody)(doc);
    if (node)
    {
        if (TY_(AttrGetById)(node, TidyAttr_BACKGROUND) ||
            TY_(AttrGetById)(node, TidyAttr_BGCOLOR)    ||
            TY_(AttrGetById)(node, TidyAttr_TEXT)       ||
            TY_(AttrGetById)(node, TidyAttr_LINK)       ||
            TY_(AttrGetById)(node, TidyAttr_VLINK)      ||
            TY_(AttrGetById)(node, TidyAttr_ALINK))
        {
            doc->badLayout |= USING_BODY;
            return no;
        }
    }

    return yes;
}

/* create style element using rules from dictionary */
static void CreateStyleElement( TidyDocImpl* doc )
{
    Lexer* lexer = doc->lexer;
    Node *node, *head, *body;
    TagStyle *style;
    AttVal *av;

    if ( lexer->styles == NULL && NiceBody(doc) )
        return;

    node = TY_(NewNode)( doc->allocator, lexer );
    node->type = StartTag;
    node->implicit = yes;
    node->element = TY_(tmbstrdup)(doc->allocator, "style");
    TY_(FindTag)( doc, node );

    /* insert type attribute */
    av = TY_(NewAttributeEx)( doc, "type", "text/css", '"' );
    TY_(InsertAttributeAtStart)( node, av );

    body = TY_(FindBody)( doc );
    lexer->txtstart = lexer->lexsize;
    if ( body )
        CleanBodyAttrs( doc, body );

    for (style = lexer->styles; style; style = style->next)
    {
        TY_(AddCharToLexer)(lexer, ' ');
        TY_(AddStringLiteral)(lexer, style->tag);
        TY_(AddCharToLexer)(lexer, '.');
        TY_(AddStringLiteral)(lexer, style->tag_class);
        TY_(AddCharToLexer)(lexer, ' ');
        TY_(AddCharToLexer)(lexer, '{');
        TY_(AddStringLiteral)(lexer, style->properties);
        TY_(AddCharToLexer)(lexer, '}');
        TY_(AddCharToLexer)(lexer, '\n');
    }

    lexer->txtend = lexer->lexsize;

    TY_(InsertNodeAtEnd)( node, TY_(TextToken)(lexer) );

    /*
     now insert style element into document head

     doc is root node. search its children for html node
     the head node should be first child of html node
    */
    if ( NULL != (head = TY_(FindHEAD)( doc )) )
        TY_(InsertNodeAtEnd)( head, node );
}


/* ensure bidirectional links are consistent */
void TY_(FixNodeLinks)(Node *node)
{
    Node *child;

    if (node->prev)
        node->prev->next = node;
    else
        node->parent->content = node;

    if (node->next)
        node->next->prev = node;
    else
        node->parent->last = node;

    for (child = node->content; child; child = child->next)
        child->parent = node;
}

/*
 used to strip child of node when
 the node has one and only one child
*/
static void StripOnlyChild(TidyDocImpl* doc, Node *node)
{
    Node *child;

    child = node->content;
    node->content = child->content;
    node->last = child->last;
    child->content = NULL;
    TY_(FreeNode)(doc, child);

    for (child = node->content; child; child = child->next)
        child->parent = node;
}

/*
  used to strip font start and end tags.
  Extricate "element", replace it by its content and delete it.
*/
static void DiscardContainer( TidyDocImpl* doc, Node *element, Node **pnode)
{
    if (element->content)
    {
        Node *node, *parent = element->parent;

        element->last->next = element->next;

        if (element->next)
        {
            element->next->prev = element->last;
        }
        else
            parent->last = element->last;

        if (element->prev)
        {
            element->content->prev = element->prev;
            element->prev->next = element->content;
        }
        else
            parent->content = element->content;

        for (node = element->content; node; node = node->next)
            node->parent = parent;

        *pnode = element->content;

        element->next = element->content = NULL;
        TY_(FreeNode)(doc, element);
    }
    else
    {
        *pnode = TY_(DiscardElement)(doc, element);
    }
}

/*
  Create new string that consists of the
  combined style properties in s1 and s2

  To merge property lists, we build a linked
  list of property/values and insert properties
  into the list in order, merging values for
  the same property name.
*/
static tmbstr MergeProperties( TidyDocImpl* doc, ctmbstr s1, ctmbstr s2 )
{
    tmbstr s;
    StyleProp *prop;

    prop = CreateProps(doc, NULL, s1);
    prop = CreateProps(doc, prop, s2);
    s = CreatePropString(doc, prop);
    FreeStyleProps(doc, prop);
    return s;
}

/*
 Add style property to element, creating style
 attribute as needed and adding ; delimiter
*/
void TY_(AddStyleProperty)(TidyDocImpl* doc, Node *node, ctmbstr property )
{
    AttVal *av = TY_(AttrGetById)(node, TidyAttr_STYLE);

    /* if style attribute already exists then insert property */

    if ( av )
    {
        if (av->value != NULL)
        {
            tmbstr s = MergeProperties( doc, av->value, property );
            TidyDocFree( doc, av->value );
            av->value = s;
        }
        else
        {
            av->value = TY_(tmbstrdup)( doc->allocator, property );
        }
    }
    else /* else create new style attribute */
    {
        av = TY_(NewAttributeEx)( doc, "style", property, '"' );
        TY_(InsertAttributeAtStart)( node, av );
    }
}

static void MergeClasses(TidyDocImpl* doc, Node *node, Node *child)
{
    AttVal *av;
    tmbstr s1, s2, names;

    for (s2 = NULL, av = child->attributes; av; av = av->next)
    {
        if (attrIsCLASS(av))
        {
            s2 = av->value;
            break;
        }
    }

    for (s1 = NULL, av = node->attributes; av; av = av->next)
    {
        if (attrIsCLASS(av))
        {
            s1 = av->value;
            break;
        }
    }

    if (s1)
    {
        if (s2)  /* merge class names from both */
        {
            uint l1, l2;
            l1 = TY_(tmbstrlen)(s1);
            l2 = TY_(tmbstrlen)(s2);
            names = (tmbstr) TidyDocAlloc(doc, l1 + l2 + 2);
            TY_(tmbstrcpy)(names, s1);
            names[l1] = ' ';
            TY_(tmbstrcpy)(names+l1+1, s2);
            TidyDocFree(doc, av->value);
            av->value = names;
        }
    }
    else if (s2)  /* copy class names from child */
    {
        av = TY_(NewAttributeEx)( doc, "class", s2, '"' );
        TY_(InsertAttributeAtStart)( node, av );
    }
}

static void MergeStyles(TidyDocImpl* doc, Node *node, Node *child)
{
    AttVal *av;
    tmbstr s1, s2, style;

    /*
       the child may have a class attribute used
       for attaching styles, if so the class name
       needs to be copied to node's class
    */
    MergeClasses(doc, node, child);

    for (s2 = NULL, av = child->attributes; av; av = av->next)
    {
        if (attrIsSTYLE(av))
        {
            s2 = av->value;
            break;
        }
    }

    for (s1 = NULL, av = node->attributes; av; av = av->next)
    {
        if (attrIsSTYLE(av))
        {
            s1 = av->value;
            break;
        }
    }

    if (s1)
    {
        if (s2)  /* merge styles from both */
        {
            style = MergeProperties(doc, s1, s2);
            TidyDocFree(doc, av->value);
            av->value = style;
        }
    }
    else if (s2)  /* copy style of child */
    {
        av = TY_(NewAttributeEx)( doc, "style", s2, '"' );
        TY_(InsertAttributeAtStart)( node, av );
    }
}

static ctmbstr FontSize2Name(ctmbstr size)
{
    static const ctmbstr sizes[7] =
    {
        "60%", "70%", "80%", NULL,
        "120%", "150%", "200%"
    };

    /* increment of 0.8 */
    static const ctmbstr minussizes[] =
    {
        "100%", "80%", "64%", "51%",
        "40%", "32%", "26%"
    };

    /* increment of 1.2 */
    static const ctmbstr plussizes[] =
    {
        "100%", "120%", "144%", "172%",
        "207%", "248%", "298%"
    };

    if (size[0] == '\0')
        return NULL;

    if ('0' <= size[0] && size[0] <= '6')
    {
        int n = size[0] - '0';
        return sizes[n];
    }

    if (size[0] == '-')
    {
        if ('0' <= size[1] && size[1] <= '6')
        {
            int n = size[1] - '0';
            return minussizes[n];
        }
        return "smaller"; /*"70%"; */
    }

    if ('0' <= size[1] && size[1] <= '6')
    {
        int n = size[1] - '0';
        return plussizes[n];
    }

    return "larger"; /* "140%" */
}

static void AddFontFace( TidyDocImpl* doc, Node *node, ctmbstr face )
{
    tmbchar buf[256];
    TY_(tmbsnprintf)(buf, sizeof(buf), "font-family: %s", face );
    TY_(AddStyleProperty)( doc, node, buf );
}

static void AddFontSize( TidyDocImpl* doc, Node* node, ctmbstr size )
{
    ctmbstr value = NULL;

    if (nodeIsP(node))
    {
        if (TY_(tmbstrcmp)(size, "6") == 0)
            value = "h1";
        else if (TY_(tmbstrcmp)(size, "5") == 0)
            value = "h2";
        else if (TY_(tmbstrcmp)(size, "4") == 0)
            value = "h3";

        if (value)
        {
            TidyDocFree(doc, node->element);
            node->element = TY_(tmbstrdup)(doc->allocator, value);
            TY_(FindTag)(doc, node);
            return;
        }
    }

    value = FontSize2Name(size);

    if (value)
    {
        tmbchar buf[64];
        TY_(tmbsnprintf)(buf, sizeof(buf), "font-size: %s", value);
        TY_(AddStyleProperty)( doc, node, buf );
    }
}

static void AddFontColor( TidyDocImpl* doc, Node *node, ctmbstr color)
{
    tmbchar buf[128];
    TY_(tmbsnprintf)(buf, sizeof(buf), "color: %s", color);
    TY_(AddStyleProperty)( doc, node, buf );
}

/* force alignment value to lower case */
static void AddAlign( TidyDocImpl* doc, Node *node, ctmbstr align )
{
    uint i;
    tmbchar buf[128];

    TY_(tmbstrcpy)( buf, "text-align: " );
    for ( i = 12; i < sizeof(buf)/sizeof(buf[0])-1; ++i )
    {
        if ( (buf[i] = (tmbchar)TY_(ToLower)(*align++)) == '\0' )
            break;
    }
    buf[i] = '\0';
    TY_(AddStyleProperty)( doc, node, buf );
}

/*
 add style properties to node corresponding to
 the font face, size and color attributes
*/
static void AddFontStyles( TidyDocImpl* doc, Node *node, AttVal *av)
{
    while (av)
    {
        if (AttrHasValue(av))
        {
            if (attrIsFACE(av))
                AddFontFace( doc, node, av->value );
            else if (attrIsSIZE(av))
                AddFontSize( doc, node, av->value );
            else if (attrIsCOLOR(av))
                AddFontColor( doc, node, av->value );
        }
        av = av->next;
    }
}

/*
    Symptom: <p align=center>
    Action: <p style="text-align: center">
*/
static void TextAlign( TidyDocImpl* doc, Node* node )
{
    AttVal *av, *prev;

    prev = NULL;

    for (av = node->attributes; av; av = av->next)
    {
        if (attrIsALIGN(av))
        {
            if (prev)
                prev->next = av->next;
            else
                node->attributes = av->next;

            if (av->value)
                AddAlign( doc, node, av->value );

            TY_(FreeAttribute)(doc, av);
            break;
        }

        prev = av;
    }
}

/*
    Symptom: <table bgcolor="red">
    Action: <table style="background-color: red">
*/
static void TableBgColor( TidyDocImpl* doc, Node* node )
{
    AttVal* attr;
    tmbchar buf[256];

    if (NULL != (attr = TY_(AttrGetById)(node, TidyAttr_BGCOLOR)))
    {
        TY_(tmbsnprintf)(buf, sizeof(buf), "background-color: %s", attr->value );
        TY_(RemoveAttribute)( doc, node, attr );
        TY_(AddStyleProperty)( doc, node, buf );
    }
}

/*
   The clean up rules use the pnode argument to return the
   next node when the original node has been deleted
*/

/*
    Symptom: <dir> <li> where <li> is only child
    Action: coerce <dir> <li> to <div> with indent.
*/

static Bool Dir2Div( TidyDocImpl* doc, Node *node, Node **ARG_UNUSED(pnode))
{
    Node *child;

    if ( nodeIsDIR(node) || nodeIsUL(node) || nodeIsOL(node) )
    {
        child = node->content;

        if (child == NULL)
            return no;

        /* check child has no peers */

        if (child->next)
            return no;

        if ( !nodeIsLI(child) )
            return no;

        if ( !child->implicit )
            return no;

        /* coerce dir to div */
        node->tag = TY_(LookupTagDef)( TidyTag_DIV );
        TidyDocFree( doc, node->element );
        node->element = TY_(tmbstrdup)(doc->allocator, "div");
        TY_(AddStyleProperty)( doc, node, "margin-left: 2em" );
        StripOnlyChild( doc, node );
        return yes;
    }

    return no;
}

/*
    Symptom: <center>
    Action: replace <center> by <div style="text-align: center">
*/

static Bool Center2Div( TidyDocImpl* doc, Node *node, Node **pnode)
{
    if ( nodeIsCENTER(node) )
    {
        RenameElem( doc, node, TidyTag_DIV );
        TY_(AddStyleProperty)( doc, node, "text-align: center" );
        return yes;
    }

    return no;
}

/* Copy child attributes to node. Duplicate attributes are overwritten.
   Unique attributes (such as ID) disable the action.
   Attributes style and class are not dealt with. A call to MergeStyles
   will do that.
*/
static Bool CopyAttrs( TidyDocImpl* doc, Node *node, Node *child)
{
    AttVal *av1, *av2;
    TidyAttrId id;

    /* Detect attributes that cannot be merged or overwritten. */
    if (TY_(AttrGetById)(child, TidyAttr_ID) != NULL
        && TY_(AttrGetById)(node, TidyAttr_ID) != NULL)
        return no;

    /* Move child attributes to node. Attributes in node
     can be overwritten or merged. */
    for (av2 = child->attributes; av2; )
    {
        /* Dealt by MergeStyles. */
        if (attrIsSTYLE(av2) || attrIsCLASS(av2))
        {
            av2 = av2->next;
            continue;
        }
        /* Avoid duplicates in node */
        if ((id=AttrId(av2)) != TidyAttr_UNKNOWN
            && (av1=TY_(AttrGetById)(node, id))!= NULL)
            TY_(RemoveAttribute)( doc, node, av1 );

        /* Move attribute from child to node */
        TY_(DetachAttribute)( child, av2 );
        av1 = av2;
        av2 = av2->next;
        av1->next = NULL;
        TY_(InsertAttributeAtEnd)( node, av1 );
    }

    return yes;
}

/*
    Symptom <XX><XX>...</XX></XX>
    Action: merge the two XXs

  For instance, this is useful after nested <dir>s used by Word
  for indenting have been converted to <div>s

  If state is "no", no merging.
  If state is "yes", inner element is discarded. Only Style and Class
  attributes are merged using MergeStyles().
  If state is "auto", atttibutes are merged as described in CopyAttrs().
  Style and Class attributes are merged using MergeStyles().
*/
static Bool MergeNestedElements( TidyDocImpl* doc,
                                 TidyTagId Id, TidyTriState state, Node *node,
                                 Node **ARG_UNUSED(pnode))
{
    Node *child;

    if ( state == TidyNoState
         || !TagIsId(node, Id) )
        return no;

    child = node->content;

    if ( child == NULL
         || child->next != NULL
         || !TagIsId(child, Id) )
        return no;

    if ( state == TidyAutoState
         && CopyAttrs(doc, node, child) == no )
        return no;

    MergeStyles( doc, node, child );
    StripOnlyChild( doc, node );
    return yes;
}

/*
    Symptom: <ul><li><ul>...</ul></li></ul>
    Action: discard outer list
*/

static Bool NestedList( TidyDocImpl* doc, Node *node, Node **pnode )
{
    Node *child, *list;

    if ( nodeIsUL(node) || nodeIsOL(node) )
    {
        child = node->content;

        if (child == NULL)
            return no;

        /* check child has no peers */

        if (child->next)
            return no;

        list = child->content;

        if (!list)
            return no;

        if (list->tag != node->tag)
            return no;

        /* check list has no peers */
        if (list->next)
            return no;

        *pnode = list;  /* Set node to resume iteration */

        /* move inner list node into position of outer node */
        list->prev = node->prev;
        list->next = node->next;
        list->parent = node->parent;
        TY_(FixNodeLinks)(list);

        /* get rid of outer ul and its li */
        child->content = NULL;
        TY_(FreeNode)( doc, child ); /* See test #427841. */
        child = NULL;
        node->content = NULL;
        node->next = NULL;
        TY_(FreeNode)( doc, node );
        node = NULL;

        /*
          If prev node was a list the chances are this node
          should be appended to that list. Word has no way of
          recognizing nested lists and just uses indents
        */

        if (list->prev)
        {
            if ( (nodeIsUL(list->prev) || nodeIsOL(list->prev))
                 && list->prev->last )
            {
                node = list;
                list = node->prev;

                child = list->last;  /* <li> */

                list->next = node->next;
                TY_(FixNodeLinks)(list);

                node->parent = child;
                node->next = NULL;
                node->prev = child->last;
                TY_(FixNodeLinks)(node);
                CleanNode( doc, node );
            }
        }

        return yes;
    }

    return no;
}

/* Find CSS equivalent in a SPAN element */
static
Bool FindCSSSpanEq( Node *node, ctmbstr *s, Bool deprecatedOnly )
{
    struct
    {
        TidyTagId id;
        ctmbstr CSSeq;
        Bool deprecated;
    }
    const CSS_SpanEq[] =
        {
            { TidyTag_B, "font-weight: bold", no },
            { TidyTag_I, "font-style: italic", no },
            { TidyTag_S, "text-decoration: line-through", yes},
            { TidyTag_STRIKE, "text-decoration: line-through", yes},
            { TidyTag_U, "text-decoration: underline", yes},
            { TidyTag_UNKNOWN, NULL, no }
        };
    uint i;

    for (i=0; CSS_SpanEq[i].CSSeq; ++i)
        if ( (!deprecatedOnly || CSS_SpanEq[i].deprecated)
             && TagIsId(node, CSS_SpanEq[i].id) )
        {
            *s = CSS_SpanEq[i].CSSeq;
            return yes;
        }
    return no; 
}

/* Necessary conditions to apply BlockStyle(). */
static Bool CanApplyBlockStyle( Node *node )
{
    if (TY_(nodeHasCM)(node,CM_BLOCK | CM_LIST | CM_DEFLIST | CM_TABLE)
        && !nodeIsDIV(node) && !nodeIsP(node)
        && !nodeIsTABLE(node) && !nodeIsTR(node) && !nodeIsLI(node) )
    {
        return yes;
    }
    return no;
}

/*
  Symptom: the only child of a block-level element is a
  presentation element such as B, I or FONT

  Action: add style "font-weight: bold" to the block and
  strip the <b> element, leaving its children.

  example:

    <p>
      <b><font face="Arial" size="6">Draft Recommended Practice</font></b>
    </p>

  becomes:

      <p style="font-weight: bold; font-family: Arial; font-size: 6">
        Draft Recommended Practice
      </p>

  This code also replaces the align attribute by a style attribute.
  However, to avoid CSS problems with Navigator 4, this isn't done
  for the elements: caption, tr and table
*/
static Bool BlockStyle( TidyDocImpl* doc, Node *node, Node **ARG_UNUSED(pnode) )
{
    Node *child;
    ctmbstr CSSeq;

    /* check for bgcolor */
    if (   nodeIsTABLE(node)
        || nodeIsTD(node) || nodeIsTH(node) || nodeIsTR( node ))
        TableBgColor( doc, node );

    if (CanApplyBlockStyle(node))
    {
        /* check for align attribute */
        if ( !nodeIsCAPTION(node) )
            TextAlign( doc, node );

        child = node->content;
        if (child == NULL)
            return no;

        /* check child has no peers */
        if (child->next)
            return no;

        if ( FindCSSSpanEq(child, &CSSeq, no) )
        {
            MergeStyles( doc, node, child );
            TY_(AddStyleProperty)( doc, node, CSSeq );
            StripOnlyChild( doc, node );
            return yes;
        }
        else if ( nodeIsFONT(child) )
        {
            MergeStyles( doc, node, child );
            AddFontStyles( doc, node, child->attributes );
            StripOnlyChild( doc, node );
            return yes;
        }
    }

    return no;
}

/* Necessary conditions to apply InlineStyle(). */
static Bool CanApplyInlineStyle( Node *node )
{
    return !nodeIsFONT(node) && TY_(nodeHasCM)(node, CM_INLINE|CM_ROW);
}

/* the only child of table cell or an inline element such as em */
static Bool InlineStyle( TidyDocImpl* doc, Node *node, Node **ARG_UNUSED(pnode) )
{
    Node *child;
    ctmbstr CSSeq;

    if ( CanApplyInlineStyle(node) )
    {
        child = node->content;

        if (child == NULL)
            return no;

        /* check child has no peers */

        if (child->next)
            return no;

        if ( FindCSSSpanEq(child, &CSSeq, no) )
        {
            MergeStyles( doc, node, child );
            TY_(AddStyleProperty)( doc, node, CSSeq );
            StripOnlyChild( doc, node );
            return yes;
        }
        else if ( nodeIsFONT(child) )
        {
            MergeStyles( doc, node, child );
            AddFontStyles( doc, node, child->attributes );
            StripOnlyChild( doc, node );
            return yes;
        }
    }

    return no;
}

/*
    Transform element to equivalent CSS
*/
static Bool InlineElementToCSS( TidyDocImpl* doc, Node* node,
                                Node **ARG_UNUSED(pnode)  )
{
    ctmbstr CSSeq;

    /* if node is the only child of parent element then leave alone
          Do so only if BlockStyle may be succesful. */
    if ( node->parent->content == node && node->next == NULL &&
         (CanApplyBlockStyle(node->parent)
          || CanApplyInlineStyle(node->parent)) )
        return no;

    if ( FindCSSSpanEq(node, &CSSeq, yes) )
    {
        RenameElem( doc, node, TidyTag_SPAN );
        TY_(AddStyleProperty)( doc, node, CSSeq );
        return yes;
    }
    return no;
} 

/*
  Replace font elements by span elements, deleting
  the font element's attributes and replacing them
  by a single style attribute.
*/
static Bool Font2Span( TidyDocImpl* doc, Node *node, Node **pnode )
{
    AttVal *av, *style, *next;

    if ( nodeIsFONT(node) )
    {
        /* if node is the only child of parent element then leave alone
          Do so only if BlockStyle may be succesful. */
        if ( node->parent->content == node && node->next == NULL &&
             CanApplyBlockStyle(node->parent) )
            return no;

        AddFontStyles( doc, node, node->attributes );

        /* extract style attribute and free the rest */
        av = node->attributes;
        style = NULL;

        while (av)
        {
            next = av->next;

            if (attrIsSTYLE(av))
            {
                av->next = NULL;
                style = av;
            }
            else
            {
                TY_(FreeAttribute)( doc, av );
            }
            av = next;
        }

        node->attributes = style;
        RenameElem( doc, node, TidyTag_SPAN );
        return yes;
    }

    return no;
}

/*
  Applies all matching rules to a node.
*/
Node* CleanNode( TidyDocImpl* doc, Node *node )
{
    Node *next = NULL;
    TidyTriState mergeDivs = cfgAutoBool(doc, TidyMergeDivs);
    TidyTriState mergeSpans = cfgAutoBool(doc, TidyMergeSpans);

    for (next = node; TY_(nodeIsElement)(node); node = next)
    {
        if ( Dir2Div(doc, node, &next) )
            continue;

        /* Special case: true result means
        ** that arg node and its parent no longer exist.
        ** So we must jump back up the CreateStyleProperties()
        ** call stack until we have a valid node reference.
        */
        if ( NestedList(doc, node, &next) )
            return next;

        if ( Center2Div(doc, node, &next) )
            continue;

        if ( MergeNestedElements(doc, TidyTag_DIV, mergeDivs, node, &next) )
            continue;

        if ( MergeNestedElements(doc, TidyTag_SPAN, mergeSpans, node, &next) )
            continue;

        if ( BlockStyle(doc, node, &next) )
            continue;

        if ( InlineStyle(doc, node, &next) )
            continue;

        if ( InlineElementToCSS(doc, node, &next) )
            continue;

        if ( Font2Span(doc, node, &next) )
            continue;

        break;
    }

    return next;
}

/* Special case: if the current node is destroyed by
** CleanNode() lower in the tree, this node and its parent
** no longer exist.  So we must jump back up the CleanTree()
** call stack until we have a valid node reference.
*/

static Node* CleanTree( TidyDocImpl* doc, Node *node )
{
    if (node->content)
    {
        Node *child;
        for (child = node->content; child != NULL; child = child->next)
        {
            child = CleanTree( doc, child );
            if ( !child )
                break;
        }
    }

    return CleanNode( doc, node );
}

static void DefineStyleRules( TidyDocImpl* doc, Node *node )
{
    Node *child;

    if (node->content)
    {
        for (child = node->content;
                child != NULL; child = child->next)
        {
            DefineStyleRules( doc, child );
        }
    }

    Style2Rule( doc, node );
}

void TY_(CleanDocument)( TidyDocImpl* doc )
{
    /* placeholder.  CleanTree()/CleanNode() will not
    ** zap root element 
    */
    CleanTree( doc, &doc->root );

    if ( cfgBool(doc, TidyMakeClean) )
    {
        DefineStyleRules( doc, &doc->root );
        CreateStyleElement( doc );
    }
}

/* simplifies <b><b> ... </b> ...</b> etc. */
void TY_(NestedEmphasis)( TidyDocImpl* doc, Node* node )
{
    Node *next;

    while (node)
    {
        next = node->next;

        if ( (nodeIsB(node) || nodeIsI(node))
             && node->parent && node->parent->tag == node->tag)
        {
            /* strip redundant inner element */
            DiscardContainer( doc, node, &next );
            node = next;
            continue;
        }

        if ( node->content )
            TY_(NestedEmphasis)( doc, node->content );

        node = next;
    }
}



/* replace i by em and b by strong */
void TY_(EmFromI)( TidyDocImpl* doc, Node* node )
{
    while (node)
    {
        if ( nodeIsI(node) )
            RenameElem( doc, node, TidyTag_EM );
        else if ( nodeIsB(node) )
            RenameElem( doc, node, TidyTag_STRONG );

        if ( node->content )
            TY_(EmFromI)( doc, node->content );

        node = node->next;
    }
}

static Bool HasOneChild(Node *node)
{
    return (node->content && node->content->next == NULL);
}

/*
 Some people use dir or ul without an li
 to indent the content. The pattern to
 look for is a list with a single implicit
 li. This is recursively replaced by an
 implicit blockquote.
*/
void TY_(List2BQ)( TidyDocImpl* doc, Node* node )
{
    while (node)
    {
        if (node->content)
            TY_(List2BQ)( doc, node->content );

        if ( node->tag && node->tag->parser == TY_(ParseList) &&
             HasOneChild(node) && node->content->implicit )
        {
            StripOnlyChild( doc, node );
            RenameElem( doc, node, TidyTag_BLOCKQUOTE );
            node->implicit = yes;
        }

        node = node->next;
    }
}


/*
 Replace implicit blockquote by div with an indent
 taking care to reduce nested blockquotes to a single
 div with the indent set to match the nesting depth
*/
void TY_(BQ2Div)( TidyDocImpl* doc, Node *node )
{
    tmbchar indent_buf[ 32 ];
    uint indent;

    while (node)
    {
        if ( nodeIsBLOCKQUOTE(node) && node->implicit )
        {
            indent = 1;

            while( HasOneChild(node) &&
                   nodeIsBLOCKQUOTE(node->content) &&
                   node->implicit)
            {
                ++indent;
                StripOnlyChild( doc, node );
            }

            if (node->content)
                TY_(BQ2Div)( doc, node->content );

            TY_(tmbsnprintf)(indent_buf, sizeof(indent_buf), "margin-left: %dem",
                             2*indent);

            RenameElem( doc, node, TidyTag_DIV );
            TY_(AddStyleProperty)(doc, node, indent_buf );
        }
        else if (node->content)
            TY_(BQ2Div)( doc, node->content );

        node = node->next;
    }
}


static Node* FindEnclosingCell( TidyDocImpl* ARG_UNUSED(doc), Node *node)
{
    Node *check;

    for ( check=node; check; check = check->parent )
    {
      if ( nodeIsTD(check) )
        return check;
    }
    return NULL;
}

/* node is <![if ...]> prune up to <![endif]> */
static Node* PruneSection( TidyDocImpl* doc, Node *node )
{
    Lexer* lexer = doc->lexer;

    for (;;)
    {
        ctmbstr lexbuf = lexer->lexbuf + node->start;
        if ( TY_(tmbstrncmp)(lexbuf, "if !supportEmptyParas", 21) == 0 )
        {
          Node* cell = FindEnclosingCell( doc, node );
          if ( cell )
          {
            /* Need to put &nbsp; into cell so it doesn't look weird
            */
            Node* nbsp = TY_(NewLiteralTextNode)( lexer, "\240" );
            assert( (byte)'\240' == (byte)160 );
            TY_(InsertNodeBeforeElement)( node, nbsp );
          }
        }

        /* discard node and returns next, unless it is a text node */
        if ( node->type == TextNode )
            node = node->next;
        else
            node = TY_(DiscardElement)( doc, node );

        if (node == NULL)
            return NULL;
        
        if (node->type == SectionTag)
        {
            if (TY_(tmbstrncmp)(lexer->lexbuf + node->start, "if", 2) == 0)
            {
                node = PruneSection( doc, node );
                continue;
            }

            if (TY_(tmbstrncmp)(lexer->lexbuf + node->start, "endif", 5) == 0)
            {
                node = TY_(DiscardElement)( doc, node );
                break;
            }
        }
    }

    return node;
}

void TY_(DropSections)( TidyDocImpl* doc, Node* node )
{
    Lexer* lexer = doc->lexer;
    while (node)
    {
        if (node->type == SectionTag)
        {
            /* prune up to matching endif */
            if ((TY_(tmbstrncmp)(lexer->lexbuf + node->start, "if", 2) == 0) &&
                (TY_(tmbstrncmp)(lexer->lexbuf + node->start, "if !vml", 7) != 0)) /* #444394 - fix 13 Sep 01 */
            {
                node = PruneSection( doc, node );
                continue;
            }

            /* discard others as well */
            node = TY_(DiscardElement)( doc, node );
            continue;
        }

        if (node->content)
            TY_(DropSections)( doc, node->content );

        node = node->next;
    }
}

static void PurgeWord2000Attributes( TidyDocImpl* doc, Node* node )
{
    AttVal *attr, *next, *prev = NULL;

    for ( attr = node->attributes; attr; attr = next )
    {
        next = attr->next;

        /* special check for class="Code" denoting pre text */
        /* Pass thru user defined styles as HTML class names */
        if (attrIsCLASS(attr))
        {
            if (AttrValueIs(attr, "Code") ||
                 TY_(tmbstrncmp)(attr->value, "Mso", 3) != 0 )
            {
                prev = attr;
                continue;
            }
        }

        if (attrIsCLASS(attr) ||
            attrIsSTYLE(attr) ||
            attrIsLANG(attr)  ||
             ( (attrIsHEIGHT(attr) || attrIsWIDTH(attr)) &&
               (nodeIsTD(node) || nodeIsTR(node) || nodeIsTH(node)) ) ||
             (attr->attribute && TY_(tmbstrncmp)(attr->attribute, "x:", 2) == 0) )
        {
            if (prev)
                prev->next = next;
            else
                node->attributes = next;

            TY_(FreeAttribute)( doc, attr );
        }
        else
            prev = attr;
    }
}

/* Word2000 uses span excessively, so we strip span out */
static Node* StripSpan( TidyDocImpl* doc, Node* span )
{
    Node *node, *prev = NULL, *content;

    /*
     deal with span elements that have content
     by splicing the content in place of the span
     after having processed it
    */

    TY_(CleanWord2000)( doc, span->content );
    content = span->content;

    if (span->prev)
        prev = span->prev;
    else if (content)
    {
        node = content;
        content = content->next;
        TY_(RemoveNode)(node);
        TY_(InsertNodeBeforeElement)(span, node);
        prev = node;
    }

    while (content)
    {
        node = content;
        content = content->next;
        TY_(RemoveNode)(node);
        TY_(InsertNodeAfterElement)(prev, node);
        prev = node;
    }

    if (span->next == NULL)
        span->parent->last = prev;

    node = span->next;
    span->content = NULL;
    TY_(DiscardElement)( doc, span );
    return node;
}

/* map non-breaking spaces to regular spaces */
void TY_(NormalizeSpaces)(Lexer *lexer, Node *node)
{
    while ( node )
    {
        if ( node->content )
            TY_(NormalizeSpaces)( lexer, node->content );

        if (TY_(nodeIsText)(node))
        {
            uint i, c;
            tmbstr p = lexer->lexbuf + node->start;

            for (i = node->start; i < node->end; ++i)
            {
                c = (byte) lexer->lexbuf[i];

                /* look for UTF-8 multibyte character */
                if ( c > 0x7F )
                    i += TY_(GetUTF8)( lexer->lexbuf + i, &c );

                if ( c == 160 )
                    c = ' ';

                p = TY_(PutUTF8)(p, c);
            }
            node->end = p - lexer->lexbuf;
        }

        node = node->next;
    }
}

/* used to hunt for hidden preformatted sections */
static Bool NoMargins(Node *node)
{
    AttVal *attval = TY_(AttrGetById)(node, TidyAttr_STYLE);

    if ( !AttrHasValue(attval) )
        return no;

    /* search for substring "margin-top: 0" */
    if (!TY_(tmbsubstr)(attval->value, "margin-top: 0"))
        return no;

    /* search for substring "margin-bottom: 0" */
    if (!TY_(tmbsubstr)(attval->value, "margin-bottom: 0"))
        return no;

    return yes;
}

/* does element have a single space as its content? */
static Bool SingleSpace( Lexer* lexer, Node* node )
{
    if ( node->content )
    {
        node = node->content;

        if ( node->next != NULL )
            return no;

        if ( node->type != TextNode )
            return no;

        if ( (node->end - node->start) == 1 &&
             lexer->lexbuf[node->start] == ' ' )
            return yes;

        if ( (node->end - node->start) == 2 )
        {
            uint c = 0;
            TY_(GetUTF8)( lexer->lexbuf + node->start, &c );
            if ( c == 160 )
                return yes;
        }
    }

    return no;
}

/*
 This is a major clean up to strip out all the extra stuff you get
 when you save as web page from Word 2000. It doesn't yet know what
 to do with VML tags, but these will appear as errors unless you
 declare them as new tags, such as o:p which needs to be declared
 as inline.
*/
void TY_(CleanWord2000)( TidyDocImpl* doc, Node *node)
{
    /* used to a list from a sequence of bulletted p's */
    Lexer* lexer = doc->lexer;
    Node* list = NULL;
    AttVal *next_attr, *attval;

    while ( node )
    {
        /* get rid of Word's xmlns attributes */
        if ( nodeIsHTML(node) )
        {
            /* check that it's a Word 2000 document */
            if ( !TY_(GetAttrByName)(node, "xmlns:o") &&
                 !cfgBool(doc, TidyMakeBare) )
                return;

            /* Output proprietary attributes to maintain errout compatability
             * with traditional Tidy. This is a result of moving all of the
             * proprietary checks to near the end of the cleanup process,
             * meaning this result would not ordinarily be displayed. 
             */
            attval = node->attributes;
            while ( attval ) {
                next_attr = attval->next;

                /* Issue #591 - take care of a NULL attribute, too. */
                if ( !attval->attribute || ( strcmp(attval->attribute, "xmlns") != 0 ))
                    TY_(ReportAttrError)(doc, node, attval, PROPRIETARY_ATTRIBUTE);
                attval = next_attr;
            }

            TY_(FreeAttrs)( doc, node );
        }

        /* fix up preformatted sections by looking for a
        ** sequence of paragraphs with zero top/bottom margin
        */
        if ( nodeIsP(node) )
        {
            if (NoMargins(node))
            {
                Node *pre, *next;
                TY_(CoerceNode)(doc, node, TidyTag_PRE, no, yes);

                PurgeWord2000Attributes( doc, node );

                if (node->content)
                    TY_(CleanWord2000)( doc, node->content );

                pre = node;
                node = node->next;

                /* continue to strip p's */

                while ( nodeIsP(node) && NoMargins(node) )
                {
                    next = node->next;
                    TY_(RemoveNode)(node);
                    TY_(InsertNodeAtEnd)(pre, TY_(NewLineNode)(lexer));
                    TY_(InsertNodeAtEnd)(pre, node);
                    StripSpan( doc, node );
                    node = next;
                }

                if (node == NULL)
                    break;
            }
        }

        if (node->tag && (node->tag->model & CM_BLOCK)
            && SingleSpace(lexer, node))
        {
            node = StripSpan( doc, node );
            continue;
        }
        /* discard Word's style verbiage */
        if ( nodeIsSTYLE(node) || nodeIsMETA(node) ||
             node->type == CommentTag )
        {
            node = TY_(DiscardElement)( doc, node );
            continue;
        }

        /* strip out all span and font tags Word scatters so liberally! */
        if ( nodeIsSPAN(node) || nodeIsFONT(node) )
        {
            node = StripSpan( doc, node );
            continue;
        }

        if ( nodeIsLINK(node) )
        {
            AttVal *attr = TY_(AttrGetById)(node, TidyAttr_REL);

            if (AttrValueIs(attr, "File-List"))
            {
                node = TY_(DiscardElement)( doc, node );
                continue;
            }
        }

        /* discards <o:p> which encodes the paragraph mark */
        if ( node->tag && TY_(tmbstrcmp)(node->tag->name,"o:p")==0)
        {
            /* Output proprietary elements to maintain errout compatability
             * with traditional Tidy. This is a result of moving all of the
             * proprietary checks to near the end of the cleanup process,
             * meaning this result would not ordinarily be displayed.
             */
            Node* next;
            TY_(Report)(doc, NULL, node, PROPRIETARY_ELEMENT);
            DiscardContainer( doc, node, &next );
            node = next;
            continue;
        }

        /* discard empty paragraphs */

        if ( node->content == NULL && nodeIsP(node) )
        {
            /*  Use the existing function to ensure consistency */
            Node *next = TY_(TrimEmptyElement)( doc, node );
            node = next;
            continue;
        }

        if ( nodeIsP(node) )
        {
            AttVal *attr, *atrStyle;
            
            attr = TY_(AttrGetById)(node, TidyAttr_CLASS);
            atrStyle = TY_(AttrGetById)(node, TidyAttr_STYLE);
            /*
               (JES) Sometimes Word marks a list item with the following hokie syntax
               <p class="MsoNormal" style="...;mso-list:l1 level1 lfo1;
                translate these into <li>
            */
            /* map sequence of <p class="MsoListBullet"> to <ul>...</ul> */
            /* map <p class="MsoListNumber"> to <ol>...</ol> */
            if ( AttrValueIs(attr, "MsoListBullet") ||
                 AttrValueIs(attr, "MsoListNumber") ||
                 AttrContains(atrStyle, "mso-list:") )
            {
                TidyTagId listType = TidyTag_UL;
                if (AttrValueIs(attr, "MsoListNumber"))
                    listType = TidyTag_OL;

                TY_(CoerceNode)(doc, node, TidyTag_LI, no, yes);

                if ( !list || TagId(list) != listType )
                {
                    const Dict* tag = TY_(LookupTagDef)( listType );
                    list = TY_(InferredTag)(doc, tag->id);
                    TY_(InsertNodeBeforeElement)(node, list);
                }

                PurgeWord2000Attributes( doc, node );

                if ( node->content )
                    TY_(CleanWord2000)( doc, node->content );

                /* remove node and append to contents of list */
                TY_(RemoveNode)(node);
                TY_(InsertNodeAtEnd)(list, node);
                node = list;
            }
            /* map sequence of <p class="Code"> to <pre>...</pre> */
            else if (AttrValueIs(attr, "Code"))
            {
                Node *br = TY_(NewLineNode)(lexer);
                TY_(NormalizeSpaces)(lexer, node->content);

                if ( !list || TagId(list) != TidyTag_PRE )
                {
                    list = TY_(InferredTag)(doc, TidyTag_PRE);
                    TY_(InsertNodeBeforeElement)(node, list);
                }

                /* remove node and append to contents of list */
                TY_(RemoveNode)(node);
                TY_(InsertNodeAtEnd)(list, node);
                StripSpan( doc, node );
                TY_(InsertNodeAtEnd)(list, br);
                node = list->next;
            }
            else
                list = NULL;
        }
        else
            list = NULL;

        if (!node)
            return;

        /* strip out style and class attributes */
        if (TY_(nodeIsElement)(node))
            PurgeWord2000Attributes( doc, node );

        if (node->content)
            TY_(CleanWord2000)( doc, node->content );

        node = node->next;
    }
}

Bool TY_(IsWord2000)( TidyDocImpl* doc )
{
    AttVal *attval;
    Node *node, *head;
    Node *html = TY_(FindHTML)( doc );

    if (html && TY_(GetAttrByName)(html, "xmlns:o"))
        return yes;
    
    /* search for <meta name="GENERATOR" content="Microsoft ..."> */
    head = TY_(FindHEAD)( doc );

    if (head)
    {
        for (node = head->content; node; node = node->next)
        {
            if ( !nodeIsMETA(node) )
                continue;

            attval = TY_(AttrGetById)( node, TidyAttr_NAME );

            if ( !AttrValueIs(attval, "generator") )
                continue;

            attval =  TY_(AttrGetById)( node, TidyAttr_CONTENT );

            if ( AttrContains(attval, "Microsoft") )
                return yes;
        }
    }

    return no;
}

/* where appropriate move object elements from head to body */
void TY_(BumpObject)( TidyDocImpl* doc, Node *html )
{
    Node *node, *next, *head = NULL, *body = NULL;

    if (!html)
        return;

    for ( node = html->content; node != NULL; node = node->next )
    {
        if ( nodeIsHEAD(node) )
            head = node;

        if ( nodeIsBODY(node) )
            body = node;
    }

    if ( head != NULL && body != NULL )
    {
        for (node = head->content; node != NULL; node = next)
        {
            next = node->next;

            if ( nodeIsOBJECT(node) )
            {
                Node *child;
                Bool bump = no;

                for (child = node->content; child != NULL; child = child->next)
                {
                    /* bump to body unless content is param */
                    if ( (TY_(nodeIsText)(child) && !TY_(IsBlank)(doc->lexer, node))
                         || !nodeIsPARAM(child) )
                    {
                            bump = yes;
                            break;
                    }
                }

                if ( bump )
                {
                    TY_(RemoveNode)( node );
                    TY_(InsertNodeAtStart)( body, node );
                }
            }
        }
    }
}


/*\
*  Issue #456 - Check meta charset
*  1. if there is no meta charset, it adds one, according to doctype, no warning.
*  2. if there is a meta charset, it moves it to the top if HEAD. Not sure this required?
*  3. if it doesn't match the output encoding, and fix. Naybe no warning?
*  4. if there are duplicates, discard them, with warning.
\*/
Bool TY_(TidyMetaCharset)(TidyDocImpl* doc)
{
    AttVal *charsetAttr;
    AttVal *contentAttr;
    AttVal *httpEquivAttr;
    Bool charsetFound = no;
    uint outenc = cfg(doc, TidyOutCharEncoding);
    ctmbstr enc = TY_(GetEncodingNameFromTidyId)(outenc);
    Node *currentNode;
    Node *head = TY_(FindHEAD)(doc);
    Node *metaTag;
    Node *prevNode;
    TidyBuffer buf;
    TidyBuffer charsetString;
    /* tmbstr httpEquivAttrValue; */
    /* tmbstr lcontent; */
    tmbstr newValue;
    Bool add_meta = cfgBool(doc, TidyMetaCharset);

    /* We can't do anything we don't have a head or encoding is NULL */
    if (!head || !enc || !TY_(tmbstrlen)(enc))
        return no;
    if (outenc == RAW)
        return no;
#ifndef NO_NATIVE_ISO2022_SUPPORT
    if (outenc == ISO2022)
        return no;
#endif
    if (cfgAutoBool(doc, TidyBodyOnly) == TidyYesState)
        return no; /* nothing to do here if showing body only */

    tidyBufInit(&charsetString);
    /* Set up the content test 'charset=value' */
    tidyBufClear(&charsetString);
    tidyBufAppend(&charsetString, "charset=", 8);
    tidyBufAppend(&charsetString, (char*)enc, TY_(tmbstrlen)(enc));
    tidyBufAppend(&charsetString, "\0", 1); /* zero terminate the buffer */
    /* process the children of the head */
    /* Issue #656 - guard against 'currentNode' being set NULL in loop */
    for (currentNode = head->content; currentNode; 
        currentNode = (currentNode ? currentNode->next : NULL))
    {
        if (!nodeIsMETA(currentNode))
            continue;   /* not a meta node */
        charsetAttr = attrGetCHARSET(currentNode);
        httpEquivAttr = attrGetHTTP_EQUIV(currentNode);
        if (!charsetAttr && !httpEquivAttr)
            continue;   /* has no charset attribute */
                        /*
                        Meta charset comes in quite a few flavors:
                        1. <meta charset="value"> - expected for (X)HTML5.
                        */
        if (charsetAttr && !httpEquivAttr)
        {
            /* we already found one, so remove the rest. */
            if (charsetFound || !charsetAttr->value)
            {
                prevNode = currentNode->prev;
                TY_(Report)(doc, head, currentNode, DISCARDING_UNEXPECTED);
                TY_(DiscardElement)(doc, currentNode);
                currentNode = prevNode;
                continue;
            }
            charsetFound = yes;
            /* Fix mismatched attribute value */
            if (TY_(tmbstrcasecmp)(charsetAttr->value, enc) != 0)
            {
                newValue = (tmbstr)TidyDocAlloc(doc, TY_(tmbstrlen)(enc) + 1);   /* allocate + 1 for 0 */
                TY_(tmbstrcpy)(newValue, enc);
                /* Note: previously http-equiv had been modified, without warning
                in void TY_(VerifyHTTPEquiv)(TidyDocImpl* doc, Node *head)
                */
                TY_(ReportAttrError)(doc, currentNode, charsetAttr, ATTRIBUTE_VALUE_REPLACED);
                TidyDocFree(doc, charsetAttr->value);   /* free current value */
                charsetAttr->value = newValue;
            }
            /* Make sure it's the first element. */
            if (currentNode != head->content->next) {
                TY_(RemoveNode)(currentNode);
                TY_(InsertNodeAtStart)(head, currentNode);
            }
            continue;
        }
        /*
        2. <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        expected for HTML4. This is normally ok - but can clash.
        */
        if (httpEquivAttr && !charsetAttr)
        {
            contentAttr = TY_(AttrGetById)(currentNode, TidyAttr_CONTENT);
            if (!contentAttr)
                continue;   /* has no 'content' attribute */
            if (!httpEquivAttr->value)
            {
                prevNode = currentNode->prev;
                TY_(Report)(doc, head, currentNode, DISCARDING_UNEXPECTED);
                TY_(DiscardElement)(doc, currentNode);
                currentNode = prevNode;
                continue;
            }
            /* httpEquivAttrValue = TY_(tmbstrtolower)(httpEquivAttr->value); */
            if (TY_(tmbstrcasecmp)(httpEquivAttr->value, (tmbstr) "content-type") != 0)
                continue;   /* is not 'content-type' */
            if (!contentAttr->value)
            {
                continue; /* has no 'content' attribute has NO VALUE! */
            }
            /* check encoding matches
            If a miss-match found here, fix it. previous silently done
            in void TY_(VerifyHTTPEquiv)(TidyDocImpl* doc, Node *head)
            lcontent = TY_(tmbstrtolower)(contentAttr->value);
            */
            if (TY_(tmbstrcasecmp)(contentAttr->value, (ctmbstr)charsetString.bp) == 0)
            {
                /* we already found one, so remove the rest. */
                if (charsetFound)
                {
                    prevNode = currentNode->prev;
                    TY_(Report)(doc, head, currentNode, DISCARDING_UNEXPECTED);
                    TY_(DiscardElement)(doc, currentNode);
                    currentNode = prevNode;
                    continue;
                }
                charsetFound = yes;
            }
            else
            {
                /* fix a mis-match */
                if (charsetFound)
                {
                    prevNode = currentNode->prev;
                    TY_(Report)(doc, head, currentNode, DISCARDING_UNEXPECTED);
                    TY_(DiscardElement)(doc, currentNode);
                    currentNode = prevNode;
                }
                else
                {
                    /* correct the content */
                    newValue = (tmbstr)TidyDocAlloc(doc, 19 + TY_(tmbstrlen)(enc) + 1);
                    TY_(tmbstrcpy)(newValue, "text/html; charset=");
                    TY_(tmbstrcpy)(newValue + 19, enc);
                    if (cfgBool(doc, TidyShowMetaChange))   /* Issue #456 - backward compatibility only */
                        TY_(ReportAttrError)(doc, currentNode, contentAttr, ATTRIBUTE_VALUE_REPLACED);
                    TidyDocFree(doc, contentAttr->value);
                    contentAttr->value = newValue;
                    charsetFound = yes;
                }
            }
            continue;
        }
        /*
        3. <meta charset="utf-8" http-equiv="Content-Type" content="...">
        This is generally bad. Discard and warn.
        */
        if (httpEquivAttr && charsetAttr)
        {
            /* printf("WARN ABOUT HTTP EQUIV AND CHARSET ATTR! \n"); */
            prevNode = currentNode->prev;
            TY_(Report)(doc, head, currentNode, DISCARDING_UNEXPECTED);
            TY_(DiscardElement)(doc, currentNode);
            currentNode = prevNode;
        }
    }

    /* completed head scan - add appropriate meta - if 'yes' and none exists */
    if (add_meta && !charsetFound)
    {
        /* add appropriate meta charset tag - no warning */
        metaTag = TY_(InferredTag)(doc, TidyTag_META);
        switch (TY_(HTMLVersion)(doc))
        {
        case HT50:
        case XH50:
            TY_(AddAttribute)(doc, metaTag, "charset", enc);
            break;
        default:
            tidyBufInit(&buf);
            tidyBufAppend(&buf, "text/html; ", 11);
            tidyBufAppend(&buf, charsetString.bp, TY_(tmbstrlen)((ctmbstr)charsetString.bp));
            tidyBufAppend(&buf, "\0", 1);   /* zero terminate the buffer */
            TY_(AddAttribute)(doc, metaTag, "http-equiv", "Content-Type"); /* add 'http-equiv' const. */
            TY_(AddAttribute)(doc, metaTag, "content", (char*)buf.bp);  /* add 'content="<enc>"' */
            tidyBufFree(&buf);
        }
        TY_(InsertNodeAtStart)(head, metaTag);
        TY_(Report)(doc, metaTag, head, ADDED_MISSING_CHARSET); /* actually just 'Info:' */
    }
    tidyBufFree(&charsetString);
    return yes;
}


void TY_(DropComments)(TidyDocImpl* doc, Node* node)
{
    Node* next;

    while (node)
    {
        next = node->next;

        if (node->type == CommentTag)
        {
            TY_(RemoveNode)(node);
            TY_(FreeNode)(doc, node);
            node = next;
            continue;
        }

        if (node->content)
            TY_(DropComments)(doc, node->content);

        node = next;
    }
}

void TY_(DropFontElements)(TidyDocImpl* doc, Node* node, Node **ARG_UNUSED(pnode))
{
    Node* next;

    while (node)
    {
        next = node->next;

        if (nodeIsFONT(node))
        {
            DiscardContainer(doc, node, &next);
            node = next;
            continue;
        }

        if (node->content)
            TY_(DropFontElements)(doc, node->content, &next);

        node = next;
    }
}

void TY_(WbrToSpace)(TidyDocImpl* doc, Node* node)
{
    Node* next;

    while (node)
    {
        next = node->next;

        if (nodeIsWBR(node))
        {
            Node* text;
            text = TY_(NewLiteralTextNode)(doc->lexer, " ");
            TY_(InsertNodeAfterElement)(node, text);
            TY_(RemoveNode)(node);
            TY_(FreeNode)(doc, node);
            node = next;
            continue;
        }

        if (node->content)
            TY_(WbrToSpace)(doc, node->content);

        node = next;
   }
}

/*
  Filters from Word and PowerPoint often use smart
  quotes resulting in character codes between 128
  and 159. Unfortunately, the corresponding HTML 4.0
  entities for these are not widely supported. The
  following converts dashes and quotation marks to
  the nearest ASCII equivalent. My thanks to
  Andrzej Novosiolov for his help with this code.

  Note: The old code in the pretty printer applied
  this to all node types and attribute values while
  this routine applies it only to text nodes. First,
  Microsoft Office products rarely put the relevant
  characters into these tokens, second support for
  them is much better now and last but not least, it
  can be harmful to replace these characters since
  US-ASCII quote marks are often used as syntax
  characters, a simple

    <a onmouseover="alert('&#x2018;')">...</a>

  would be broken if the U+2018 is replaced by "'".
  The old code would neither take care whether the
  quote mark is already used as delimiter,

    <p title='&#x2018;'>...</p>

  got
  
    <p title='''>...</p>

  Since browser support is much better nowadays and
  high-quality typography is better than ASCII it'd
  be probably a good idea to drop the feature...
*/
void TY_(DowngradeTypography)(TidyDocImpl* doc, Node* node)
{
    Node* next;
    Lexer* lexer = doc->lexer;

    while (node)
    {
        next = node->next;

        if (TY_(nodeIsText)(node))
        {
            uint i, c;
            tmbstr p = lexer->lexbuf + node->start;

            for (i = node->start; i < node->end; ++i)
            {
                c = (unsigned char) lexer->lexbuf[i];

                if (c > 0x7F)
                    i += TY_(GetUTF8)(lexer->lexbuf + i, &c);

                if (c >= 0x2013 && c <= 0x201E)
                {
                    switch (c)
                    {
                    case 0x2013: /* en dash */
                    case 0x2014: /* em dash */
                        c = '-';
                        break;
                    case 0x2018: /* left single  quotation mark */
                    case 0x2019: /* right single quotation mark */
                    case 0x201A: /* single low-9 quotation mark */
                        c = '\'';
                        break;
                    case 0x201C: /* left double  quotation mark */
                    case 0x201D: /* right double quotation mark */
                    case 0x201E: /* double low-9 quotation mark */
                        c = '"';
                        break;
                    }
                }

                p = TY_(PutUTF8)(p, c);
            }

            node->end = p - lexer->lexbuf;
        }

        if (node->content)
            TY_(DowngradeTypography)(doc, node->content);

        node = next;
    }
}

void TY_(ReplacePreformattedSpaces)(TidyDocImpl* doc, Node* node)
{
    Node* next;

    while (node)
    {
        next = node->next;

        if (node->tag && node->tag->parser == TY_(ParsePre))
        {
            TY_(NormalizeSpaces)(doc->lexer, node->content);
            node = next;
            continue;
        }

        if (node->content)
            TY_(ReplacePreformattedSpaces)(doc, node->content);

        node = next;
    }
}

void TY_(ConvertCDATANodes)(TidyDocImpl* doc, Node* node)
{
    Node* next;

    while (node)
    {
        next = node->next;

        if (node->type == CDATATag)
            node->type = TextNode;

        if (node->content)
            TY_(ConvertCDATANodes)(doc, node->content);

        node = next;
    }
}

/*
  FixLanguageInformation ensures that the document contains (only)
  the attributes for language information desired by the output
  document type. For example, for XHTML 1.0 documents both
  'xml:lang' and 'lang' are desired, for XHTML 1.1 only 'xml:lang'
  is desired and for HTML 4.01 only 'lang' is desired.
*/
void TY_(FixLanguageInformation)(TidyDocImpl* doc, Node* node, Bool wantXmlLang, Bool wantLang)
{
    Node* next;

    while (node)
    {
        next = node->next;

        /* todo: report modifications made here to the report system */

        if (TY_(nodeIsElement)(node))
        {
            AttVal* lang = TY_(AttrGetById)(node, TidyAttr_LANG);
            AttVal* xmlLang = TY_(AttrGetById)(node, TidyAttr_XML_LANG);

            if (lang && xmlLang)
            {
                /*
                  todo: check whether both attributes are in sync,
                  here or elsewhere, where elsewhere is probably
                  preferable.
                  AD - March 2005: not mandatory according the standards.
                */
            }
            else if (lang && wantXmlLang)
            {
                if (TY_(NodeAttributeVersions)( node, TidyAttr_XML_LANG )
                    & doc->lexer->versionEmitted)
                    TY_(RepairAttrValue)(doc, node, "xml:lang", lang->value);
            }
            else if (xmlLang && wantLang)
            {
                if (TY_(NodeAttributeVersions)( node, TidyAttr_LANG )
                    & doc->lexer->versionEmitted)
                    TY_(RepairAttrValue)(doc, node, "lang", xmlLang->value);
            }

            if (lang && !wantLang)
                TY_(RemoveAttribute)(doc, node, lang);
            
            if (xmlLang && !wantXmlLang)
                TY_(RemoveAttribute)(doc, node, xmlLang);
        }

        if (node->content)
            TY_(FixLanguageInformation)(doc, node->content, wantXmlLang, wantLang);

        node = next;
    }
}

/*
  Set/fix/remove <html xmlns='...'>
*/
void TY_(FixXhtmlNamespace)(TidyDocImpl* doc, Bool wantXmlns)
{
    Node* html = TY_(FindHTML)(doc);
    AttVal* xmlns;

    if (!html)
        return;

    xmlns = TY_(AttrGetById)(html, TidyAttr_XMLNS);

    if (wantXmlns)
    {
        if (!AttrValueIs(xmlns, XHTML_NAMESPACE))
            TY_(RepairAttrValue)(doc, html, "xmlns", XHTML_NAMESPACE);
    }
    else if (xmlns)
    {
        TY_(RemoveAttribute)(doc, html, xmlns);
    }
}

/*
  ...
*/
void TY_(FixAnchors)(TidyDocImpl* doc, Node *node, Bool wantName, Bool wantId)
{
    Node* next;

    while (node)
    {
        next = node->next;

        if (TY_(IsAnchorElement)(doc, node))
        {
            AttVal *name = TY_(AttrGetById)(node, TidyAttr_NAME);
            AttVal *id = TY_(AttrGetById)(node, TidyAttr_ID);
            Bool hadName = name!=NULL;
            Bool hadId = id!=NULL;
            Bool IdEmitted = no;
            Bool NameEmitted = no;

            /* todo: how are empty name/id attributes handled? */

            if (name && id)
            {
                Bool NameHasValue = AttrHasValue(name);
                Bool IdHasValue = AttrHasValue(id);
                if ( (NameHasValue != IdHasValue) ||
                     (NameHasValue && IdHasValue &&
                     TY_(tmbstrcmp)(name->value, id->value) != 0 ) )
                    TY_(ReportAttrError)( doc, node, name, ID_NAME_MISMATCH);
            }
            else if (name && wantId)
            {
                if (TY_(NodeAttributeVersions)( node, TidyAttr_ID )
                    & doc->lexer->versionEmitted)
                {
                    if (TY_(IsValidHTMLID)(name->value))
                    {
                        TY_(RepairAttrValue)(doc, node, "id", name->value);
                        IdEmitted = yes;
                    }
                    else
                        TY_(ReportAttrError)(doc, node, name, INVALID_XML_ID);
                 }
            }
            else if (id && wantName)
            {
                if (TY_(NodeAttributeVersions)( node, TidyAttr_NAME )
                    & doc->lexer->versionEmitted)
                {
                    /* todo: do not assume id is valid */
                    TY_(RepairAttrValue)(doc, node, "name", id->value);
                    NameEmitted = yes;
                }
            }

            if (id && !wantId
                /* make sure that Name has been emitted if requested */
                && (hadName || !wantName || NameEmitted) ) {
                if (!wantId && !wantName)
                    TY_(RemoveAnchorByNode)(doc, id->value, node);
                TY_(RemoveAttribute)(doc, node, id);
            }

            if (name && !wantName
                /* make sure that Id has been emitted if requested */
                && (hadId || !wantId || IdEmitted) ) {
                if (!wantId && !wantName)
                    TY_(RemoveAnchorByNode)(doc, name->value, node);
                TY_(RemoveAttribute)(doc, node, name);
            }
        }

        if (node->content)
            TY_(FixAnchors)(doc, node->content, wantName, wantId);

        node = next;
    }
}

/* Issue #567 - move style elements from body to head 
 * ==================================================
 */
static void StyleToHead(TidyDocImpl* doc, Node *head, Node *node, Bool fix, int indent)
{
	Node *next;
	while (node)
	{
		next = node->next;	/* get 'next' now , in case the node is moved */
		/* dbg_show_node(doc, node, 0, indent); */
		if (nodeIsSTYLE(node))
		{
			if (fix)
			{
				TY_(RemoveNode)(node); /* unhook style node from body */
				TY_(InsertNodeAtEnd)(head, node);   /* add to end of head */
				TY_(Report)(doc, node, head, MOVED_STYLE_TO_HEAD); /* report move */
			}
			else
			{
				TY_(Report)(doc, node, head, FOUND_STYLE_IN_BODY);
			}
		}
		else if (node->content)
		{
			StyleToHead(doc, head, node->content, fix, indent + 1);
		}
		node = next;	/* process the 'next', if any */
	}
}


void TY_(CleanStyle)(TidyDocImpl* doc, Node *html)
{
    Node *head = NULL, *body = NULL;
    Bool fix = cfgBool(doc, TidyStyleTags);

    if (!html)
        return; /* oops, not given a start node */

    head = TY_(FindHEAD)( doc );
    body = TY_(FindBody)( doc );

    if ((head != NULL) && (body != NULL))
    {
		StyleToHead(doc, head, body, fix, 0); /* found head and body */
    }
}
/* ==================================================
 */

/*
 * local variables:
 * mode: c
 * indent-tabs-mode: nil
 * c-basic-offset: 4
 * eval: (c-set-offset 'substatement-open 0)
 * end:
 */