summaryrefslogtreecommitdiffstats
path: root/editor/txtsvc/nsTextServicesDocument.cpp
blob: e0c779683b974226dea5ff50b8b106bd927a42c3 (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
/* -*- 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 <stddef.h>                     // for nullptr

#include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
#include "mozilla/dom/Selection.h"
#include "mozilla/mozalloc.h"           // for operator new, etc
#include "nsAString.h"                  // for nsAString_internal::Length, etc
#include "nsContentUtils.h"             // for nsContentUtils
#include "nsDebug.h"                    // for NS_ENSURE_TRUE, etc
#include "nsDependentSubstring.h"       // for Substring
#include "nsError.h"                    // for NS_OK, NS_ERROR_FAILURE, etc
#include "nsFilteredContentIterator.h"  // for nsFilteredContentIterator
#include "nsIContent.h"                 // for nsIContent, etc
#include "nsIContentIterator.h"         // for nsIContentIterator
#include "nsID.h"                       // for NS_GET_IID
#include "nsIDOMDocument.h"             // for nsIDOMDocument
#include "nsIDOMElement.h"              // for nsIDOMElement
#include "nsIDOMHTMLDocument.h"         // for nsIDOMHTMLDocument
#include "nsIDOMHTMLElement.h"          // for nsIDOMHTMLElement
#include "nsIDOMNode.h"                 // for nsIDOMNode, etc
#include "nsIDOMRange.h"                // for nsIDOMRange, etc
#include "nsIEditor.h"                  // for nsIEditor, etc
#include "nsINode.h"                    // for nsINode
#include "nsIPlaintextEditor.h"         // for nsIPlaintextEditor
#include "nsISelection.h"               // for nsISelection
#include "nsISelectionController.h"     // for nsISelectionController, etc
#include "nsISupportsBase.h"            // for nsISupports
#include "nsISupportsUtils.h"           // for NS_IF_ADDREF, NS_ADDREF, etc
#include "nsITextServicesFilter.h"      // for nsITextServicesFilter
#include "nsIWordBreaker.h"             // for nsWordRange, nsIWordBreaker
#include "nsRange.h"                    // for nsRange
#include "nsStaticAtom.h"               // for NS_STATIC_ATOM, etc
#include "nsString.h"                   // for nsString, nsAutoString
#include "nsTextServicesDocument.h"
#include "nscore.h"                     // for nsresult, NS_IMETHODIMP, etc

#define LOCK_DOC(doc)
#define UNLOCK_DOC(doc)

using namespace mozilla;
using namespace mozilla::dom;

class OffsetEntry
{
public:
  OffsetEntry(nsIDOMNode *aNode, int32_t aOffset, int32_t aLength)
    : mNode(aNode), mNodeOffset(0), mStrOffset(aOffset), mLength(aLength),
      mIsInsertedText(false), mIsValid(true)
  {
    if (mStrOffset < 1) {
      mStrOffset = 0;
    }
    if (mLength < 1) {
      mLength = 0;
    }
  }

  virtual ~OffsetEntry()
  {
    mNode       = 0;
    mNodeOffset = 0;
    mStrOffset  = 0;
    mLength     = 0;
    mIsValid    = false;
  }

  nsIDOMNode *mNode;
  int32_t mNodeOffset;
  int32_t mStrOffset;
  int32_t mLength;
  bool    mIsInsertedText;
  bool    mIsValid;
};

#define TS_ATOM(name_, value_) nsIAtom* nsTextServicesDocument::name_ = 0;
#include "nsTSAtomList.h" // IWYU pragma: keep
#undef TS_ATOM

nsTextServicesDocument::nsTextServicesDocument()
{
  mSelStartIndex  = -1;
  mSelStartOffset = -1;
  mSelEndIndex    = -1;
  mSelEndOffset   = -1;

  mIteratorStatus = eIsDone;
}

nsTextServicesDocument::~nsTextServicesDocument()
{
  ClearOffsetTable(&mOffsetTable);
}

#define TS_ATOM(name_, value_) NS_STATIC_ATOM_BUFFER(name_##_buffer, value_)
#include "nsTSAtomList.h" // IWYU pragma: keep
#undef TS_ATOM

/* static */
void
nsTextServicesDocument::RegisterAtoms()
{
  static const nsStaticAtom ts_atoms[] = {
#define TS_ATOM(name_, value_) NS_STATIC_ATOM(name_##_buffer, &name_),
#include "nsTSAtomList.h" // IWYU pragma: keep
#undef TS_ATOM
  };

  NS_RegisterStaticAtoms(ts_atoms);
}

NS_IMPL_CYCLE_COLLECTING_ADDREF(nsTextServicesDocument)
NS_IMPL_CYCLE_COLLECTING_RELEASE(nsTextServicesDocument)

NS_INTERFACE_MAP_BEGIN(nsTextServicesDocument)
  NS_INTERFACE_MAP_ENTRY(nsITextServicesDocument)
  NS_INTERFACE_MAP_ENTRY(nsIEditActionListener)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsITextServicesDocument)
  NS_INTERFACE_MAP_ENTRIES_CYCLE_COLLECTION(nsTextServicesDocument)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTION(nsTextServicesDocument,
                         mDOMDocument,
                         mSelCon,
                         mIterator,
                         mPrevTextBlock,
                         mNextTextBlock,
                         mExtent,
                         mTxtSvcFilter)

NS_IMETHODIMP
nsTextServicesDocument::InitWithEditor(nsIEditor *aEditor)
{
  nsCOMPtr<nsISelectionController> selCon;
  nsCOMPtr<nsIDOMDocument> doc;

  NS_ENSURE_TRUE(aEditor, NS_ERROR_NULL_POINTER);

  LOCK_DOC(this);

  // Check to see if we already have an mSelCon. If we do, it
  // better be the same one the editor uses!

  nsresult rv = aEditor->GetSelectionController(getter_AddRefs(selCon));

  if (NS_FAILED(rv)) {
    UNLOCK_DOC(this);
    return rv;
  }

  if (!selCon || (mSelCon && selCon != mSelCon)) {
    UNLOCK_DOC(this);
    return NS_ERROR_FAILURE;
  }

  if (!mSelCon) {
    mSelCon = selCon;
  }

  // Check to see if we already have an mDOMDocument. If we do, it
  // better be the same one the editor uses!

  rv = aEditor->GetDocument(getter_AddRefs(doc));

  if (NS_FAILED(rv)) {
    UNLOCK_DOC(this);
    return rv;
  }

  if (!doc || (mDOMDocument && doc != mDOMDocument)) {
    UNLOCK_DOC(this);
    return NS_ERROR_FAILURE;
  }

  if (!mDOMDocument) {
    mDOMDocument = doc;

    rv = CreateDocumentContentIterator(getter_AddRefs(mIterator));

    if (NS_FAILED(rv)) {
      UNLOCK_DOC(this);
      return rv;
    }

    mIteratorStatus = nsTextServicesDocument::eIsDone;

    rv = FirstBlock();

    if (NS_FAILED(rv)) {
      UNLOCK_DOC(this);
      return rv;
    }
  }

  mEditor = do_GetWeakReference(aEditor);

  rv = aEditor->AddEditActionListener(this);

  UNLOCK_DOC(this);

  return rv;
}

NS_IMETHODIMP
nsTextServicesDocument::GetDocument(nsIDOMDocument **aDoc)
{
  NS_ENSURE_TRUE(aDoc, NS_ERROR_NULL_POINTER);

  *aDoc = nullptr; // init out param
  NS_ENSURE_TRUE(mDOMDocument, NS_ERROR_NOT_INITIALIZED);

  *aDoc = mDOMDocument;
  NS_ADDREF(*aDoc);

  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::SetExtent(nsIDOMRange* aDOMRange)
{
  NS_ENSURE_ARG_POINTER(aDOMRange);
  NS_ENSURE_TRUE(mDOMDocument, NS_ERROR_FAILURE);

  LOCK_DOC(this);

  // We need to store a copy of aDOMRange since we don't
  // know where it came from.

  mExtent = static_cast<nsRange*>(aDOMRange)->CloneRange();

  // Create a new iterator based on our new extent range.

  nsresult rv = CreateContentIterator(mExtent, getter_AddRefs(mIterator));

  if (NS_FAILED(rv)) {
    UNLOCK_DOC(this);
    return rv;
  }

  // Now position the iterator at the start of the first block
  // in the range.

  mIteratorStatus = nsTextServicesDocument::eIsDone;

  rv = FirstBlock();

  UNLOCK_DOC(this);

  return rv;
}

NS_IMETHODIMP
nsTextServicesDocument::ExpandRangeToWordBoundaries(nsIDOMRange *aRange)
{
  NS_ENSURE_ARG_POINTER(aRange);
  RefPtr<nsRange> range = static_cast<nsRange*>(aRange);

  // Get the end points of the range.

  nsCOMPtr<nsIDOMNode> rngStartNode, rngEndNode;
  int32_t rngStartOffset, rngEndOffset;

  nsresult rv = GetRangeEndPoints(range, getter_AddRefs(rngStartNode),
                                  &rngStartOffset,
                                  getter_AddRefs(rngEndNode),
                                  &rngEndOffset);

  NS_ENSURE_SUCCESS(rv, rv);

  // Create a content iterator based on the range.

  nsCOMPtr<nsIContentIterator> iter;
  rv = CreateContentIterator(range, getter_AddRefs(iter));

  NS_ENSURE_SUCCESS(rv, rv);

  // Find the first text node in the range.

  TSDIteratorStatus iterStatus;

  rv = FirstTextNode(iter, &iterStatus);
  NS_ENSURE_SUCCESS(rv, rv);

  if (iterStatus == nsTextServicesDocument::eIsDone) {
    // No text was found so there's no adjustment necessary!
    return NS_OK;
  }

  nsINode *firstText = iter->GetCurrentNode();
  NS_ENSURE_TRUE(firstText, NS_ERROR_FAILURE);

  // Find the last text node in the range.

  rv = LastTextNode(iter, &iterStatus);
  NS_ENSURE_SUCCESS(rv, rv);

  if (iterStatus == nsTextServicesDocument::eIsDone) {
    // We should never get here because a first text block
    // was found above.
    NS_ASSERTION(false, "Found a first without a last!");
    return NS_ERROR_FAILURE;
  }

  nsINode *lastText = iter->GetCurrentNode();
  NS_ENSURE_TRUE(lastText, NS_ERROR_FAILURE);

  // Now make sure our end points are in terms of text nodes in the range!

  nsCOMPtr<nsIDOMNode> firstTextNode = do_QueryInterface(firstText);
  NS_ENSURE_TRUE(firstTextNode, NS_ERROR_FAILURE);

  if (rngStartNode != firstTextNode) {
    // The range includes the start of the first text node!
    rngStartNode = firstTextNode;
    rngStartOffset = 0;
  }

  nsCOMPtr<nsIDOMNode> lastTextNode = do_QueryInterface(lastText);
  NS_ENSURE_TRUE(lastTextNode, NS_ERROR_FAILURE);

  if (rngEndNode != lastTextNode) {
    // The range includes the end of the last text node!
    rngEndNode = lastTextNode;
    nsAutoString str;
    lastTextNode->GetNodeValue(str);
    rngEndOffset = str.Length();
  }

  // Create a doc iterator so that we can scan beyond
  // the bounds of the extent range.

  nsCOMPtr<nsIContentIterator> docIter;
  rv = CreateDocumentContentIterator(getter_AddRefs(docIter));
  NS_ENSURE_SUCCESS(rv, rv);

  // Grab all the text in the block containing our
  // first text node.

  rv = docIter->PositionAt(firstText);
  NS_ENSURE_SUCCESS(rv, rv);

  iterStatus = nsTextServicesDocument::eValid;

  nsTArray<OffsetEntry*> offsetTable;
  nsAutoString blockStr;

  rv = CreateOffsetTable(&offsetTable, docIter, &iterStatus,
                         nullptr, &blockStr);
  if (NS_FAILED(rv)) {
    ClearOffsetTable(&offsetTable);
    return rv;
  }

  nsCOMPtr<nsIDOMNode> wordStartNode, wordEndNode;
  int32_t wordStartOffset, wordEndOffset;

  rv = FindWordBounds(&offsetTable, &blockStr,
                      rngStartNode, rngStartOffset,
                      getter_AddRefs(wordStartNode), &wordStartOffset,
                      getter_AddRefs(wordEndNode), &wordEndOffset);

  ClearOffsetTable(&offsetTable);

  NS_ENSURE_SUCCESS(rv, rv);

  rngStartNode = wordStartNode;
  rngStartOffset = wordStartOffset;

  // Grab all the text in the block containing our
  // last text node.

  rv = docIter->PositionAt(lastText);
  NS_ENSURE_SUCCESS(rv, rv);

  iterStatus = nsTextServicesDocument::eValid;

  rv = CreateOffsetTable(&offsetTable, docIter, &iterStatus,
                         nullptr, &blockStr);
  if (NS_FAILED(rv)) {
    ClearOffsetTable(&offsetTable);
    return rv;
  }

  rv = FindWordBounds(&offsetTable, &blockStr,
                      rngEndNode, rngEndOffset,
                      getter_AddRefs(wordStartNode), &wordStartOffset,
                      getter_AddRefs(wordEndNode), &wordEndOffset);

  ClearOffsetTable(&offsetTable);

  NS_ENSURE_SUCCESS(rv, rv);

  // To prevent expanding the range too much, we only change
  // rngEndNode and rngEndOffset if it isn't already at the start of the
  // word and isn't equivalent to rngStartNode and rngStartOffset.

  if (rngEndNode != wordStartNode ||
      rngEndOffset != wordStartOffset ||
      (rngEndNode == rngStartNode && rngEndOffset == rngStartOffset)) {
    rngEndNode = wordEndNode;
    rngEndOffset = wordEndOffset;
  }

  // Now adjust the range so that it uses our new
  // end points.

  rv = range->SetEnd(rngEndNode, rngEndOffset);
  NS_ENSURE_SUCCESS(rv, rv);

  return range->SetStart(rngStartNode, rngStartOffset);
}

NS_IMETHODIMP
nsTextServicesDocument::SetFilter(nsITextServicesFilter *aFilter)
{
  // Hang on to the filter so we can set it into the filtered iterator.
  mTxtSvcFilter = aFilter;

  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::GetCurrentTextBlock(nsString *aStr)
{
  NS_ENSURE_TRUE(aStr, NS_ERROR_NULL_POINTER);

  aStr->Truncate();

  NS_ENSURE_TRUE(mIterator, NS_ERROR_FAILURE);

  LOCK_DOC(this);

  nsresult rv = CreateOffsetTable(&mOffsetTable, mIterator, &mIteratorStatus,
                                  mExtent, aStr);

  UNLOCK_DOC(this);

  return rv;
}

NS_IMETHODIMP
nsTextServicesDocument::FirstBlock()
{
  NS_ENSURE_TRUE(mIterator, NS_ERROR_FAILURE);

  LOCK_DOC(this);

  nsresult rv = FirstTextNode(mIterator, &mIteratorStatus);

  if (NS_FAILED(rv)) {
    UNLOCK_DOC(this);
    return rv;
  }

  // Keep track of prev and next blocks, just in case
  // the text service blows away the current block.

  if (mIteratorStatus == nsTextServicesDocument::eValid) {
    mPrevTextBlock  = nullptr;
    rv = GetFirstTextNodeInNextBlock(getter_AddRefs(mNextTextBlock));
  } else {
    // There's no text block in the document!

    mPrevTextBlock  = nullptr;
    mNextTextBlock  = nullptr;
  }

  UNLOCK_DOC(this);

  // XXX Result of FirstTextNode() or GetFirstTextNodeInNextBlock().
  return rv;
}

NS_IMETHODIMP
nsTextServicesDocument::LastSelectedBlock(TSDBlockSelectionStatus *aSelStatus,
                                          int32_t *aSelOffset,
                                          int32_t *aSelLength)
{
  NS_ENSURE_TRUE(aSelStatus && aSelOffset && aSelLength, NS_ERROR_NULL_POINTER);

  LOCK_DOC(this);

  mIteratorStatus = nsTextServicesDocument::eIsDone;

  *aSelStatus = nsITextServicesDocument::eBlockNotFound;
  *aSelOffset = *aSelLength = -1;

  if (!mSelCon || !mIterator) {
    UNLOCK_DOC(this);
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsISelection> domSelection;
  nsresult rv = mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                                      getter_AddRefs(domSelection));
  if (NS_FAILED(rv)) {
    UNLOCK_DOC(this);
    return rv;
  }

  RefPtr<Selection> selection = domSelection->AsSelection();

  bool isCollapsed = selection->IsCollapsed();

  nsCOMPtr<nsIContentIterator> iter;
  RefPtr<nsRange> range;
  nsCOMPtr<nsIDOMNode>         parent;
  int32_t rangeCount, offset;

  if (isCollapsed) {
    // We have a caret. Check if the caret is in a text node.
    // If it is, make the text node's block the current block.
    // If the caret isn't in a text node, search forwards in
    // the document, till we find a text node.

    range = selection->GetRangeAt(0);

    if (!range) {
      UNLOCK_DOC(this);
      return NS_ERROR_FAILURE;
    }

    rv = range->GetStartContainer(getter_AddRefs(parent));

    if (NS_FAILED(rv)) {
      UNLOCK_DOC(this);
      return rv;
    }

    if (!parent) {
      UNLOCK_DOC(this);
      return NS_ERROR_FAILURE;
    }

    rv = range->GetStartOffset(&offset);

    if (NS_FAILED(rv)) {
      UNLOCK_DOC(this);
      return rv;
    }

    if (IsTextNode(parent)) {
      // The caret is in a text node. Find the beginning
      // of the text block containing this text node and
      // return.

      nsCOMPtr<nsIContent> content(do_QueryInterface(parent));

      if (!content) {
        UNLOCK_DOC(this);
        return NS_ERROR_FAILURE;
      }

      rv = mIterator->PositionAt(content);

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }

      rv = FirstTextNodeInCurrentBlock(mIterator);

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }

      mIteratorStatus = nsTextServicesDocument::eValid;

      rv = CreateOffsetTable(&mOffsetTable, mIterator, &mIteratorStatus,
                             mExtent, nullptr);

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }

      rv = GetSelection(aSelStatus, aSelOffset, aSelLength);

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }

      if (*aSelStatus == nsITextServicesDocument::eBlockContains) {
        rv = SetSelectionInternal(*aSelOffset, *aSelLength, false);
      }
    } else {
      // The caret isn't in a text node. Create an iterator
      // based on a range that extends from the current caret
      // position to the end of the document, then walk forwards
      // till you find a text node, then find the beginning of it's block.

      rv = CreateDocumentContentRootToNodeOffsetRange(parent, offset, false,
                                                      getter_AddRefs(range));

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }

      rv = range->GetCollapsed(&isCollapsed);

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }

      if (isCollapsed) {
        // If we get here, the range is collapsed because there is nothing after
        // the caret! Just return NS_OK;

        UNLOCK_DOC(this);
        return NS_OK;
      }

      rv = CreateContentIterator(range, getter_AddRefs(iter));

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }

      iter->First();

      nsCOMPtr<nsIContent> content;
      while (!iter->IsDone()) {
        content = do_QueryInterface(iter->GetCurrentNode());

        if (IsTextNode(content)) {
          break;
        }

        content = nullptr;

        iter->Next();
      }

      if (!content) {
        UNLOCK_DOC(this);
        return NS_OK;
      }

      rv = mIterator->PositionAt(content);

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }

      rv = FirstTextNodeInCurrentBlock(mIterator);

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }

      mIteratorStatus = nsTextServicesDocument::eValid;

      rv = CreateOffsetTable(&mOffsetTable, mIterator, &mIteratorStatus,
                             mExtent, nullptr);

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }

      rv = GetSelection(aSelStatus, aSelOffset, aSelLength);

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }
    }

    UNLOCK_DOC(this);

    // Result of SetSelectionInternal() in the |if| block or NS_OK.
    return rv;
  }

  // If we get here, we have an uncollapsed selection!
  // Look backwards through each range in the selection till you
  // find the first text node. If you find one, find the
  // beginning of its text block, and make it the current
  // block.

  rv = selection->GetRangeCount(&rangeCount);

  if (NS_FAILED(rv)) {
    UNLOCK_DOC(this);
    return rv;
  }

  NS_ASSERTION(rangeCount > 0, "Unexpected range count!");

  if (rangeCount <= 0) {
    UNLOCK_DOC(this);
    return NS_OK;
  }

  // XXX: We may need to add some code here to make sure
  //      the ranges are sorted in document appearance order!

  for (int32_t i = rangeCount - 1; i >= 0; i--) {
    // Get the i'th range from the selection.

    range = selection->GetRangeAt(i);

    if (!range) {
      UNLOCK_DOC(this);
      return NS_OK; // XXX Really?
    }

    // Create an iterator for the range.

    rv = CreateContentIterator(range, getter_AddRefs(iter));

    if (NS_FAILED(rv)) {
      UNLOCK_DOC(this);
      return rv;
    }

    iter->Last();

    // Now walk through the range till we find a text node.

    while (!iter->IsDone()) {
      if (iter->GetCurrentNode()->NodeType() == nsIDOMNode::TEXT_NODE) {
        // We found a text node, so position the document's
        // iterator at the beginning of the block, then get
        // the selection in terms of the string offset.
        nsCOMPtr<nsIContent> content = iter->GetCurrentNode()->AsContent();

        rv = mIterator->PositionAt(content);

        if (NS_FAILED(rv)) {
          UNLOCK_DOC(this);
          return rv;
        }

        rv = FirstTextNodeInCurrentBlock(mIterator);

        if (NS_FAILED(rv)) {
          UNLOCK_DOC(this);
          return rv;
        }

        mIteratorStatus = nsTextServicesDocument::eValid;

        rv = CreateOffsetTable(&mOffsetTable, mIterator, &mIteratorStatus,
                               mExtent, nullptr);

        if (NS_FAILED(rv)) {
          UNLOCK_DOC(this);
          return rv;
        }

        rv = GetSelection(aSelStatus, aSelOffset, aSelLength);

        UNLOCK_DOC(this);

        return rv;

      }

      iter->Prev();
    }
  }

  // If we get here, we didn't find any text node in the selection!
  // Create a range that extends from the end of the selection,
  // to the end of the document, then iterate forwards through
  // it till you find a text node!

  range = selection->GetRangeAt(rangeCount - 1);

  if (!range) {
    UNLOCK_DOC(this);
    return NS_ERROR_FAILURE;
  }

  rv = range->GetEndContainer(getter_AddRefs(parent));

  if (NS_FAILED(rv)) {
    UNLOCK_DOC(this);
    return rv;
  }

  if (!parent) {
    UNLOCK_DOC(this);
    return NS_ERROR_FAILURE;
  }

  rv = range->GetEndOffset(&offset);

  if (NS_FAILED(rv)) {
    UNLOCK_DOC(this);
    return rv;
  }

  rv = CreateDocumentContentRootToNodeOffsetRange(parent, offset, false,
                                                  getter_AddRefs(range));

  if (NS_FAILED(rv)) {
    UNLOCK_DOC(this);
    return rv;
  }

  rv = range->GetCollapsed(&isCollapsed);

  if (NS_FAILED(rv)) {
    UNLOCK_DOC(this);
    return rv;
  }

  if (isCollapsed) {
    // If we get here, the range is collapsed because there is nothing after
    // the current selection! Just return NS_OK;

    UNLOCK_DOC(this);
    return NS_OK;
  }

  rv = CreateContentIterator(range, getter_AddRefs(iter));

  if (NS_FAILED(rv)) {
    UNLOCK_DOC(this);
    return rv;
  }

  iter->First();

  while (!iter->IsDone()) {
    if (iter->GetCurrentNode()->NodeType() == nsIDOMNode::TEXT_NODE) {
      // We found a text node! Adjust the document's iterator to point
      // to the beginning of its text block, then get the current selection.
      nsCOMPtr<nsIContent> content = iter->GetCurrentNode()->AsContent();

      rv = mIterator->PositionAt(content);

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }

      rv = FirstTextNodeInCurrentBlock(mIterator);

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }


      mIteratorStatus = nsTextServicesDocument::eValid;

      rv = CreateOffsetTable(&mOffsetTable, mIterator, &mIteratorStatus,
                             mExtent, nullptr);

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }

      rv = GetSelection(aSelStatus, aSelOffset, aSelLength);

      UNLOCK_DOC(this);

      return rv;
    }

    iter->Next();
  }

  // If we get here, we didn't find any block before or inside
  // the selection! Just return OK.

  UNLOCK_DOC(this);

  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::PrevBlock()
{
  NS_ENSURE_TRUE(mIterator, NS_ERROR_FAILURE);

  LOCK_DOC(this);

  if (mIteratorStatus == nsTextServicesDocument::eIsDone) {
    return NS_OK;
  }

  switch (mIteratorStatus) {
    case nsTextServicesDocument::eValid:
    case nsTextServicesDocument::eNext: {

      nsresult rv = FirstTextNodeInPrevBlock(mIterator);

      if (NS_FAILED(rv)) {
        mIteratorStatus = nsTextServicesDocument::eIsDone;
        UNLOCK_DOC(this);
        return rv;
      }

      if (mIterator->IsDone()) {
        mIteratorStatus = nsTextServicesDocument::eIsDone;
        UNLOCK_DOC(this);
        return NS_OK;
      }

      mIteratorStatus = nsTextServicesDocument::eValid;
      break;
    }
    case nsTextServicesDocument::ePrev:

      // The iterator already points to the previous
      // block, so don't do anything.

      mIteratorStatus = nsTextServicesDocument::eValid;
      break;

    default:

      mIteratorStatus = nsTextServicesDocument::eIsDone;
      break;
  }

  // Keep track of prev and next blocks, just in case
  // the text service blows away the current block.
  nsresult rv = NS_OK;
  if (mIteratorStatus == nsTextServicesDocument::eValid) {
    GetFirstTextNodeInPrevBlock(getter_AddRefs(mPrevTextBlock));
    rv = GetFirstTextNodeInNextBlock(getter_AddRefs(mNextTextBlock));
  } else {
    // We must be done!
    mPrevTextBlock = nullptr;
    mNextTextBlock = nullptr;
  }

  UNLOCK_DOC(this);

  // XXX The result of GetFirstTextNodeInNextBlock() or NS_OK.
  return rv;
}

NS_IMETHODIMP
nsTextServicesDocument::NextBlock()
{
  NS_ENSURE_TRUE(mIterator, NS_ERROR_FAILURE);

  LOCK_DOC(this);

  if (mIteratorStatus == nsTextServicesDocument::eIsDone) {
    return NS_OK;
  }

  switch (mIteratorStatus) {
    case nsTextServicesDocument::eValid: {

      // Advance the iterator to the next text block.

      nsresult rv = FirstTextNodeInNextBlock(mIterator);

      if (NS_FAILED(rv)) {
        mIteratorStatus = nsTextServicesDocument::eIsDone;
        UNLOCK_DOC(this);
        return rv;
      }

      if (mIterator->IsDone()) {
        mIteratorStatus = nsTextServicesDocument::eIsDone;
        UNLOCK_DOC(this);
        return NS_OK;
      }

      mIteratorStatus = nsTextServicesDocument::eValid;
      break;
    }
    case nsTextServicesDocument::eNext:

      // The iterator already points to the next block,
      // so don't do anything to it!

      mIteratorStatus = nsTextServicesDocument::eValid;
      break;

    case nsTextServicesDocument::ePrev:

      // If the iterator is pointing to the previous block,
      // we know that there is no next text block! Just
      // fall through to the default case!

    default:

      mIteratorStatus = nsTextServicesDocument::eIsDone;
      break;
  }

  // Keep track of prev and next blocks, just in case
  // the text service blows away the current block.
  nsresult rv = NS_OK;
  if (mIteratorStatus == nsTextServicesDocument::eValid) {
    GetFirstTextNodeInPrevBlock(getter_AddRefs(mPrevTextBlock));
    rv = GetFirstTextNodeInNextBlock(getter_AddRefs(mNextTextBlock));
  } else {
    // We must be done.
    mPrevTextBlock = nullptr;
    mNextTextBlock = nullptr;
  }

  UNLOCK_DOC(this);

  // The result of GetFirstTextNodeInNextBlock() or NS_OK.
  return rv;
}

NS_IMETHODIMP
nsTextServicesDocument::IsDone(bool *aIsDone)
{
  NS_ENSURE_TRUE(aIsDone, NS_ERROR_NULL_POINTER);

  *aIsDone = false;

  NS_ENSURE_TRUE(mIterator, NS_ERROR_FAILURE);

  LOCK_DOC(this);

  *aIsDone = (mIteratorStatus == nsTextServicesDocument::eIsDone) ? true : false;

  UNLOCK_DOC(this);

  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::SetSelection(int32_t aOffset, int32_t aLength)
{
  NS_ENSURE_TRUE(mSelCon && aOffset >= 0 && aLength >= 0, NS_ERROR_FAILURE);

  LOCK_DOC(this);

  nsresult rv = SetSelectionInternal(aOffset, aLength, true);

  UNLOCK_DOC(this);

  //**** KDEBUG ****
  // printf("\n * Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset);
  //**** KDEBUG ****

  return rv;
}

NS_IMETHODIMP
nsTextServicesDocument::ScrollSelectionIntoView()
{
  NS_ENSURE_TRUE(mSelCon, NS_ERROR_FAILURE);

  LOCK_DOC(this);

  // After ScrollSelectionIntoView(), the pending notifications might be flushed
  // and PresShell/PresContext/Frames may be dead. See bug 418470.
  nsresult rv =
    mSelCon->ScrollSelectionIntoView(
      nsISelectionController::SELECTION_NORMAL,
      nsISelectionController::SELECTION_FOCUS_REGION,
      nsISelectionController::SCROLL_SYNCHRONOUS);

  UNLOCK_DOC(this);

  return rv;
}

NS_IMETHODIMP
nsTextServicesDocument::DeleteSelection()
{
  // We don't allow deletion during a collapsed selection!
  nsCOMPtr<nsIEditor> editor (do_QueryReferent(mEditor));
  NS_ASSERTION(editor, "DeleteSelection called without an editor present!");
  NS_ASSERTION(SelectionIsValid(), "DeleteSelection called without a valid selection!");

  if (!editor || !SelectionIsValid()) {
    return NS_ERROR_FAILURE;
  }
  if (SelectionIsCollapsed()) {
    return NS_OK;
  }

  LOCK_DOC(this);

  //**** KDEBUG ****
  // printf("\n---- Before Delete\n");
  // printf("Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset);
  // PrintOffsetTable();
  //**** KDEBUG ****

  // If we have an mExtent, save off its current set of
  // end points so we can compare them against mExtent's
  // set after the deletion of the content.

  nsCOMPtr<nsIDOMNode> origStartNode, origEndNode;
  int32_t origStartOffset = 0, origEndOffset = 0;

  if (mExtent) {
    nsresult rv =
      GetRangeEndPoints(mExtent,
                        getter_AddRefs(origStartNode), &origStartOffset,
                        getter_AddRefs(origEndNode), &origEndOffset);

    if (NS_FAILED(rv)) {
      UNLOCK_DOC(this);
      return rv;
    }
  }

  int32_t selLength;
  OffsetEntry *entry, *newEntry;

  for (int32_t i = mSelStartIndex; i <= mSelEndIndex; i++) {
    entry = mOffsetTable[i];

    if (i == mSelStartIndex) {
      // Calculate the length of the selection. Note that the
      // selection length can be zero if the start of the selection
      // is at the very end of a text node entry.

      if (entry->mIsInsertedText) {
        // Inserted text offset entries have no width when
        // talking in terms of string offsets! If the beginning
        // of the selection is in an inserted text offset entry,
        // the caret is always at the end of the entry!

        selLength = 0;
      } else {
        selLength = entry->mLength - (mSelStartOffset - entry->mStrOffset);
      }

      if (selLength > 0 && mSelStartOffset > entry->mStrOffset) {
        // Selection doesn't start at the beginning of the
        // text node entry. We need to split this entry into
        // two pieces, the piece before the selection, and
        // the piece inside the selection.

        nsresult rv = SplitOffsetEntry(i, selLength);

        if (NS_FAILED(rv)) {
          UNLOCK_DOC(this);
          return rv;
        }

        // Adjust selection indexes to account for new entry:

        ++mSelStartIndex;
        ++mSelEndIndex;
        ++i;

        entry = mOffsetTable[i];
      }


      if (selLength > 0 && mSelStartIndex < mSelEndIndex) {
        // The entire entry is contained in the selection. Mark the
        // entry invalid.
        entry->mIsValid = false;
      }
    }

  //**** KDEBUG ****
  // printf("\n---- Middle Delete\n");
  // printf("Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset);
  // PrintOffsetTable();
  //**** KDEBUG ****

    if (i == mSelEndIndex) {
      if (entry->mIsInsertedText) {
        // Inserted text offset entries have no width when
        // talking in terms of string offsets! If the end
        // of the selection is in an inserted text offset entry,
        // the selection includes the entire entry!

        entry->mIsValid = false;
      } else {
        // Calculate the length of the selection. Note that the
        // selection length can be zero if the end of the selection
        // is at the very beginning of a text node entry.

        selLength = mSelEndOffset - entry->mStrOffset;

        if (selLength > 0 &&
            mSelEndOffset < entry->mStrOffset + entry->mLength) {
          // mStrOffset is guaranteed to be inside the selection, even
          // when mSelStartIndex == mSelEndIndex.

          nsresult rv = SplitOffsetEntry(i, entry->mLength - selLength);

          if (NS_FAILED(rv)) {
            UNLOCK_DOC(this);
            return rv;
          }

          // Update the entry fields:

          newEntry = mOffsetTable[i+1];
          newEntry->mNodeOffset = entry->mNodeOffset;
        }


        if (selLength > 0 &&
            mSelEndOffset == entry->mStrOffset + entry->mLength) {
          // The entire entry is contained in the selection. Mark the
          // entry invalid.
          entry->mIsValid = false;
        }
      }
    }

    if (i != mSelStartIndex && i != mSelEndIndex) {
      // The entire entry is contained in the selection. Mark the
      // entry invalid.
      entry->mIsValid = false;
    }
  }

  // Make sure mIterator always points to something valid!

  AdjustContentIterator();

  // Now delete the actual content!

  nsresult rv =
    editor->DeleteSelection(nsIEditor::ePrevious, nsIEditor::eStrip);

  if (NS_FAILED(rv)) {
    UNLOCK_DOC(this);
    return rv;
  }

  // Now that we've actually deleted the selected content,
  // check to see if our mExtent has changed, if so, then
  // we have to create a new content iterator!

  if (origStartNode && origEndNode) {
    nsCOMPtr<nsIDOMNode> curStartNode, curEndNode;
    int32_t curStartOffset = 0, curEndOffset = 0;

    rv = GetRangeEndPoints(mExtent,
                           getter_AddRefs(curStartNode), &curStartOffset,
                           getter_AddRefs(curEndNode), &curEndOffset);

    if (NS_FAILED(rv)) {
      UNLOCK_DOC(this);
      return rv;
    }

    if (origStartNode != curStartNode || origEndNode != curEndNode) {
      // The range has changed, so we need to create a new content
      // iterator based on the new range.

      nsCOMPtr<nsIContent> curContent;

      if (mIteratorStatus != nsTextServicesDocument::eIsDone) {
        // The old iterator is still pointing to something valid,
        // so get its current node so we can restore it after we
        // create the new iterator!

        curContent = mIterator->GetCurrentNode()
                     ? mIterator->GetCurrentNode()->AsContent()
                     : nullptr;
      }

      // Create the new iterator.

      rv = CreateContentIterator(mExtent, getter_AddRefs(mIterator));

      if (NS_FAILED(rv)) {
        UNLOCK_DOC(this);
        return rv;
      }

      // Now make the new iterator point to the content node
      // the old one was pointing at.

      if (curContent) {
        rv = mIterator->PositionAt(curContent);

        if (NS_FAILED(rv)) {
          mIteratorStatus = eIsDone;
        } else {
          mIteratorStatus = eValid;
        }
      }
    }
  }

  entry = 0;

  // Move the caret to the end of the first valid entry.
  // Start with mSelStartIndex since it may still be valid.

  for (int32_t i = mSelStartIndex; !entry && i >= 0; i--) {
    entry = mOffsetTable[i];

    if (!entry->mIsValid) {
      entry = 0;
    } else {
      mSelStartIndex  = mSelEndIndex  = i;
      mSelStartOffset = mSelEndOffset = entry->mStrOffset + entry->mLength;
    }
  }

  // If we still don't have a valid entry, move the caret
  // to the next valid entry after the selection:

  for (int32_t i = mSelEndIndex;
       !entry && i < static_cast<int32_t>(mOffsetTable.Length()); i++) {
    entry = mOffsetTable[i];

    if (!entry->mIsValid) {
      entry = 0;
    } else {
      mSelStartIndex = mSelEndIndex = i;
      mSelStartOffset = mSelEndOffset = entry->mStrOffset;
    }
  }

  if (entry) {
    SetSelection(mSelStartOffset, 0);
  } else {
    // Uuughh we have no valid offset entry to place our
    // caret ... just mark the selection invalid.
    mSelStartIndex  = mSelEndIndex  = -1;
    mSelStartOffset = mSelEndOffset = -1;
  }

  // Now remove any invalid entries from the offset table.

  rv = RemoveInvalidOffsetEntries();

  //**** KDEBUG ****
  // printf("\n---- After Delete\n");
  // printf("Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset);
  // PrintOffsetTable();
  //**** KDEBUG ****

  UNLOCK_DOC(this);

  return rv;
}

NS_IMETHODIMP
nsTextServicesDocument::InsertText(const nsString *aText)
{
  nsCOMPtr<nsIEditor> editor (do_QueryReferent(mEditor));
  NS_ASSERTION(editor, "InsertText called without an editor present!");

  if (!editor || !SelectionIsValid()) {
    return NS_ERROR_FAILURE;
  }

  NS_ENSURE_TRUE(aText, NS_ERROR_NULL_POINTER);

  // If the selection is not collapsed, we need to save
  // off the selection offsets so we can restore the
  // selection and delete the selected content after we've
  // inserted the new text. This is necessary to try and
  // retain as much of the original style of the content
  // being deleted.

  bool collapsedSelection = SelectionIsCollapsed();
  int32_t savedSelOffset = mSelStartOffset;
  int32_t savedSelLength = mSelEndOffset - mSelStartOffset;

  if (!collapsedSelection) {
    // Collapse to the start of the current selection
    // for the insert!

    nsresult rv = SetSelection(mSelStartOffset, 0);

    NS_ENSURE_SUCCESS(rv, rv);
  }


  LOCK_DOC(this);

  nsresult rv = editor->BeginTransaction();

  if (NS_FAILED(rv)) {
    UNLOCK_DOC(this);
    return rv;
  }

  nsCOMPtr<nsIPlaintextEditor> textEditor (do_QueryInterface(editor, &rv));
  if (textEditor) {
    rv = textEditor->InsertText(*aText);
  }

  if (NS_FAILED(rv)) {
    editor->EndTransaction();
    UNLOCK_DOC(this);
    return rv;
  }

  //**** KDEBUG ****
  // printf("\n---- Before Insert\n");
  // printf("Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset);
  // PrintOffsetTable();
  //**** KDEBUG ****

  int32_t strLength = aText->Length();

  nsCOMPtr<nsISelection> selection;
  OffsetEntry *itEntry;
  OffsetEntry *entry = mOffsetTable[mSelStartIndex];
  void *node         = entry->mNode;

  NS_ASSERTION((entry->mIsValid), "Invalid insertion point!");

  if (entry->mStrOffset == mSelStartOffset) {
    if (entry->mIsInsertedText) {
      // If the caret is in an inserted text offset entry,
      // we simply insert the text at the end of the entry.

      entry->mLength += strLength;
    } else {
      // Insert an inserted text offset entry before the current
      // entry!

      itEntry = new OffsetEntry(entry->mNode, entry->mStrOffset, strLength);

      if (!itEntry) {
        editor->EndTransaction();
        UNLOCK_DOC(this);
        return NS_ERROR_OUT_OF_MEMORY;
      }

      itEntry->mIsInsertedText = true;
      itEntry->mNodeOffset = entry->mNodeOffset;

      if (!mOffsetTable.InsertElementAt(mSelStartIndex, itEntry)) {
        editor->EndTransaction();
        UNLOCK_DOC(this);
        return NS_ERROR_FAILURE;
      }
    }
  } else if (entry->mStrOffset + entry->mLength == mSelStartOffset) {
    // We are inserting text at the end of the current offset entry.
    // Look at the next valid entry in the table. If it's an inserted
    // text entry, add to its length and adjust its node offset. If
    // it isn't, add a new inserted text entry.

    // XXX Rename this!
    uint32_t i = mSelStartIndex + 1;
    itEntry = 0;

    if (mOffsetTable.Length() > i) {
      itEntry = mOffsetTable[i];

      if (!itEntry) {
        editor->EndTransaction();
        UNLOCK_DOC(this);
        return NS_ERROR_FAILURE;
      }

      // Check if the entry is a match. If it isn't, set
      // iEntry to zero.

      if (!itEntry->mIsInsertedText || itEntry->mStrOffset != mSelStartOffset) {
        itEntry = 0;
      }
    }

    if (!itEntry) {
      // We didn't find an inserted text offset entry, so
      // create one.

      itEntry = new OffsetEntry(entry->mNode, mSelStartOffset, 0);

      if (!itEntry) {
        editor->EndTransaction();
        UNLOCK_DOC(this);
        return NS_ERROR_OUT_OF_MEMORY;
      }

      itEntry->mNodeOffset = entry->mNodeOffset + entry->mLength;
      itEntry->mIsInsertedText = true;

      if (!mOffsetTable.InsertElementAt(i, itEntry)) {
        delete itEntry;
        return NS_ERROR_FAILURE;
      }
    }

    // We have a valid inserted text offset entry. Update its
    // length, adjust the selection indexes, and make sure the
    // caret is properly placed!

    itEntry->mLength += strLength;

    mSelStartIndex = mSelEndIndex = i;

    rv = mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                               getter_AddRefs(selection));

    if (NS_FAILED(rv)) {
      editor->EndTransaction();
      UNLOCK_DOC(this);
      return rv;
    }

    rv = selection->Collapse(itEntry->mNode,
                             itEntry->mNodeOffset + itEntry->mLength);

    if (NS_FAILED(rv)) {
      editor->EndTransaction();
      UNLOCK_DOC(this);
      return rv;
    }
  } else if (entry->mStrOffset + entry->mLength > mSelStartOffset) {
    // We are inserting text into the middle of the current offset entry.
    // split the current entry into two parts, then insert an inserted text
    // entry between them!

    // XXX Rename this!
    uint32_t i = entry->mLength - (mSelStartOffset - entry->mStrOffset);

    rv = SplitOffsetEntry(mSelStartIndex, i);

    if (NS_FAILED(rv)) {
      editor->EndTransaction();
      UNLOCK_DOC(this);
      return rv;
    }

    itEntry = new OffsetEntry(entry->mNode, mSelStartOffset, strLength);

    if (!itEntry) {
      editor->EndTransaction();
      UNLOCK_DOC(this);
      return NS_ERROR_OUT_OF_MEMORY;
    }

    itEntry->mIsInsertedText = true;
    itEntry->mNodeOffset     = entry->mNodeOffset + entry->mLength;

    if (!mOffsetTable.InsertElementAt(mSelStartIndex + 1, itEntry)) {
      editor->EndTransaction();
      UNLOCK_DOC(this);
      return NS_ERROR_FAILURE;
    }

    mSelEndIndex = ++mSelStartIndex;
  }

  // We've just finished inserting an inserted text offset entry.
  // update all entries with the same mNode pointer that follow
  // it in the table!

  for (size_t i = mSelStartIndex + 1; i < mOffsetTable.Length(); i++) {
    entry = mOffsetTable[i];
    if (entry->mNode != node) {
      break;
    }
    if (entry->mIsValid) {
      entry->mNodeOffset += strLength;
    }
  }

  //**** KDEBUG ****
  // printf("\n---- After Insert\n");
  // printf("Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset);
  // PrintOffsetTable();
  //**** KDEBUG ****

  if (!collapsedSelection) {
    rv = SetSelection(savedSelOffset, savedSelLength);

    if (NS_FAILED(rv)) {
      editor->EndTransaction();
      UNLOCK_DOC(this);
      return rv;
    }

    rv = DeleteSelection();

    if (NS_FAILED(rv)) {
      editor->EndTransaction();
      UNLOCK_DOC(this);
      return rv;
    }
  }

  rv = editor->EndTransaction();

  UNLOCK_DOC(this);

  return rv;
}

NS_IMETHODIMP
nsTextServicesDocument::DidInsertNode(nsIDOMNode *aNode,
                                      nsIDOMNode *aParent,
                                      int32_t     aPosition,
                                      nsresult    aResult)
{
  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::DidDeleteNode(nsIDOMNode *aChild, nsresult aResult)
{
  NS_ENSURE_SUCCESS(aResult, NS_OK);

  NS_ENSURE_TRUE(mIterator, NS_ERROR_FAILURE);

  //**** KDEBUG ****
  // printf("** DeleteNode: 0x%.8x\n", aChild);
  // fflush(stdout);
  //**** KDEBUG ****

  LOCK_DOC(this);

  int32_t nodeIndex = 0;
  bool hasEntry = false;
  OffsetEntry *entry;

  nsresult rv =
    NodeHasOffsetEntry(&mOffsetTable, aChild, &hasEntry, &nodeIndex);

  if (NS_FAILED(rv)) {
    UNLOCK_DOC(this);
    return rv;
  }

  if (!hasEntry) {
    // It's okay if the node isn't in the offset table, the
    // editor could be cleaning house.
    UNLOCK_DOC(this);
    return NS_OK;
  }

  nsCOMPtr<nsIDOMNode> node = do_QueryInterface(mIterator->GetCurrentNode());

  if (node && node == aChild &&
      mIteratorStatus != nsTextServicesDocument::eIsDone) {
    // XXX: This should never really happen because
    // AdjustContentIterator() should have been called prior
    // to the delete to try and position the iterator on the
    // next valid text node in the offset table, and if there
    // wasn't a next, it would've set mIteratorStatus to eIsDone.

    NS_ERROR("DeleteNode called for current iterator node.");
  }

  int32_t tcount = mOffsetTable.Length();

  while (nodeIndex < tcount) {
    entry = mOffsetTable[nodeIndex];

    if (!entry) {
      UNLOCK_DOC(this);
      return NS_ERROR_FAILURE;
    }

    if (entry->mNode == aChild) {
      entry->mIsValid = false;
    }

    nodeIndex++;
  }

  UNLOCK_DOC(this);

  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::DidSplitNode(nsIDOMNode *aExistingRightNode,
                                     int32_t     aOffset,
                                     nsIDOMNode *aNewLeftNode,
                                     nsresult    aResult)
{
  //**** KDEBUG ****
  // printf("** SplitNode: 0x%.8x  %d  0x%.8x\n", aExistingRightNode, aOffset, aNewLeftNode);
  // fflush(stdout);
  //**** KDEBUG ****
  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::DidJoinNodes(nsIDOMNode  *aLeftNode,
                                     nsIDOMNode  *aRightNode,
                                     nsIDOMNode  *aParent,
                                     nsresult     aResult)
{
  NS_ENSURE_SUCCESS(aResult, NS_OK);

  //**** KDEBUG ****
  // printf("** JoinNodes: 0x%.8x  0x%.8x  0x%.8x\n", aLeftNode, aRightNode, aParent);
  // fflush(stdout);
  //**** KDEBUG ****

  // Make sure that both nodes are text nodes -- otherwise we don't care.

  uint16_t type;
  nsresult rv = aLeftNode->GetNodeType(&type);
  NS_ENSURE_SUCCESS(rv, NS_OK);
  if (nsIDOMNode::TEXT_NODE != type) {
    return NS_OK;
  }

  rv = aRightNode->GetNodeType(&type);
  NS_ENSURE_SUCCESS(rv, NS_OK);
  if (nsIDOMNode::TEXT_NODE != type) {
    return NS_OK;
  }

  // Note: The editor merges the contents of the left node into the
  //       contents of the right.

  int32_t leftIndex = 0;
  int32_t rightIndex = 0;
  bool leftHasEntry = false;
  bool rightHasEntry = false;

  rv = NodeHasOffsetEntry(&mOffsetTable, aLeftNode, &leftHasEntry, &leftIndex);

  NS_ENSURE_SUCCESS(rv, rv);

  if (!leftHasEntry) {
    // It's okay if the node isn't in the offset table, the
    // editor could be cleaning house.
    return NS_OK;
  }

  rv = NodeHasOffsetEntry(&mOffsetTable, aRightNode,
                          &rightHasEntry, &rightIndex);

  NS_ENSURE_SUCCESS(rv, rv);

  if (!rightHasEntry) {
    // It's okay if the node isn't in the offset table, the
    // editor could be cleaning house.
    return NS_OK;
  }

  NS_ASSERTION(leftIndex < rightIndex, "Indexes out of order.");

  if (leftIndex > rightIndex) {
    // Don't know how to handle this situation.
    return NS_ERROR_FAILURE;
  }

  LOCK_DOC(this);

  OffsetEntry *entry = mOffsetTable[rightIndex];
  NS_ASSERTION(entry->mNodeOffset == 0, "Unexpected offset value for rightIndex.");

  // Run through the table and change all entries referring to
  // the left node so that they now refer to the right node:

  nsAutoString str;
  aLeftNode->GetNodeValue(str);
  int32_t nodeLength = str.Length();

  for (int32_t i = leftIndex; i < rightIndex; i++) {
    entry = mOffsetTable[i];
    if (entry->mNode != aLeftNode) {
      break;
    }
    if (entry->mIsValid) {
      entry->mNode = aRightNode;
    }
  }

  // Run through the table and adjust the node offsets
  // for all entries referring to the right node.

  for (int32_t i = rightIndex;
       i < static_cast<int32_t>(mOffsetTable.Length()); i++) {
    entry = mOffsetTable[i];
    if (entry->mNode != aRightNode) {
      break;
    }
    if (entry->mIsValid) {
      entry->mNodeOffset += nodeLength;
    }
  }

  // Now check to see if the iterator is pointing to the
  // left node. If it is, make it point to the right node!

  nsCOMPtr<nsIContent> leftContent = do_QueryInterface(aLeftNode);
  nsCOMPtr<nsIContent> rightContent = do_QueryInterface(aRightNode);

  if (!leftContent || !rightContent) {
    UNLOCK_DOC(this);
    return NS_ERROR_FAILURE;
  }

  if (mIterator->GetCurrentNode() == leftContent) {
    mIterator->PositionAt(rightContent);
  }

  UNLOCK_DOC(this);

  return NS_OK;
}

nsresult
nsTextServicesDocument::CreateContentIterator(nsRange* aRange,
                                              nsIContentIterator** aIterator)
{
  NS_ENSURE_TRUE(aRange && aIterator, NS_ERROR_NULL_POINTER);

  *aIterator = nullptr;

  // Create a nsFilteredContentIterator
  // This class wraps the ContentIterator in order to give itself a chance
  // to filter out certain content nodes
  RefPtr<nsFilteredContentIterator> filter = new nsFilteredContentIterator(mTxtSvcFilter);

  nsresult rv = filter->Init(aRange);
  if (NS_FAILED(rv)) {
    return rv;
  }

  filter.forget(aIterator);
  return NS_OK;
}

nsresult
nsTextServicesDocument::GetDocumentContentRootNode(nsIDOMNode **aNode)
{
  NS_ENSURE_TRUE(aNode, NS_ERROR_NULL_POINTER);

  *aNode = 0;

  NS_ENSURE_TRUE(mDOMDocument, NS_ERROR_FAILURE);

  nsCOMPtr<nsIDOMHTMLDocument> htmlDoc = do_QueryInterface(mDOMDocument);

  if (htmlDoc) {
    // For HTML documents, the content root node is the body.

    nsCOMPtr<nsIDOMHTMLElement> bodyElement;

    nsresult rv = htmlDoc->GetBody(getter_AddRefs(bodyElement));

    NS_ENSURE_SUCCESS(rv, rv);

    NS_ENSURE_TRUE(bodyElement, NS_ERROR_FAILURE);

    bodyElement.forget(aNode);
  } else {
    // For non-HTML documents, the content root node will be the document element.

    nsCOMPtr<nsIDOMElement> docElement;

    nsresult rv = mDOMDocument->GetDocumentElement(getter_AddRefs(docElement));

    NS_ENSURE_SUCCESS(rv, rv);

    NS_ENSURE_TRUE(docElement, NS_ERROR_FAILURE);

    docElement.forget(aNode);
  }

  return NS_OK;
}

nsresult
nsTextServicesDocument::CreateDocumentContentRange(nsRange** aRange)
{
  *aRange = nullptr;

  nsCOMPtr<nsIDOMNode> node;
  nsresult rv = GetDocumentContentRootNode(getter_AddRefs(node));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(node, NS_ERROR_NULL_POINTER);

  nsCOMPtr<nsINode> nativeNode = do_QueryInterface(node);
  NS_ENSURE_STATE(nativeNode);

  RefPtr<nsRange> range = new nsRange(nativeNode);

  rv = range->SelectNodeContents(node);
  NS_ENSURE_SUCCESS(rv, rv);

  range.forget(aRange);
  return NS_OK;
}

nsresult
nsTextServicesDocument::CreateDocumentContentRootToNodeOffsetRange(
    nsIDOMNode* aParent, int32_t aOffset, bool aToStart, nsRange** aRange)
{
  NS_ENSURE_TRUE(aParent && aRange, NS_ERROR_NULL_POINTER);

  *aRange = 0;

  NS_ASSERTION(aOffset >= 0, "Invalid offset!");

  if (aOffset < 0) {
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIDOMNode> bodyNode;
  nsresult rv = GetDocumentContentRootNode(getter_AddRefs(bodyNode));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(bodyNode, NS_ERROR_NULL_POINTER);

  nsCOMPtr<nsIDOMNode> startNode;
  nsCOMPtr<nsIDOMNode> endNode;
  int32_t startOffset, endOffset;

  if (aToStart) {
    // The range should begin at the start of the document
    // and extend up until (aParent, aOffset).

    startNode   = bodyNode;
    startOffset = 0;
    endNode     = aParent;
    endOffset   = aOffset;
  } else {
    // The range should begin at (aParent, aOffset) and
    // extend to the end of the document.

    startNode   = aParent;
    startOffset = aOffset;
    endNode     = bodyNode;

    nsCOMPtr<nsINode> body = do_QueryInterface(bodyNode);
    endOffset = body ? int32_t(body->GetChildCount()) : 0;
  }

  return nsRange::CreateRange(startNode, startOffset, endNode, endOffset,
                              aRange);
}

nsresult
nsTextServicesDocument::CreateDocumentContentIterator(nsIContentIterator **aIterator)
{
  NS_ENSURE_TRUE(aIterator, NS_ERROR_NULL_POINTER);

  RefPtr<nsRange> range;

  nsresult rv = CreateDocumentContentRange(getter_AddRefs(range));

  NS_ENSURE_SUCCESS(rv, rv);

  return CreateContentIterator(range, aIterator);
}

nsresult
nsTextServicesDocument::AdjustContentIterator()
{
  NS_ENSURE_TRUE(mIterator, NS_ERROR_FAILURE);

  nsCOMPtr<nsIDOMNode> node(do_QueryInterface(mIterator->GetCurrentNode()));

  NS_ENSURE_TRUE(node, NS_ERROR_FAILURE);

  nsIDOMNode *nodePtr = node.get();
  int32_t tcount      = mOffsetTable.Length();

  nsIDOMNode *prevValidNode = 0;
  nsIDOMNode *nextValidNode = 0;
  bool foundEntry = false;
  OffsetEntry *entry;

  for (int32_t i = 0; i < tcount && !nextValidNode; i++) {
    entry = mOffsetTable[i];

    NS_ENSURE_TRUE(entry, NS_ERROR_FAILURE);

    if (entry->mNode == nodePtr) {
      if (entry->mIsValid) {
        // The iterator is still pointing to something valid!
        // Do nothing!
        return NS_OK;
      }
      // We found an invalid entry that points to
      // the current iterator node. Stop looking for
      // a previous valid node!
      foundEntry = true;
    }

    if (entry->mIsValid) {
      if (!foundEntry) {
        prevValidNode = entry->mNode;
      } else {
        nextValidNode = entry->mNode;
      }
    }
  }

  nsCOMPtr<nsIContent> content;

  if (prevValidNode) {
    content = do_QueryInterface(prevValidNode);
  } else if (nextValidNode) {
    content = do_QueryInterface(nextValidNode);
  }

  if (content) {
    nsresult rv = mIterator->PositionAt(content);

    if (NS_FAILED(rv)) {
      mIteratorStatus = eIsDone;
    } else {
      mIteratorStatus = eValid;
    }
    return rv;
  }

  // If we get here, there aren't any valid entries
  // in the offset table! Try to position the iterator
  // on the next text block first, then previous if
  // one doesn't exist!

  if (mNextTextBlock) {
    nsresult rv = mIterator->PositionAt(mNextTextBlock);

    if (NS_FAILED(rv)) {
      mIteratorStatus = eIsDone;
      return rv;
    }

    mIteratorStatus = eNext;
  } else if (mPrevTextBlock) {
    nsresult rv = mIterator->PositionAt(mPrevTextBlock);

    if (NS_FAILED(rv)) {
      mIteratorStatus = eIsDone;
      return rv;
    }

    mIteratorStatus = ePrev;
  } else {
    mIteratorStatus = eIsDone;
  }
  return NS_OK;
}

bool
nsTextServicesDocument::DidSkip(nsIContentIterator* aFilteredIter)
{
  // We can assume here that the Iterator is a nsFilteredContentIterator because
  // all the iterator are created in CreateContentIterator which create a
  // nsFilteredContentIterator
  // So if the iterator bailed on one of the "filtered" content nodes then we
  // consider that to be a block and bail with true
  if (aFilteredIter) {
    nsFilteredContentIterator* filter = static_cast<nsFilteredContentIterator *>(aFilteredIter);
    if (filter && filter->DidSkip()) {
      return true;
    }
  }
  return false;
}

void
nsTextServicesDocument::ClearDidSkip(nsIContentIterator* aFilteredIter)
{
  // Clear filter's skip flag
  if (aFilteredIter) {
    nsFilteredContentIterator* filter = static_cast<nsFilteredContentIterator *>(aFilteredIter);
    filter->ClearDidSkip();
  }
}

bool
nsTextServicesDocument::IsBlockNode(nsIContent *aContent)
{
  if (!aContent) {
    NS_ERROR("How did a null pointer get passed to IsBlockNode?");
    return false;
  }

  nsIAtom *atom = aContent->NodeInfo()->NameAtom();

  return (sAAtom       != atom &&
          sAddressAtom != atom &&
          sBigAtom     != atom &&
          sBAtom       != atom &&
          sCiteAtom    != atom &&
          sCodeAtom    != atom &&
          sDfnAtom     != atom &&
          sEmAtom      != atom &&
          sFontAtom    != atom &&
          sIAtom       != atom &&
          sKbdAtom     != atom &&
          sKeygenAtom  != atom &&
          sNobrAtom    != atom &&
          sSAtom       != atom &&
          sSampAtom    != atom &&
          sSmallAtom   != atom &&
          sSpacerAtom  != atom &&
          sSpanAtom    != atom &&
          sStrikeAtom  != atom &&
          sStrongAtom  != atom &&
          sSubAtom     != atom &&
          sSupAtom     != atom &&
          sTtAtom      != atom &&
          sUAtom       != atom &&
          sVarAtom     != atom &&
          sWbrAtom     != atom);
}

bool
nsTextServicesDocument::HasSameBlockNodeParent(nsIContent *aContent1, nsIContent *aContent2)
{
  nsIContent* p1 = aContent1->GetParent();
  nsIContent* p2 = aContent2->GetParent();

  // Quick test:

  if (p1 == p2) {
    return true;
  }

  // Walk up the parent hierarchy looking for closest block boundary node:

  while (p1 && !IsBlockNode(p1)) {
    p1 = p1->GetParent();
  }

  while (p2 && !IsBlockNode(p2)) {
    p2 = p2->GetParent();
  }

  return p1 == p2;
}

bool
nsTextServicesDocument::IsTextNode(nsIContent *aContent)
{
  NS_ENSURE_TRUE(aContent, false);
  return nsIDOMNode::TEXT_NODE == aContent->NodeType();
}

bool
nsTextServicesDocument::IsTextNode(nsIDOMNode *aNode)
{
  NS_ENSURE_TRUE(aNode, false);

  nsCOMPtr<nsIContent> content = do_QueryInterface(aNode);
  return IsTextNode(content);
}

nsresult
nsTextServicesDocument::SetSelectionInternal(int32_t aOffset, int32_t aLength, bool aDoUpdate)
{
  NS_ENSURE_TRUE(mSelCon && aOffset >= 0 && aLength >= 0, NS_ERROR_FAILURE);

  nsIDOMNode *sNode = 0, *eNode = 0;
  int32_t sOffset = 0, eOffset = 0;
  OffsetEntry *entry;

  // Find start of selection in node offset terms:

  for (size_t i = 0; !sNode && i < mOffsetTable.Length(); i++) {
    entry = mOffsetTable[i];
    if (entry->mIsValid) {
      if (entry->mIsInsertedText) {
        // Caret can only be placed at the end of an
        // inserted text offset entry, if the offsets
        // match exactly!

        if (entry->mStrOffset == aOffset) {
          sNode   = entry->mNode;
          sOffset = entry->mNodeOffset + entry->mLength;
        }
      } else if (aOffset >= entry->mStrOffset) {
        bool foundEntry = false;
        int32_t strEndOffset = entry->mStrOffset + entry->mLength;

        if (aOffset < strEndOffset) {
          foundEntry = true;
        } else if (aOffset == strEndOffset) {
          // Peek after this entry to see if we have any
          // inserted text entries belonging to the same
          // entry->mNode. If so, we have to place the selection
          // after it!

          if (i + 1 < mOffsetTable.Length()) {
            OffsetEntry *nextEntry = mOffsetTable[i+1];

            if (!nextEntry->mIsValid || nextEntry->mStrOffset != aOffset) {
              // Next offset entry isn't an exact match, so we'll
              // just use the current entry.
              foundEntry = true;
            }
          }
        }

        if (foundEntry) {
          sNode   = entry->mNode;
          sOffset = entry->mNodeOffset + aOffset - entry->mStrOffset;
        }
      }

      if (sNode) {
        mSelStartIndex = static_cast<int32_t>(i);
        mSelStartOffset = aOffset;
      }
    }
  }

  NS_ENSURE_TRUE(sNode, NS_ERROR_FAILURE);

  // XXX: If we ever get a SetSelection() method in nsIEditor, we should
  //      use it.

  nsCOMPtr<nsISelection> selection;

  if (aDoUpdate) {
    nsresult rv =
      mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                            getter_AddRefs(selection));

    NS_ENSURE_SUCCESS(rv, rv);

    rv = selection->Collapse(sNode, sOffset);

    NS_ENSURE_SUCCESS(rv, rv);
   }

  if (aLength <= 0) {
    // We have a collapsed selection. (Caret)

    mSelEndIndex  = mSelStartIndex;
    mSelEndOffset = mSelStartOffset;

   //**** KDEBUG ****
   // printf("\n* Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset);
   //**** KDEBUG ****

    return NS_OK;
  }

  // Find the end of the selection in node offset terms:
  int32_t endOffset = aOffset + aLength;
  for (int32_t i = mOffsetTable.Length() - 1; !eNode && i >= 0; i--) {
    entry = mOffsetTable[i];

    if (entry->mIsValid) {
      if (entry->mIsInsertedText) {
        if (entry->mStrOffset == eOffset) {
          // If the selection ends on an inserted text offset entry,
          // the selection includes the entire entry!

          eNode   = entry->mNode;
          eOffset = entry->mNodeOffset + entry->mLength;
        }
      } else if (endOffset >= entry->mStrOffset &&
                 endOffset <= entry->mStrOffset + entry->mLength) {
        eNode   = entry->mNode;
        eOffset = entry->mNodeOffset + endOffset - entry->mStrOffset;
      }

      if (eNode) {
        mSelEndIndex = i;
        mSelEndOffset = endOffset;
      }
    }
  }

  if (aDoUpdate && eNode) {
    nsresult rv = selection->Extend(eNode, eOffset);

    NS_ENSURE_SUCCESS(rv, rv);
  }

  //**** KDEBUG ****
  // printf("\n * Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset);
  //**** KDEBUG ****

  return NS_OK;
}

nsresult
nsTextServicesDocument::GetSelection(nsITextServicesDocument::TSDBlockSelectionStatus *aSelStatus, int32_t *aSelOffset, int32_t *aSelLength)
{
  NS_ENSURE_TRUE(aSelStatus && aSelOffset && aSelLength, NS_ERROR_NULL_POINTER);

  *aSelStatus = nsITextServicesDocument::eBlockNotFound;
  *aSelOffset = -1;
  *aSelLength = -1;

  NS_ENSURE_TRUE(mDOMDocument && mSelCon, NS_ERROR_FAILURE);

  if (mIteratorStatus == nsTextServicesDocument::eIsDone) {
    return NS_OK;
  }

  nsCOMPtr<nsISelection> selection;
  bool isCollapsed;

  nsresult rv = mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                                      getter_AddRefs(selection));

  NS_ENSURE_SUCCESS(rv, rv);

  NS_ENSURE_TRUE(selection, NS_ERROR_FAILURE);

  rv = selection->GetIsCollapsed(&isCollapsed);

  NS_ENSURE_SUCCESS(rv, rv);

  // XXX: If we expose this method publicly, we need to
  //      add LOCK_DOC/UNLOCK_DOC calls!

  // LOCK_DOC(this);

  if (isCollapsed) {
    rv = GetCollapsedSelection(aSelStatus, aSelOffset, aSelLength);
  } else {
    rv = GetUncollapsedSelection(aSelStatus, aSelOffset, aSelLength);
  }

  // UNLOCK_DOC(this);

  // XXX The result of GetCollapsedSelection() or GetUncollapsedSelection().
  return rv;
}

nsresult
nsTextServicesDocument::GetCollapsedSelection(nsITextServicesDocument::TSDBlockSelectionStatus *aSelStatus, int32_t *aSelOffset, int32_t *aSelLength)
{
  nsCOMPtr<nsISelection> domSelection;
  nsresult rv =
    mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                          getter_AddRefs(domSelection));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(domSelection, NS_ERROR_FAILURE);

  RefPtr<Selection> selection = domSelection->AsSelection();

  // The calling function should have done the GetIsCollapsed()
  // check already. Just assume it's collapsed!
  *aSelStatus = nsITextServicesDocument::eBlockOutside;
  *aSelOffset = *aSelLength = -1;

  int32_t tableCount = mOffsetTable.Length();

  if (!tableCount) {
    return NS_OK;
  }

  // Get pointers to the first and last offset entries
  // in the table.

  OffsetEntry* eStart = mOffsetTable[0];
  OffsetEntry* eEnd;
  if (tableCount > 1) {
    eEnd = mOffsetTable[tableCount - 1];
  } else {
    eEnd = eStart;
  }

  int32_t eStartOffset = eStart->mNodeOffset;
  int32_t eEndOffset   = eEnd->mNodeOffset + eEnd->mLength;

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

  nsCOMPtr<nsIDOMNode> domParent;
  rv = range->GetStartContainer(getter_AddRefs(domParent));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsINode> parent = do_QueryInterface(domParent);
  MOZ_ASSERT(parent);

  int32_t offset;
  rv = range->GetStartOffset(&offset);
  NS_ENSURE_SUCCESS(rv, rv);

  int32_t e1s1 = nsContentUtils::ComparePoints(eStart->mNode, eStartOffset,
                                               domParent, offset);
  int32_t e2s1 = nsContentUtils::ComparePoints(eEnd->mNode, eEndOffset,
                                               domParent, offset);

  if (e1s1 > 0 || e2s1 < 0) {
    // We're done if the caret is outside the current text block.
    return NS_OK;
  }

  if (parent->NodeType() == nsIDOMNode::TEXT_NODE) {
    // Good news, the caret is in a text node. Look
    // through the offset table for the entry that
    // matches its parent and offset.

    for (int32_t i = 0; i < tableCount; i++) {
      OffsetEntry* entry = mOffsetTable[i];
      NS_ENSURE_TRUE(entry, NS_ERROR_FAILURE);

      if (entry->mNode == domParent.get() &&
          entry->mNodeOffset <= offset &&
          offset <= entry->mNodeOffset + entry->mLength) {
        *aSelStatus = nsITextServicesDocument::eBlockContains;
        *aSelOffset = entry->mStrOffset + (offset - entry->mNodeOffset);
        *aSelLength = 0;

        return NS_OK;
      }
    }

    // If we get here, we didn't find a text node entry
    // in our offset table that matched.

    return NS_ERROR_FAILURE;
  }

  // The caret is in our text block, but it's positioned in some
  // non-text node (ex. <b>). Create a range based on the start
  // and end of the text block, then create an iterator based on
  // this range, with its initial position set to the closest
  // child of this non-text node. Then look for the closest text
  // node.

  rv = CreateRange(eStart->mNode, eStartOffset, eEnd->mNode, eEndOffset,
                   getter_AddRefs(range));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIContentIterator> iter;
  rv = CreateContentIterator(range, getter_AddRefs(iter));
  NS_ENSURE_SUCCESS(rv, rv);

  nsIContent* saveNode;
  if (parent->HasChildren()) {
    // XXX: We need to make sure that all of parent's
    //      children are in the text block.

    // If the parent has children, position the iterator
    // on the child that is to the left of the offset.

    uint32_t childIndex = (uint32_t)offset;

    if (childIndex > 0) {
      uint32_t numChildren = parent->GetChildCount();
      NS_ASSERTION(childIndex <= numChildren, "Invalid selection offset!");

      if (childIndex > numChildren) {
        childIndex = numChildren;
      }

      childIndex -= 1;
    }

    nsIContent* content = parent->GetChildAt(childIndex);
    NS_ENSURE_TRUE(content, NS_ERROR_FAILURE);

    rv = iter->PositionAt(content);
    NS_ENSURE_SUCCESS(rv, rv);

    saveNode = content;
  } else {
    // The parent has no children, so position the iterator
    // on the parent.
    NS_ENSURE_TRUE(parent->IsContent(), NS_ERROR_FAILURE);
    nsCOMPtr<nsIContent> content = parent->AsContent();

    rv = iter->PositionAt(content);
    NS_ENSURE_SUCCESS(rv, rv);

    saveNode = content;
  }

  // Now iterate to the left, towards the beginning of
  // the text block, to find the first text node you
  // come across.

  nsIContent* node = nullptr;
  while (!iter->IsDone()) {
    nsINode* current = iter->GetCurrentNode();
    if (current->NodeType() == nsIDOMNode::TEXT_NODE) {
      node = static_cast<nsIContent*>(current);
      break;
    }

    iter->Prev();
  }

  if (node) {
    // We found a node, now set the offset to the end
    // of the text node.
    offset = node->TextLength();
  } else {
    // We should never really get here, but I'm paranoid.

    // We didn't find a text node above, so iterate to
    // the right, towards the end of the text block, looking
    // for a text node.

    rv = iter->PositionAt(saveNode);
    NS_ENSURE_SUCCESS(rv, rv);

    node = nullptr;
    while (!iter->IsDone()) {
      nsINode* current = iter->GetCurrentNode();

      if (current->NodeType() == nsIDOMNode::TEXT_NODE) {
        node = static_cast<nsIContent*>(current);
        break;
      }

      iter->Next();
    }

    NS_ENSURE_TRUE(node, NS_ERROR_FAILURE);

    // We found a text node, so set the offset to
    // the beginning of the node.

    offset = 0;
  }

  for (int32_t i = 0; i < tableCount; i++) {
    OffsetEntry* entry = mOffsetTable[i];
    NS_ENSURE_TRUE(entry, NS_ERROR_FAILURE);

    if (entry->mNode == node->AsDOMNode() &&
        entry->mNodeOffset <= offset &&
        offset <= entry->mNodeOffset + entry->mLength) {
      *aSelStatus = nsITextServicesDocument::eBlockContains;
      *aSelOffset = entry->mStrOffset + (offset - entry->mNodeOffset);
      *aSelLength = 0;

      // Now move the caret so that it is actually in the text node.
      // We do this to keep things in sync.
      //
      // In most cases, the user shouldn't see any movement in the caret
      // on screen.

      return SetSelectionInternal(*aSelOffset, *aSelLength, true);
    }
  }

  return NS_ERROR_FAILURE;
}

nsresult
nsTextServicesDocument::GetUncollapsedSelection(nsITextServicesDocument::TSDBlockSelectionStatus *aSelStatus, int32_t *aSelOffset, int32_t *aSelLength)
{
  RefPtr<nsRange> range;
  OffsetEntry *entry;

  nsCOMPtr<nsISelection> domSelection;
  nsresult rv = mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                                      getter_AddRefs(domSelection));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(domSelection, NS_ERROR_FAILURE);

  RefPtr<Selection> selection = domSelection->AsSelection();

  // It is assumed that the calling function has made sure that the
  // selection is not collapsed, and that the input params to this
  // method are initialized to some defaults.

  nsCOMPtr<nsIDOMNode> startParent, endParent;
  int32_t startOffset, endOffset;
  int32_t rangeCount, tableCount;
  int32_t e1s1 = 0, e1s2 = 0, e2s1 = 0, e2s2 = 0;

  OffsetEntry *eStart, *eEnd;
  int32_t eStartOffset, eEndOffset;

  tableCount = mOffsetTable.Length();

  // Get pointers to the first and last offset entries
  // in the table.

  eStart = mOffsetTable[0];

  if (tableCount > 1) {
    eEnd = mOffsetTable[tableCount - 1];
  } else {
    eEnd = eStart;
  }

  eStartOffset = eStart->mNodeOffset;
  eEndOffset   = eEnd->mNodeOffset + eEnd->mLength;

  rv = selection->GetRangeCount(&rangeCount);

  NS_ENSURE_SUCCESS(rv, rv);

  // Find the first range in the selection that intersects
  // the current text block.

  for (int32_t i = 0; i < rangeCount; i++) {
    range = selection->GetRangeAt(i);
    NS_ENSURE_STATE(range);

    rv = GetRangeEndPoints(range,
                           getter_AddRefs(startParent), &startOffset,
                           getter_AddRefs(endParent), &endOffset);

    NS_ENSURE_SUCCESS(rv, rv);

    e1s2 = nsContentUtils::ComparePoints(eStart->mNode, eStartOffset,
                                         endParent, endOffset);
    e2s1 = nsContentUtils::ComparePoints(eEnd->mNode, eEndOffset,
                                         startParent, startOffset);

    // Break out of the loop if the text block intersects the current range.

    if (e1s2 <= 0 && e2s1 >= 0) {
      break;
    }
  }

  // We're done if we didn't find an intersecting range.

  if (rangeCount < 1 || e1s2 > 0 || e2s1 < 0) {
    *aSelStatus = nsITextServicesDocument::eBlockOutside;
    *aSelOffset = *aSelLength = -1;
    return NS_OK;
  }

  // Now that we have an intersecting range, find out more info:

  e1s1 = nsContentUtils::ComparePoints(eStart->mNode, eStartOffset,
                                       startParent, startOffset);
  e2s2 = nsContentUtils::ComparePoints(eEnd->mNode, eEndOffset,
                                       endParent, endOffset);

  if (rangeCount > 1) {
    // There are multiple selection ranges, we only deal
    // with the first one that intersects the current,
    // text block, so mark this a as a partial.
    *aSelStatus = nsITextServicesDocument::eBlockPartial;
  } else if (e1s1 > 0 && e2s2 < 0) {
    // The range extends beyond the start and
    // end of the current text block.
    *aSelStatus = nsITextServicesDocument::eBlockInside;
  } else if (e1s1 <= 0 && e2s2 >= 0) {
    // The current text block contains the entire
    // range.
    *aSelStatus = nsITextServicesDocument::eBlockContains;
  } else {
    // The range partially intersects the block.
    *aSelStatus = nsITextServicesDocument::eBlockPartial;
  }

  // Now create a range based on the intersection of the
  // text block and range:

  nsCOMPtr<nsIDOMNode> p1, p2;
  int32_t     o1,  o2;

  // The start of the range will be the rightmost
  // start node.

  if (e1s1 >= 0) {
    p1 = do_QueryInterface(eStart->mNode);
    o1 = eStartOffset;
  } else {
    p1 = startParent;
    o1 = startOffset;
  }

  // The end of the range will be the leftmost
  // end node.

  if (e2s2 <= 0) {
    p2 = do_QueryInterface(eEnd->mNode);
    o2 = eEndOffset;
  } else {
    p2 = endParent;
    o2 = endOffset;
  }

  rv = CreateRange(p1, o1, p2, o2, getter_AddRefs(range));

  NS_ENSURE_SUCCESS(rv, rv);

  // Now iterate over this range to figure out the selection's
  // block offset and length.

  nsCOMPtr<nsIContentIterator> iter;

  rv = CreateContentIterator(range, getter_AddRefs(iter));

  NS_ENSURE_SUCCESS(rv, rv);

  // Find the first text node in the range.

  bool found;
  nsCOMPtr<nsIContent> content;

  iter->First();

  if (!IsTextNode(p1)) {
    found = false;

    while (!iter->IsDone()) {
      content = do_QueryInterface(iter->GetCurrentNode());

      if (IsTextNode(content)) {
        p1 = do_QueryInterface(content);

        NS_ENSURE_TRUE(p1, NS_ERROR_FAILURE);

        o1 = 0;
        found = true;

        break;
      }

      iter->Next();
    }

    NS_ENSURE_TRUE(found, NS_ERROR_FAILURE);
  }

  // Find the last text node in the range.

  iter->Last();

  if (!IsTextNode(p2)) {
    found = false;
    while (!iter->IsDone()) {
      content = do_QueryInterface(iter->GetCurrentNode());
      if (IsTextNode(content)) {
        p2 = do_QueryInterface(content);

        NS_ENSURE_TRUE(p2, NS_ERROR_FAILURE);

        nsString str;

        rv = p2->GetNodeValue(str);

        NS_ENSURE_SUCCESS(rv, rv);

        o2 = str.Length();
        found = true;

        break;
      }

      iter->Prev();
    }

    NS_ENSURE_TRUE(found, NS_ERROR_FAILURE);
  }

  found    = false;
  *aSelLength = 0;

  for (int32_t i = 0; i < tableCount; i++) {
    entry = mOffsetTable[i];
    NS_ENSURE_TRUE(entry, NS_ERROR_FAILURE);
    if (!found) {
      if (entry->mNode == p1.get() &&
          entry->mNodeOffset <= o1 &&
          o1 <= entry->mNodeOffset + entry->mLength) {
        *aSelOffset = entry->mStrOffset + (o1 - entry->mNodeOffset);
        if (p1 == p2 &&
            entry->mNodeOffset <= o2 &&
            o2 <= entry->mNodeOffset + entry->mLength) {
          // The start and end of the range are in the same offset
          // entry. Calculate the length of the range then we're done.
          *aSelLength = o2 - o1;
          break;
        }
        // Add the length of the sub string in this offset entry
        // that follows the start of the range.
        *aSelLength = entry->mLength - (o1 - entry->mNodeOffset);
        found = true;
      }
    } else { // Found.
      if (entry->mNode == p2.get() &&
          entry->mNodeOffset <= o2 &&
          o2 <= entry->mNodeOffset + entry->mLength) {
        // We found the end of the range. Calculate the length of the
        // sub string that is before the end of the range, then we're done.
        *aSelLength += o2 - entry->mNodeOffset;
        break;
      }
      // The entire entry must be in the range.
      *aSelLength += entry->mLength;
    }
  }

  return NS_OK;
}

bool
nsTextServicesDocument::SelectionIsCollapsed()
{
  return(mSelStartIndex == mSelEndIndex && mSelStartOffset == mSelEndOffset);
}

bool
nsTextServicesDocument::SelectionIsValid()
{
  return(mSelStartIndex >= 0);
}

nsresult
nsTextServicesDocument::GetRangeEndPoints(nsRange* aRange,
                                          nsIDOMNode **aStartParent, int32_t *aStartOffset,
                                          nsIDOMNode **aEndParent, int32_t *aEndOffset)
{
  NS_ENSURE_TRUE(aRange && aStartParent && aStartOffset && aEndParent && aEndOffset, NS_ERROR_NULL_POINTER);

  nsresult rv = aRange->GetStartContainer(aStartParent);

  NS_ENSURE_SUCCESS(rv, rv);

  NS_ENSURE_TRUE(aStartParent, NS_ERROR_FAILURE);

  rv = aRange->GetStartOffset(aStartOffset);

  NS_ENSURE_SUCCESS(rv, rv);

  rv = aRange->GetEndContainer(aEndParent);

  NS_ENSURE_SUCCESS(rv, rv);

  NS_ENSURE_TRUE(aEndParent, NS_ERROR_FAILURE);

  return aRange->GetEndOffset(aEndOffset);
}

nsresult
nsTextServicesDocument::CreateRange(nsIDOMNode *aStartParent, int32_t aStartOffset,
                                    nsIDOMNode *aEndParent, int32_t aEndOffset,
                                    nsRange** aRange)
{
  return nsRange::CreateRange(aStartParent, aStartOffset, aEndParent,
                              aEndOffset, aRange);
}

nsresult
nsTextServicesDocument::FirstTextNode(nsIContentIterator *aIterator,
                                      TSDIteratorStatus *aIteratorStatus)
{
  if (aIteratorStatus) {
    *aIteratorStatus = nsTextServicesDocument::eIsDone;
  }

  aIterator->First();

  while (!aIterator->IsDone()) {
    if (aIterator->GetCurrentNode()->NodeType() == nsIDOMNode::TEXT_NODE) {
      if (aIteratorStatus) {
        *aIteratorStatus = nsTextServicesDocument::eValid;
      }
      break;
    }
    aIterator->Next();
  }

  return NS_OK;
}

nsresult
nsTextServicesDocument::LastTextNode(nsIContentIterator *aIterator,
                                     TSDIteratorStatus *aIteratorStatus)
{
  if (aIteratorStatus) {
    *aIteratorStatus = nsTextServicesDocument::eIsDone;
  }

  aIterator->Last();

  while (!aIterator->IsDone()) {
    if (aIterator->GetCurrentNode()->NodeType() == nsIDOMNode::TEXT_NODE) {
      if (aIteratorStatus) {
        *aIteratorStatus = nsTextServicesDocument::eValid;
      }
      break;
    }
    aIterator->Prev();
  }

  return NS_OK;
}

nsresult
nsTextServicesDocument::FirstTextNodeInCurrentBlock(nsIContentIterator *iter)
{
  NS_ENSURE_TRUE(iter, NS_ERROR_NULL_POINTER);

  ClearDidSkip(iter);

  nsCOMPtr<nsIContent> last;

  // Walk backwards over adjacent text nodes until
  // we hit a block boundary:

  while (!iter->IsDone()) {
    nsCOMPtr<nsIContent> content = iter->GetCurrentNode()->IsContent()
                                   ? iter->GetCurrentNode()->AsContent()
                                   : nullptr;
    if (last && IsBlockNode(content)) {
      break;
    }
    if (IsTextNode(content)) {
      if (last && !HasSameBlockNodeParent(content, last)) {
        // We're done, the current text node is in a
        // different block.
        break;
      }
      last = content;
    }

    iter->Prev();

    if (DidSkip(iter)) {
      break;
    }
  }

  if (last) {
    iter->PositionAt(last);
  }

  // XXX: What should we return if last is null?

  return NS_OK;
}

nsresult
nsTextServicesDocument::FirstTextNodeInPrevBlock(nsIContentIterator *aIterator)
{
  NS_ENSURE_TRUE(aIterator, NS_ERROR_NULL_POINTER);

  // XXX: What if mIterator is not currently on a text node?

  // Make sure mIterator is pointing to the first text node in the
  // current block:

  nsresult rv = FirstTextNodeInCurrentBlock(aIterator);

  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);

  // Point mIterator to the first node before the first text node:

  aIterator->Prev();

  if (aIterator->IsDone()) {
    return NS_ERROR_FAILURE;
  }

  // Now find the first text node of the next block:

  return FirstTextNodeInCurrentBlock(aIterator);
}

nsresult
nsTextServicesDocument::FirstTextNodeInNextBlock(nsIContentIterator *aIterator)
{
  nsCOMPtr<nsIContent> prev;
  bool crossedBlockBoundary = false;

  NS_ENSURE_TRUE(aIterator, NS_ERROR_NULL_POINTER);

  ClearDidSkip(aIterator);

  while (!aIterator->IsDone()) {
    nsCOMPtr<nsIContent> content = aIterator->GetCurrentNode()->IsContent()
                                   ? aIterator->GetCurrentNode()->AsContent()
                                   : nullptr;

    if (IsTextNode(content)) {
      if (crossedBlockBoundary ||
          (prev && !HasSameBlockNodeParent(prev, content))) {
        break;
      }
      prev = content;
    } else if (!crossedBlockBoundary && IsBlockNode(content)) {
      crossedBlockBoundary = true;
    }

    aIterator->Next();

    if (!crossedBlockBoundary && DidSkip(aIterator)) {
      crossedBlockBoundary = true;
    }
  }

  return NS_OK;
}

nsresult
nsTextServicesDocument::GetFirstTextNodeInPrevBlock(nsIContent **aContent)
{
  NS_ENSURE_TRUE(aContent, NS_ERROR_NULL_POINTER);

  *aContent = 0;

  // Save the iterator's current content node so we can restore
  // it when we are done:

  nsINode* node = mIterator->GetCurrentNode();

  nsresult rv = FirstTextNodeInPrevBlock(mIterator);

  if (NS_FAILED(rv)) {
    // Try to restore the iterator before returning.
    mIterator->PositionAt(node);
    return rv;
  }

  if (!mIterator->IsDone()) {
    nsCOMPtr<nsIContent> current = mIterator->GetCurrentNode()->IsContent()
                                   ? mIterator->GetCurrentNode()->AsContent()
                                   : nullptr;
    current.forget(aContent);
  }

  // Restore the iterator:

  return mIterator->PositionAt(node);
}

nsresult
nsTextServicesDocument::GetFirstTextNodeInNextBlock(nsIContent **aContent)
{
  NS_ENSURE_TRUE(aContent, NS_ERROR_NULL_POINTER);

  *aContent = 0;

  // Save the iterator's current content node so we can restore
  // it when we are done:

  nsINode* node = mIterator->GetCurrentNode();

  nsresult rv = FirstTextNodeInNextBlock(mIterator);

  if (NS_FAILED(rv)) {
    // Try to restore the iterator before returning.
    mIterator->PositionAt(node);
    return rv;
  }

  if (!mIterator->IsDone()) {
    nsCOMPtr<nsIContent> current = mIterator->GetCurrentNode()->IsContent()
                                   ? mIterator->GetCurrentNode()->AsContent()
                                   : nullptr;
    current.forget(aContent);
  }

  // Restore the iterator:
  return mIterator->PositionAt(node);
}

nsresult
nsTextServicesDocument::CreateOffsetTable(nsTArray<OffsetEntry*> *aOffsetTable,
                                          nsIContentIterator *aIterator,
                                          TSDIteratorStatus *aIteratorStatus,
                                          nsRange* aIterRange, nsString* aStr)
{
  nsCOMPtr<nsIContent> first;
  nsCOMPtr<nsIContent> prev;

  NS_ENSURE_TRUE(aIterator, NS_ERROR_NULL_POINTER);

  ClearOffsetTable(aOffsetTable);

  if (aStr) {
    aStr->Truncate();
  }

  if (*aIteratorStatus == nsTextServicesDocument::eIsDone) {
    return NS_OK;
  }

  // If we have an aIterRange, retrieve the endpoints so
  // they can be used in the while loop below to trim entries
  // for text nodes that are partially selected by aIterRange.

  nsCOMPtr<nsIDOMNode> rngStartNode, rngEndNode;
  int32_t rngStartOffset = 0, rngEndOffset = 0;

  if (aIterRange) {
    nsresult rv =
      GetRangeEndPoints(aIterRange,
                        getter_AddRefs(rngStartNode), &rngStartOffset,
                        getter_AddRefs(rngEndNode), &rngEndOffset);

    NS_ENSURE_SUCCESS(rv, rv);
  }

  // The text service could have added text nodes to the beginning
  // of the current block and called this method again. Make sure
  // we really are at the beginning of the current block:

  nsresult rv = FirstTextNodeInCurrentBlock(aIterator);

  NS_ENSURE_SUCCESS(rv, rv);

  int32_t offset = 0;

  ClearDidSkip(aIterator);

  while (!aIterator->IsDone()) {
    nsCOMPtr<nsIContent> content = aIterator->GetCurrentNode()->IsContent()
                                   ? aIterator->GetCurrentNode()->AsContent()
                                   : nullptr;
    if (IsTextNode(content)) {
      if (prev && !HasSameBlockNodeParent(prev, content)) {
        break;
      }

      nsCOMPtr<nsIDOMNode> node = do_QueryInterface(content);
      if (node) {
        nsString str;

        rv = node->GetNodeValue(str);

        NS_ENSURE_SUCCESS(rv, rv);

        // Add an entry for this text node into the offset table:

        OffsetEntry *entry = new OffsetEntry(node, offset, str.Length());
        aOffsetTable->AppendElement(entry);

        // If one or both of the endpoints of the iteration range
        // are in the text node for this entry, make sure the entry
        // only accounts for the portion of the text node that is
        // in the range.

        int32_t startOffset = 0;
        int32_t endOffset   = str.Length();
        bool adjustStr    = false;

        if (entry->mNode == rngStartNode) {
          entry->mNodeOffset = startOffset = rngStartOffset;
          adjustStr = true;
        }

        if (entry->mNode == rngEndNode) {
          endOffset = rngEndOffset;
          adjustStr = true;
        }

        if (adjustStr) {
          entry->mLength = endOffset - startOffset;
          str = Substring(str, startOffset, entry->mLength);
        }

        offset += str.Length();

        if (aStr) {
          // Append the text node's string to the output string:
          if (!first) {
            *aStr = str;
          } else {
            *aStr += str;
          }
        }
      }

      prev = content;

      if (!first) {
        first = content;
      }
    }
    // XXX This should be checked before IsTextNode(), but IsBlockNode() returns
    //     true even if content is a text node.  See bug 1311934.
    else if (IsBlockNode(content)) {
      break;
    }

    aIterator->Next();

    if (DidSkip(aIterator)) {
      break;
    }
  }

  if (first) {
    // Always leave the iterator pointing at the first
    // text node of the current block!
    aIterator->PositionAt(first);
  } else {
    // If we never ran across a text node, the iterator
    // might have been pointing to something invalid to
    // begin with.
    *aIteratorStatus = nsTextServicesDocument::eIsDone;
  }

  return NS_OK;
}

nsresult
nsTextServicesDocument::RemoveInvalidOffsetEntries()
{
  for (size_t i = 0; i < mOffsetTable.Length(); ) {
    OffsetEntry* entry = mOffsetTable[i];
    if (!entry->mIsValid) {
      mOffsetTable.RemoveElementAt(i);
      if (mSelStartIndex >= 0 && static_cast<size_t>(mSelStartIndex) >= i) {
        // We are deleting an entry that comes before
        // mSelStartIndex, decrement mSelStartIndex so
        // that it points to the correct entry!

        NS_ASSERTION(i != static_cast<size_t>(mSelStartIndex),
                     "Invalid selection index.");

        --mSelStartIndex;
        --mSelEndIndex;
      }
    } else {
      i++;
    }
  }

  return NS_OK;
}

nsresult
nsTextServicesDocument::ClearOffsetTable(nsTArray<OffsetEntry*> *aOffsetTable)
{
  for (size_t i = 0; i < aOffsetTable->Length(); i++) {
    delete aOffsetTable->ElementAt(i);
  }

  aOffsetTable->Clear();

  return NS_OK;
}

nsresult
nsTextServicesDocument::SplitOffsetEntry(int32_t aTableIndex, int32_t aNewEntryLength)
{
  OffsetEntry *entry = mOffsetTable[aTableIndex];

  NS_ASSERTION((aNewEntryLength > 0), "aNewEntryLength <= 0");
  NS_ASSERTION((aNewEntryLength < entry->mLength), "aNewEntryLength >= mLength");

  if (aNewEntryLength < 1 || aNewEntryLength >= entry->mLength) {
    return NS_ERROR_FAILURE;
  }

  int32_t oldLength = entry->mLength - aNewEntryLength;

  OffsetEntry *newEntry = new OffsetEntry(entry->mNode,
                                          entry->mStrOffset + oldLength,
                                          aNewEntryLength);

  if (!mOffsetTable.InsertElementAt(aTableIndex + 1, newEntry)) {
    delete newEntry;
    return NS_ERROR_FAILURE;
  }

   // Adjust entry fields:

   entry->mLength        = oldLength;
   newEntry->mNodeOffset = entry->mNodeOffset + oldLength;

  return NS_OK;
}

nsresult
nsTextServicesDocument::NodeHasOffsetEntry(nsTArray<OffsetEntry*> *aOffsetTable, nsIDOMNode *aNode, bool *aHasEntry, int32_t *aEntryIndex)
{
  NS_ENSURE_TRUE(aNode && aHasEntry && aEntryIndex, NS_ERROR_NULL_POINTER);

  for (size_t i = 0; i < aOffsetTable->Length(); i++) {
    OffsetEntry* entry = (*aOffsetTable)[i];

    NS_ENSURE_TRUE(entry, NS_ERROR_FAILURE);

    if (entry->mNode == aNode) {
      *aHasEntry   = true;
      *aEntryIndex = i;
      return NS_OK;
    }
  }

  *aHasEntry   = false;
  *aEntryIndex = -1;
  return NS_OK;
}

// Spellchecker code has this. See bug 211343
#define IS_NBSP_CHAR(c) (((unsigned char)0xa0)==(c))

nsresult
nsTextServicesDocument::FindWordBounds(nsTArray<OffsetEntry*> *aOffsetTable,
                                       nsString *aBlockStr,
                                       nsIDOMNode *aNode,
                                       int32_t aNodeOffset,
                                       nsIDOMNode **aWordStartNode,
                                       int32_t *aWordStartOffset,
                                       nsIDOMNode **aWordEndNode,
                                       int32_t *aWordEndOffset)
{
  // Initialize return values.

  if (aWordStartNode) {
    *aWordStartNode = nullptr;
  }
  if (aWordStartOffset) {
    *aWordStartOffset = 0;
  }
  if (aWordEndNode) {
    *aWordEndNode = nullptr;
  }
  if (aWordEndOffset) {
    *aWordEndOffset = 0;
  }

  int32_t entryIndex = 0;
  bool hasEntry = false;

  // It's assumed that aNode is a text node. The first thing
  // we do is get its index in the offset table so we can
  // calculate the dom point's string offset.

  nsresult rv = NodeHasOffsetEntry(aOffsetTable, aNode, &hasEntry, &entryIndex);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(hasEntry, NS_ERROR_FAILURE);

  // Next we map aNodeOffset into a string offset.

  OffsetEntry *entry = (*aOffsetTable)[entryIndex];
  uint32_t strOffset = entry->mStrOffset + aNodeOffset - entry->mNodeOffset;

  // Now we use the word breaker to find the beginning and end
  // of the word from our calculated string offset.

  const char16_t *str = aBlockStr->get();
  uint32_t strLen = aBlockStr->Length();

  nsIWordBreaker* wordBreaker = nsContentUtils::WordBreaker();
  nsWordRange res = wordBreaker->FindWord(str, strLen, strOffset);
  if (res.mBegin > strLen) {
    return str ? NS_ERROR_ILLEGAL_VALUE : NS_ERROR_NULL_POINTER;
  }

  // Strip out the NBSPs at the ends
  while (res.mBegin <= res.mEnd && IS_NBSP_CHAR(str[res.mBegin])) {
    res.mBegin++;
  }
  if (str[res.mEnd] == (unsigned char)0x20) {
    uint32_t realEndWord = res.mEnd - 1;
    while (realEndWord > res.mBegin && IS_NBSP_CHAR(str[realEndWord])) {
      realEndWord--;
    }
    if (realEndWord < res.mEnd - 1) {
      res.mEnd = realEndWord + 1;
    }
  }

  // Now that we have the string offsets for the beginning
  // and end of the word, run through the offset table and
  // convert them back into dom points.

  size_t lastIndex = aOffsetTable->Length() - 1;
  for (size_t i = 0; i <= lastIndex; i++) {
    entry = (*aOffsetTable)[i];

    int32_t strEndOffset = entry->mStrOffset + entry->mLength;

    // Check to see if res.mBegin is within the range covered
    // by this entry. Note that if res.mBegin is after the last
    // character covered by this entry, we will use the next
    // entry if there is one.

    if (uint32_t(entry->mStrOffset) <= res.mBegin &&
        (res.mBegin < static_cast<uint32_t>(strEndOffset) ||
         (res.mBegin == static_cast<uint32_t>(strEndOffset) &&
          i == lastIndex))) {
      if (aWordStartNode) {
        *aWordStartNode = entry->mNode;
        NS_IF_ADDREF(*aWordStartNode);
      }

      if (aWordStartOffset) {
        *aWordStartOffset = entry->mNodeOffset + res.mBegin - entry->mStrOffset;
      }

      if (!aWordEndNode && !aWordEndOffset) {
        // We've found our start entry, but if we're not looking
        // for end entries, we're done.
        break;
      }
    }

    // Check to see if res.mEnd is within the range covered
    // by this entry.

    if (static_cast<uint32_t>(entry->mStrOffset) <= res.mEnd &&
        res.mEnd <= static_cast<uint32_t>(strEndOffset)) {
      if (res.mBegin == res.mEnd &&
          res.mEnd == static_cast<uint32_t>(strEndOffset) &&
          i != lastIndex) {
        // Wait for the next round so that we use the same entry
        // we did for aWordStartNode.
        continue;
      }

      if (aWordEndNode) {
        *aWordEndNode = entry->mNode;
        NS_IF_ADDREF(*aWordEndNode);
      }

      if (aWordEndOffset) {
        *aWordEndOffset = entry->mNodeOffset + res.mEnd - entry->mStrOffset;
      }
      break;
    }
  }


  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::WillInsertNode(nsIDOMNode *aNode,
                              nsIDOMNode *aParent,
                              int32_t     aPosition)
{
  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::WillDeleteNode(nsIDOMNode *aChild)
{
  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::WillSplitNode(nsIDOMNode *aExistingRightNode,
                             int32_t     aOffset)
{
  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::WillJoinNodes(nsIDOMNode  *aLeftNode,
                             nsIDOMNode  *aRightNode,
                             nsIDOMNode  *aParent)
{
  return NS_OK;
}

// -------------------------------
// stubs for unused listen methods
// -------------------------------

NS_IMETHODIMP
nsTextServicesDocument::WillCreateNode(const nsAString& aTag, nsIDOMNode *aParent, int32_t aPosition)
{
  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::DidCreateNode(const nsAString& aTag, nsIDOMNode *aNode, nsIDOMNode *aParent, int32_t aPosition, nsresult aResult)
{
  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::WillInsertText(nsIDOMCharacterData *aTextNode, int32_t aOffset, const nsAString &aString)
{
  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::DidInsertText(nsIDOMCharacterData *aTextNode, int32_t aOffset, const nsAString &aString, nsresult aResult)
{
  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::WillDeleteText(nsIDOMCharacterData *aTextNode, int32_t aOffset, int32_t aLength)
{
  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::DidDeleteText(nsIDOMCharacterData *aTextNode, int32_t aOffset, int32_t aLength, nsresult aResult)
{
  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::WillDeleteSelection(nsISelection *aSelection)
{
  return NS_OK;
}

NS_IMETHODIMP
nsTextServicesDocument::DidDeleteSelection(nsISelection *aSelection)
{
  return NS_OK;
}