summaryrefslogtreecommitdiffstats
path: root/editor/libeditor/HTMLEditor.cpp
blob: 4cda49ab51ab8b66cf41f5eee3c5fed109038c42 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
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
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/HTMLEditor.h"

#include "mozilla/DebugOnly.h"
#include "mozilla/EventStates.h"
#include "mozilla/TextEvents.h"

#include "nsCRT.h"

#include "nsUnicharUtils.h"

#include "HTMLEditorEventListener.h"
#include "HTMLEditRules.h"
#include "HTMLEditUtils.h"
#include "HTMLURIRefObject.h"
#include "SetDocumentTitleTransaction.h"
#include "StyleSheetTransactions.h"
#include "TextEditUtils.h"
#include "TypeInState.h"

#include "nsIDOMText.h"
#include "nsIDOMMozNamedAttrMap.h"
#include "nsIDOMNodeList.h"
#include "nsIDOMDocument.h"
#include "nsIDOMAttr.h"
#include "nsIDocumentInlines.h"
#include "nsIDOMEventTarget.h"
#include "nsIDOMKeyEvent.h"
#include "nsIDOMMouseEvent.h"
#include "nsIDOMHTMLAnchorElement.h"
#include "nsISelectionController.h"
#include "nsIDOMHTMLDocument.h"
#include "nsILinkHandler.h"
#include "nsIInlineSpellChecker.h"

#include "mozilla/css/Loader.h"
#include "nsIDOMStyleSheet.h"

#include "nsIContent.h"
#include "nsIContentIterator.h"
#include "nsIMutableArray.h"
#include "nsContentUtils.h"
#include "nsIDocumentEncoder.h"
#include "nsIPresShell.h"
#include "nsPresContext.h"
#include "nsFocusManager.h"
#include "nsPIDOMWindow.h"

// netwerk
#include "nsIURI.h"
#include "nsNetUtil.h"

// Misc
#include "mozilla/EditorUtils.h"
#include "HTMLEditorObjectResizerUtils.h"
#include "TextEditorTest.h"
#include "WSRunObject.h"
#include "nsGkAtoms.h"
#include "nsIWidget.h"

#include "nsIFrame.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/DocumentFragment.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/EventTarget.h"
#include "mozilla/dom/HTMLBodyElement.h"
#include "nsElementTable.h"
#include "nsTextFragment.h"
#include "nsContentList.h"
#include "mozilla/StyleSheet.h"
#include "mozilla/StyleSheetInlines.h"

namespace mozilla {

using namespace dom;
using namespace widget;

// Some utilities to handle overloading of "A" tag for link and named anchor.
static bool
IsLinkTag(const nsString& s)
{
  return s.EqualsIgnoreCase("href");
}

static bool
IsNamedAnchorTag(const nsString& s)
{
  return s.EqualsIgnoreCase("anchor") || s.EqualsIgnoreCase("namedanchor");
}

HTMLEditor::HTMLEditor()
  : mCRInParagraphCreatesParagraph(false)
  , mCSSAware(false)
  , mSelectedCellIndex(0)
  , mIsObjectResizingEnabled(true)
  , mIsResizing(false)
  , mPreserveRatio(false)
  , mResizedObjectIsAnImage(false)
  , mIsAbsolutelyPositioningEnabled(true)
  , mResizedObjectIsAbsolutelyPositioned(false)
  , mGrabberClicked(false)
  , mIsMoving(false)
  , mSnapToGridEnabled(false)
  , mIsInlineTableEditingEnabled(true)
  , mOriginalX(0)
  , mOriginalY(0)
  , mResizedObjectX(0)
  , mResizedObjectY(0)
  , mResizedObjectWidth(0)
  , mResizedObjectHeight(0)
  , mResizedObjectMarginLeft(0)
  , mResizedObjectMarginTop(0)
  , mResizedObjectBorderLeft(0)
  , mResizedObjectBorderTop(0)
  , mXIncrementFactor(0)
  , mYIncrementFactor(0)
  , mWidthIncrementFactor(0)
  , mHeightIncrementFactor(0)
  , mInfoXIncrement(20)
  , mInfoYIncrement(20)
  , mPositionedObjectX(0)
  , mPositionedObjectY(0)
  , mPositionedObjectWidth(0)
  , mPositionedObjectHeight(0)
  , mPositionedObjectMarginLeft(0)
  , mPositionedObjectMarginTop(0)
  , mPositionedObjectBorderLeft(0)
  , mPositionedObjectBorderTop(0)
  , mGridSize(0)
{
}

HTMLEditor::~HTMLEditor()
{
  // remove the rules as an action listener.  Else we get a bad
  // ownership loop later on.  it's ok if the rules aren't a listener;
  // we ignore the error.
  nsCOMPtr<nsIEditActionListener> mListener = do_QueryInterface(mRules);
  RemoveEditActionListener(mListener);

  //the autopointers will clear themselves up.
  //but we need to also remove the listeners or we have a leak
  RefPtr<Selection> selection = GetSelection();
  // if we don't get the selection, just skip this
  if (selection) {
    nsCOMPtr<nsISelectionListener>listener;
    listener = do_QueryInterface(mTypeInState);
    if (listener) {
      selection->RemoveSelectionListener(listener);
    }
    listener = do_QueryInterface(mSelectionListenerP);
    if (listener) {
      selection->RemoveSelectionListener(listener);
    }
  }

  mTypeInState = nullptr;
  mSelectionListenerP = nullptr;

  // free any default style propItems
  RemoveAllDefaultProperties();

  if (mLinkHandler && IsInitialized()) {
    nsCOMPtr<nsIPresShell> ps = GetPresShell();

    if (ps && ps->GetPresContext()) {
      ps->GetPresContext()->SetLinkHandler(mLinkHandler);
    }
  }

  RemoveEventListeners();

  HideAnonymousEditingUIs();
}

void
HTMLEditor::HideAnonymousEditingUIs()
{
  if (mAbsolutelyPositionedObject) {
    HideGrabber();
  }
  if (mInlineEditedCell) {
    HideInlineTableEditingUI();
  }
  if (mResizedObject) {
    HideResizers();
  }
}

NS_IMPL_CYCLE_COLLECTION_CLASS(HTMLEditor)

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(HTMLEditor, TextEditor)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mTypeInState)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mStyleSheets)

  tmp->HideAnonymousEditingUIs();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(HTMLEditor, TextEditor)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTypeInState)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStyleSheets)

  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTopLeftHandle)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTopHandle)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTopRightHandle)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLeftHandle)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRightHandle)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBottomLeftHandle)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBottomHandle)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBottomRightHandle)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mActivatedHandle)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResizingShadow)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResizingInfo)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResizedObject)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mMouseMotionListenerP)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSelectionListenerP)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResizeEventListenerP)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mObjectResizeEventListeners)

  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAbsolutelyPositionedObject)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mGrabber)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPositioningShadow)

  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mInlineEditedCell)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAddColumnBeforeButton)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRemoveColumnButton)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAddColumnAfterButton)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAddRowBeforeButton)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRemoveRowButton)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAddRowAfterButton)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_IMPL_ADDREF_INHERITED(HTMLEditor, EditorBase)
NS_IMPL_RELEASE_INHERITED(HTMLEditor, EditorBase)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(HTMLEditor)
  NS_INTERFACE_MAP_ENTRY(nsIHTMLEditor)
  NS_INTERFACE_MAP_ENTRY(nsIHTMLObjectResizer)
  NS_INTERFACE_MAP_ENTRY(nsIHTMLAbsPosEditor)
  NS_INTERFACE_MAP_ENTRY(nsIHTMLInlineTableEditor)
  NS_INTERFACE_MAP_ENTRY(nsITableEditor)
  NS_INTERFACE_MAP_ENTRY(nsIEditorStyleSheets)
  NS_INTERFACE_MAP_ENTRY(nsICSSLoaderObserver)
  NS_INTERFACE_MAP_ENTRY(nsIMutationObserver)
NS_INTERFACE_MAP_END_INHERITING(TextEditor)

NS_IMETHODIMP
HTMLEditor::Init(nsIDOMDocument* aDoc,
                 nsIContent* aRoot,
                 nsISelectionController* aSelCon,
                 uint32_t aFlags,
                 const nsAString& aInitialValue)
{
  NS_PRECONDITION(aDoc && !aSelCon, "bad arg");
  NS_ENSURE_TRUE(aDoc, NS_ERROR_NULL_POINTER);
  MOZ_ASSERT(aInitialValue.IsEmpty(), "Non-empty initial values not supported");

  nsresult rulesRv = NS_OK;

  {
    // block to scope AutoEditInitRulesTrigger
    AutoEditInitRulesTrigger rulesTrigger(this, rulesRv);

    // Init the plaintext editor
    nsresult rv = TextEditor::Init(aDoc, aRoot, nullptr, aFlags, aInitialValue);
    if (NS_FAILED(rv)) {
      return rv;
    }

    // Init mutation observer
    nsCOMPtr<nsINode> document = do_QueryInterface(aDoc);
    document->AddMutationObserverUnlessExists(this);

    if (!mRootElement) {
      UpdateRootElement();
    }

    // disable Composer-only features
    if (IsMailEditor()) {
      SetAbsolutePositioningEnabled(false);
      SetSnapToGridEnabled(false);
    }

    // Init the HTML-CSS utils
    mCSSEditUtils = MakeUnique<CSSEditUtils>(this);

    // disable links
    nsCOMPtr<nsIPresShell> presShell = GetPresShell();
    NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
    nsPresContext *context = presShell->GetPresContext();
    NS_ENSURE_TRUE(context, NS_ERROR_NULL_POINTER);
    if (!IsPlaintextEditor() && !IsInteractionAllowed()) {
      mLinkHandler = context->GetLinkHandler();
      context->SetLinkHandler(nullptr);
    }

    // init the type-in state
    mTypeInState = new TypeInState();

    // init the selection listener for image resizing
    mSelectionListenerP = new ResizerSelectionListener(this);

    if (!IsInteractionAllowed()) {
      // ignore any errors from this in case the file is missing
      AddOverrideStyleSheet(NS_LITERAL_STRING("resource://gre/res/EditorOverride.css"));
    }

    RefPtr<Selection> selection = GetSelection();
    if (selection) {
      nsCOMPtr<nsISelectionListener>listener;
      listener = do_QueryInterface(mTypeInState);
      if (listener) {
        selection->AddSelectionListener(listener);
      }
      listener = do_QueryInterface(mSelectionListenerP);
      if (listener) {
        selection->AddSelectionListener(listener);
      }
    }
  }
  NS_ENSURE_SUCCESS(rulesRv, rulesRv);

  return NS_OK;
}

NS_IMETHODIMP
HTMLEditor::PreDestroy(bool aDestroyingFrames)
{
  if (mDidPreDestroy) {
    return NS_OK;
  }

  nsCOMPtr<nsIDocument> document = GetDocument();
  if (document) {
    document->RemoveMutationObserver(this);
  }

  while (!mStyleSheetURLs.IsEmpty()) {
    RemoveOverrideStyleSheet(mStyleSheetURLs[0]);
  }

  // Clean up after our anonymous content -- we don't want these nodes to
  // stay around (which they would, since the frames have an owning reference).
  HideAnonymousEditingUIs();

  return TextEditor::PreDestroy(aDestroyingFrames);
}

void
HTMLEditor::UpdateRootElement()
{
  // Use the HTML documents body element as the editor root if we didn't
  // get a root element during initialization.

  nsCOMPtr<nsIDOMElement> rootElement;
  nsCOMPtr<nsIDOMHTMLElement> bodyElement;
  GetBodyElement(getter_AddRefs(bodyElement));
  if (bodyElement) {
    rootElement = bodyElement;
  } else {
    // If there is no HTML body element,
    // we should use the document root element instead.
    nsCOMPtr<nsIDOMDocument> doc = GetDOMDocument();
    if (doc) {
      doc->GetDocumentElement(getter_AddRefs(rootElement));
    }
  }

  mRootElement = do_QueryInterface(rootElement);
}

already_AddRefed<nsIContent>
HTMLEditor::FindSelectionRoot(nsINode* aNode)
{
  NS_PRECONDITION(aNode->IsNodeOfType(nsINode::eDOCUMENT) ||
                  aNode->IsNodeOfType(nsINode::eCONTENT),
                  "aNode must be content or document node");

  nsCOMPtr<nsIDocument> doc = aNode->GetUncomposedDoc();
  if (!doc) {
    return nullptr;
  }

  nsCOMPtr<nsIContent> content;
  if (doc->HasFlag(NODE_IS_EDITABLE) || !aNode->IsContent()) {
    content = doc->GetRootElement();
    return content.forget();
  }
  content = aNode->AsContent();

  // XXX If we have readonly flag, shouldn't return the element which has
  // contenteditable="true"?  However, such case isn't there without chrome
  // permission script.
  if (IsReadonly()) {
    // We still want to allow selection in a readonly editor.
    content = do_QueryInterface(GetRoot());
    return content.forget();
  }

  if (!content->HasFlag(NODE_IS_EDITABLE)) {
    // If the content is in read-write state but is not editable itself,
    // return it as the selection root.
    if (content->IsElement() &&
        content->AsElement()->State().HasState(NS_EVENT_STATE_MOZ_READWRITE)) {
      return content.forget();
    }
    return nullptr;
  }

  // For non-readonly editors we want to find the root of the editable subtree
  // containing aContent.
  content = content->GetEditingHost();
  return content.forget();
}

void
HTMLEditor::CreateEventListeners()
{
  // Don't create the handler twice
  if (!mEventListener) {
    mEventListener = new HTMLEditorEventListener();
  }
}

nsresult
HTMLEditor::InstallEventListeners()
{
  if (NS_WARN_IF(!IsInitialized()) || NS_WARN_IF(!mEventListener)) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  // NOTE: HTMLEditor doesn't need to initialize mEventTarget here because
  // the target must be document node and it must be referenced as weak pointer.

  HTMLEditorEventListener* listener =
    reinterpret_cast<HTMLEditorEventListener*>(mEventListener.get());
  return listener->Connect(this);
}

void
HTMLEditor::RemoveEventListeners()
{
  if (!IsInitialized()) {
    return;
  }

  nsCOMPtr<nsIDOMEventTarget> target = GetDOMEventTarget();

  if (target) {
    // Both mMouseMotionListenerP and mResizeEventListenerP can be
    // registerd with other targets than the DOM event receiver that
    // we can reach from here. But nonetheless, unregister the event
    // listeners with the DOM event reveiver (if it's registerd with
    // other targets, it'll get unregisterd once the target goes
    // away).

    if (mMouseMotionListenerP) {
      // mMouseMotionListenerP might be registerd either as bubbling or
      // capturing, unregister by both.
      target->RemoveEventListener(NS_LITERAL_STRING("mousemove"),
                                  mMouseMotionListenerP, false);
      target->RemoveEventListener(NS_LITERAL_STRING("mousemove"),
                                  mMouseMotionListenerP, true);
    }

    if (mResizeEventListenerP) {
      target->RemoveEventListener(NS_LITERAL_STRING("resize"),
                                  mResizeEventListenerP, false);
    }
  }

  mMouseMotionListenerP = nullptr;
  mResizeEventListenerP = nullptr;

  TextEditor::RemoveEventListeners();
}

NS_IMETHODIMP
HTMLEditor::SetFlags(uint32_t aFlags)
{
  nsresult rv = TextEditor::SetFlags(aFlags);
  NS_ENSURE_SUCCESS(rv, rv);

  // Sets mCSSAware to correspond to aFlags. This toggles whether CSS is
  // used to style elements in the editor. Note that the editor is only CSS
  // aware by default in Composer and in the mail editor.
  mCSSAware = !NoCSS() && !IsMailEditor();

  return NS_OK;
}

NS_IMETHODIMP
HTMLEditor::InitRules()
{
  if (!mRules) {
    // instantiate the rules for the html editor
    mRules = new HTMLEditRules();
  }
  return mRules->Init(static_cast<TextEditor*>(this));
}

NS_IMETHODIMP
HTMLEditor::BeginningOfDocument()
{
  // XXX Why doesn't this check if the document is alive?
  if (!IsInitialized()) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  // Get the selection
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NOT_INITIALIZED);

  // Get the root element.
  nsCOMPtr<Element> rootElement = GetRoot();
  if (!rootElement) {
    NS_WARNING("GetRoot() returned a null pointer (mRootElement is null)");
    return NS_OK;
  }

  // Find first editable thingy
  bool done = false;
  nsCOMPtr<nsINode> curNode = rootElement.get(), selNode;
  int32_t curOffset = 0, selOffset = 0;
  while (!done) {
    WSRunObject wsObj(this, curNode, curOffset);
    int32_t visOffset = 0;
    WSType visType;
    nsCOMPtr<nsINode> visNode;
    wsObj.NextVisibleNode(curNode, curOffset, address_of(visNode), &visOffset,
                          &visType);
    if (visType == WSType::normalWS || visType == WSType::text) {
      selNode = visNode;
      selOffset = visOffset;
      done = true;
    } else if (visType == WSType::br || visType == WSType::special) {
      selNode = visNode->GetParentNode();
      selOffset = selNode ? selNode->IndexOf(visNode) : -1;
      done = true;
    } else if (visType == WSType::otherBlock) {
      // By definition of WSRunObject, a block element terminates a
      // whitespace run. That is, although we are calling a method that is
      // named "NextVisibleNode", the node returned might not be
      // visible/editable!
      //
      // If the given block does not contain any visible/editable items, we
      // want to skip it and continue our search.

      if (!IsContainer(visNode)) {
        // However, we were given a block that is not a container.  Since the
        // block can not contain anything that's visible, such a block only
        // makes sense if it is visible by itself, like a <hr>.  We want to
        // place the caret in front of that block.
        selNode = visNode->GetParentNode();
        selOffset = selNode ? selNode->IndexOf(visNode) : -1;
        done = true;
      } else {
        bool isEmptyBlock;
        if (NS_SUCCEEDED(IsEmptyNode(visNode, &isEmptyBlock)) &&
            isEmptyBlock) {
          // Skip the empty block
          curNode = visNode->GetParentNode();
          curOffset = curNode ? curNode->IndexOf(visNode) : -1;
          curOffset++;
        } else {
          curNode = visNode;
          curOffset = 0;
        }
        // Keep looping
      }
    } else {
      // Else we found nothing useful
      selNode = curNode;
      selOffset = curOffset;
      done = true;
    }
  }
  return selection->Collapse(selNode, selOffset);
}

nsresult
HTMLEditor::HandleKeyPressEvent(nsIDOMKeyEvent* aKeyEvent)
{
  // NOTE: When you change this method, you should also change:
  //   * editor/libeditor/tests/test_htmleditor_keyevent_handling.html

  if (IsReadonly() || IsDisabled()) {
    // When we're not editable, the events are handled on EditorBase, so, we can
    // bypass TextEditor.
    return EditorBase::HandleKeyPressEvent(aKeyEvent);
  }

  WidgetKeyboardEvent* nativeKeyEvent =
    aKeyEvent->AsEvent()->WidgetEventPtr()->AsKeyboardEvent();
  NS_ENSURE_TRUE(nativeKeyEvent, NS_ERROR_UNEXPECTED);
  NS_ASSERTION(nativeKeyEvent->mMessage == eKeyPress,
               "HandleKeyPressEvent gets non-keypress event");

  switch (nativeKeyEvent->mKeyCode) {
    case NS_VK_META:
    case NS_VK_WIN:
    case NS_VK_SHIFT:
    case NS_VK_CONTROL:
    case NS_VK_ALT:
    case NS_VK_BACK:
    case NS_VK_DELETE:
      // These keys are handled on EditorBase, so, we can bypass
      // TextEditor.
      return EditorBase::HandleKeyPressEvent(aKeyEvent);
    case NS_VK_TAB: {
      if (IsPlaintextEditor()) {
        // If this works as plain text editor, e.g., mail editor for plain
        // text, should be handled on TextEditor.
        return TextEditor::HandleKeyPressEvent(aKeyEvent);
      }

      if (IsTabbable()) {
        return NS_OK; // let it be used for focus switching
      }

      if (nativeKeyEvent->IsControl() || nativeKeyEvent->IsAlt() ||
          nativeKeyEvent->IsMeta() || nativeKeyEvent->IsOS()) {
        return NS_OK;
      }

      RefPtr<Selection> selection = GetSelection();
      NS_ENSURE_TRUE(selection && selection->RangeCount(), NS_ERROR_FAILURE);

      nsCOMPtr<nsINode> node = selection->GetRangeAt(0)->GetStartParent();
      MOZ_ASSERT(node);

      nsCOMPtr<Element> blockParent = GetBlock(*node);

      if (!blockParent) {
        break;
      }

      bool handled = false;
      nsresult rv = NS_OK;
      if (HTMLEditUtils::IsTableElement(blockParent)) {
        rv = TabInTable(nativeKeyEvent->IsShift(), &handled);
        if (handled) {
          ScrollSelectionIntoView(false);
        }
      } else if (HTMLEditUtils::IsListItem(blockParent)) {
        rv = Indent(nativeKeyEvent->IsShift()
                    ? NS_LITERAL_STRING("outdent")
                    : NS_LITERAL_STRING("indent"));
        handled = true;
      }
      NS_ENSURE_SUCCESS(rv, rv);
      if (handled) {
        return aKeyEvent->AsEvent()->PreventDefault(); // consumed
      }
      if (nativeKeyEvent->IsShift()) {
        return NS_OK; // don't type text for shift tabs
      }
      aKeyEvent->AsEvent()->PreventDefault();
      return TypedText(NS_LITERAL_STRING("\t"), eTypedText);
    }
    case NS_VK_RETURN:
      if (nativeKeyEvent->IsControl() || nativeKeyEvent->IsAlt() ||
          nativeKeyEvent->IsMeta() || nativeKeyEvent->IsOS()) {
        return NS_OK;
      }
      aKeyEvent->AsEvent()->PreventDefault(); // consumed
      if (nativeKeyEvent->IsShift() && !IsPlaintextEditor()) {
        // only inserts a br node
        return TypedText(EmptyString(), eTypedBR);
      }
      // uses rules to figure out what to insert
      return TypedText(EmptyString(), eTypedBreak);
  }

  // NOTE: On some keyboard layout, some characters are inputted with Control
  // key or Alt key, but at that time, widget sets FALSE to these keys.
  if (!nativeKeyEvent->mCharCode || nativeKeyEvent->IsControl() ||
      nativeKeyEvent->IsAlt() || nativeKeyEvent->IsMeta() ||
      nativeKeyEvent->IsOS()) {
    // we don't PreventDefault() here or keybindings like control-x won't work
    return NS_OK;
  }
  aKeyEvent->AsEvent()->PreventDefault();
  nsAutoString str(nativeKeyEvent->mCharCode);
  return TypedText(str, eTypedText);
}

/**
 * Returns true if the id represents an element of block type.
 * Can be used to determine if a new paragraph should be started.
 */
bool
HTMLEditor::NodeIsBlockStatic(const nsINode* aElement)
{
  MOZ_ASSERT(aElement);

  // We want to treat these as block nodes even though nsHTMLElement says
  // they're not.
  if (aElement->IsAnyOfHTMLElements(nsGkAtoms::body,
                                    nsGkAtoms::head,
                                    nsGkAtoms::tbody,
                                    nsGkAtoms::thead,
                                    nsGkAtoms::tfoot,
                                    nsGkAtoms::tr,
                                    nsGkAtoms::th,
                                    nsGkAtoms::td,
                                    nsGkAtoms::dt,
                                    nsGkAtoms::dd)) {
    return true;
  }

  return nsHTMLElement::IsBlock(
    nsHTMLTags::AtomTagToId(aElement->NodeInfo()->NameAtom()));
}

nsresult
HTMLEditor::NodeIsBlockStatic(nsIDOMNode* aNode,
                              bool* aIsBlock)
{
  if (!aNode || !aIsBlock) {
    return NS_ERROR_NULL_POINTER;
  }

  nsCOMPtr<dom::Element> element = do_QueryInterface(aNode);
  *aIsBlock = element && NodeIsBlockStatic(element);
  return NS_OK;
}

NS_IMETHODIMP
HTMLEditor::NodeIsBlock(nsIDOMNode* aNode,
                        bool* aIsBlock)
{
  return NodeIsBlockStatic(aNode, aIsBlock);
}

bool
HTMLEditor::IsBlockNode(nsINode* aNode)
{
  return aNode && NodeIsBlockStatic(aNode);
}

// Non-static version for the nsIEditor interface and JavaScript
NS_IMETHODIMP
HTMLEditor::SetDocumentTitle(const nsAString& aTitle)
{
  RefPtr<SetDocumentTitleTransaction> transaction =
    new SetDocumentTitleTransaction();
  NS_ENSURE_TRUE(transaction, NS_ERROR_OUT_OF_MEMORY);

  nsresult rv = transaction->Init(this, &aTitle);
  NS_ENSURE_SUCCESS(rv, rv);

  //Don't let Rules System change the selection
  AutoTransactionsConserveSelection dontChangeSelection(this);
  return EditorBase::DoTransaction(transaction);
}

/**
 * GetBlockNodeParent returns enclosing block level ancestor, if any.
 */
Element*
HTMLEditor::GetBlockNodeParent(nsINode* aNode)
{
  MOZ_ASSERT(aNode);

  nsCOMPtr<nsINode> p = aNode->GetParentNode();

  while (p) {
    if (NodeIsBlockStatic(p)) {
      return p->AsElement();
    }
    p = p->GetParentNode();
  }

  return nullptr;
}

nsIDOMNode*
HTMLEditor::GetBlockNodeParent(nsIDOMNode* aNode)
{
  nsCOMPtr<nsINode> node = do_QueryInterface(aNode);

  if (!node) {
    NS_NOTREACHED("null node passed to GetBlockNodeParent()");
    return nullptr;
  }

  return GetAsDOMNode(GetBlockNodeParent(node));
}

/**
 * Returns the node if it's a block, otherwise GetBlockNodeParent
 */
Element*
HTMLEditor::GetBlock(nsINode& aNode)
{
  if (NodeIsBlockStatic(&aNode)) {
    return aNode.AsElement();
  }
  return GetBlockNodeParent(&aNode);
}

/**
 * IsNextCharInNodeWhitespace() checks the adjacent content in the same node to
 * see if following selection is whitespace or nbsp.
 */
void
HTMLEditor::IsNextCharInNodeWhitespace(nsIContent* aContent,
                                       int32_t aOffset,
                                       bool* outIsSpace,
                                       bool* outIsNBSP,
                                       nsIContent** outNode,
                                       int32_t* outOffset)
{
  MOZ_ASSERT(aContent && outIsSpace && outIsNBSP);
  MOZ_ASSERT((outNode && outOffset) || (!outNode && !outOffset));
  *outIsSpace = false;
  *outIsNBSP = false;
  if (outNode && outOffset) {
    *outNode = nullptr;
    *outOffset = -1;
  }

  if (aContent->IsNodeOfType(nsINode::eTEXT) &&
      (uint32_t)aOffset < aContent->Length()) {
    char16_t ch = aContent->GetText()->CharAt(aOffset);
    *outIsSpace = nsCRT::IsAsciiSpace(ch);
    *outIsNBSP = (ch == kNBSP);
    if (outNode && outOffset) {
      NS_IF_ADDREF(*outNode = aContent);
      // yes, this is _past_ the character
      *outOffset = aOffset + 1;
    }
  }
}


/**
 * IsPrevCharInNodeWhitespace() checks the adjacent content in the same node to
 * see if following selection is whitespace.
 */
void
HTMLEditor::IsPrevCharInNodeWhitespace(nsIContent* aContent,
                                       int32_t aOffset,
                                       bool* outIsSpace,
                                       bool* outIsNBSP,
                                       nsIContent** outNode,
                                       int32_t* outOffset)
{
  MOZ_ASSERT(aContent && outIsSpace && outIsNBSP);
  MOZ_ASSERT((outNode && outOffset) || (!outNode && !outOffset));
  *outIsSpace = false;
  *outIsNBSP = false;
  if (outNode && outOffset) {
    *outNode = nullptr;
    *outOffset = -1;
  }

  if (aContent->IsNodeOfType(nsINode::eTEXT) && aOffset > 0) {
    char16_t ch = aContent->GetText()->CharAt(aOffset - 1);
    *outIsSpace = nsCRT::IsAsciiSpace(ch);
    *outIsNBSP = (ch == kNBSP);
    if (outNode && outOffset) {
      NS_IF_ADDREF(*outNode = aContent);
      *outOffset = aOffset - 1;
    }
  }
}

bool
HTMLEditor::IsVisBreak(nsINode* aNode)
{
  MOZ_ASSERT(aNode);
  if (!TextEditUtils::IsBreak(aNode)) {
    return false;
  }
  // Check if there is a later node in block after br
  nsCOMPtr<nsINode> nextNode = GetNextHTMLNode(aNode, true);
  if (nextNode && TextEditUtils::IsBreak(nextNode)) {
    return true;
  }

  // A single line break before a block boundary is not displayed, so e.g.
  // foo<p>bar<br></p> and foo<br><p>bar</p> display the same as foo<p>bar</p>.
  // But if there are multiple <br>s in a row, all but the last are visible.
  if (!nextNode) {
    // This break is trailer in block, it's not visible
    return false;
  }
  if (IsBlockNode(nextNode)) {
    // Break is right before a block, it's not visible
    return false;
  }

  // If there's an inline node after this one that's not a break, and also a
  // prior break, this break must be visible.
  nsCOMPtr<nsINode> priorNode = GetPriorHTMLNode(aNode, true);
  if (priorNode && TextEditUtils::IsBreak(priorNode)) {
    return true;
  }

  // Sigh.  We have to use expensive whitespace calculation code to
  // determine what is going on
  int32_t selOffset;
  nsCOMPtr<nsINode> selNode = GetNodeLocation(aNode, &selOffset);
  // Let's look after the break
  selOffset++;
  WSRunObject wsObj(this, selNode, selOffset);
  nsCOMPtr<nsINode> unused;
  int32_t visOffset = 0;
  WSType visType;
  wsObj.NextVisibleNode(selNode, selOffset, address_of(unused),
                        &visOffset, &visType);
  if (visType & WSType::block) {
    return false;
  }

  return true;
}

NS_IMETHODIMP
HTMLEditor::GetIsDocumentEditable(bool* aIsDocumentEditable)
{
  NS_ENSURE_ARG_POINTER(aIsDocumentEditable);

  nsCOMPtr<nsIDOMDocument> doc = GetDOMDocument();
  *aIsDocumentEditable = doc && IsModifiable();

  return NS_OK;
}

bool
HTMLEditor::IsModifiable()
{
  return !IsReadonly();
}

NS_IMETHODIMP
HTMLEditor::UpdateBaseURL()
{
  nsCOMPtr<nsIDocument> doc = GetDocument();
  NS_ENSURE_TRUE(doc, NS_ERROR_FAILURE);

  // Look for an HTML <base> tag
  RefPtr<nsContentList> nodeList =
    doc->GetElementsByTagName(NS_LITERAL_STRING("base"));

  // If no base tag, then set baseURL to the document's URL.  This is very
  // important, else relative URLs for links and images are wrong
  if (!nodeList || !nodeList->Item(0)) {
    doc->SetBaseURI(doc->GetDocumentURI());
  }
  return NS_OK;
}

/**
 * This routine is needed to provide a bottleneck for typing for logging
 * purposes.  Can't use HandleKeyPress() (above) for that since it takes
 * a nsIDOMKeyEvent* parameter.  So instead we pass enough info through
 * to TypedText() to determine what action to take, but without passing
 * an event.
 */
NS_IMETHODIMP
HTMLEditor::TypedText(const nsAString& aString,
                      ETypingAction aAction)
{
  AutoPlaceHolderBatch batch(this, nsGkAtoms::TypingTxnName);

  if (aAction == eTypedBR) {
    // only inserts a br node
    nsCOMPtr<nsIDOMNode> brNode;
    return InsertBR(address_of(brNode));
  }

  return TextEditor::TypedText(aString, aAction);
}

NS_IMETHODIMP
HTMLEditor::TabInTable(bool inIsShift,
                       bool* outHandled)
{
  NS_ENSURE_TRUE(outHandled, NS_ERROR_NULL_POINTER);
  *outHandled = false;

  // Find enclosing table cell from selection (cell may be selected element)
  nsCOMPtr<Element> cellElement =
    GetElementOrParentByTagName(NS_LITERAL_STRING("td"), nullptr);
  // Do nothing -- we didn't find a table cell
  NS_ENSURE_TRUE(cellElement, NS_OK);

  // find enclosing table
  nsCOMPtr<Element> table = GetEnclosingTable(cellElement);
  NS_ENSURE_TRUE(table, NS_OK);

  // advance to next cell
  // first create an iterator over the table
  nsCOMPtr<nsIContentIterator> iter = NS_NewContentIterator();
  nsresult rv = iter->Init(table);
  NS_ENSURE_SUCCESS(rv, rv);
  // position iter at block
  rv = iter->PositionAt(cellElement);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsINode> node;
  do {
    if (inIsShift) {
      iter->Prev();
    } else {
      iter->Next();
    }

    node = iter->GetCurrentNode();

    if (node && HTMLEditUtils::IsTableCell(node) &&
        GetEnclosingTable(node) == table) {
      CollapseSelectionToDeepestNonTableFirstChild(nullptr, node);
      *outHandled = true;
      return NS_OK;
    }
  } while (!iter->IsDone());

  if (!(*outHandled) && !inIsShift) {
    // If we haven't handled it yet, then we must have run off the end of the
    // table.  Insert a new row.
    rv = InsertTableRow(1, true);
    NS_ENSURE_SUCCESS(rv, rv);
    *outHandled = true;
    // Put selection in right place.  Use table code to get selection and index
    // to new row...
    RefPtr<Selection> selection;
    nsCOMPtr<nsIDOMElement> tblElement, cell;
    int32_t row;
    rv = GetCellContext(getter_AddRefs(selection),
                        getter_AddRefs(tblElement),
                        getter_AddRefs(cell),
                        nullptr, nullptr,
                        &row, nullptr);
    NS_ENSURE_SUCCESS(rv, rv);
    // ...so that we can ask for first cell in that row...
    rv = GetCellAt(tblElement, row, 0, getter_AddRefs(cell));
    NS_ENSURE_SUCCESS(rv, rv);
    // ...and then set selection there.  (Note that normally you should use
    // CollapseSelectionToDeepestNonTableFirstChild(), but we know cell is an
    // empty new cell, so this works fine)
    if (cell) {
      selection->Collapse(cell, 0);
    }
  }

  return NS_OK;
}

already_AddRefed<Element>
HTMLEditor::CreateBR(nsINode* aNode,
                     int32_t aOffset,
                     EDirection aSelect)
{
  nsCOMPtr<nsIDOMNode> parent = GetAsDOMNode(aNode);
  int32_t offset = aOffset;
  nsCOMPtr<nsIDOMNode> outBRNode;
  // We assume everything is fine if the br is not null, irrespective of retval
  CreateBRImpl(address_of(parent), &offset, address_of(outBRNode), aSelect);
  nsCOMPtr<Element> ret = do_QueryInterface(outBRNode);
  return ret.forget();
}

NS_IMETHODIMP
HTMLEditor::CreateBR(nsIDOMNode* aNode,
                     int32_t aOffset,
                     nsCOMPtr<nsIDOMNode>* outBRNode,
                     EDirection aSelect)
{
  nsCOMPtr<nsIDOMNode> parent = aNode;
  int32_t offset = aOffset;
  return CreateBRImpl(address_of(parent), &offset, outBRNode, aSelect);
}

void
HTMLEditor::CollapseSelectionToDeepestNonTableFirstChild(Selection* aSelection,
                                                         nsINode* aNode)
{
  MOZ_ASSERT(aNode);

  RefPtr<Selection> selection = aSelection;
  if (!selection) {
    selection = GetSelection();
  }
  if (!selection) {
    // Nothing to do
    return;
  }

  nsCOMPtr<nsINode> node = aNode;

  for (nsCOMPtr<nsIContent> child = node->GetFirstChild();
       child;
       child = child->GetFirstChild()) {
    // Stop if we find a table, don't want to go into nested tables
    if (HTMLEditUtils::IsTable(child) || !IsContainer(child)) {
      break;
    }
    node = child;
  }

  selection->Collapse(node, 0);
}


/**
 * This is mostly like InsertHTMLWithCharsetAndContext, but we can't use that
 * because it is selection-based and the rules code won't let us edit under the
 * <head> node
 */
NS_IMETHODIMP
HTMLEditor::ReplaceHeadContentsWithHTML(const nsAString& aSourceToInsert)
{
  // don't do any post processing, rules get confused
  AutoRules beginRulesSniffing(this, EditAction::ignore, nsIEditor::eNone);
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);

  ForceCompositionEnd();

  // Do not use AutoRules -- rules code won't let us insert in <head>.  Use
  // the head node as a parent and delete/insert directly.
  nsCOMPtr<nsIDocument> document = GetDocument();
  if (NS_WARN_IF(!document)) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  RefPtr<nsContentList> nodeList =
    document->GetElementsByTagName(NS_LITERAL_STRING("head"));
  NS_ENSURE_TRUE(nodeList, NS_ERROR_NULL_POINTER);

  nsCOMPtr<nsIContent> headNode = nodeList->Item(0);
  NS_ENSURE_TRUE(headNode, NS_ERROR_NULL_POINTER);

  // First, make sure there are no return chars in the source.  Bad things
  // happen if you insert returns (instead of dom newlines, \n) into an editor
  // document.
  nsAutoString inputString (aSourceToInsert);  // hope this does copy-on-write

  // Windows linebreaks: Map CRLF to LF:
  inputString.ReplaceSubstring(u"\r\n", u"\n");

  // Mac linebreaks: Map any remaining CR to LF:
  inputString.ReplaceSubstring(u"\r", u"\n");

  AutoEditBatch beginBatching(this);

  // Get the first range in the selection, for context:
  RefPtr<nsRange> range = selection->GetRangeAt(0);
  NS_ENSURE_TRUE(range, NS_ERROR_NULL_POINTER);

  ErrorResult err;
  RefPtr<DocumentFragment> docfrag =
    range->CreateContextualFragment(inputString, err);

  // XXXX BUG 50965: This is not returning the text between <title>...</title>
  // Special code is needed in JS to handle title anyway, so it doesn't matter!

  if (err.Failed()) {
#ifdef DEBUG
    printf("Couldn't create contextual fragment: error was %X\n",
           err.ErrorCodeAsInt());
#endif
    return err.StealNSResult();
  }
  NS_ENSURE_TRUE(docfrag, NS_ERROR_NULL_POINTER);

  // First delete all children in head
  while (nsCOMPtr<nsIContent> child = headNode->GetFirstChild()) {
    nsresult rv = DeleteNode(child);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // Now insert the new nodes
  int32_t offsetOfNewNode = 0;

  // Loop over the contents of the fragment and move into the document
  while (nsCOMPtr<nsIContent> child = docfrag->GetFirstChild()) {
    nsresult rv = InsertNode(*child, *headNode, offsetOfNewNode++);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return NS_OK;
}

NS_IMETHODIMP
HTMLEditor::RebuildDocumentFromSource(const nsAString& aSourceString)
{
  ForceCompositionEnd();

  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);

  nsCOMPtr<Element> bodyElement = GetRoot();
  NS_ENSURE_TRUE(bodyElement, NS_ERROR_NULL_POINTER);

  // Find where the <body> tag starts.
  nsReadingIterator<char16_t> beginbody;
  nsReadingIterator<char16_t> endbody;
  aSourceString.BeginReading(beginbody);
  aSourceString.EndReading(endbody);
  bool foundbody = CaseInsensitiveFindInReadable(NS_LITERAL_STRING("<body"),
                                                 beginbody, endbody);

  nsReadingIterator<char16_t> beginhead;
  nsReadingIterator<char16_t> endhead;
  aSourceString.BeginReading(beginhead);
  aSourceString.EndReading(endhead);
  bool foundhead = CaseInsensitiveFindInReadable(NS_LITERAL_STRING("<head"),
                                                 beginhead, endhead);
  // a valid head appears before the body
  if (foundbody && beginhead.get() > beginbody.get()) {
    foundhead = false;
  }

  nsReadingIterator<char16_t> beginclosehead;
  nsReadingIterator<char16_t> endclosehead;
  aSourceString.BeginReading(beginclosehead);
  aSourceString.EndReading(endclosehead);

  // Find the index after "<head>"
  bool foundclosehead = CaseInsensitiveFindInReadable(
           NS_LITERAL_STRING("</head>"), beginclosehead, endclosehead);
  // a valid close head appears after a found head
  if (foundhead && beginhead.get() > beginclosehead.get()) {
    foundclosehead = false;
  }
  // a valid close head appears before a found body
  if (foundbody && beginclosehead.get() > beginbody.get()) {
    foundclosehead = false;
  }

  // Time to change the document
  AutoEditBatch beginBatching(this);

  nsReadingIterator<char16_t> endtotal;
  aSourceString.EndReading(endtotal);

  if (foundhead) {
    if (foundclosehead) {
      nsresult rv =
        ReplaceHeadContentsWithHTML(Substring(beginhead, beginclosehead));
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }
    } else if (foundbody) {
      nsresult rv =
        ReplaceHeadContentsWithHTML(Substring(beginhead, beginbody));
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }
    } else {
      // XXX Without recourse to some parser/content sink/docshell hackery we
      // don't really know where the head ends and the body begins so we assume
      // that there is no body
      nsresult rv = ReplaceHeadContentsWithHTML(Substring(beginhead, endtotal));
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }
    }
  } else {
    nsReadingIterator<char16_t> begintotal;
    aSourceString.BeginReading(begintotal);
    NS_NAMED_LITERAL_STRING(head, "<head>");
    if (foundclosehead) {
      nsresult rv =
        ReplaceHeadContentsWithHTML(head + Substring(begintotal,
                                                     beginclosehead));
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }
    } else if (foundbody) {
      nsresult rv = ReplaceHeadContentsWithHTML(head + Substring(begintotal,
                                                                 beginbody));
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }
    } else {
      // XXX Without recourse to some parser/content sink/docshell hackery we
      // don't really know where the head ends and the body begins so we assume
      // that there is no head
      nsresult rv = ReplaceHeadContentsWithHTML(head);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }
    }
  }

  nsresult rv = SelectAll();
  NS_ENSURE_SUCCESS(rv, rv);

  if (!foundbody) {
    NS_NAMED_LITERAL_STRING(body, "<body>");
    // XXX Without recourse to some parser/content sink/docshell hackery we
    // don't really know where the head ends and the body begins
    if (foundclosehead) {
      // assume body starts after the head ends
      nsresult rv = LoadHTML(body + Substring(endclosehead, endtotal));
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }
    } else if (foundhead) {
      // assume there is no body
      nsresult rv = LoadHTML(body);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }
    } else {
      // assume there is no head, the entire source is body
      nsresult rv = LoadHTML(body + aSourceString);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }
    }

    nsCOMPtr<Element> divElement =
      CreateElementWithDefaults(NS_LITERAL_STRING("div"));
    NS_ENSURE_TRUE(divElement, NS_ERROR_FAILURE);

    CloneAttributes(bodyElement, divElement);

    return BeginningOfDocument();
  }

  rv = LoadHTML(Substring(beginbody, endtotal));
  NS_ENSURE_SUCCESS(rv, rv);

  // Now we must copy attributes user might have edited on the <body> tag
  // because InsertHTML (actually, CreateContextualFragment()) will never
  // return a body node in the DOM fragment

  // We already know where "<body" begins
  nsReadingIterator<char16_t> beginclosebody = beginbody;
  nsReadingIterator<char16_t> endclosebody;
  aSourceString.EndReading(endclosebody);
  if (!FindInReadable(NS_LITERAL_STRING(">"), beginclosebody, endclosebody)) {
    return NS_ERROR_FAILURE;
  }

  // Truncate at the end of the body tag.  Kludge of the year: fool the parser
  // by replacing "body" with "div" so we get a node
  nsAutoString bodyTag;
  bodyTag.AssignLiteral("<div ");
  bodyTag.Append(Substring(endbody, endclosebody));

  RefPtr<nsRange> range = selection->GetRangeAt(0);
  NS_ENSURE_TRUE(range, NS_ERROR_FAILURE);

  ErrorResult erv;
  RefPtr<DocumentFragment> docfrag =
    range->CreateContextualFragment(bodyTag, erv);
  NS_ENSURE_TRUE(!erv.Failed(), erv.StealNSResult());
  NS_ENSURE_TRUE(docfrag, NS_ERROR_NULL_POINTER);

  nsCOMPtr<nsIContent> child = docfrag->GetFirstChild();
  NS_ENSURE_TRUE(child && child->IsElement(), NS_ERROR_NULL_POINTER);

  // Copy all attributes from the div child to current body element
  CloneAttributes(bodyElement, child->AsElement());

  // place selection at first editable content
  return BeginningOfDocument();
}

void
HTMLEditor::NormalizeEOLInsertPosition(nsINode* firstNodeToInsert,
                                       nsCOMPtr<nsIDOMNode>* insertParentNode,
                                       int32_t* insertOffset)
{
  /*
    This function will either correct the position passed in,
    or leave the position unchanged.

    When the (first) item to insert is a block level element,
    and our insertion position is after the last visible item in a line,
    i.e. the insertion position is just before a visible line break <br>,
    we want to skip to the position just after the line break (see bug 68767)

    However, our logic to detect whether we should skip or not
    needs to be more clever.
    We must not skip when the caret appears to be positioned at the beginning
    of a block, in that case skipping the <br> would not insert the <br>
    at the caret position, but after the current empty line.

    So we have several cases to test:

    1) We only ever want to skip, if the next visible thing after the current position is a break

    2) We do not want to skip if there is no previous visible thing at all
       That is detected if the call to PriorVisibleNode gives us an offset of zero.
       Because PriorVisibleNode always positions after the prior node, we would
       see an offset > 0, if there were a prior node.

    3) We do not want to skip, if both the next and the previous visible things are breaks.

    4) We do not want to skip if the previous visible thing is in a different block
       than the insertion position.
  */

  if (!IsBlockNode(firstNodeToInsert)) {
    return;
  }

  WSRunObject wsObj(this, *insertParentNode, *insertOffset);
  nsCOMPtr<nsINode> nextVisNode, prevVisNode;
  int32_t nextVisOffset=0;
  WSType nextVisType;
  int32_t prevVisOffset=0;
  WSType prevVisType;

  nsCOMPtr<nsINode> parent(do_QueryInterface(*insertParentNode));
  wsObj.NextVisibleNode(parent, *insertOffset, address_of(nextVisNode), &nextVisOffset, &nextVisType);
  if (!nextVisNode) {
    return;
  }

  if (!(nextVisType & WSType::br)) {
    return;
  }

  wsObj.PriorVisibleNode(parent, *insertOffset, address_of(prevVisNode), &prevVisOffset, &prevVisType);
  if (!prevVisNode) {
    return;
  }

  if (prevVisType & WSType::br) {
    return;
  }

  if (prevVisType & WSType::thisBlock) {
    return;
  }

  int32_t brOffset=0;
  nsCOMPtr<nsIDOMNode> brNode = GetNodeLocation(GetAsDOMNode(nextVisNode), &brOffset);

  *insertParentNode = brNode;
  *insertOffset = brOffset + 1;
}

NS_IMETHODIMP
HTMLEditor::InsertElementAtSelection(nsIDOMElement* aElement,
                                     bool aDeleteSelection)
{
  // Protect the edit rules object from dying
  nsCOMPtr<nsIEditRules> rules(mRules);

  nsCOMPtr<Element> element = do_QueryInterface(aElement);
  NS_ENSURE_TRUE(element, NS_ERROR_NULL_POINTER);

  nsCOMPtr<nsIDOMNode> node = do_QueryInterface(aElement);

  ForceCompositionEnd();
  AutoEditBatch beginBatching(this);
  AutoRules beginRulesSniffing(this, EditAction::insertElement,
                               nsIEditor::eNext);

  RefPtr<Selection> selection = GetSelection();
  if (!selection) {
    return NS_ERROR_FAILURE;
  }

  // hand off to the rules system, see if it has anything to say about this
  bool cancel, handled;
  TextRulesInfo ruleInfo(EditAction::insertElement);
  ruleInfo.insertElement = aElement;
  nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
  if (cancel || NS_FAILED(rv)) {
    return rv;
  }

  if (!handled) {
    if (aDeleteSelection) {
      if (!IsBlockNode(element)) {
        // E.g., inserting an image.  In this case we don't need to delete any
        // inline wrappers before we do the insertion.  Otherwise we let
        // DeleteSelectionAndPrepareToCreateNode do the deletion for us, which
        // calls DeleteSelection with aStripWrappers = eStrip.
        rv = DeleteSelection(nsIEditor::eNone, nsIEditor::eNoStrip);
        NS_ENSURE_SUCCESS(rv, rv);
      }

      nsresult rv = DeleteSelectionAndPrepareToCreateNode();
      NS_ENSURE_SUCCESS(rv, rv);
    }

    // If deleting, selection will be collapsed.
    // so if not, we collapse it
    if (!aDeleteSelection) {
      // Named Anchor is a special case,
      // We collapse to insert element BEFORE the selection
      // For all other tags, we insert AFTER the selection
      if (HTMLEditUtils::IsNamedAnchor(node)) {
        selection->CollapseToStart();
      } else {
        selection->CollapseToEnd();
      }
    }

    nsCOMPtr<nsIDOMNode> parentSelectedNode;
    int32_t offsetForInsert;
    rv = selection->GetAnchorNode(getter_AddRefs(parentSelectedNode));
    // XXX: ERROR_HANDLING bad XPCOM usage
    if (NS_SUCCEEDED(rv) &&
        NS_SUCCEEDED(selection->GetAnchorOffset(&offsetForInsert)) &&
        parentSelectedNode) {
      // Adjust position based on the node we are going to insert.
      NormalizeEOLInsertPosition(element, address_of(parentSelectedNode),
                                 &offsetForInsert);

      rv = InsertNodeAtPoint(node, address_of(parentSelectedNode),
                             &offsetForInsert, false);
      NS_ENSURE_SUCCESS(rv, rv);
      // Set caret after element, but check for special case
      //  of inserting table-related elements: set in first cell instead
      if (!SetCaretInTableCell(aElement)) {
        rv = SetCaretAfterElement(aElement);
        NS_ENSURE_SUCCESS(rv, rv);
      }
      // check for inserting a whole table at the end of a block. If so insert a br after it.
      if (HTMLEditUtils::IsTable(node)) {
        bool isLast;
        rv = IsLastEditableChild(node, &isLast);
        NS_ENSURE_SUCCESS(rv, rv);
        if (isLast) {
          nsCOMPtr<nsIDOMNode> brNode;
          rv = CreateBR(parentSelectedNode, offsetForInsert + 1,
                        address_of(brNode));
          NS_ENSURE_SUCCESS(rv, rv);
          selection->Collapse(parentSelectedNode, offsetForInsert+1);
        }
      }
    }
  }
  rv = rules->DidDoAction(selection, &ruleInfo, rv);
  return rv;
}


/**
 * InsertNodeAtPoint() attempts to insert aNode into the document, at a point
 * specified by {*ioParent,*ioOffset}.  Checks with strict dtd to see if
 * containment is allowed.  If not allowed, will attempt to find a parent in
 * the parent hierarchy of *ioParent that will accept aNode as a child.  If
 * such a parent is found, will split the document tree from
 * {*ioParent,*ioOffset} up to parent, and then insert aNode.
 * ioParent & ioOffset are then adjusted to point to the actual location that
 * aNode was inserted at.  aNoEmptyNodes specifies if the splitting process
 * is allowed to reslt in empty nodes.
 *
 * @param aNode             Node to insert.
 * @param ioParent          Insertion parent.
 * @param ioOffset          Insertion offset.
 * @param aNoEmptyNodes     Splitting can result in empty nodes?
 */
nsresult
HTMLEditor::InsertNodeAtPoint(nsIDOMNode* aNode,
                              nsCOMPtr<nsIDOMNode>* ioParent,
                              int32_t* ioOffset,
                              bool aNoEmptyNodes)
{
  nsCOMPtr<nsIContent> node = do_QueryInterface(aNode);
  NS_ENSURE_TRUE(node, NS_ERROR_NULL_POINTER);
  NS_ENSURE_TRUE(ioParent, NS_ERROR_NULL_POINTER);
  NS_ENSURE_TRUE(*ioParent, NS_ERROR_NULL_POINTER);
  NS_ENSURE_TRUE(ioOffset, NS_ERROR_NULL_POINTER);

  nsCOMPtr<nsIContent> parent = do_QueryInterface(*ioParent);
  NS_ENSURE_TRUE(parent, NS_ERROR_NULL_POINTER);
  nsCOMPtr<nsIContent> topChild = parent;
  nsCOMPtr<nsIContent> origParent = parent;

  // Search up the parent chain to find a suitable container
  while (!CanContain(*parent, *node)) {
    // If the current parent is a root (body or table element)
    // then go no further - we can't insert
    if (parent->IsHTMLElement(nsGkAtoms::body) ||
        HTMLEditUtils::IsTableElement(parent)) {
      return NS_ERROR_FAILURE;
    }
    // Get the next parent
    NS_ENSURE_TRUE(parent->GetParentNode(), NS_ERROR_FAILURE);
    if (!IsEditable(parent->GetParentNode())) {
      // There's no suitable place to put the node in this editing host.  Maybe
      // someone is trying to put block content in a span.  So just put it
      // where we were originally asked.
      parent = topChild = origParent;
      break;
    }
    topChild = parent;
    parent = parent->GetParent();
  }
  if (parent != topChild) {
    // we need to split some levels above the original selection parent
    int32_t offset = SplitNodeDeep(*topChild, *origParent, *ioOffset,
                                   aNoEmptyNodes ? EmptyContainers::no
                                                 : EmptyContainers::yes);
    NS_ENSURE_STATE(offset != -1);
    *ioParent = GetAsDOMNode(parent);
    *ioOffset = offset;
  }
  // Now we can insert the new node
  return InsertNode(*node, *parent, *ioOffset);
}

NS_IMETHODIMP
HTMLEditor::SelectElement(nsIDOMElement* aElement)
{
  nsCOMPtr<Element> element = do_QueryInterface(aElement);
  NS_ENSURE_STATE(element || !aElement);

  // Must be sure that element is contained in the document body
  if (!IsDescendantOfEditorRoot(element)) {
    return NS_ERROR_NULL_POINTER;
  }

  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
  nsCOMPtr<nsIDOMNode>parent;
  nsresult rv = aElement->GetParentNode(getter_AddRefs(parent));
  if (NS_SUCCEEDED(rv) && parent) {
    int32_t offsetInParent = GetChildOffset(aElement, parent);

    // Collapse selection to just before desired element,
    rv = selection->Collapse(parent, offsetInParent);
    if (NS_SUCCEEDED(rv)) {
      // then extend it to just after
      rv = selection->Extend(parent, offsetInParent + 1);
    }
  }
  return rv;
}

NS_IMETHODIMP
HTMLEditor::SetCaretAfterElement(nsIDOMElement* aElement)
{
  nsCOMPtr<Element> element = do_QueryInterface(aElement);
  NS_ENSURE_STATE(element || !aElement);

  // Be sure the element is contained in the document body
  if (!aElement || !IsDescendantOfEditorRoot(element)) {
    return NS_ERROR_NULL_POINTER;
  }

  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
  nsCOMPtr<nsIDOMNode>parent;
  nsresult rv = aElement->GetParentNode(getter_AddRefs(parent));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(parent, NS_ERROR_NULL_POINTER);
  int32_t offsetInParent = GetChildOffset(aElement, parent);
  // Collapse selection to just after desired element,
  return selection->Collapse(parent, offsetInParent + 1);
}

NS_IMETHODIMP
HTMLEditor::SetParagraphFormat(const nsAString& aParagraphFormat)
{
  nsAutoString tag; tag.Assign(aParagraphFormat);
  ToLowerCase(tag);
  if (tag.EqualsLiteral("dd") || tag.EqualsLiteral("dt")) {
    return MakeDefinitionItem(tag);
  }
  return InsertBasicBlock(tag);
}

NS_IMETHODIMP
HTMLEditor::GetParagraphState(bool* aMixed,
                              nsAString& outFormat)
{
  if (!mRules) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  NS_ENSURE_TRUE(aMixed, NS_ERROR_NULL_POINTER);
  RefPtr<HTMLEditRules> htmlRules =
    static_cast<HTMLEditRules*>(mRules.get());

  return htmlRules->GetParagraphState(aMixed, outFormat);
}

NS_IMETHODIMP
HTMLEditor::GetBackgroundColorState(bool* aMixed,
                                    nsAString& aOutColor)
{
  if (IsCSSEnabled()) {
    // if we are in CSS mode, we have to check if the containing block defines
    // a background color
    return GetCSSBackgroundColorState(aMixed, aOutColor, true);
  }
  // in HTML mode, we look only at page's background
  return GetHTMLBackgroundColorState(aMixed, aOutColor);
}

NS_IMETHODIMP
HTMLEditor::GetHighlightColorState(bool* aMixed,
                                   nsAString& aOutColor)
{
  *aMixed = false;
  aOutColor.AssignLiteral("transparent");
  if (!IsCSSEnabled()) {
    return NS_OK;
  }

  // in CSS mode, text background can be added by the Text Highlight button
  // we need to query the background of the selection without looking for
  // the block container of the ranges in the selection
  return GetCSSBackgroundColorState(aMixed, aOutColor, false);
}

nsresult
HTMLEditor::GetCSSBackgroundColorState(bool* aMixed,
                                       nsAString& aOutColor,
                                       bool aBlockLevel)
{
  NS_ENSURE_TRUE(aMixed, NS_ERROR_NULL_POINTER);
  *aMixed = false;
  // the default background color is transparent
  aOutColor.AssignLiteral("transparent");

  // get selection
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_STATE(selection && selection->GetRangeAt(0));

  // get selection location
  nsCOMPtr<nsINode> parent = selection->GetRangeAt(0)->GetStartParent();
  int32_t offset = selection->GetRangeAt(0)->StartOffset();
  NS_ENSURE_TRUE(parent, NS_ERROR_NULL_POINTER);

  // is the selection collapsed?
  nsCOMPtr<nsINode> nodeToExamine;
  if (selection->Collapsed() || IsTextNode(parent)) {
    // we want to look at the parent and ancestors
    nodeToExamine = parent;
  } else {
    // otherwise we want to look at the first editable node after
    // {parent,offset} and its ancestors for divs with alignment on them
    nodeToExamine = parent->GetChildAt(offset);
    //GetNextNode(parent, offset, true, address_of(nodeToExamine));
  }

  NS_ENSURE_TRUE(nodeToExamine, NS_ERROR_NULL_POINTER);

  if (aBlockLevel) {
    // we are querying the block background (and not the text background), let's
    // climb to the block container
    nsCOMPtr<Element> blockParent = GetBlock(*nodeToExamine);
    NS_ENSURE_TRUE(blockParent, NS_OK);

    // Make sure to not walk off onto the Document node
    do {
      // retrieve the computed style of background-color for blockParent
      mCSSEditUtils->GetComputedProperty(*blockParent,
                                         *nsGkAtoms::backgroundColor,
                                         aOutColor);
      blockParent = blockParent->GetParentElement();
      // look at parent if the queried color is transparent and if the node to
      // examine is not the root of the document
    } while (aOutColor.EqualsLiteral("transparent") && blockParent);
    if (aOutColor.EqualsLiteral("transparent")) {
      // we have hit the root of the document and the color is still transparent !
      // Grumble... Let's look at the default background color because that's the
      // color we are looking for
      mCSSEditUtils->GetDefaultBackgroundColor(aOutColor);
    }
  }
  else {
    // no, we are querying the text background for the Text Highlight button
    if (IsTextNode(nodeToExamine)) {
      // if the node of interest is a text node, let's climb a level
      nodeToExamine = nodeToExamine->GetParentNode();
    }
    do {
      // is the node to examine a block ?
      if (NodeIsBlockStatic(nodeToExamine)) {
        // yes it is a block; in that case, the text background color is transparent
        aOutColor.AssignLiteral("transparent");
        break;
      } else {
        // no, it's not; let's retrieve the computed style of background-color for the
        // node to examine
        mCSSEditUtils->GetComputedProperty(*nodeToExamine,
                                           *nsGkAtoms::backgroundColor,
                                           aOutColor);
        if (!aOutColor.EqualsLiteral("transparent")) {
          break;
        }
      }
      nodeToExamine = nodeToExamine->GetParentNode();
    } while ( aOutColor.EqualsLiteral("transparent") && nodeToExamine );
  }
  return NS_OK;
}

NS_IMETHODIMP
HTMLEditor::GetHTMLBackgroundColorState(bool* aMixed,
                                        nsAString& aOutColor)
{
  //TODO: We don't handle "mixed" correctly!
  NS_ENSURE_TRUE(aMixed, NS_ERROR_NULL_POINTER);
  *aMixed = false;
  aOutColor.Truncate();

  nsCOMPtr<nsIDOMElement> domElement;
  int32_t selectedCount;
  nsAutoString tagName;
  nsresult rv = GetSelectedOrParentTableElement(tagName,
                                                &selectedCount,
                                                getter_AddRefs(domElement));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<dom::Element> element = do_QueryInterface(domElement);

  while (element) {
    // We are in a cell or selected table
    element->GetAttr(kNameSpaceID_None, nsGkAtoms::bgcolor, aOutColor);

    // Done if we have a color explicitly set
    if (!aOutColor.IsEmpty()) {
      return NS_OK;
    }

    // Once we hit the body, we're done
    if (element->IsHTMLElement(nsGkAtoms::body)) {
      return NS_OK;
    }

    // No color is set, but we need to report visible color inherited
    // from nested cells/tables, so search up parent chain
    element = element->GetParentElement();
  }

  // If no table or cell found, get page body
  dom::Element* bodyElement = GetRoot();
  NS_ENSURE_TRUE(bodyElement, NS_ERROR_NULL_POINTER);

  bodyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::bgcolor, aOutColor);
  return NS_OK;
}

NS_IMETHODIMP
HTMLEditor::GetListState(bool* aMixed,
                         bool* aOL,
                         bool* aUL,
                         bool* aDL)
{
  if (!mRules) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  NS_ENSURE_TRUE(aMixed && aOL && aUL && aDL, NS_ERROR_NULL_POINTER);
  RefPtr<HTMLEditRules> htmlRules =
    static_cast<HTMLEditRules*>(mRules.get());

  return htmlRules->GetListState(aMixed, aOL, aUL, aDL);
}

NS_IMETHODIMP
HTMLEditor::GetListItemState(bool* aMixed,
                             bool* aLI,
                             bool* aDT,
                             bool* aDD)
{
  if (!mRules) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  NS_ENSURE_TRUE(aMixed && aLI && aDT && aDD, NS_ERROR_NULL_POINTER);

  RefPtr<HTMLEditRules> htmlRules =
    static_cast<HTMLEditRules*>(mRules.get());

  return htmlRules->GetListItemState(aMixed, aLI, aDT, aDD);
}

NS_IMETHODIMP
HTMLEditor::GetAlignment(bool* aMixed,
                         nsIHTMLEditor::EAlignment* aAlign)
{
  if (!mRules) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  NS_ENSURE_TRUE(aMixed && aAlign, NS_ERROR_NULL_POINTER);
  RefPtr<HTMLEditRules> htmlRules =
    static_cast<HTMLEditRules*>(mRules.get());

  return htmlRules->GetAlignment(aMixed, aAlign);
}

NS_IMETHODIMP
HTMLEditor::GetIndentState(bool* aCanIndent,
                           bool* aCanOutdent)
{
  if (!mRules) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  NS_ENSURE_TRUE(aCanIndent && aCanOutdent, NS_ERROR_NULL_POINTER);

  RefPtr<HTMLEditRules> htmlRules =
    static_cast<HTMLEditRules*>(mRules.get());

  return htmlRules->GetIndentState(aCanIndent, aCanOutdent);
}

NS_IMETHODIMP
HTMLEditor::MakeOrChangeList(const nsAString& aListType,
                             bool entireList,
                             const nsAString& aBulletType)
{
  if (!mRules) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  // Protect the edit rules object from dying
  nsCOMPtr<nsIEditRules> rules(mRules);

  bool cancel, handled;

  AutoEditBatch beginBatching(this);
  AutoRules beginRulesSniffing(this, EditAction::makeList, nsIEditor::eNext);

  // pre-process
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);

  TextRulesInfo ruleInfo(EditAction::makeList);
  ruleInfo.blockType = &aListType;
  ruleInfo.entireList = entireList;
  ruleInfo.bulletType = &aBulletType;
  nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
  if (cancel || NS_FAILED(rv)) {
    return rv;
  }

  if (!handled) {
    // Find out if the selection is collapsed:
    bool isCollapsed = selection->Collapsed();

    NS_ENSURE_TRUE(selection->GetRangeAt(0) &&
                   selection->GetRangeAt(0)->GetStartParent() &&
                   selection->GetRangeAt(0)->GetStartParent()->IsContent(),
                   NS_ERROR_FAILURE);
    OwningNonNull<nsIContent> node =
      *selection->GetRangeAt(0)->GetStartParent()->AsContent();
    int32_t offset = selection->GetRangeAt(0)->StartOffset();

    if (isCollapsed) {
      // have to find a place to put the list
      nsCOMPtr<nsIContent> parent = node;
      nsCOMPtr<nsIContent> topChild = node;

      nsCOMPtr<nsIAtom> listAtom = NS_Atomize(aListType);
      while (!CanContainTag(*parent, *listAtom)) {
        topChild = parent;
        parent = parent->GetParent();
      }

      if (parent != node) {
        // we need to split up to the child of parent
        offset = SplitNodeDeep(*topChild, *node, offset);
        NS_ENSURE_STATE(offset != -1);
      }

      // make a list
      nsCOMPtr<Element> newList = CreateNode(listAtom, parent, offset);
      NS_ENSURE_STATE(newList);
      // make a list item
      nsCOMPtr<Element> newItem = CreateNode(nsGkAtoms::li, newList, 0);
      NS_ENSURE_STATE(newItem);
      rv = selection->Collapse(newItem, 0);
      NS_ENSURE_SUCCESS(rv, rv);
    }
  }

  return rules->DidDoAction(selection, &ruleInfo, rv);
}

NS_IMETHODIMP
HTMLEditor::RemoveList(const nsAString& aListType)
{
  if (!mRules) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  // Protect the edit rules object from dying
  nsCOMPtr<nsIEditRules> rules(mRules);

  bool cancel, handled;

  AutoEditBatch beginBatching(this);
  AutoRules beginRulesSniffing(this, EditAction::removeList, nsIEditor::eNext);

  // pre-process
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);

  TextRulesInfo ruleInfo(EditAction::removeList);
  if (aListType.LowerCaseEqualsLiteral("ol")) {
    ruleInfo.bOrdered = true;
  } else {
    ruleInfo.bOrdered = false;
  }
  nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
  if (cancel || NS_FAILED(rv)) {
    return rv;
  }

  // no default behavior for this yet.  what would it mean?

  return rules->DidDoAction(selection, &ruleInfo, rv);
}

nsresult
HTMLEditor::MakeDefinitionItem(const nsAString& aItemType)
{
  if (!mRules) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  // Protect the edit rules object from dying
  nsCOMPtr<nsIEditRules> rules(mRules);

  bool cancel, handled;

  AutoEditBatch beginBatching(this);
  AutoRules beginRulesSniffing(this, EditAction::makeDefListItem,
                               nsIEditor::eNext);

  // pre-process
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
  TextRulesInfo ruleInfo(EditAction::makeDefListItem);
  ruleInfo.blockType = &aItemType;
  nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
  if (cancel || NS_FAILED(rv)) {
    return rv;
  }

  if (!handled) {
    // todo: no default for now.  we count on rules to handle it.
  }

  return rules->DidDoAction(selection, &ruleInfo, rv);
}

nsresult
HTMLEditor::InsertBasicBlock(const nsAString& aBlockType)
{
  if (!mRules) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  // Protect the edit rules object from dying
  nsCOMPtr<nsIEditRules> rules(mRules);

  bool cancel, handled;

  AutoEditBatch beginBatching(this);
  AutoRules beginRulesSniffing(this, EditAction::makeBasicBlock,
                               nsIEditor::eNext);

  // pre-process
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
  TextRulesInfo ruleInfo(EditAction::makeBasicBlock);
  ruleInfo.blockType = &aBlockType;
  nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
  if (cancel || NS_FAILED(rv)) {
    return rv;
  }

  if (!handled) {
    // Find out if the selection is collapsed:
    bool isCollapsed = selection->Collapsed();

    NS_ENSURE_TRUE(selection->GetRangeAt(0) &&
                   selection->GetRangeAt(0)->GetStartParent() &&
                   selection->GetRangeAt(0)->GetStartParent()->IsContent(),
                   NS_ERROR_FAILURE);
    OwningNonNull<nsIContent> node =
      *selection->GetRangeAt(0)->GetStartParent()->AsContent();
    int32_t offset = selection->GetRangeAt(0)->StartOffset();

    if (isCollapsed) {
      // have to find a place to put the block
      nsCOMPtr<nsIContent> parent = node;
      nsCOMPtr<nsIContent> topChild = node;

      nsCOMPtr<nsIAtom> blockAtom = NS_Atomize(aBlockType);
      while (!CanContainTag(*parent, *blockAtom)) {
        NS_ENSURE_TRUE(parent->GetParent(), NS_ERROR_FAILURE);
        topChild = parent;
        parent = parent->GetParent();
      }

      if (parent != node) {
        // we need to split up to the child of parent
        offset = SplitNodeDeep(*topChild, *node, offset);
        NS_ENSURE_STATE(offset != -1);
      }

      // make a block
      nsCOMPtr<Element> newBlock = CreateNode(blockAtom, parent, offset);
      NS_ENSURE_STATE(newBlock);

      // reposition selection to inside the block
      rv = selection->Collapse(newBlock, 0);
      NS_ENSURE_SUCCESS(rv, rv);
    }
  }

  return rules->DidDoAction(selection, &ruleInfo, rv);
}

NS_IMETHODIMP
HTMLEditor::Indent(const nsAString& aIndent)
{
  if (!mRules) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  // Protect the edit rules object from dying
  nsCOMPtr<nsIEditRules> rules(mRules);

  bool cancel, handled;
  EditAction opID = EditAction::indent;
  if (aIndent.LowerCaseEqualsLiteral("outdent")) {
    opID = EditAction::outdent;
  }
  AutoEditBatch beginBatching(this);
  AutoRules beginRulesSniffing(this, opID, nsIEditor::eNext);

  // pre-process
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);

  TextRulesInfo ruleInfo(opID);
  nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
  if (cancel || NS_FAILED(rv)) {
    return rv;
  }

  if (!handled) {
    // Do default - insert a blockquote node if selection collapsed
    bool isCollapsed = selection->Collapsed();

    NS_ENSURE_TRUE(selection->GetRangeAt(0) &&
                   selection->GetRangeAt(0)->GetStartParent() &&
                   selection->GetRangeAt(0)->GetStartParent()->IsContent(),
                   NS_ERROR_FAILURE);
    OwningNonNull<nsIContent> node =
      *selection->GetRangeAt(0)->GetStartParent()->AsContent();
    int32_t offset = selection->GetRangeAt(0)->StartOffset();

    if (aIndent.EqualsLiteral("indent")) {
      if (isCollapsed) {
        // have to find a place to put the blockquote
        nsCOMPtr<nsIContent> parent = node;
        nsCOMPtr<nsIContent> topChild = node;
        while (!CanContainTag(*parent, *nsGkAtoms::blockquote)) {
          NS_ENSURE_TRUE(parent->GetParent(), NS_ERROR_FAILURE);
          topChild = parent;
          parent = parent->GetParent();
        }

        if (parent != node) {
          // we need to split up to the child of parent
          offset = SplitNodeDeep(*topChild, *node, offset);
          NS_ENSURE_STATE(offset != -1);
        }

        // make a blockquote
        nsCOMPtr<Element> newBQ = CreateNode(nsGkAtoms::blockquote, parent, offset);
        NS_ENSURE_STATE(newBQ);
        // put a space in it so layout will draw the list item
        rv = selection->Collapse(newBQ, 0);
        NS_ENSURE_SUCCESS(rv, rv);
        rv = InsertText(NS_LITERAL_STRING(" "));
        NS_ENSURE_SUCCESS(rv, rv);
        // reposition selection to before the space character
        NS_ENSURE_STATE(selection->GetRangeAt(0));
        rv = selection->Collapse(selection->GetRangeAt(0)->GetStartParent(), 0);
        NS_ENSURE_SUCCESS(rv, rv);
      }
    }
  }
  return rules->DidDoAction(selection, &ruleInfo, rv);
}

//TODO: IMPLEMENT ALIGNMENT!

NS_IMETHODIMP
HTMLEditor::Align(const nsAString& aAlignType)
{
  // Protect the edit rules object from dying
  nsCOMPtr<nsIEditRules> rules(mRules);

  AutoEditBatch beginBatching(this);
  AutoRules beginRulesSniffing(this, EditAction::align, nsIEditor::eNext);

  bool cancel, handled;

  // Find out if the selection is collapsed:
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
  TextRulesInfo ruleInfo(EditAction::align);
  ruleInfo.alignType = &aAlignType;
  nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
  if (cancel || NS_FAILED(rv)) {
    return rv;
  }

  return rules->DidDoAction(selection, &ruleInfo, rv);
}

already_AddRefed<Element>
HTMLEditor::GetElementOrParentByTagName(const nsAString& aTagName,
                                        nsINode* aNode)
{
  MOZ_ASSERT(!aTagName.IsEmpty());

  nsCOMPtr<nsINode> node = aNode;
  if (!node) {
    // If no node supplied, get it from anchor node of current selection
    RefPtr<Selection> selection = GetSelection();
    NS_ENSURE_TRUE(selection, nullptr);

    nsCOMPtr<nsINode> anchorNode = selection->GetAnchorNode();
    NS_ENSURE_TRUE(anchorNode, nullptr);

    // Try to get the actual selected node
    if (anchorNode->HasChildNodes() && anchorNode->IsContent()) {
      node = anchorNode->GetChildAt(selection->AnchorOffset());
    }
    // Anchor node is probably a text node - just use that
    if (!node) {
      node = anchorNode;
    }
  }

  nsCOMPtr<Element> current;
  if (node->IsElement()) {
    current = node->AsElement();
  } else if (node->GetParentElement()) {
    current = node->GetParentElement();
  } else {
    // Neither aNode nor its parent is an element, so no ancestor is
    MOZ_ASSERT(!node->GetParentNode() ||
               !node->GetParentNode()->GetParentNode());
    return nullptr;
  }

  nsAutoString tagName(aTagName);
  ToLowerCase(tagName);
  bool getLink = IsLinkTag(tagName);
  bool getNamedAnchor = IsNamedAnchorTag(tagName);
  if (getLink || getNamedAnchor) {
    tagName.Assign('a');
  }
  bool findTableCell = tagName.EqualsLiteral("td");
  bool findList = tagName.EqualsLiteral("list");

  for (; current; current = current->GetParentElement()) {
    // Test if we have a link (an anchor with href set)
    if ((getLink && HTMLEditUtils::IsLink(current)) ||
        (getNamedAnchor && HTMLEditUtils::IsNamedAnchor(current))) {
      return current.forget();
    }
    if (findList) {
      // Match "ol", "ul", or "dl" for lists
      if (HTMLEditUtils::IsList(current)) {
        return current.forget();
      }
    } else if (findTableCell) {
      // Table cells are another special case: match either "td" or "th"
      if (HTMLEditUtils::IsTableCell(current)) {
        return current.forget();
      }
    } else if (current->NodeName().Equals(tagName,
                   nsCaseInsensitiveStringComparator())) {
      return current.forget();
    }

    // Stop searching if parent is a body tag.  Note: Originally used IsRoot to
    // stop at table cells, but that's too messy when you are trying to find
    // the parent table
    if (current->GetParentElement() &&
        current->GetParentElement()->IsHTMLElement(nsGkAtoms::body)) {
      break;
    }
  }

  return nullptr;
}

NS_IMETHODIMP
HTMLEditor::GetElementOrParentByTagName(const nsAString& aTagName,
                                        nsIDOMNode* aNode,
                                        nsIDOMElement** aReturn)
{
  NS_ENSURE_TRUE(!aTagName.IsEmpty(), NS_ERROR_NULL_POINTER);
  NS_ENSURE_TRUE(aReturn, NS_ERROR_NULL_POINTER);

  nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
  nsCOMPtr<Element> parent =
    GetElementOrParentByTagName(aTagName, node);
  nsCOMPtr<nsIDOMElement> ret = do_QueryInterface(parent);

  if (!ret) {
    return NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND;
  }

  ret.forget(aReturn);
  return NS_OK;
}

NS_IMETHODIMP
HTMLEditor::GetSelectedElement(const nsAString& aTagName,
                               nsIDOMElement** aReturn)
{
  NS_ENSURE_TRUE(aReturn , NS_ERROR_NULL_POINTER);

  // default is null - no element found
  *aReturn = nullptr;

  // First look for a single element in selection
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);

  bool bNodeFound = false;
  bool isCollapsed = selection->Collapsed();

  nsAutoString domTagName;
  nsAutoString TagName(aTagName);
  ToLowerCase(TagName);
  // Empty string indicates we should match any element tag
  bool anyTag = (TagName.IsEmpty());
  bool isLinkTag = IsLinkTag(TagName);
  bool isNamedAnchorTag = IsNamedAnchorTag(TagName);

  nsCOMPtr<nsIDOMElement> selectedElement;
  RefPtr<nsRange> range = selection->GetRangeAt(0);
  NS_ENSURE_STATE(range);

  nsCOMPtr<nsIDOMNode> startParent;
  nsresult rv = range->GetStartContainer(getter_AddRefs(startParent));
  NS_ENSURE_SUCCESS(rv, rv);
  uint32_t startOffset = range->StartOffset();

  nsCOMPtr<nsIDOMNode> endParent;
  rv = range->GetEndContainer(getter_AddRefs(endParent));
  NS_ENSURE_SUCCESS(rv, rv);
  uint32_t endOffset = range->EndOffset();

  // Optimization for a single selected element
  if (startParent && startParent == endParent && endOffset - startOffset == 1) {
    nsCOMPtr<nsIDOMNode> selectedNode =
      GetChildAt(startParent, static_cast<int32_t>(startOffset));
    NS_ENSURE_SUCCESS(rv, NS_OK);
    if (selectedNode) {
      selectedNode->GetNodeName(domTagName);
      ToLowerCase(domTagName);

      // Test for appropriate node type requested
      if (anyTag || (TagName == domTagName) ||
          (isLinkTag && HTMLEditUtils::IsLink(selectedNode)) ||
          (isNamedAnchorTag && HTMLEditUtils::IsNamedAnchor(selectedNode))) {
        bNodeFound = true;
        selectedElement = do_QueryInterface(selectedNode);
      }
    }
  }

  if (!bNodeFound) {
    if (isLinkTag) {
      // Link tag is a special case - we return the anchor node
      //  found for any selection that is totally within a link,
      //  included a collapsed selection (just a caret in a link)
      nsCOMPtr<nsIDOMNode> anchorNode;
      rv = selection->GetAnchorNode(getter_AddRefs(anchorNode));
      NS_ENSURE_SUCCESS(rv, rv);
      int32_t anchorOffset = -1;
      if (anchorNode) {
        selection->GetAnchorOffset(&anchorOffset);
      }

      nsCOMPtr<nsIDOMNode> focusNode;
      rv = selection->GetFocusNode(getter_AddRefs(focusNode));
      NS_ENSURE_SUCCESS(rv, rv);
      int32_t focusOffset = -1;
      if (focusNode) {
        selection->GetFocusOffset(&focusOffset);
      }

      // Link node must be the same for both ends of selection
      if (NS_SUCCEEDED(rv) && anchorNode) {
        nsCOMPtr<nsIDOMElement> parentLinkOfAnchor;
        rv = GetElementOrParentByTagName(NS_LITERAL_STRING("href"),
                                         anchorNode,
                                         getter_AddRefs(parentLinkOfAnchor));
        // XXX: ERROR_HANDLING  can parentLinkOfAnchor be null?
        if (NS_SUCCEEDED(rv) && parentLinkOfAnchor) {
          if (isCollapsed) {
            // We have just a caret in the link
            bNodeFound = true;
          } else if (focusNode) {
            // Link node must be the same for both ends of selection.
            nsCOMPtr<nsIDOMElement> parentLinkOfFocus;
            rv = GetElementOrParentByTagName(NS_LITERAL_STRING("href"),
                                             focusNode,
                                             getter_AddRefs(parentLinkOfFocus));
            if (NS_SUCCEEDED(rv) && parentLinkOfFocus == parentLinkOfAnchor) {
              bNodeFound = true;
            }
          }

          // We found a link node parent
          if (bNodeFound) {
            // GetElementOrParentByTagName addref'd this, so we don't need to do it here
            *aReturn = parentLinkOfAnchor;
            NS_IF_ADDREF(*aReturn);
            return NS_OK;
          }
        } else if (anchorOffset >= 0) {
          // Check if link node is the only thing selected
          nsCOMPtr<nsIDOMNode> anchorChild;
          anchorChild = GetChildAt(anchorNode,anchorOffset);
          if (anchorChild && HTMLEditUtils::IsLink(anchorChild) &&
              anchorNode == focusNode && focusOffset == anchorOffset + 1) {
            selectedElement = do_QueryInterface(anchorChild);
            bNodeFound = true;
          }
        }
      }
    }

    if (!isCollapsed) {
      RefPtr<nsRange> currange = selection->GetRangeAt(0);
      if (currange) {
        nsCOMPtr<nsIContentIterator> iter =
          do_CreateInstance("@mozilla.org/content/post-content-iterator;1",
                            &rv);
        NS_ENSURE_SUCCESS(rv, rv);

        iter->Init(currange);
        // loop through the content iterator for each content node
        while (!iter->IsDone()) {
          // Query interface to cast nsIContent to nsIDOMNode
          //  then get tagType to compare to  aTagName
          // Clone node of each desired type and append it to the aDomFrag
          selectedElement = do_QueryInterface(iter->GetCurrentNode());
          if (selectedElement) {
            // If we already found a node, then we have another element,
            //  thus there's not just one element selected
            if (bNodeFound) {
              bNodeFound = false;
              break;
            }

            selectedElement->GetNodeName(domTagName);
            ToLowerCase(domTagName);

            if (anyTag) {
              // Get name of first selected element
              selectedElement->GetTagName(TagName);
              ToLowerCase(TagName);
              anyTag = false;
            }

            // The "A" tag is a pain,
            //  used for both link(href is set) and "Named Anchor"
            nsCOMPtr<nsIDOMNode> selectedNode = do_QueryInterface(selectedElement);
            if ((isLinkTag &&
                 HTMLEditUtils::IsLink(selectedNode)) ||
                (isNamedAnchorTag &&
                 HTMLEditUtils::IsNamedAnchor(selectedNode))) {
              bNodeFound = true;
            } else if (TagName == domTagName) { // All other tag names are handled here
              bNodeFound = true;
            }
            if (!bNodeFound) {
              // Check if node we have is really part of the selection???
              break;
            }
          }
          iter->Next();
        }
      } else {
        // Should never get here?
        isCollapsed = true;
        NS_WARNING("isCollapsed was FALSE, but no elements found in selection\n");
      }
    }
  }

  if (!bNodeFound) {
    return NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND;
  }

  *aReturn = selectedElement;
  if (selectedElement) {
    // Getters must addref
    NS_ADDREF(*aReturn);
  }
  return rv;
}

already_AddRefed<Element>
HTMLEditor::CreateElementWithDefaults(const nsAString& aTagName)
{
  MOZ_ASSERT(!aTagName.IsEmpty());

  nsAutoString tagName(aTagName);
  ToLowerCase(tagName);
  nsAutoString realTagName;

  if (IsLinkTag(tagName) || IsNamedAnchorTag(tagName)) {
    realTagName.Assign('a');
  } else {
    realTagName = tagName;
  }
  // We don't use editor's CreateElement because we don't want to go through
  // the transaction system

  // New call to use instead to get proper HTML element, bug 39919
  nsCOMPtr<nsIAtom> realTagAtom = NS_Atomize(realTagName);
  nsCOMPtr<Element> newElement = CreateHTMLContent(realTagAtom);
  if (!newElement) {
    return nullptr;
  }

  // Mark the new element dirty, so it will be formatted
  ErrorResult rv;
  newElement->SetAttribute(NS_LITERAL_STRING("_moz_dirty"), EmptyString(), rv);

  // Set default values for new elements
  if (tagName.EqualsLiteral("table")) {
    newElement->SetAttribute(NS_LITERAL_STRING("cellpadding"),
                             NS_LITERAL_STRING("2"), rv);
    if (NS_WARN_IF(rv.Failed())) {
      rv.SuppressException();
      return nullptr;
    }
    newElement->SetAttribute(NS_LITERAL_STRING("cellspacing"),
                             NS_LITERAL_STRING("2"), rv);
    if (NS_WARN_IF(rv.Failed())) {
      rv.SuppressException();
      return nullptr;
    }
    newElement->SetAttribute(NS_LITERAL_STRING("border"),
                             NS_LITERAL_STRING("1"), rv);
    if (NS_WARN_IF(rv.Failed())) {
      rv.SuppressException();
      return nullptr;
    }
  } else if (tagName.EqualsLiteral("td")) {
    nsresult rv =
      SetAttributeOrEquivalent(
        static_cast<nsIDOMElement*>(newElement->AsDOMNode()),
        NS_LITERAL_STRING("valign"), NS_LITERAL_STRING("top"), true);
    NS_ENSURE_SUCCESS(rv, nullptr);
  }
  // ADD OTHER TAGS HERE

  return newElement.forget();
}

NS_IMETHODIMP
HTMLEditor::CreateElementWithDefaults(const nsAString& aTagName,
                                      nsIDOMElement** aReturn)
{
  NS_ENSURE_TRUE(!aTagName.IsEmpty() && aReturn, NS_ERROR_NULL_POINTER);
  *aReturn = nullptr;

  nsCOMPtr<Element> newElement = CreateElementWithDefaults(aTagName);
  nsCOMPtr<nsIDOMElement> ret = do_QueryInterface(newElement);
  NS_ENSURE_TRUE(ret, NS_ERROR_FAILURE);

  ret.forget(aReturn);
  return NS_OK;
}

NS_IMETHODIMP
HTMLEditor::InsertLinkAroundSelection(nsIDOMElement* aAnchorElement)
{
  NS_ENSURE_TRUE(aAnchorElement, NS_ERROR_NULL_POINTER);

  // We must have a real selection
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);

  if (selection->Collapsed()) {
    NS_WARNING("InsertLinkAroundSelection called but there is no selection!!!");
    return NS_OK;
  }

  // Be sure we were given an anchor element
  nsCOMPtr<nsIDOMHTMLAnchorElement> anchor = do_QueryInterface(aAnchorElement);
  if (!anchor) {
    return NS_OK;
  }

  nsAutoString href;
  nsresult rv = anchor->GetHref(href);
  NS_ENSURE_SUCCESS(rv, rv);
  if (href.IsEmpty()) {
    return NS_OK;
  }

  AutoEditBatch beginBatching(this);

  // Set all attributes found on the supplied anchor element
  nsCOMPtr<nsIDOMMozNamedAttrMap> attrMap;
  aAnchorElement->GetAttributes(getter_AddRefs(attrMap));
  NS_ENSURE_TRUE(attrMap, NS_ERROR_FAILURE);

  uint32_t count;
  attrMap->GetLength(&count);
  nsAutoString name, value;

  for (uint32_t i = 0; i < count; ++i) {
    nsCOMPtr<nsIDOMAttr> attribute;
    rv = attrMap->Item(i, getter_AddRefs(attribute));
    NS_ENSURE_SUCCESS(rv, rv);

    if (attribute) {
      // We must clear the string buffers
      //   because GetName, GetValue appends to previous string!
      name.Truncate();
      value.Truncate();

      rv = attribute->GetName(name);
      NS_ENSURE_SUCCESS(rv, rv);

      rv = attribute->GetValue(value);
      NS_ENSURE_SUCCESS(rv, rv);

      rv = SetInlineProperty(nsGkAtoms::a, name, value);
      NS_ENSURE_SUCCESS(rv, rv);
    }
  }
  return NS_OK;
}

nsresult
HTMLEditor::SetHTMLBackgroundColor(const nsAString& aColor)
{
  MOZ_ASSERT(IsInitialized(), "The HTMLEditor hasn't been initialized yet");

  // Find a selected or enclosing table element to set background on
  nsCOMPtr<nsIDOMElement> element;
  int32_t selectedCount;
  nsAutoString tagName;
  nsresult rv = GetSelectedOrParentTableElement(tagName, &selectedCount,
                                                getter_AddRefs(element));
  NS_ENSURE_SUCCESS(rv, rv);

  bool setColor = !aColor.IsEmpty();

  NS_NAMED_LITERAL_STRING(bgcolor, "bgcolor");
  if (element) {
    if (selectedCount > 0) {
      // Traverse all selected cells
      nsCOMPtr<nsIDOMElement> cell;
      rv = GetFirstSelectedCell(nullptr, getter_AddRefs(cell));
      if (NS_SUCCEEDED(rv) && cell) {
        while (cell) {
          rv = setColor ? SetAttribute(cell, bgcolor, aColor) :
                          RemoveAttribute(cell, bgcolor);
          if (NS_FAILED(rv)) {
            return rv;
          }

          GetNextSelectedCell(nullptr, getter_AddRefs(cell));
        }
        return NS_OK;
      }
    }
    // If we failed to find a cell, fall through to use originally-found element
  } else {
    // No table element -- set the background color on the body tag
    element = do_QueryInterface(GetRoot());
    NS_ENSURE_TRUE(element, NS_ERROR_NULL_POINTER);
  }
  // Use the editor method that goes through the transaction system
  return setColor ? SetAttribute(element, bgcolor, aColor) :
                    RemoveAttribute(element, bgcolor);
}

NS_IMETHODIMP
HTMLEditor::SetBodyAttribute(const nsAString& aAttribute,
                             const nsAString& aValue)
{
  // TODO: Check selection for Cell, Row, Column or table and do color on appropriate level

  MOZ_ASSERT(IsInitialized(), "The HTMLEditor hasn't been initialized yet");

  // Set the background color attribute on the body tag
  nsCOMPtr<nsIDOMElement> bodyElement = do_QueryInterface(GetRoot());
  NS_ENSURE_TRUE(bodyElement, NS_ERROR_NULL_POINTER);

  // Use the editor method that goes through the transaction system
  return SetAttribute(bodyElement, aAttribute, aValue);
}

NS_IMETHODIMP
HTMLEditor::GetLinkedObjects(nsIArray** aNodeList)
{
  NS_ENSURE_TRUE(aNodeList, NS_ERROR_NULL_POINTER);

  nsresult rv;
  nsCOMPtr<nsIMutableArray> nodes = do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  nsCOMPtr<nsIContentIterator> iter =
    do_CreateInstance("@mozilla.org/content/post-content-iterator;1", &rv);
  NS_ENSURE_TRUE(iter, NS_ERROR_NULL_POINTER);
  if (NS_SUCCEEDED(rv)) {
    nsCOMPtr<nsIDocument> doc = GetDocument();
    NS_ENSURE_TRUE(doc, NS_ERROR_UNEXPECTED);

    iter->Init(doc->GetRootElement());

    // loop through the content iterator for each content node
    while (!iter->IsDone()) {
      nsCOMPtr<nsIDOMNode> node (do_QueryInterface(iter->GetCurrentNode()));
      if (node) {
        // Let nsURIRefObject make the hard decisions:
        nsCOMPtr<nsIURIRefObject> refObject;
        rv = NS_NewHTMLURIRefObject(getter_AddRefs(refObject), node);
        if (NS_SUCCEEDED(rv)) {
          nodes->AppendElement(refObject, false);
        }
      }
      iter->Next();
    }
  }

  nodes.forget(aNodeList);
  return NS_OK;
}


NS_IMETHODIMP
HTMLEditor::AddStyleSheet(const nsAString& aURL)
{
  // Enable existing sheet if already loaded.
  if (EnableExistingStyleSheet(aURL)) {
    return NS_OK;
  }

  // Lose the previously-loaded sheet so there's nothing to replace
  // This pattern is different from Override methods because
  //  we must wait to remove mLastStyleSheetURL and add new sheet
  //  at the same time (in StyleSheetLoaded callback) so they are undoable together
  mLastStyleSheetURL.Truncate();
  return ReplaceStyleSheet(aURL);
}

NS_IMETHODIMP
HTMLEditor::ReplaceStyleSheet(const nsAString& aURL)
{
  // Enable existing sheet if already loaded.
  if (EnableExistingStyleSheet(aURL)) {
    // Disable last sheet if not the same as new one
    if (!mLastStyleSheetURL.IsEmpty() && !mLastStyleSheetURL.Equals(aURL)) {
      return EnableStyleSheet(mLastStyleSheetURL, false);
    }
    return NS_OK;
  }

  // Make sure the pres shell doesn't disappear during the load.
  if (NS_WARN_IF(!IsInitialized())) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  nsCOMPtr<nsIPresShell> ps = GetPresShell();
  NS_ENSURE_TRUE(ps, NS_ERROR_NOT_INITIALIZED);

  nsCOMPtr<nsIURI> uaURI;
  nsresult rv = NS_NewURI(getter_AddRefs(uaURI), aURL);
  NS_ENSURE_SUCCESS(rv, rv);

  return ps->GetDocument()->CSSLoader()->
    LoadSheet(uaURI, false, nullptr, EmptyCString(), this);
}

NS_IMETHODIMP
HTMLEditor::RemoveStyleSheet(const nsAString& aURL)
{
  RefPtr<StyleSheet> sheet = GetStyleSheetForURL(aURL);
  NS_ENSURE_TRUE(sheet, NS_ERROR_UNEXPECTED);

  RefPtr<RemoveStyleSheetTransaction> transaction;
  nsresult rv =
    CreateTxnForRemoveStyleSheet(sheet, getter_AddRefs(transaction));
  if (!transaction) {
    rv = NS_ERROR_NULL_POINTER;
  }
  if (NS_SUCCEEDED(rv)) {
    rv = DoTransaction(transaction);
    if (NS_SUCCEEDED(rv)) {
      mLastStyleSheetURL.Truncate();        // forget it
    }
    // Remove it from our internal list
    rv = RemoveStyleSheetFromList(aURL);
  }

  return rv;
}


NS_IMETHODIMP
HTMLEditor::AddOverrideStyleSheet(const nsAString& aURL)
{
  // Enable existing sheet if already loaded.
  if (EnableExistingStyleSheet(aURL)) {
    return NS_OK;
  }

  // Make sure the pres shell doesn't disappear during the load.
  nsCOMPtr<nsIPresShell> ps = GetPresShell();
  NS_ENSURE_TRUE(ps, NS_ERROR_NOT_INITIALIZED);

  nsCOMPtr<nsIURI> uaURI;
  nsresult rv = NS_NewURI(getter_AddRefs(uaURI), aURL);
  NS_ENSURE_SUCCESS(rv, rv);

  // We MUST ONLY load synchronous local files (no @import)
  // XXXbz Except this will actually try to load remote files
  // synchronously, of course..
  RefPtr<StyleSheet> sheet;
  // Editor override style sheets may want to style Gecko anonymous boxes
  rv = ps->GetDocument()->CSSLoader()->
    LoadSheetSync(uaURI, mozilla::css::eAgentSheetFeatures, true,
                  &sheet);

  // Synchronous loads should ALWAYS return completed
  NS_ENSURE_TRUE(sheet, NS_ERROR_NULL_POINTER);

  // Add the override style sheet
  // (This checks if already exists)
  ps->AddOverrideStyleSheet(sheet);

  ps->RestyleForCSSRuleChanges();

  // Save as the last-loaded sheet
  mLastOverrideStyleSheetURL = aURL;

  //Add URL and style sheet to our lists
  return AddNewStyleSheetToList(aURL, sheet);
}

NS_IMETHODIMP
HTMLEditor::ReplaceOverrideStyleSheet(const nsAString& aURL)
{
  // Enable existing sheet if already loaded.
  if (EnableExistingStyleSheet(aURL)) {
    // Disable last sheet if not the same as new one
    if (!mLastOverrideStyleSheetURL.IsEmpty() &&
        !mLastOverrideStyleSheetURL.Equals(aURL)) {
      return EnableStyleSheet(mLastOverrideStyleSheetURL, false);
    }
    return NS_OK;
  }
  // Remove the previous sheet
  if (!mLastOverrideStyleSheetURL.IsEmpty()) {
    RemoveOverrideStyleSheet(mLastOverrideStyleSheetURL);
  }
  return AddOverrideStyleSheet(aURL);
}

// Do NOT use transaction system for override style sheets
NS_IMETHODIMP
HTMLEditor::RemoveOverrideStyleSheet(const nsAString& aURL)
{
  RefPtr<StyleSheet> sheet = GetStyleSheetForURL(aURL);

  // Make sure we remove the stylesheet from our internal list in all
  // cases.
  nsresult rv = RemoveStyleSheetFromList(aURL);

  NS_ENSURE_TRUE(sheet, NS_OK); /// Don't fail if sheet not found

  if (NS_WARN_IF(!IsInitialized())) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  nsCOMPtr<nsIPresShell> ps = GetPresShell();
  NS_ENSURE_TRUE(ps, NS_ERROR_NOT_INITIALIZED);

  ps->RemoveOverrideStyleSheet(sheet);
  ps->RestyleForCSSRuleChanges();

  // Remove it from our internal list
  return rv;
}

NS_IMETHODIMP
HTMLEditor::EnableStyleSheet(const nsAString& aURL,
                             bool aEnable)
{
  RefPtr<StyleSheet> sheet = GetStyleSheetForURL(aURL);
  NS_ENSURE_TRUE(sheet, NS_OK); // Don't fail if sheet not found

  // Ensure the style sheet is owned by our document.
  nsCOMPtr<nsIDocument> document = GetDocument();
  sheet->SetAssociatedDocument(document, StyleSheet::NotOwnedByDocument);

  if (sheet->IsServo()) {
    // XXXheycam ServoStyleSheets don't support being enabled/disabled yet.
    NS_ERROR("stylo: ServoStyleSheets can't be disabled yet");
    return NS_ERROR_FAILURE;
  }
  return sheet->AsGecko()->SetDisabled(!aEnable);
}

bool
HTMLEditor::EnableExistingStyleSheet(const nsAString& aURL)
{
  RefPtr<StyleSheet> sheet = GetStyleSheetForURL(aURL);

  // Enable sheet if already loaded.
  if (!sheet) {
    return false;
  }

  // Ensure the style sheet is owned by our document.
  nsCOMPtr<nsIDocument> document = GetDocument();
  sheet->SetAssociatedDocument(document, StyleSheet::NotOwnedByDocument);

  if (sheet->IsServo()) {
    // XXXheycam ServoStyleSheets don't support being enabled/disabled yet.
    NS_ERROR("stylo: ServoStyleSheets can't be disabled yet");
    return true;
  }
  sheet->AsGecko()->SetDisabled(false);
  return true;
}

nsresult
HTMLEditor::AddNewStyleSheetToList(const nsAString& aURL,
                                   StyleSheet* aStyleSheet)
{
  uint32_t countSS = mStyleSheets.Length();
  uint32_t countU = mStyleSheetURLs.Length();

  if (countSS != countU) {
    return NS_ERROR_UNEXPECTED;
  }

  if (!mStyleSheetURLs.AppendElement(aURL)) {
    return NS_ERROR_UNEXPECTED;
  }

  return mStyleSheets.AppendElement(aStyleSheet) ? NS_OK : NS_ERROR_UNEXPECTED;
}

nsresult
HTMLEditor::RemoveStyleSheetFromList(const nsAString& aURL)
{
  // is it already in the list?
  size_t foundIndex;
  foundIndex = mStyleSheetURLs.IndexOf(aURL);
  if (foundIndex == mStyleSheetURLs.NoIndex) {
    return NS_ERROR_FAILURE;
  }

  // Attempt both removals; if one fails there's not much we can do.
  mStyleSheets.RemoveElementAt(foundIndex);
  mStyleSheetURLs.RemoveElementAt(foundIndex);

  return NS_OK;
}

StyleSheet*
HTMLEditor::GetStyleSheetForURL(const nsAString& aURL)
{
  // is it already in the list?
  size_t foundIndex;
  foundIndex = mStyleSheetURLs.IndexOf(aURL);
  if (foundIndex == mStyleSheetURLs.NoIndex) {
    return nullptr;
  }

  MOZ_ASSERT(mStyleSheets[foundIndex]);
  return mStyleSheets[foundIndex];
}

void
HTMLEditor::GetURLForStyleSheet(StyleSheet* aStyleSheet,
                                nsAString& aURL)
{
  // is it already in the list?
  int32_t foundIndex = mStyleSheets.IndexOf(aStyleSheet);

  // Don't fail if we don't find it in our list
  if (foundIndex == -1) {
    return;
  }

  // Found it in the list!
  aURL = mStyleSheetURLs[foundIndex];
}

NS_IMETHODIMP
HTMLEditor::GetEmbeddedObjects(nsIArray** aNodeList)
{
  NS_ENSURE_TRUE(aNodeList, NS_ERROR_NULL_POINTER);

  nsresult rv;
  nsCOMPtr<nsIMutableArray> nodes = do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIContentIterator> iter =
      do_CreateInstance("@mozilla.org/content/post-content-iterator;1", &rv);
  NS_ENSURE_TRUE(iter, NS_ERROR_NULL_POINTER);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIDocument> doc = GetDocument();
  NS_ENSURE_TRUE(doc, NS_ERROR_UNEXPECTED);

  iter->Init(doc->GetRootElement());

  // Loop through the content iterator for each content node.
  while (!iter->IsDone()) {
    nsINode* node = iter->GetCurrentNode();
    if (node->IsElement()) {
      dom::Element* element = node->AsElement();

      // See if it's an image or an embed and also include all links.
      // Let mail decide which link to send or not
      if (element->IsAnyOfHTMLElements(nsGkAtoms::img, nsGkAtoms::embed,
                                       nsGkAtoms::a) ||
          (element->IsHTMLElement(nsGkAtoms::body) &&
           element->HasAttr(kNameSpaceID_None, nsGkAtoms::background))) {
        nsCOMPtr<nsIDOMNode> domNode = do_QueryInterface(node);
        nodes->AppendElement(domNode, false);
       }
     }
     iter->Next();
   }

  nodes.forget(aNodeList);
  return rv;
}

NS_IMETHODIMP
HTMLEditor::DeleteSelectionImpl(EDirection aAction,
                                EStripWrappers aStripWrappers)
{
  MOZ_ASSERT(aStripWrappers == eStrip || aStripWrappers == eNoStrip);

  nsresult rv = EditorBase::DeleteSelectionImpl(aAction, aStripWrappers);
  NS_ENSURE_SUCCESS(rv, rv);

  // If we weren't asked to strip any wrappers, we're done.
  if (aStripWrappers == eNoStrip) {
    return NS_OK;
  }

  RefPtr<Selection> selection = GetSelection();
  // Just checking that the selection itself is collapsed doesn't seem to work
  // right in the multi-range case
  NS_ENSURE_STATE(selection);
  NS_ENSURE_STATE(selection->GetAnchorFocusRange());
  NS_ENSURE_STATE(selection->GetAnchorFocusRange()->Collapsed());

  NS_ENSURE_STATE(selection->GetAnchorNode()->IsContent());
  nsCOMPtr<nsIContent> content = selection->GetAnchorNode()->AsContent();

  // Don't strip wrappers if this is the only wrapper in the block.  Then we'll
  // add a <br> later, so it won't be an empty wrapper in the end.
  nsCOMPtr<nsIContent> blockParent = content;
  while (blockParent && !IsBlockNode(blockParent)) {
    blockParent = blockParent->GetParent();
  }
  if (!blockParent) {
    return NS_OK;
  }
  bool emptyBlockParent;
  rv = IsEmptyNode(blockParent, &emptyBlockParent);
  NS_ENSURE_SUCCESS(rv, rv);
  if (emptyBlockParent) {
    return NS_OK;
  }

  if (content && !IsBlockNode(content) && !content->Length() &&
      content->IsEditable() && content != content->GetEditingHost()) {
    while (content->GetParent() && !IsBlockNode(content->GetParent()) &&
           content->GetParent()->Length() == 1 &&
           content->GetParent()->IsEditable() &&
           content->GetParent() != content->GetEditingHost()) {
      content = content->GetParent();
    }
    rv = DeleteNode(content);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return NS_OK;
}

nsresult
HTMLEditor::DeleteNode(nsINode* aNode)
{
  nsCOMPtr<nsIDOMNode> node = do_QueryInterface(aNode);
  return DeleteNode(node);
}

NS_IMETHODIMP
HTMLEditor::DeleteNode(nsIDOMNode* aNode)
{
  // do nothing if the node is read-only
  nsCOMPtr<nsIContent> content = do_QueryInterface(aNode);
  if (!IsModifiableNode(aNode) && !IsMozEditorBogusNode(content)) {
    return NS_ERROR_FAILURE;
  }

  return EditorBase::DeleteNode(aNode);
}

nsresult
HTMLEditor::DeleteText(nsGenericDOMDataNode& aCharData,
                       uint32_t aOffset,
                       uint32_t aLength)
{
  // Do nothing if the node is read-only
  if (!IsModifiableNode(&aCharData)) {
    return NS_ERROR_FAILURE;
  }

  return EditorBase::DeleteText(aCharData, aOffset, aLength);
}

nsresult
HTMLEditor::InsertTextImpl(const nsAString& aStringToInsert,
                           nsCOMPtr<nsINode>* aInOutNode,
                           int32_t* aInOutOffset,
                           nsIDocument* aDoc)
{
  // Do nothing if the node is read-only
  if (!IsModifiableNode(*aInOutNode)) {
    return NS_ERROR_FAILURE;
  }

  return EditorBase::InsertTextImpl(aStringToInsert, aInOutNode, aInOutOffset,
                                    aDoc);
}

void
HTMLEditor::ContentAppended(nsIDocument* aDocument,
                            nsIContent* aContainer,
                            nsIContent* aFirstNewContent,
                            int32_t aIndexInContainer)
{
  DoContentInserted(aDocument, aContainer, aFirstNewContent, aIndexInContainer,
                    eAppended);
}

void
HTMLEditor::ContentInserted(nsIDocument* aDocument,
                            nsIContent* aContainer,
                            nsIContent* aChild,
                            int32_t aIndexInContainer)
{
  DoContentInserted(aDocument, aContainer, aChild, aIndexInContainer,
                    eInserted);
}

bool
HTMLEditor::IsInObservedSubtree(nsIDocument* aDocument,
                                nsIContent* aContainer,
                                nsIContent* aChild)
{
  if (!aChild) {
    return false;
  }

  Element* root = GetRoot();
  // To be super safe here, check both ChromeOnlyAccess and GetBindingParent.
  // That catches (also unbound) native anonymous content, XBL and ShadowDOM.
  if (root &&
      (root->ChromeOnlyAccess() != aChild->ChromeOnlyAccess() ||
       root->GetBindingParent() != aChild->GetBindingParent())) {
    return false;
  }

  return !aChild->ChromeOnlyAccess() && !aChild->GetBindingParent();
}

void
HTMLEditor::DoContentInserted(nsIDocument* aDocument,
                              nsIContent* aContainer,
                              nsIContent* aChild,
                              int32_t aIndexInContainer,
                              InsertedOrAppended aInsertedOrAppended)
{
  if (!IsInObservedSubtree(aDocument, aContainer, aChild)) {
    return;
  }

  nsCOMPtr<nsIHTMLEditor> kungFuDeathGrip(this);

  if (ShouldReplaceRootElement()) {
    UpdateRootElement();
    nsContentUtils::AddScriptRunner(NewRunnableMethod(
      this, &HTMLEditor::NotifyRootChanged));
  }
  // We don't need to handle our own modifications
  else if (!mAction && (aContainer ? aContainer->IsEditable() : aDocument->IsEditable())) {
    if (IsMozEditorBogusNode(aChild)) {
      // Ignore insertion of the bogus node
      return;
    }
    // Protect the edit rules object from dying
    nsCOMPtr<nsIEditRules> rules(mRules);
    rules->DocumentModified();

    // Update spellcheck for only the newly-inserted node (bug 743819)
    if (mInlineSpellChecker) {
      RefPtr<nsRange> range = new nsRange(aChild);
      int32_t endIndex = aIndexInContainer + 1;
      if (aInsertedOrAppended == eAppended) {
        // Count all the appended nodes
        nsIContent* sibling = aChild->GetNextSibling();
        while (sibling) {
          endIndex++;
          sibling = sibling->GetNextSibling();
        }
      }
      nsresult rv = range->SetStartAndEnd(aContainer, aIndexInContainer,
                                          aContainer, endIndex);
      if (NS_SUCCEEDED(rv)) {
        mInlineSpellChecker->SpellCheckRange(range);
      }
    }
  }
}

void
HTMLEditor::ContentRemoved(nsIDocument* aDocument,
                           nsIContent* aContainer,
                           nsIContent* aChild,
                           int32_t aIndexInContainer,
                           nsIContent* aPreviousSibling)
{
  if (!IsInObservedSubtree(aDocument, aContainer, aChild)) {
    return;
  }

  nsCOMPtr<nsIHTMLEditor> kungFuDeathGrip(this);

  if (SameCOMIdentity(aChild, mRootElement)) {
    mRootElement = nullptr;
    nsContentUtils::AddScriptRunner(NewRunnableMethod(
      this, &HTMLEditor::NotifyRootChanged));
  }
  // We don't need to handle our own modifications
  else if (!mAction && (aContainer ? aContainer->IsEditable() : aDocument->IsEditable())) {
    if (aChild && IsMozEditorBogusNode(aChild)) {
      // Ignore removal of the bogus node
      return;
    }
    // Protect the edit rules object from dying
    nsCOMPtr<nsIEditRules> rules(mRules);
    rules->DocumentModified();
  }
}

NS_IMETHODIMP_(bool)
HTMLEditor::IsModifiableNode(nsIDOMNode* aNode)
{
  nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
  return IsModifiableNode(node);
}

bool
HTMLEditor::IsModifiableNode(nsINode* aNode)
{
  return !aNode || aNode->IsEditable();
}

NS_IMETHODIMP
HTMLEditor::GetIsSelectionEditable(bool* aIsSelectionEditable)
{
  MOZ_ASSERT(aIsSelectionEditable);

  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);

  nsINode* anchorNode = selection->GetAnchorNode();
  nsINode* focusNode = selection->GetFocusNode();
  if (!anchorNode || !focusNode) {
    return NS_ERROR_FAILURE;
  }

  // Per the editing spec as of June 2012: we have to have a selection whose
  // start and end nodes are editable, and which share an ancestor editing
  // host.  (Bug 766387.)
  *aIsSelectionEditable = selection->RangeCount() &&
                          anchorNode->IsEditable() &&
                          focusNode->IsEditable();

  if (*aIsSelectionEditable) {
    nsINode* commonAncestor =
      selection->GetAnchorFocusRange()->GetCommonAncestor();
    while (commonAncestor && !commonAncestor->IsEditable()) {
      commonAncestor = commonAncestor->GetParentNode();
    }
    if (!commonAncestor) {
      // No editable common ancestor
      *aIsSelectionEditable = false;
    }
  }

  return NS_OK;
}

static nsresult
SetSelectionAroundHeadChildren(Selection* aSelection,
                               nsCOMPtr<nsIDocument>& aDocument)
{
  MOZ_ASSERT(aDocument);

  // Set selection around <head> node
  dom::Element* headNode = aDocument->GetHeadElement();
  NS_ENSURE_STATE(headNode);

  // Collapse selection to before first child of the head,
  nsresult rv = aSelection->CollapseNative(headNode, 0);
  NS_ENSURE_SUCCESS(rv, rv);

  // Then extend it to just after.
  uint32_t childCount = headNode->GetChildCount();
  return aSelection->ExtendNative(headNode, childCount + 1);
}

NS_IMETHODIMP
HTMLEditor::GetHeadContentsAsHTML(nsAString& aOutputString)
{
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);

  // Save current selection
  AutoSelectionRestorer selectionRestorer(selection, this);

  nsCOMPtr<nsIDocument> document = GetDocument();
  if (NS_WARN_IF(!document)) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  nsresult rv = SetSelectionAroundHeadChildren(selection, document);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = OutputToString(NS_LITERAL_STRING("text/html"),
                      nsIDocumentEncoder::OutputSelectionOnly,
                      aOutputString);
  if (NS_FAILED(rv)) {
    return rv;
  }

  // Selection always includes <body></body>,
  //  so terminate there
  nsReadingIterator<char16_t> findIter,endFindIter;
  aOutputString.BeginReading(findIter);
  aOutputString.EndReading(endFindIter);
  //counting on our parser to always lower case!!!
  if (CaseInsensitiveFindInReadable(NS_LITERAL_STRING("<body"),
                                    findIter, endFindIter)) {
    nsReadingIterator<char16_t> beginIter;
    aOutputString.BeginReading(beginIter);
    int32_t offset = Distance(beginIter, findIter);//get the distance

    nsWritingIterator<char16_t> writeIter;
    aOutputString.BeginWriting(writeIter);
    // Ensure the string ends in a newline
    char16_t newline ('\n');
    findIter.advance(-1);
    if (!offset || (offset > 0 && (*findIter) != newline)) {
      writeIter.advance(offset);
      *writeIter = newline;
      aOutputString.Truncate(offset+1);
    }
  }
  return NS_OK;
}

NS_IMETHODIMP
HTMLEditor::DebugUnitTests(int32_t* outNumTests,
                           int32_t* outNumTestsFailed)
{
#ifdef DEBUG
  NS_ENSURE_TRUE(outNumTests && outNumTestsFailed, NS_ERROR_NULL_POINTER);

  TextEditorTest *tester = new TextEditorTest();
  NS_ENSURE_TRUE(tester, NS_ERROR_OUT_OF_MEMORY);

  tester->Run(this, outNumTests, outNumTestsFailed);
  delete tester;
  return NS_OK;
#else
  return NS_ERROR_NOT_IMPLEMENTED;
#endif
}

NS_IMETHODIMP
HTMLEditor::StyleSheetLoaded(StyleSheet* aSheet,
                             bool aWasAlternate,
                             nsresult aStatus)
{
  nsresult rv = NS_OK;
  AutoEditBatch batchIt(this);

  if (!mLastStyleSheetURL.IsEmpty())
    RemoveStyleSheet(mLastStyleSheetURL);

  RefPtr<AddStyleSheetTransaction> transaction;
  rv = CreateTxnForAddStyleSheet(aSheet, getter_AddRefs(transaction));
  if (!transaction) {
    rv = NS_ERROR_NULL_POINTER;
  }
  if (NS_SUCCEEDED(rv)) {
    rv = DoTransaction(transaction);
    if (NS_SUCCEEDED(rv)) {
      // Get the URI, then url spec from the sheet
      nsAutoCString spec;
      rv = aSheet->GetSheetURI()->GetSpec(spec);

      if (NS_SUCCEEDED(rv)) {
        // Save it so we can remove before applying the next one
        mLastStyleSheetURL.AssignWithConversion(spec.get());

        // Also save in our arrays of urls and sheets
        AddNewStyleSheetToList(mLastStyleSheetURL, aSheet);
      }
    }
  }

  return NS_OK;
}

/**
 * All editor operations which alter the doc should be prefaced
 * with a call to StartOperation, naming the action and direction.
 */
NS_IMETHODIMP
HTMLEditor::StartOperation(EditAction opID,
                           nsIEditor::EDirection aDirection)
{
  // Protect the edit rules object from dying
  nsCOMPtr<nsIEditRules> rules(mRules);

  EditorBase::StartOperation(opID, aDirection);  // will set mAction, mDirection
  if (rules) {
    return rules->BeforeEdit(mAction, mDirection);
  }
  return NS_OK;
}

/**
 * All editor operations which alter the doc should be followed
 * with a call to EndOperation.
 */
NS_IMETHODIMP
HTMLEditor::EndOperation()
{
  // Protect the edit rules object from dying
  nsCOMPtr<nsIEditRules> rules(mRules);

  // post processing
  nsresult rv = rules ? rules->AfterEdit(mAction, mDirection) : NS_OK;
  EditorBase::EndOperation();  // will clear mAction, mDirection
  return rv;
}

bool
HTMLEditor::TagCanContainTag(nsIAtom& aParentTag,
                             nsIAtom& aChildTag)
{
  int32_t childTagEnum;
  // XXX Should this handle #cdata-section too?
  if (&aChildTag == nsGkAtoms::textTagName) {
    childTagEnum = eHTMLTag_text;
  } else {
    childTagEnum = nsHTMLTags::AtomTagToId(&aChildTag);
  }

  int32_t parentTagEnum = nsHTMLTags::AtomTagToId(&aParentTag);
  return HTMLEditUtils::CanContain(parentTagEnum, childTagEnum);
}

bool
HTMLEditor::IsContainer(nsINode* aNode)
{
  MOZ_ASSERT(aNode);

  int32_t tagEnum;
  // XXX Should this handle #cdata-section too?
  if (aNode->IsNodeOfType(nsINode::eTEXT)) {
    tagEnum = eHTMLTag_text;
  } else {
    tagEnum = nsHTMLTags::StringTagToId(aNode->NodeName());
  }

  return HTMLEditUtils::IsContainer(tagEnum);
}

bool
HTMLEditor::IsContainer(nsIDOMNode* aNode)
{
  nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
  if (!node) {
    return false;
  }
  return IsContainer(node);
}


nsresult
HTMLEditor::SelectEntireDocument(Selection* aSelection)
{
  if (!aSelection || !mRules) {
    return NS_ERROR_NULL_POINTER;
  }

  // Protect the edit rules object from dying
  nsCOMPtr<nsIEditRules> rules(mRules);

  // is doc empty?
  if (rules->DocumentIsEmpty()) {
    // get editor root node
    Element* rootElement = GetRoot();

    // if its empty dont select entire doc - that would select the bogus node
    return aSelection->Collapse(rootElement, 0);
  }

  return EditorBase::SelectEntireDocument(aSelection);
}

NS_IMETHODIMP
HTMLEditor::SelectAll()
{
  ForceCompositionEnd();

  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_STATE(selection);

  nsCOMPtr<nsIDOMNode> anchorNode;
  nsresult rv = selection->GetAnchorNode(getter_AddRefs(anchorNode));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIContent> anchorContent = do_QueryInterface(anchorNode, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsIContent *rootContent;
  if (anchorContent->HasIndependentSelection()) {
    rv = selection->SetAncestorLimiter(nullptr);
    NS_ENSURE_SUCCESS(rv, rv);
    rootContent = mRootElement;
  } else {
    nsCOMPtr<nsIPresShell> ps = GetPresShell();
    rootContent = anchorContent->GetSelectionRootContent(ps);
  }

  NS_ENSURE_TRUE(rootContent, NS_ERROR_UNEXPECTED);

  nsCOMPtr<nsIDOMNode> rootElement = do_QueryInterface(rootContent, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  Maybe<mozilla::dom::Selection::AutoUserInitiated> userSelection;
  if (!rootContent->IsEditable()) {
    userSelection.emplace(selection);
  }
  return selection->SelectAllChildren(rootElement);
}

// this will NOT find aAttribute unless aAttribute has a non-null value
// so singleton attributes like <Table border> will not be matched!
bool
HTMLEditor::IsTextPropertySetByContent(nsINode* aNode,
                                       nsIAtom* aProperty,
                                       const nsAString* aAttribute,
                                       const nsAString* aValue,
                                       nsAString* outValue)
{
  MOZ_ASSERT(aNode && aProperty);
  bool isSet;
  IsTextPropertySetByContent(aNode->AsDOMNode(), aProperty, aAttribute, aValue,
                             isSet, outValue);
  return isSet;
}

void
HTMLEditor::IsTextPropertySetByContent(nsIDOMNode* aNode,
                                       nsIAtom* aProperty,
                                       const nsAString* aAttribute,
                                       const nsAString* aValue,
                                       bool& aIsSet,
                                       nsAString* outValue)
{
  aIsSet = false;  // must be initialized to false for code below to work
  nsAutoString propName;
  aProperty->ToString(propName);
  nsCOMPtr<nsIDOMNode>node = aNode;

  while (node) {
    nsCOMPtr<nsIDOMElement>element;
    element = do_QueryInterface(node);
    if (element) {
      nsAutoString tag, value;
      element->GetTagName(tag);
      if (propName.Equals(tag, nsCaseInsensitiveStringComparator())) {
        bool found = false;
        if (aAttribute && !aAttribute->IsEmpty()) {
          element->GetAttribute(*aAttribute, value);
          if (outValue) {
            *outValue = value;
          }
          if (!value.IsEmpty()) {
            if (!aValue) {
              found = true;
            } else {
              nsString tString(*aValue);
              if (tString.Equals(value, nsCaseInsensitiveStringComparator())) {
                found = true;
              } else {
                // We found the prop with the attribute, but the value doesn't
                // match.
                break;
              }
            }
          }
        } else {
          found = true;
        }
        if (found) {
          aIsSet = true;
          break;
        }
      }
    }
    nsCOMPtr<nsIDOMNode>temp;
    if (NS_SUCCEEDED(node->GetParentNode(getter_AddRefs(temp))) && temp) {
      node = temp;
    } else {
      node = nullptr;
    }
  }
}

bool
HTMLEditor::SetCaretInTableCell(nsIDOMElement* aElement)
{
  nsCOMPtr<dom::Element> element = do_QueryInterface(aElement);
  if (!element || !element->IsHTMLElement() ||
      !HTMLEditUtils::IsTableElement(element) ||
      !IsDescendantOfEditorRoot(element)) {
    return false;
  }

  nsIContent* node = element;
  while (node->HasChildren()) {
    node = node->GetFirstChild();
  }

  // Set selection at beginning of the found node
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, false);

  return NS_SUCCEEDED(selection->CollapseNative(node, 0));
}

/**
 * GetEnclosingTable() finds ancestor who is a table, if any.
 */
Element*
HTMLEditor::GetEnclosingTable(nsINode* aNode)
{
  MOZ_ASSERT(aNode);

  for (nsCOMPtr<Element> block = GetBlockNodeParent(aNode);
       block;
       block = GetBlockNodeParent(block)) {
    if (HTMLEditUtils::IsTable(block)) {
      return block;
    }
  }
  return nullptr;
}

nsIDOMNode*
HTMLEditor::GetEnclosingTable(nsIDOMNode* aNode)
{
  NS_PRECONDITION(aNode, "null node passed to HTMLEditor::GetEnclosingTable");
  nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
  NS_ENSURE_TRUE(node, nullptr);
  nsCOMPtr<Element> table = GetEnclosingTable(node);
  nsCOMPtr<nsIDOMNode> ret = do_QueryInterface(table);
  return ret;
}


/**
 * This method scans the selection for adjacent text nodes
 * and collapses them into a single text node.
 * "adjacent" means literally adjacent siblings of the same parent.
 * Uses EditorBase::JoinNodes so action is undoable.
 * Should be called within the context of a batch transaction.
 */
nsresult
HTMLEditor::CollapseAdjacentTextNodes(nsRange* aInRange)
{
  NS_ENSURE_TRUE(aInRange, NS_ERROR_NULL_POINTER);
  AutoTransactionsConserveSelection dontSpazMySelection(this);
  nsTArray<nsCOMPtr<nsIDOMNode> > textNodes;
  // we can't actually do anything during iteration, so store the text nodes in an array
  // don't bother ref counting them because we know we can hold them for the
  // lifetime of this method


  // build a list of editable text nodes
  nsresult rv = NS_ERROR_UNEXPECTED;
  nsCOMPtr<nsIContentIterator> iter =
    do_CreateInstance("@mozilla.org/content/subtree-content-iterator;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  iter->Init(aInRange);

  while (!iter->IsDone()) {
    nsINode* node = iter->GetCurrentNode();
    if (node->NodeType() == nsIDOMNode::TEXT_NODE &&
        IsEditable(static_cast<nsIContent*>(node))) {
      nsCOMPtr<nsIDOMNode> domNode = do_QueryInterface(node);
      textNodes.AppendElement(domNode);
    }

    iter->Next();
  }

  // now that I have a list of text nodes, collapse adjacent text nodes
  // NOTE: assumption that JoinNodes keeps the righthand node
  while (textNodes.Length() > 1) {
    // we assume a textNodes entry can't be nullptr
    nsIDOMNode *leftTextNode = textNodes[0];
    nsIDOMNode *rightTextNode = textNodes[1];
    NS_ASSERTION(leftTextNode && rightTextNode,"left or rightTextNode null in CollapseAdjacentTextNodes");

    // get the prev sibling of the right node, and see if its leftTextNode
    nsCOMPtr<nsIDOMNode> prevSibOfRightNode;
    rv = rightTextNode->GetPreviousSibling(getter_AddRefs(prevSibOfRightNode));
    NS_ENSURE_SUCCESS(rv, rv);
    if (prevSibOfRightNode && prevSibOfRightNode == leftTextNode) {
      nsCOMPtr<nsIDOMNode> parent;
      rv = rightTextNode->GetParentNode(getter_AddRefs(parent));
      NS_ENSURE_SUCCESS(rv, rv);
      NS_ENSURE_TRUE(parent, NS_ERROR_NULL_POINTER);
      rv = JoinNodes(leftTextNode, rightTextNode, parent);
      NS_ENSURE_SUCCESS(rv, rv);
    }

    textNodes.RemoveElementAt(0); // remove the leftmost text node from the list
  }

  return NS_OK;
}

nsresult
HTMLEditor::SetSelectionAtDocumentStart(Selection* aSelection)
{
  dom::Element* rootElement = GetRoot();
  NS_ENSURE_TRUE(rootElement, NS_ERROR_NULL_POINTER);

  return aSelection->CollapseNative(rootElement, 0);
}

/**
 * Remove aNode, reparenting any children into the parent of aNode.  In
 * addition, insert any br's needed to preserve identity of removed block.
 */
nsresult
HTMLEditor::RemoveBlockContainer(nsIContent& aNode)
{
  // Two possibilities: the container could be empty of editable content.  If
  // that is the case, we need to compare what is before and after aNode to
  // determine if we need a br.
  //
  // Or it could be not empty, in which case we have to compare previous
  // sibling and first child to determine if we need a leading br, and compare
  // following sibling and last child to determine if we need a trailing br.

  nsCOMPtr<nsIContent> child = GetFirstEditableChild(aNode);

  if (child) {
    // The case of aNode not being empty.  We need a br at start unless:
    // 1) previous sibling of aNode is a block, OR
    // 2) previous sibling of aNode is a br, OR
    // 3) first child of aNode is a block OR
    // 4) either is null

    nsCOMPtr<nsIContent> sibling = GetPriorHTMLSibling(&aNode);
    if (sibling && !IsBlockNode(sibling) &&
        !sibling->IsHTMLElement(nsGkAtoms::br) && !IsBlockNode(child)) {
      // Insert br node
      nsCOMPtr<Element> br = CreateBR(&aNode, 0);
      NS_ENSURE_STATE(br);
    }

    // We need a br at end unless:
    // 1) following sibling of aNode is a block, OR
    // 2) last child of aNode is a block, OR
    // 3) last child of aNode is a br OR
    // 4) either is null

    sibling = GetNextHTMLSibling(&aNode);
    if (sibling && !IsBlockNode(sibling)) {
      child = GetLastEditableChild(aNode);
      MOZ_ASSERT(child, "aNode has first editable child but not last?");
      if (!IsBlockNode(child) && !child->IsHTMLElement(nsGkAtoms::br)) {
        // Insert br node
        nsCOMPtr<Element> br = CreateBR(&aNode, aNode.Length());
        NS_ENSURE_STATE(br);
      }
    }
  } else {
    // The case of aNode being empty.  We need a br at start unless:
    // 1) previous sibling of aNode is a block, OR
    // 2) previous sibling of aNode is a br, OR
    // 3) following sibling of aNode is a block, OR
    // 4) following sibling of aNode is a br OR
    // 5) either is null
    nsCOMPtr<nsIContent> sibling = GetPriorHTMLSibling(&aNode);
    if (sibling && !IsBlockNode(sibling) &&
        !sibling->IsHTMLElement(nsGkAtoms::br)) {
      sibling = GetNextHTMLSibling(&aNode);
      if (sibling && !IsBlockNode(sibling) &&
          !sibling->IsHTMLElement(nsGkAtoms::br)) {
        // Insert br node
        nsCOMPtr<Element> br = CreateBR(&aNode, 0);
        NS_ENSURE_STATE(br);
      }
    }
  }

  // Now remove container
  nsresult rv = RemoveContainer(&aNode);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

/**
 * GetPriorHTMLSibling() returns the previous editable sibling, if there is
 * one within the parent.
 */
nsIContent*
HTMLEditor::GetPriorHTMLSibling(nsINode* aNode)
{
  MOZ_ASSERT(aNode);

  nsIContent* node = aNode->GetPreviousSibling();
  while (node && !IsEditable(node)) {
    node = node->GetPreviousSibling();
  }

  return node;
}

nsresult
HTMLEditor::GetPriorHTMLSibling(nsIDOMNode* inNode,
                                nsCOMPtr<nsIDOMNode>* outNode)
{
  NS_ENSURE_TRUE(outNode, NS_ERROR_NULL_POINTER);
  *outNode = nullptr;

  nsCOMPtr<nsINode> node = do_QueryInterface(inNode);
  NS_ENSURE_TRUE(node, NS_ERROR_NULL_POINTER);

  *outNode = do_QueryInterface(GetPriorHTMLSibling(node));
  return NS_OK;
}

/**
 * GetPriorHTMLSibling() returns the previous editable sibling, if there is
 * one within the parent.  just like above routine but takes a parent/offset
 * instead of a node.
 */
nsIContent*
HTMLEditor::GetPriorHTMLSibling(nsINode* aParent,
                                int32_t aOffset)
{
  MOZ_ASSERT(aParent);

  nsIContent* node = aParent->GetChildAt(aOffset - 1);
  if (!node || IsEditable(node)) {
    return node;
  }

  return GetPriorHTMLSibling(node);
}

nsresult
HTMLEditor::GetPriorHTMLSibling(nsIDOMNode* inParent,
                                int32_t inOffset,
                                nsCOMPtr<nsIDOMNode>* outNode)
{
  NS_ENSURE_TRUE(outNode, NS_ERROR_NULL_POINTER);
  *outNode = nullptr;

  nsCOMPtr<nsINode> parent = do_QueryInterface(inParent);
  NS_ENSURE_TRUE(parent, NS_ERROR_NULL_POINTER);

  *outNode = do_QueryInterface(GetPriorHTMLSibling(parent, inOffset));
  return NS_OK;
}

/**
 * GetNextHTMLSibling() returns the next editable sibling, if there is
 * one within the parent.
 */
nsIContent*
HTMLEditor::GetNextHTMLSibling(nsINode* aNode)
{
  MOZ_ASSERT(aNode);

  nsIContent* node = aNode->GetNextSibling();
  while (node && !IsEditable(node)) {
    node = node->GetNextSibling();
  }

  return node;
}

nsresult
HTMLEditor::GetNextHTMLSibling(nsIDOMNode* inNode,
                               nsCOMPtr<nsIDOMNode>* outNode)
{
  NS_ENSURE_TRUE(outNode, NS_ERROR_NULL_POINTER);
  *outNode = nullptr;

  nsCOMPtr<nsINode> node = do_QueryInterface(inNode);
  NS_ENSURE_TRUE(node, NS_ERROR_NULL_POINTER);

  *outNode = do_QueryInterface(GetNextHTMLSibling(node));
  return NS_OK;
}

/**
 * GetNextHTMLSibling() returns the next editable sibling, if there is
 * one within the parent.  just like above routine but takes a parent/offset
 * instead of a node.
 */
nsIContent*
HTMLEditor::GetNextHTMLSibling(nsINode* aParent,
                               int32_t aOffset)
{
  MOZ_ASSERT(aParent);

  nsIContent* node = aParent->GetChildAt(aOffset + 1);
  if (!node || IsEditable(node)) {
    return node;
  }

  return GetNextHTMLSibling(node);
}

nsresult
HTMLEditor::GetNextHTMLSibling(nsIDOMNode* inParent,
                               int32_t inOffset,
                               nsCOMPtr<nsIDOMNode>* outNode)
{
  NS_ENSURE_TRUE(outNode, NS_ERROR_NULL_POINTER);
  *outNode = nullptr;

  nsCOMPtr<nsINode> parent = do_QueryInterface(inParent);
  NS_ENSURE_TRUE(parent, NS_ERROR_NULL_POINTER);

  *outNode = do_QueryInterface(GetNextHTMLSibling(parent, inOffset));
  return NS_OK;
}

/**
 * GetPriorHTMLNode() returns the previous editable leaf node, if there is
 * one within the <body>.
 */
nsIContent*
HTMLEditor::GetPriorHTMLNode(nsINode* aNode,
                             bool aNoBlockCrossing)
{
  MOZ_ASSERT(aNode);

  if (!GetActiveEditingHost()) {
    return nullptr;
  }

  return GetPriorNode(aNode, true, aNoBlockCrossing);
}

nsresult
HTMLEditor::GetPriorHTMLNode(nsIDOMNode* aNode,
                             nsCOMPtr<nsIDOMNode>* aResultNode,
                             bool aNoBlockCrossing)
{
  NS_ENSURE_TRUE(aResultNode, NS_ERROR_NULL_POINTER);

  nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
  NS_ENSURE_TRUE(node, NS_ERROR_NULL_POINTER);

  *aResultNode = do_QueryInterface(GetPriorHTMLNode(node, aNoBlockCrossing));
  return NS_OK;
}

/**
 * GetPriorHTMLNode() is same as above but takes {parent,offset} instead of
 * node.
 */
nsIContent*
HTMLEditor::GetPriorHTMLNode(nsINode* aParent,
                             int32_t aOffset,
                             bool aNoBlockCrossing)
{
  MOZ_ASSERT(aParent);

  if (!GetActiveEditingHost()) {
    return nullptr;
  }

  return GetPriorNode(aParent, aOffset, true, aNoBlockCrossing);
}

nsresult
HTMLEditor::GetPriorHTMLNode(nsIDOMNode* aNode,
                             int32_t aOffset,
                             nsCOMPtr<nsIDOMNode>* aResultNode,
                             bool aNoBlockCrossing)
{
  NS_ENSURE_TRUE(aResultNode, NS_ERROR_NULL_POINTER);

  nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
  NS_ENSURE_TRUE(node, NS_ERROR_NULL_POINTER);

  *aResultNode = do_QueryInterface(GetPriorHTMLNode(node, aOffset,
                                                    aNoBlockCrossing));
  return NS_OK;
}

/**
 * GetNextHTMLNode() returns the next editable leaf node, if there is
 * one within the <body>.
 */
nsIContent*
HTMLEditor::GetNextHTMLNode(nsINode* aNode,
                            bool aNoBlockCrossing)
{
  MOZ_ASSERT(aNode);

  nsIContent* result = GetNextNode(aNode, true, aNoBlockCrossing);

  if (result && !IsDescendantOfEditorRoot(result)) {
    return nullptr;
  }

  return result;
}

nsresult
HTMLEditor::GetNextHTMLNode(nsIDOMNode* aNode,
                            nsCOMPtr<nsIDOMNode>* aResultNode,
                            bool aNoBlockCrossing)
{
  NS_ENSURE_TRUE(aResultNode, NS_ERROR_NULL_POINTER);

  nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
  NS_ENSURE_TRUE(node, NS_ERROR_NULL_POINTER);

  *aResultNode = do_QueryInterface(GetNextHTMLNode(node, aNoBlockCrossing));
  return NS_OK;
}

/**
 * GetNextHTMLNode() is same as above but takes {parent,offset} instead of node.
 */
nsIContent*
HTMLEditor::GetNextHTMLNode(nsINode* aParent,
                            int32_t aOffset,
                            bool aNoBlockCrossing)
{
  nsIContent* content = GetNextNode(aParent, aOffset, true, aNoBlockCrossing);
  if (content && !IsDescendantOfEditorRoot(content)) {
    return nullptr;
  }
  return content;
}

nsresult
HTMLEditor::GetNextHTMLNode(nsIDOMNode* aNode,
                            int32_t aOffset,
                            nsCOMPtr<nsIDOMNode>* aResultNode,
                            bool aNoBlockCrossing)
{
  NS_ENSURE_TRUE(aResultNode, NS_ERROR_NULL_POINTER);

  nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
  NS_ENSURE_TRUE(node, NS_ERROR_NULL_POINTER);

  *aResultNode = do_QueryInterface(GetNextHTMLNode(node, aOffset,
                                                   aNoBlockCrossing));
  return NS_OK;
}

nsresult
HTMLEditor::IsFirstEditableChild(nsIDOMNode* aNode,
                                 bool* aOutIsFirst)
{
  nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
  NS_ENSURE_TRUE(aOutIsFirst && node, NS_ERROR_NULL_POINTER);

  // init out parms
  *aOutIsFirst = false;

  // find first editable child and compare it to aNode
  nsCOMPtr<nsINode> parent = node->GetParentNode();
  NS_ENSURE_TRUE(parent, NS_ERROR_FAILURE);

  *aOutIsFirst = (GetFirstEditableChild(*parent) == node);
  return NS_OK;
}

nsresult
HTMLEditor::IsLastEditableChild(nsIDOMNode* aNode,
                                bool* aOutIsLast)
{
  nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
  NS_ENSURE_TRUE(aOutIsLast && node, NS_ERROR_NULL_POINTER);

  // init out parms
  *aOutIsLast = false;

  // find last editable child and compare it to aNode
  nsCOMPtr<nsINode> parent = node->GetParentNode();
  NS_ENSURE_TRUE(parent, NS_ERROR_FAILURE);

  *aOutIsLast = (GetLastEditableChild(*parent) == node);
  return NS_OK;
}

nsIContent*
HTMLEditor::GetFirstEditableChild(nsINode& aNode)
{
  nsCOMPtr<nsIContent> child = aNode.GetFirstChild();

  while (child && !IsEditable(child)) {
    child = child->GetNextSibling();
  }

  return child;
}

nsIContent*
HTMLEditor::GetLastEditableChild(nsINode& aNode)
{
  nsCOMPtr<nsIContent> child = aNode.GetLastChild();

  while (child && !IsEditable(child)) {
    child = child->GetPreviousSibling();
  }

  return child;
}

nsIContent*
HTMLEditor::GetFirstEditableLeaf(nsINode& aNode)
{
  nsCOMPtr<nsIContent> child = GetLeftmostChild(&aNode);
  while (child && (!IsEditable(child) || child->HasChildren())) {
    child = GetNextHTMLNode(child);

    // Only accept nodes that are descendants of aNode
    if (!aNode.Contains(child)) {
      return nullptr;
    }
  }

  return child;
}

nsIContent*
HTMLEditor::GetLastEditableLeaf(nsINode& aNode)
{
  nsCOMPtr<nsIContent> child = GetRightmostChild(&aNode, false);
  while (child && (!IsEditable(child) || child->HasChildren())) {
    child = GetPriorHTMLNode(child);

    // Only accept nodes that are descendants of aNode
    if (!aNode.Contains(child)) {
      return nullptr;
    }
  }

  return child;
}

/**
 * IsVisTextNode() figures out if textnode aTextNode has any visible content.
 */
nsresult
HTMLEditor::IsVisTextNode(nsIContent* aNode,
                          bool* outIsEmptyNode,
                          bool aSafeToAskFrames)
{
  MOZ_ASSERT(aNode);
  MOZ_ASSERT(aNode->NodeType() == nsIDOMNode::TEXT_NODE);
  MOZ_ASSERT(outIsEmptyNode);

  *outIsEmptyNode = true;

  uint32_t length = aNode->TextLength();
  if (aSafeToAskFrames) {
    nsCOMPtr<nsISelectionController> selectionController =
      GetSelectionController();
    if (NS_WARN_IF(!selectionController)) {
      return NS_ERROR_FAILURE;
    }
    bool isVisible = false;
    // ask the selection controller for information about whether any
    // of the data in the node is really rendered.  This is really
    // something that frames know about, but we aren't supposed to talk to frames.
    // So we put a call in the selection controller interface, since it's already
    // in bed with frames anyway.  (this is a fix for bug 22227, and a
    // partial fix for bug 46209)
    nsresult rv = selectionController->CheckVisibilityContent(aNode, 0, length,
                                                              &isVisible);
    NS_ENSURE_SUCCESS(rv, rv);
    if (isVisible) {
      *outIsEmptyNode = false;
    }
  } else if (length) {
    if (aNode->TextIsOnlyWhitespace()) {
      WSRunObject wsRunObj(this, aNode, 0);
      nsCOMPtr<nsINode> visNode;
      int32_t outVisOffset=0;
      WSType visType;
      wsRunObj.NextVisibleNode(aNode, 0, address_of(visNode),
                               &outVisOffset, &visType);
      if (visType == WSType::normalWS || visType == WSType::text) {
        *outIsEmptyNode = (aNode != visNode);
      }
    } else {
      *outIsEmptyNode = false;
    }
  }
  return NS_OK;
}

/**
 * IsEmptyNode() figures out if aNode is an empty node.  A block can have
 * children and still be considered empty, if the children are empty or
 * non-editable.
 */
nsresult
HTMLEditor::IsEmptyNode(nsIDOMNode*aNode,
                        bool* outIsEmptyNode,
                        bool aSingleBRDoesntCount,
                        bool aListOrCellNotEmpty,
                        bool aSafeToAskFrames)
{
  nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
  return IsEmptyNode(node, outIsEmptyNode, aSingleBRDoesntCount,
                     aListOrCellNotEmpty, aSafeToAskFrames);
}

nsresult
HTMLEditor::IsEmptyNode(nsINode* aNode,
                        bool* outIsEmptyNode,
                        bool aSingleBRDoesntCount,
                        bool aListOrCellNotEmpty,
                        bool aSafeToAskFrames)
{
  NS_ENSURE_TRUE(aNode && outIsEmptyNode, NS_ERROR_NULL_POINTER);
  *outIsEmptyNode = true;
  bool seenBR = false;
  return IsEmptyNodeImpl(aNode, outIsEmptyNode, aSingleBRDoesntCount,
                         aListOrCellNotEmpty, aSafeToAskFrames, &seenBR);
}

/**
 * IsEmptyNodeImpl() is workhorse for IsEmptyNode().
 */
nsresult
HTMLEditor::IsEmptyNodeImpl(nsINode* aNode,
                            bool* outIsEmptyNode,
                            bool aSingleBRDoesntCount,
                            bool aListOrCellNotEmpty,
                            bool aSafeToAskFrames,
                            bool* aSeenBR)
{
  NS_ENSURE_TRUE(aNode && outIsEmptyNode && aSeenBR, NS_ERROR_NULL_POINTER);

  if (aNode->NodeType() == nsIDOMNode::TEXT_NODE) {
    return IsVisTextNode(static_cast<nsIContent*>(aNode), outIsEmptyNode, aSafeToAskFrames);
  }

  // if it's not a text node (handled above) and it's not a container,
  // then we don't call it empty (it's an <hr>, or <br>, etc.).
  // Also, if it's an anchor then don't treat it as empty - even though
  // anchors are containers, named anchors are "empty" but we don't
  // want to treat them as such.  Also, don't call ListItems or table
  // cells empty if caller desires.  Form Widgets not empty.
  if (!IsContainer(aNode->AsDOMNode()) ||
      (HTMLEditUtils::IsNamedAnchor(aNode) ||
       HTMLEditUtils::IsFormWidget(aNode) ||
       (aListOrCellNotEmpty &&
        (HTMLEditUtils::IsListItem(aNode) ||
         HTMLEditUtils::IsTableCell(aNode))))) {
    *outIsEmptyNode = false;
    return NS_OK;
  }

  // need this for later
  bool isListItemOrCell = HTMLEditUtils::IsListItem(aNode) ||
                          HTMLEditUtils::IsTableCell(aNode);

  // loop over children of node. if no children, or all children are either
  // empty text nodes or non-editable, then node qualifies as empty
  for (nsCOMPtr<nsIContent> child = aNode->GetFirstChild();
       child;
       child = child->GetNextSibling()) {
    // Is the child editable and non-empty?  if so, return false
    if (EditorBase::IsEditable(child)) {
      if (child->NodeType() == nsIDOMNode::TEXT_NODE) {
        nsresult rv = IsVisTextNode(child, outIsEmptyNode, aSafeToAskFrames);
        NS_ENSURE_SUCCESS(rv, rv);
        // break out if we find we aren't emtpy
        if (!*outIsEmptyNode) {
          return NS_OK;
        }
      } else {
        // An editable, non-text node. We need to check its content.
        // Is it the node we are iterating over?
        if (child == aNode) {
          break;
        }

        if (aSingleBRDoesntCount && !*aSeenBR && child->IsHTMLElement(nsGkAtoms::br)) {
          // the first br in a block doesn't count if the caller so indicated
          *aSeenBR = true;
        } else {
          // is it an empty node of some sort?
          // note: list items or table cells are not considered empty
          // if they contain other lists or tables
          if (child->IsElement()) {
            if (isListItemOrCell) {
              if (HTMLEditUtils::IsList(child) ||
                  child->IsHTMLElement(nsGkAtoms::table)) {
                // break out if we find we aren't empty
                *outIsEmptyNode = false;
                return NS_OK;
              }
            } else if (HTMLEditUtils::IsFormWidget(child)) {
              // is it a form widget?
              // break out if we find we aren't empty
              *outIsEmptyNode = false;
              return NS_OK;
            }
          }

          bool isEmptyNode = true;
          nsresult rv = IsEmptyNodeImpl(child, &isEmptyNode,
                                        aSingleBRDoesntCount,
                                        aListOrCellNotEmpty, aSafeToAskFrames,
                                        aSeenBR);
          NS_ENSURE_SUCCESS(rv, rv);
          if (!isEmptyNode) {
            // otherwise it ain't empty
            *outIsEmptyNode = false;
            return NS_OK;
          }
        }
      }
    }
  }

  return NS_OK;
}

// add to aElement the CSS inline styles corresponding to the HTML attribute
// aAttribute with its value aValue
nsresult
HTMLEditor::SetAttributeOrEquivalent(Element* aElement,
                                     nsIAtom* aAttribute,
                                     const nsAString& aValue,
                                     bool aSuppressTransaction)
{
  MOZ_ASSERT(aElement);
  MOZ_ASSERT(aAttribute);

  nsAutoScriptBlocker scriptBlocker;

  if (!IsCSSEnabled() || !mCSSEditUtils) {
    // we are not in an HTML+CSS editor; let's set the attribute the HTML way
    return aSuppressTransaction ?
             aElement->SetAttr(kNameSpaceID_None, aAttribute, aValue, true) :
             SetAttribute(aElement, aAttribute, aValue);
  }

  int32_t count =
    mCSSEditUtils->SetCSSEquivalentToHTMLStyle(aElement, nullptr,
                                               aAttribute, &aValue,
                                               aSuppressTransaction);
  if (count) {
    // we found an equivalence ; let's remove the HTML attribute itself if it
    // is set
    nsAutoString existingValue;
    if (!aElement->GetAttr(kNameSpaceID_None, aAttribute, existingValue)) {
      return NS_OK;
    }

    return aSuppressTransaction ?
             aElement->UnsetAttr(kNameSpaceID_None, aAttribute, true) :
             RemoveAttribute(aElement, aAttribute);
  }

  // count is an integer that represents the number of CSS declarations applied
  // to the element. If it is zero, we found no equivalence in this
  // implementation for the attribute
  if (aAttribute == nsGkAtoms::style) {
    // if it is the style attribute, just add the new value to the existing
    // style attribute's value
    nsAutoString existingValue;
    aElement->GetAttr(kNameSpaceID_None, nsGkAtoms::style, existingValue);
    existingValue.Append(' ');
    existingValue.Append(aValue);
    return aSuppressTransaction ?
       aElement->SetAttr(kNameSpaceID_None, aAttribute, existingValue, true) :
      SetAttribute(aElement, aAttribute, existingValue);
  }

  // we have no CSS equivalence for this attribute and it is not the style
  // attribute; let's set it the good'n'old HTML way
  return aSuppressTransaction ?
           aElement->SetAttr(kNameSpaceID_None, aAttribute, aValue, true) :
           SetAttribute(aElement, aAttribute, aValue);
}

nsresult
HTMLEditor::RemoveAttributeOrEquivalent(Element* aElement,
                                        nsIAtom* aAttribute,
                                        bool aSuppressTransaction)
{
  MOZ_ASSERT(aElement);
  MOZ_ASSERT(aAttribute);

  if (IsCSSEnabled() && mCSSEditUtils) {
    nsresult rv =
      mCSSEditUtils->RemoveCSSEquivalentToHTMLStyle(
        aElement, nullptr, aAttribute, nullptr, aSuppressTransaction);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  if (!aElement->HasAttr(kNameSpaceID_None, aAttribute)) {
    return NS_OK;
  }

  return aSuppressTransaction ?
    aElement->UnsetAttr(kNameSpaceID_None, aAttribute, /* aNotify = */ true) :
    RemoveAttribute(aElement, aAttribute);
}

nsresult
HTMLEditor::SetIsCSSEnabled(bool aIsCSSPrefChecked)
{
  if (!mCSSEditUtils) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  mCSSEditUtils->SetCSSEnabled(aIsCSSPrefChecked);

  // Disable the eEditorNoCSSMask flag if we're enabling StyleWithCSS.
  uint32_t flags = mFlags;
  if (aIsCSSPrefChecked) {
    // Turn off NoCSS as we're enabling CSS
    flags &= ~eEditorNoCSSMask;
  } else {
    // Turn on NoCSS, as we're disabling CSS.
    flags |= eEditorNoCSSMask;
  }

  return SetFlags(flags);
}

// Set the block background color
nsresult
HTMLEditor::SetCSSBackgroundColor(const nsAString& aColor)
{
  NS_ENSURE_TRUE(mRules, NS_ERROR_NOT_INITIALIZED);
  ForceCompositionEnd();

  // Protect the edit rules object from dying
  nsCOMPtr<nsIEditRules> rules(mRules);

  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_STATE(selection);

  bool isCollapsed = selection->Collapsed();

  AutoEditBatch batchIt(this);
  AutoRules beginRulesSniffing(this, EditAction::insertElement,
                               nsIEditor::eNext);
  AutoSelectionRestorer selectionRestorer(selection, this);
  AutoTransactionsConserveSelection dontSpazMySelection(this);

  bool cancel, handled;
  TextRulesInfo ruleInfo(EditAction::setTextProperty);
  nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
  NS_ENSURE_SUCCESS(rv, rv);
  if (!cancel && !handled) {
    // Loop through the ranges in the selection
    for (uint32_t i = 0; i < selection->RangeCount(); i++) {
      RefPtr<nsRange> range = selection->GetRangeAt(i);
      NS_ENSURE_TRUE(range, NS_ERROR_FAILURE);

      nsCOMPtr<Element> cachedBlockParent;

      // Check for easy case: both range endpoints in same text node
      nsCOMPtr<nsINode> startNode = range->GetStartParent();
      int32_t startOffset = range->StartOffset();
      nsCOMPtr<nsINode> endNode = range->GetEndParent();
      int32_t endOffset = range->EndOffset();
      if (startNode == endNode && IsTextNode(startNode)) {
        // Let's find the block container of the text node
        nsCOMPtr<Element> blockParent = GetBlockNodeParent(startNode);
        // And apply the background color to that block container
        if (blockParent && cachedBlockParent != blockParent) {
          cachedBlockParent = blockParent;
          mCSSEditUtils->SetCSSEquivalentToHTMLStyle(blockParent, nullptr,
                                                     nsGkAtoms::bgcolor,
                                                     &aColor, false);
        }
      } else if (startNode == endNode &&
                 startNode->IsHTMLElement(nsGkAtoms::body) && isCollapsed) {
        // No block in the document, let's apply the background to the body
        mCSSEditUtils->SetCSSEquivalentToHTMLStyle(startNode->AsElement(),
                                                   nullptr, nsGkAtoms::bgcolor,
                                                   &aColor,
                                                   false);
      } else if (startNode == endNode && (endOffset - startOffset == 1 ||
                                          (!startOffset && !endOffset))) {
        // A unique node is selected, let's also apply the background color to
        // the containing block, possibly the node itself
        nsCOMPtr<nsIContent> selectedNode = startNode->GetChildAt(startOffset);
        nsCOMPtr<Element> blockParent = GetBlock(*selectedNode);
        if (blockParent && cachedBlockParent != blockParent) {
          cachedBlockParent = blockParent;
          mCSSEditUtils->SetCSSEquivalentToHTMLStyle(blockParent, nullptr,
                                                     nsGkAtoms::bgcolor,
                                                     &aColor, false);
        }
      } else {
        // Not the easy case.  Range not contained in single text node.  There
        // are up to three phases here.  There are all the nodes reported by
        // the subtree iterator to be processed.  And there are potentially a
        // starting textnode and an ending textnode which are only partially
        // contained by the range.

        // Let's handle the nodes reported by the iterator.  These nodes are
        // entirely contained in the selection range.  We build up a list of
        // them (since doing operations on the document during iteration would
        // perturb the iterator).

        OwningNonNull<nsIContentIterator> iter =
          NS_NewContentSubtreeIterator();

        nsTArray<OwningNonNull<nsINode>> arrayOfNodes;
        nsCOMPtr<nsINode> node;

        // Iterate range and build up array
        rv = iter->Init(range);
        // Init returns an error if no nodes in range.  This can easily happen
        // with the subtree iterator if the selection doesn't contain any
        // *whole* nodes.
        if (NS_SUCCEEDED(rv)) {
          for (; !iter->IsDone(); iter->Next()) {
            node = do_QueryInterface(iter->GetCurrentNode());
            NS_ENSURE_TRUE(node, NS_ERROR_FAILURE);

            if (IsEditable(node)) {
              arrayOfNodes.AppendElement(*node);
            }
          }
        }
        // First check the start parent of the range to see if it needs to be
        // separately handled (it does if it's a text node, due to how the
        // subtree iterator works - it will not have reported it).
        if (IsTextNode(startNode) && IsEditable(startNode)) {
          nsCOMPtr<Element> blockParent = GetBlockNodeParent(startNode);
          if (blockParent && cachedBlockParent != blockParent) {
            cachedBlockParent = blockParent;
            mCSSEditUtils->SetCSSEquivalentToHTMLStyle(blockParent, nullptr,
                                                       nsGkAtoms::bgcolor,
                                                       &aColor,
                                                       false);
          }
        }

        // Then loop through the list, set the property on each node
        for (auto& node : arrayOfNodes) {
          nsCOMPtr<Element> blockParent = GetBlock(node);
          if (blockParent && cachedBlockParent != blockParent) {
            cachedBlockParent = blockParent;
            mCSSEditUtils->SetCSSEquivalentToHTMLStyle(blockParent, nullptr,
                                                       nsGkAtoms::bgcolor,
                                                       &aColor,
                                                       false);
          }
        }
        arrayOfNodes.Clear();

        // Last, check the end parent of the range to see if it needs to be
        // separately handled (it does if it's a text node, due to how the
        // subtree iterator works - it will not have reported it).
        if (IsTextNode(endNode) && IsEditable(endNode)) {
          nsCOMPtr<Element> blockParent = GetBlockNodeParent(endNode);
          if (blockParent && cachedBlockParent != blockParent) {
            cachedBlockParent = blockParent;
            mCSSEditUtils->SetCSSEquivalentToHTMLStyle(blockParent, nullptr,
                                                       nsGkAtoms::bgcolor,
                                                       &aColor,
                                                       false);
          }
        }
      }
    }
  }
  if (!cancel) {
    // Post-process
    rv = rules->DidDoAction(selection, &ruleInfo, rv);
    NS_ENSURE_SUCCESS(rv, rv);
  }
  return NS_OK;
}

NS_IMETHODIMP
HTMLEditor::SetBackgroundColor(const nsAString& aColor)
{
  if (IsCSSEnabled()) {
    // if we are in CSS mode, we have to apply the background color to the
    // containing block (or the body if we have no block-level element in
    // the document)
    return SetCSSBackgroundColor(aColor);
  }

  // but in HTML mode, we can only set the document's background color
  return SetHTMLBackgroundColor(aColor);
}

/**
 * NodesSameType() does these nodes have the same tag?
 */
bool
HTMLEditor::AreNodesSameType(nsIContent* aNode1,
                             nsIContent* aNode2)
{
  MOZ_ASSERT(aNode1);
  MOZ_ASSERT(aNode2);

  if (aNode1->NodeInfo()->NameAtom() != aNode2->NodeInfo()->NameAtom()) {
    return false;
  }

  if (!IsCSSEnabled() || !aNode1->IsHTMLElement(nsGkAtoms::span)) {
    return true;
  }

  // If CSS is enabled, we are stricter about span nodes.
  return mCSSEditUtils->ElementsSameStyle(aNode1->AsDOMNode(),
                                          aNode2->AsDOMNode());
}

nsresult
HTMLEditor::CopyLastEditableChildStyles(nsIDOMNode* aPreviousBlock,
                                        nsIDOMNode* aNewBlock,
                                        Element** aOutBrNode)
{
  nsCOMPtr<nsINode> newBlock = do_QueryInterface(aNewBlock);
  NS_ENSURE_STATE(newBlock || !aNewBlock);
  *aOutBrNode = nullptr;
  nsCOMPtr<nsIDOMNode> child, tmp;
  // first, clear out aNewBlock.  Contract is that we want only the styles from previousBlock.
  nsresult rv = aNewBlock->GetFirstChild(getter_AddRefs(child));
  while (NS_SUCCEEDED(rv) && child) {
    rv = DeleteNode(child);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = aNewBlock->GetFirstChild(getter_AddRefs(child));
  }
  // now find and clone the styles
  child = aPreviousBlock;
  tmp = aPreviousBlock;
  while (tmp) {
    child = tmp;
    nsCOMPtr<nsINode> child_ = do_QueryInterface(child);
    NS_ENSURE_STATE(child_ || !child);
    tmp = GetAsDOMNode(GetLastEditableChild(*child_));
  }
  while (child && TextEditUtils::IsBreak(child)) {
    nsCOMPtr<nsIDOMNode> priorNode;
    rv = GetPriorHTMLNode(child, address_of(priorNode));
    NS_ENSURE_SUCCESS(rv, rv);
    child = priorNode;
  }
  nsCOMPtr<Element> newStyles, deepestStyle;
  nsCOMPtr<nsINode> childNode = do_QueryInterface(child);
  nsCOMPtr<Element> childElement;
  if (childNode) {
    childElement = childNode->IsElement() ? childNode->AsElement()
                                          : childNode->GetParentElement();
  }
  while (childElement && (childElement->AsDOMNode() != aPreviousBlock)) {
    if (HTMLEditUtils::IsInlineStyle(childElement) ||
        childElement->IsHTMLElement(nsGkAtoms::span)) {
      if (newStyles) {
        newStyles = InsertContainerAbove(newStyles,
                                         childElement->NodeInfo()->NameAtom());
        NS_ENSURE_STATE(newStyles);
      } else {
        deepestStyle = newStyles =
          CreateNode(childElement->NodeInfo()->NameAtom(), newBlock, 0);
        NS_ENSURE_STATE(newStyles);
      }
      CloneAttributes(newStyles, childElement);
    }
    childElement = childElement->GetParentElement();
  }
  if (deepestStyle) {
    RefPtr<Element> retVal = CreateBR(deepestStyle, 0);
    retVal.forget(aOutBrNode);
    NS_ENSURE_STATE(*aOutBrNode);
  }
  return NS_OK;
}

nsresult
HTMLEditor::GetElementOrigin(nsIDOMElement* aElement,
                             int32_t& aX,
                             int32_t& aY)
{
  aX = 0;
  aY = 0;

  if (NS_WARN_IF(!IsInitialized())) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  nsCOMPtr<nsIPresShell> ps = GetPresShell();
  NS_ENSURE_TRUE(ps, NS_ERROR_NOT_INITIALIZED);

  nsCOMPtr<nsIContent> content = do_QueryInterface(aElement);
  nsIFrame *frame = content->GetPrimaryFrame();
  NS_ENSURE_TRUE(frame, NS_OK);

  nsIFrame *container = ps->GetAbsoluteContainingBlock(frame);
  NS_ENSURE_TRUE(container, NS_OK);
  nsPoint off = frame->GetOffsetTo(container);
  aX = nsPresContext::AppUnitsToIntCSSPixels(off.x);
  aY = nsPresContext::AppUnitsToIntCSSPixels(off.y);

  return NS_OK;
}

nsresult
HTMLEditor::EndUpdateViewBatch()
{
  nsresult rv = EditorBase::EndUpdateViewBatch();
  NS_ENSURE_SUCCESS(rv, rv);

  if (mUpdateCount) {
    return NS_OK;
  }

  // We may need to show resizing handles or update existing ones after
  // all transactions are done. This way of doing is preferred to DOM
  // mutation events listeners because all the changes the user can apply
  // to a document may result in multiple events, some of them quite hard
  // to listen too (in particular when an ancestor of the selection is
  // changed but the selection itself is not changed).
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, NS_ERROR_NOT_INITIALIZED);
  return CheckSelectionStateForAnonymousButtons(selection);
}

NS_IMETHODIMP
HTMLEditor::GetSelectionContainer(nsIDOMElement** aReturn)
{
  nsCOMPtr<nsIDOMElement> container =
    static_cast<nsIDOMElement*>(GetAsDOMNode(GetSelectionContainer()));
  NS_ENSURE_TRUE(container, NS_ERROR_FAILURE);
  container.forget(aReturn);
  return NS_OK;
}

Element*
HTMLEditor::GetSelectionContainer()
{
  // If we don't get the selection, just skip this
  NS_ENSURE_TRUE(GetSelection(), nullptr);

  OwningNonNull<Selection> selection = *GetSelection();

  nsCOMPtr<nsINode> focusNode;

  if (selection->Collapsed()) {
    focusNode = selection->GetFocusNode();
  } else {
    int32_t rangeCount = selection->RangeCount();

    if (rangeCount == 1) {
      RefPtr<nsRange> range = selection->GetRangeAt(0);

      nsCOMPtr<nsINode> startContainer = range->GetStartParent();
      int32_t startOffset = range->StartOffset();
      nsCOMPtr<nsINode> endContainer = range->GetEndParent();
      int32_t endOffset = range->EndOffset();

      if (startContainer == endContainer && startOffset + 1 == endOffset) {
        nsCOMPtr<nsIDOMElement> focusElement;
        nsresult rv = GetSelectedElement(EmptyString(),
                                         getter_AddRefs(focusElement));
        NS_ENSURE_SUCCESS(rv, nullptr);
        if (focusElement) {
          focusNode = do_QueryInterface(focusElement);
        }
      }
      if (!focusNode) {
        focusNode = range->GetCommonAncestor();
      }
    } else {
      for (int32_t i = 0; i < rangeCount; i++) {
        RefPtr<nsRange> range = selection->GetRangeAt(i);

        nsCOMPtr<nsINode> startContainer = range->GetStartParent();
        if (!focusNode) {
          focusNode = startContainer;
        } else if (focusNode != startContainer) {
          focusNode = startContainer->GetParentNode();
          break;
        }
      }
    }
  }

  if (focusNode && focusNode->GetAsText()) {
    focusNode = focusNode->GetParentNode();
  }

  if (focusNode && focusNode->IsElement()) {
    return focusNode->AsElement();
  }

  return nullptr;
}

NS_IMETHODIMP
HTMLEditor::IsAnonymousElement(nsIDOMElement* aElement,
                               bool* aReturn)
{
  NS_ENSURE_TRUE(aElement, NS_ERROR_NULL_POINTER);
  nsCOMPtr<nsIContent> content = do_QueryInterface(aElement);
  *aReturn = content->IsRootOfNativeAnonymousSubtree();
  return NS_OK;
}

nsresult
HTMLEditor::SetReturnInParagraphCreatesNewParagraph(bool aCreatesNewParagraph)
{
  mCRInParagraphCreatesParagraph = aCreatesNewParagraph;
  return NS_OK;
}

bool
HTMLEditor::GetReturnInParagraphCreatesNewParagraph()
{
  return mCRInParagraphCreatesParagraph;
}

nsresult
HTMLEditor::GetReturnInParagraphCreatesNewParagraph(bool* aCreatesNewParagraph)
{
  *aCreatesNewParagraph = mCRInParagraphCreatesParagraph;
  return NS_OK;
}

already_AddRefed<nsIContent>
HTMLEditor::GetFocusedContent()
{
  nsFocusManager* fm = nsFocusManager::GetFocusManager();
  NS_ENSURE_TRUE(fm, nullptr);

  nsCOMPtr<nsIContent> focusedContent = fm->GetFocusedContent();

  nsCOMPtr<nsIDocument> document = GetDocument();
  if (NS_WARN_IF(!document)) {
    return nullptr;
  }
  bool inDesignMode = document->HasFlag(NODE_IS_EDITABLE);
  if (!focusedContent) {
    // in designMode, nobody gets focus in most cases.
    if (inDesignMode && OurWindowHasFocus()) {
      nsCOMPtr<nsIContent> rootContent = document->GetRootElement();
      return rootContent.forget();
    }
    return nullptr;
  }

  if (inDesignMode) {
    return OurWindowHasFocus() &&
      nsContentUtils::ContentIsDescendantOf(focusedContent, document) ?
        focusedContent.forget() : nullptr;
  }

  // We're HTML editor for contenteditable

  // If the focused content isn't editable, or it has independent selection,
  // we don't have focus.
  if (!focusedContent->HasFlag(NODE_IS_EDITABLE) ||
      focusedContent->HasIndependentSelection()) {
    return nullptr;
  }
  // If our window is focused, we're focused.
  return OurWindowHasFocus() ? focusedContent.forget() : nullptr;
}

already_AddRefed<nsIContent>
HTMLEditor::GetFocusedContentForIME()
{
  nsCOMPtr<nsIContent> focusedContent = GetFocusedContent();
  if (!focusedContent) {
    return nullptr;
  }

  nsCOMPtr<nsIDocument> document = GetDocument();
  if (NS_WARN_IF(!document)) {
    return nullptr;
  }
  return document->HasFlag(NODE_IS_EDITABLE) ? nullptr :
                                               focusedContent.forget();
}

bool
HTMLEditor::IsActiveInDOMWindow()
{
  nsFocusManager* fm = nsFocusManager::GetFocusManager();
  NS_ENSURE_TRUE(fm, false);

  nsCOMPtr<nsIDocument> document = GetDocument();
  if (NS_WARN_IF(!document)) {
    return false;
  }
  bool inDesignMode = document->HasFlag(NODE_IS_EDITABLE);

  // If we're in designMode, we're always active in the DOM window.
  if (inDesignMode) {
    return true;
  }

  nsPIDOMWindowOuter* ourWindow = document->GetWindow();
  nsCOMPtr<nsPIDOMWindowOuter> win;
  nsIContent* content =
    nsFocusManager::GetFocusedDescendant(ourWindow, false,
                                         getter_AddRefs(win));
  if (!content) {
    return false;
  }

  // We're HTML editor for contenteditable

  // If the active content isn't editable, or it has independent selection,
  // we're not active).
  if (!content->HasFlag(NODE_IS_EDITABLE) ||
      content->HasIndependentSelection()) {
    return false;
  }
  return true;
}

Element*
HTMLEditor::GetActiveEditingHost()
{
  nsCOMPtr<nsIDocument> document = GetDocument();
  if (NS_WARN_IF(!document)) {
    return nullptr;
  }
  if (document->HasFlag(NODE_IS_EDITABLE)) {
    return document->GetBodyElement();
  }

  // We're HTML editor for contenteditable
  RefPtr<Selection> selection = GetSelection();
  NS_ENSURE_TRUE(selection, nullptr);
  nsCOMPtr<nsIDOMNode> focusNode;
  nsresult rv = selection->GetFocusNode(getter_AddRefs(focusNode));
  NS_ENSURE_SUCCESS(rv, nullptr);
  nsCOMPtr<nsIContent> content = do_QueryInterface(focusNode);
  if (!content) {
    return nullptr;
  }

  // If the active content isn't editable, or it has independent selection,
  // we're not active.
  if (!content->HasFlag(NODE_IS_EDITABLE) ||
      content->HasIndependentSelection()) {
    return nullptr;
  }
  return content->GetEditingHost();
}

already_AddRefed<EventTarget>
HTMLEditor::GetDOMEventTarget()
{
  // Don't use getDocument here, because we have no way of knowing
  // whether Init() was ever called.  So we need to get the document
  // ourselves, if it exists.
  MOZ_ASSERT(IsInitialized(), "The HTMLEditor has not been initialized yet");
  nsCOMPtr<mozilla::dom::EventTarget> target = GetDocument();
  return target.forget();
}

bool
HTMLEditor::ShouldReplaceRootElement()
{
  if (!mRootElement) {
    // If we don't know what is our root element, we should find our root.
    return true;
  }

  // If we temporary set document root element to mRootElement, but there is
  // body element now, we should replace the root element by the body element.
  nsCOMPtr<nsIDOMHTMLElement> docBody;
  GetBodyElement(getter_AddRefs(docBody));
  return !SameCOMIdentity(docBody, mRootElement);
}

void
HTMLEditor::NotifyRootChanged()
{
  nsCOMPtr<nsIMutationObserver> kungFuDeathGrip(this);

  RemoveEventListeners();
  nsresult rv = InstallEventListeners();
  if (NS_FAILED(rv)) {
    return;
  }

  UpdateRootElement();
  if (!mRootElement) {
    return;
  }

  rv = BeginningOfDocument();
  if (NS_FAILED(rv)) {
    return;
  }

  // When this editor has focus, we need to reset the selection limiter to
  // new root.  Otherwise, that is going to be done when this gets focus.
  nsCOMPtr<nsINode> node = GetFocusedNode();
  nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(node);
  if (target) {
    InitializeSelection(target);
  }

  SyncRealTimeSpell();
}

nsresult
HTMLEditor::GetBodyElement(nsIDOMHTMLElement** aBody)
{
  MOZ_ASSERT(IsInitialized(), "The HTMLEditor hasn't been initialized yet");
  nsCOMPtr<nsIDocument> document = GetDocument();
  if (NS_WARN_IF(!document)) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  nsCOMPtr<nsIDOMHTMLDocument> domHTMLDocument = do_QueryInterface(document);
  if (!domHTMLDocument) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  return domHTMLDocument->GetBody(aBody);
}

already_AddRefed<nsINode>
HTMLEditor::GetFocusedNode()
{
  nsCOMPtr<nsIContent> focusedContent = GetFocusedContent();
  if (!focusedContent) {
    return nullptr;
  }

  nsIFocusManager* fm = nsFocusManager::GetFocusManager();
  NS_ASSERTION(fm, "Focus manager is null");
  nsCOMPtr<nsIDOMElement> focusedElement;
  fm->GetFocusedElement(getter_AddRefs(focusedElement));
  if (focusedElement) {
    nsCOMPtr<nsINode> node = do_QueryInterface(focusedElement);
    return node.forget();
  }

  nsCOMPtr<nsIDocument> document = GetDocument();
  return document.forget();
}

bool
HTMLEditor::OurWindowHasFocus()
{
  nsIFocusManager* fm = nsFocusManager::GetFocusManager();
  NS_ENSURE_TRUE(fm, false);
  nsCOMPtr<mozIDOMWindowProxy> focusedWindow;
  fm->GetFocusedWindow(getter_AddRefs(focusedWindow));
  if (!focusedWindow) {
    return false;
  }
  nsCOMPtr<nsIDocument> document = GetDocument();
  if (NS_WARN_IF(!document)) {
    return false;
  }
  nsPIDOMWindowOuter* ourWindow = document->GetWindow();
  return ourWindow == focusedWindow;
}

bool
HTMLEditor::IsAcceptableInputEvent(WidgetGUIEvent* aGUIEvent)
{
  if (!EditorBase::IsAcceptableInputEvent(aGUIEvent)) {
    return false;
  }

  // While there is composition, all composition events in its top level window
  // are always fired on the composing editor.  Therefore, if this editor has
  // composition, the composition events should be handled in this editor.
  if (mComposition && aGUIEvent->AsCompositionEvent()) {
    return true;
  }

  nsCOMPtr<nsIDOMEventTarget> target = aGUIEvent->GetDOMEventTarget();
  NS_ENSURE_TRUE(target, false);

  nsCOMPtr<nsIDocument> document = GetDocument();
  if (NS_WARN_IF(!document)) {
    return false;
  }

  if (document->HasFlag(NODE_IS_EDITABLE)) {
    // If this editor is in designMode and the event target is the document,
    // the event is for this editor.
    nsCOMPtr<nsIDocument> targetDocument = do_QueryInterface(target);
    if (targetDocument) {
      return targetDocument == document;
    }
    // Otherwise, check whether the event target is in this document or not.
    nsCOMPtr<nsIContent> targetContent = do_QueryInterface(target);
    NS_ENSURE_TRUE(targetContent, false);
    return document == targetContent->GetUncomposedDoc();
  }

  // This HTML editor is for contenteditable.  We need to check the validity of
  // the target.
  nsCOMPtr<nsIContent> targetContent = do_QueryInterface(target);
  NS_ENSURE_TRUE(targetContent, false);

  // If the event is a mouse event, we need to check if the target content is
  // the focused editing host or its descendant.
  if (aGUIEvent->AsMouseEventBase()) {
    nsIContent* editingHost = GetActiveEditingHost();
    // If there is no active editing host, we cannot handle the mouse event
    // correctly.
    if (!editingHost) {
      return false;
    }
    // If clicked on non-editable root element but the body element is the
    // active editing host, we should assume that the click event is targetted.
    if (targetContent == document->GetRootElement() &&
        !targetContent->HasFlag(NODE_IS_EDITABLE) &&
        editingHost == document->GetBodyElement()) {
      targetContent = editingHost;
    }
    // If the target element is neither the active editing host nor a descendant
    // of it, we may not be able to handle the event.
    if (!nsContentUtils::ContentIsDescendantOf(targetContent, editingHost)) {
      return false;
    }
    // If the clicked element has an independent selection, we shouldn't
    // handle this click event.
    if (targetContent->HasIndependentSelection()) {
      return false;
    }
    // If the target content is editable, we should handle this event.
    return targetContent->HasFlag(NODE_IS_EDITABLE);
  }

  // If the target of the other events which target focused element isn't
  // editable or has an independent selection, this editor shouldn't handle the
  // event.
  if (!targetContent->HasFlag(NODE_IS_EDITABLE) ||
      targetContent->HasIndependentSelection()) {
    return false;
  }

  // Finally, check whether we're actually focused or not.  When we're not
  // focused, we should ignore the dispatched event by script (or something)
  // because content editable element needs selection in itself for editing.
  // However, when we're not focused, it's not guaranteed.
  return IsActiveInDOMWindow();
}

NS_IMETHODIMP
HTMLEditor::GetPreferredIMEState(IMEState* aState)
{
  // HTML editor don't prefer the CSS ime-mode because IE didn't do so too.
  aState->mOpen = IMEState::DONT_CHANGE_OPEN_STATE;
  if (IsReadonly() || IsDisabled()) {
    aState->mEnabled = IMEState::DISABLED;
  } else {
    aState->mEnabled = IMEState::ENABLED;
  }
  return NS_OK;
}

already_AddRefed<nsIContent>
HTMLEditor::GetInputEventTargetContent()
{
  nsCOMPtr<nsIContent> target = GetActiveEditingHost();
  return target.forget();
}

bool
HTMLEditor::IsEditable(nsINode* aNode)
{
  if (!TextEditor::IsEditable(aNode)) {
    return false;
  }
  if (aNode->IsElement()) {
    // If we're dealing with an element, then ask it whether it's editable.
    return aNode->IsEditable();
  }
  // We might be dealing with a text node for example, which we always consider
  // to be editable.
  return true;
}

Element*
HTMLEditor::GetEditorRoot()
{
  return GetActiveEditingHost();
}

} // namespace mozilla