DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (cdf352f02ac4)

VCS Links

Line Code
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
/* -*- 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 "WSRunObject.h"

#include "mozilla/Assertions.h"
#include "mozilla/Casting.h"
#include "mozilla/EditorDOMPoint.h"
#include "mozilla/HTMLEditor.h"
#include "mozilla/mozalloc.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/RangeUtils.h"
#include "mozilla/SelectionState.h"

#include "nsAString.h"
#include "nsCRT.h"
#include "nsContentUtils.h"
#include "nsDebug.h"
#include "nsError.h"
#include "nsIContent.h"
#include "nsIContentInlines.h"
#include "nsISupportsImpl.h"
#include "nsRange.h"
#include "nsString.h"
#include "nsTextFragment.h"

namespace mozilla {

using namespace dom;

const char16_t kNBSP = 160;

template WSRunScanner::WSRunScanner(const HTMLEditor* aHTMLEditor,
                                    const EditorDOMPoint& aScanStartPoint,
                                    const EditorDOMPoint& aScanEndPoint);
template WSRunScanner::WSRunScanner(const HTMLEditor* aHTMLEditor,
                                    const EditorRawDOMPoint& aScanStartPoint,
                                    const EditorRawDOMPoint& aScanEndPoint);
template WSRunObject::WSRunObject(HTMLEditor& aHTMLEditor,
                                  const EditorDOMPoint& aScanStartPoint,
                                  const EditorDOMPoint& aScanEndPoint);
template WSRunObject::WSRunObject(HTMLEditor& aHTMLEditor,
                                  const EditorRawDOMPoint& aScanStartPoint,
                                  const EditorRawDOMPoint& aScanEndPoint);
template WSScanResult WSRunScanner::ScanPreviousVisibleNodeOrBlockBoundaryFrom(
    const EditorDOMPoint& aPoint) const;
template WSScanResult WSRunScanner::ScanPreviousVisibleNodeOrBlockBoundaryFrom(
    const EditorRawDOMPoint& aPoint) const;
template WSScanResult WSRunScanner::ScanNextVisibleNodeOrBlockBoundaryFrom(
    const EditorDOMPoint& aPoint) const;
template WSScanResult WSRunScanner::ScanNextVisibleNodeOrBlockBoundaryFrom(
    const EditorRawDOMPoint& aPoint) const;

template <typename PT, typename CT>
WSRunScanner::WSRunScanner(const HTMLEditor* aHTMLEditor,
                           const EditorDOMPointBase<PT, CT>& aScanStartPoint,
                           const EditorDOMPointBase<PT, CT>& aScanEndPoint)
    : mScanStartPoint(aScanStartPoint),
      mScanEndPoint(aScanEndPoint),
      mEditingHost(aHTMLEditor->GetActiveEditingHost()),
      mPRE(false),
      mStartOffset(0),
      mEndOffset(0),
      mFirstNBSPOffset(0),
      mLastNBSPOffset(0),
      mStartRun(nullptr),
      mEndRun(nullptr),
      mHTMLEditor(aHTMLEditor),
      mStartReason(WSType::NotInitialized),
      mEndReason(WSType::NotInitialized) {
  MOZ_ASSERT(
      *nsContentUtils::ComparePoints(aScanStartPoint.ToRawRangeBoundary(),
                                     aScanEndPoint.ToRawRangeBoundary()) <= 0);
  DebugOnly<nsresult> rvIgnored = GetWSNodes();
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
                       "WSRunScanner::GetWSNodes() failed, but ignored");
  GetRuns();
}

WSRunScanner::~WSRunScanner() { ClearRuns(); }

template <typename PT, typename CT>
WSRunObject::WSRunObject(HTMLEditor& aHTMLEditor,
                         const EditorDOMPointBase<PT, CT>& aScanStartPoint,
                         const EditorDOMPointBase<PT, CT>& aScanEndPoint)
    : WSRunScanner(&aHTMLEditor, aScanStartPoint, aScanEndPoint),
      mHTMLEditor(aHTMLEditor) {}

// static
nsresult WSRunObject::Scrub(HTMLEditor& aHTMLEditor,
                            const EditorDOMPoint& aPoint) {
  MOZ_ASSERT(aPoint.IsSet());

  WSRunObject wsRunObject(aHTMLEditor, aPoint);
  nsresult rv = wsRunObject.Scrub();
  if (NS_WARN_IF(aHTMLEditor.Destroyed())) {
    return NS_ERROR_EDITOR_DESTROYED;
  }
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "WSRunObject::Scrub() failed");
  return rv;
}

// static
nsresult WSRunObject::PrepareToJoinBlocks(HTMLEditor& aHTMLEditor,
                                          Element& aLeftBlockElement,
                                          Element& aRightBlockElement) {
  WSRunObject leftWSObj(aHTMLEditor,
                        EditorRawDOMPoint::AtEndOf(aLeftBlockElement));
  WSRunObject rightWSObj(aHTMLEditor,
                         EditorRawDOMPoint(&aRightBlockElement, 0));

  nsresult rv = leftWSObj.PrepareToDeleteRangePriv(&rightWSObj);
  if (NS_WARN_IF(aHTMLEditor.Destroyed())) {
    return NS_ERROR_EDITOR_DESTROYED;
  }
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                       "WSRunObject::PrepareToDeleteRangePriv() failed");
  return rv;
}

nsresult WSRunObject::PrepareToDeleteRange(HTMLEditor& aHTMLEditor,
                                           EditorDOMPoint* aStartPoint,
                                           EditorDOMPoint* aEndPoint) {
  MOZ_ASSERT(aStartPoint);
  MOZ_ASSERT(aEndPoint);

  if (NS_WARN_IF(!aStartPoint->IsSet()) || NS_WARN_IF(!aEndPoint->IsSet())) {
    return NS_ERROR_INVALID_ARG;
  }

  AutoTrackDOMPoint trackerStart(aHTMLEditor.RangeUpdaterRef(), aStartPoint);
  AutoTrackDOMPoint trackerEnd(aHTMLEditor.RangeUpdaterRef(), aEndPoint);

  WSRunObject leftWSObj(aHTMLEditor, *aStartPoint);
  WSRunObject rightWSObj(aHTMLEditor, *aEndPoint);

  nsresult rv = leftWSObj.PrepareToDeleteRangePriv(&rightWSObj);
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                       "WSRunObject::PrepareToDeleteRangePriv() failed");
  return rv;
}

nsresult WSRunObject::PrepareToDeleteNode(HTMLEditor& aHTMLEditor,
                                          nsIContent* aContent) {
  if (NS_WARN_IF(!aContent)) {
    return NS_ERROR_INVALID_ARG;
  }

  EditorRawDOMPoint atContent(aContent);
  if (!atContent.IsSet()) {
    NS_WARNING("aContent was an orphan node");
    return NS_ERROR_INVALID_ARG;
  }

  WSRunObject leftWSObj(aHTMLEditor, atContent);
  WSRunObject rightWSObj(aHTMLEditor, atContent.NextPoint());

  nsresult rv = leftWSObj.PrepareToDeleteRangePriv(&rightWSObj);
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                       "WSRunObject::PrepareToDeleteRangePriv() failed");
  return rv;
}

nsresult WSRunObject::PrepareToSplitAcrossBlocks(HTMLEditor& aHTMLEditor,
                                                 nsCOMPtr<nsINode>* aSplitNode,
                                                 int32_t* aSplitOffset) {
  if (NS_WARN_IF(!aSplitNode) || NS_WARN_IF(!*aSplitNode) ||
      NS_WARN_IF(!aSplitOffset)) {
    return NS_ERROR_INVALID_ARG;
  }

  AutoTrackDOMPoint tracker(aHTMLEditor.RangeUpdaterRef(), aSplitNode,
                            aSplitOffset);

  WSRunObject wsObj(aHTMLEditor, MOZ_KnownLive(*aSplitNode), *aSplitOffset);

  nsresult rv = wsObj.PrepareToSplitAcrossBlocksPriv();
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                       "WSRunObject::PrepareToSplitAcrossBlocksPriv() failed");
  return rv;
}

already_AddRefed<Element> WSRunObject::InsertBreak(
    Selection& aSelection, const EditorDOMPoint& aPointToInsert,
    nsIEditor::EDirection aSelect) {
  if (NS_WARN_IF(!aPointToInsert.IsSet())) {
    return nullptr;
  }

  // MOOSE: for now, we always assume non-PRE formatting.  Fix this later.
  // meanwhile, the pre case is handled in HandleInsertText() in
  // HTMLEditSubActionHandler.cpp

  WSFragment* beforeRun = FindNearestRun(aPointToInsert, false);
  WSFragment* afterRun = FindNearestRun(aPointToInsert, true);

  EditorDOMPoint pointToInsert(aPointToInsert);
  {
    // Some scoping for AutoTrackDOMPoint.  This will track our insertion
    // point while we tweak any surrounding whitespace
    AutoTrackDOMPoint tracker(mHTMLEditor.RangeUpdaterRef(), &pointToInsert);

    // Handle any changes needed to ws run after inserted br
    if (!afterRun || afterRun->IsEndOfHardLine()) {
      // Don't need to do anything.  Just insert break.  ws won't change.
    } else if (afterRun->IsStartOfHardLine()) {
      // Delete the leading ws that is after insertion point.  We don't
      // have to (it would still not be significant after br), but it's
      // just more aesthetically pleasing to.
      nsresult rv = DeleteRange(pointToInsert, afterRun->EndPoint());
      if (NS_FAILED(rv)) {
        NS_WARNING("WSRunObject::DeleteRange() failed");
        return nullptr;
      }
    } else if (afterRun->IsVisibleAndMiddleOfHardLine()) {
      // Need to determine if break at front of non-nbsp run.  If so, convert
      // run to nbsp.
      EditorDOMPointInText atNextCharOfInsertionPoint =
          GetNextCharPoint(pointToInsert);
      if (atNextCharOfInsertionPoint.IsSet() &&
          !atNextCharOfInsertionPoint.IsEndOfContainer() &&
          atNextCharOfInsertionPoint.IsCharASCIISpace()) {
        EditorDOMPointInText atPreviousCharOfNextCharOfInsertionPoint =
            GetPreviousCharPointFromPointInText(atNextCharOfInsertionPoint);
        if (!atPreviousCharOfNextCharOfInsertionPoint.IsSet() ||
            atPreviousCharOfNextCharOfInsertionPoint.IsEndOfContainer() ||
            !atPreviousCharOfNextCharOfInsertionPoint.IsCharASCIISpace()) {
          // We are at start of non-nbsps.  Convert to a single nbsp.
          nsresult rv = InsertNBSPAndRemoveFollowingASCIIWhitespaces(
              atNextCharOfInsertionPoint);
          if (NS_FAILED(rv)) {
            NS_WARNING(
                "WSRunObject::InsertNBSPAndRemoveFollowingASCIIWhitespaces() "
                "failed");
            return nullptr;
          }
        }
      }
    }

    // Handle any changes needed to ws run before inserted br
    if (!beforeRun || beforeRun->IsStartOfHardLine()) {
      // Don't need to do anything.  Just insert break.  ws won't change.
    } else if (beforeRun->IsEndOfHardLine()) {
      // Need to delete the trailing ws that is before insertion point, because
      // it would become significant after break inserted.
      nsresult rv = DeleteRange(beforeRun->StartPoint(), pointToInsert);
      if (NS_FAILED(rv)) {
        NS_WARNING("WSRunObject::DeleteRange() failed");
        return nullptr;
      }
    } else if (beforeRun->IsVisibleAndMiddleOfHardLine()) {
      // Try to change an nbsp to a space, just to prevent nbsp proliferation
      nsresult rv = ReplacePreviousNBSPIfUnnecessary(beforeRun, pointToInsert);
      if (NS_FAILED(rv)) {
        NS_WARNING("WSRunObject::ReplacePreviousNBSPIfUnnecessary() failed");
        return nullptr;
      }
    }
  }

  RefPtr<Element> newBRElement =
      MOZ_KnownLive(mHTMLEditor)
          .InsertBRElementWithTransaction(pointToInsert, aSelect);
  NS_WARNING_ASSERTION(newBRElement,
                       "HTMLEditor::InsertBRElementWithTransaction() failed");
  return newBRElement.forget();
}

nsresult WSRunObject::InsertText(Document& aDocument,
                                 const nsAString& aStringToInsert,
                                 EditorRawDOMPoint* aPointAfterInsertedString) {
  // MOOSE: for now, we always assume non-PRE formatting.  Fix this later.
  // meanwhile, the pre case is handled in HandleInsertText() in
  // HTMLEditSubActionHandler.cpp

  // MOOSE: for now, just getting the ws logic straight.  This implementation
  // is very slow.  Will need to replace edit rules impl with a more efficient
  // text sink here that does the minimal amount of searching/replacing/copying

  if (aStringToInsert.IsEmpty()) {
    if (aPointAfterInsertedString) {
      *aPointAfterInsertedString = mScanStartPoint;
    }
    return NS_OK;
  }

  WSFragment* beforeRun = FindNearestRun(mScanStartPoint, false);
  // If mScanStartPoint isn't equal to mScanEndPoint, it will replace text (i.e.
  // committing composition). And afterRun will be end point of replaced range.
  // So we want to know this white space type (trailing whitespace etc) of
  // this end point, not inserted (start) point, so we re-scan white space type.
  WSRunObject afterRunObject(MOZ_KnownLive(mHTMLEditor), mScanEndPoint);
  WSFragment* afterRun = afterRunObject.FindNearestRun(mScanEndPoint, true);

  EditorDOMPoint pointToInsert(mScanStartPoint);
  nsAutoString theString(aStringToInsert);
  {
    // Some scoping for AutoTrackDOMPoint.  This will track our insertion
    // point while we tweak any surrounding whitespace
    AutoTrackDOMPoint tracker(mHTMLEditor.RangeUpdaterRef(), &pointToInsert);

    // Handle any changes needed to ws run after inserted text
    if (!afterRun || afterRun->IsEndOfHardLine()) {
      // Don't need to do anything.  Just insert text.  ws won't change.
    } else if (afterRun->IsStartOfHardLine()) {
      // Delete the leading ws that is after insertion point, because it
      // would become significant after text inserted.
      nsresult rv = DeleteRange(pointToInsert, afterRun->EndPoint());
      if (NS_FAILED(rv)) {
        NS_WARNING("WSRunObject::DeleteRange() failed");
        return rv;
      }
    } else if (afterRun->IsVisibleAndMiddleOfHardLine()) {
      // Try to change an nbsp to a space, if possible, just to prevent nbsp
      // proliferation
      nsresult rv = CheckLeadingNBSP(
          afterRun, MOZ_KnownLive(pointToInsert.GetContainer()),
          pointToInsert.Offset());
      if (NS_FAILED(rv)) {
        NS_WARNING("WSRunObject::CheckLeadingNBSP() failed");
        return rv;
      }
    }

    // Handle any changes needed to ws run before inserted text
    if (!beforeRun || beforeRun->IsStartOfHardLine()) {
      // Don't need to do anything.  Just insert text.  ws won't change.
    } else if (beforeRun->IsEndOfHardLine()) {
      // Need to delete the trailing ws that is before insertion point, because
      // it would become significant after text inserted.
      nsresult rv = DeleteRange(beforeRun->StartPoint(), pointToInsert);
      if (NS_FAILED(rv)) {
        NS_WARNING("WSRunObject::DeleteRange() failed");
        return rv;
      }
    } else if (beforeRun->IsVisibleAndMiddleOfHardLine()) {
      // Try to change an nbsp to a space, if possible, just to prevent nbsp
      // proliferation
      nsresult rv = ReplacePreviousNBSPIfUnnecessary(beforeRun, pointToInsert);
      if (NS_FAILED(rv)) {
        NS_WARNING("WSRunObject::ReplacePreviousNBSPIfUnnecessary() failed");
        return rv;
      }
    }

    // After this block, pointToInsert is modified by AutoTrackDOMPoint.
  }

  // Next up, tweak head and tail of string as needed.  First the head: there
  // are a variety of circumstances that would require us to convert a leading
  // ws char into an nbsp:

  if (nsCRT::IsAsciiSpace(theString[0])) {
    // We have a leading space
    if (beforeRun) {
      if (beforeRun->IsStartOfHardLine()) {
        theString.SetCharAt(kNBSP, 0);
      } else if (beforeRun->IsVisible()) {
        EditorDOMPointInText atPreviousChar =
            GetPreviousCharPoint(pointToInsert);
        if (atPreviousChar.IsSet() && !atPreviousChar.IsEndOfContainer() &&
            atPreviousChar.IsCharASCIISpace()) {
          theString.SetCharAt(kNBSP, 0);
        }
      }
    } else if (StartsFromHardLineBreak()) {
      theString.SetCharAt(kNBSP, 0);
    }
  }

  // Then the tail
  uint32_t lastCharIndex = theString.Length() - 1;

  if (nsCRT::IsAsciiSpace(theString[lastCharIndex])) {
    // We have a leading space
    if (afterRun) {
      if (afterRun->IsEndOfHardLine()) {
        theString.SetCharAt(kNBSP, lastCharIndex);
      } else if (afterRun->IsVisible()) {
        EditorDOMPointInText atNextChar = GetNextCharPoint(pointToInsert);
        if (atNextChar.IsSet() && !atNextChar.IsEndOfContainer() &&
            atNextChar.IsCharASCIISpace()) {
          theString.SetCharAt(kNBSP, lastCharIndex);
        }
      }
    } else if (afterRunObject.EndsByBlockBoundary()) {
      // When afterRun is null, it means that mScanEndPoint is last point in
      // editing host or editing block.
      // If this text insertion replaces composition, this.mEndReason is
      // start position of compositon. So we have to use afterRunObject's
      // reason instead.
      theString.SetCharAt(kNBSP, lastCharIndex);
    }
  }

  // Next, scan string for adjacent ws and convert to nbsp/space combos
  // MOOSE: don't need to convert tabs here since that is done by
  // WillInsertText() before we are called.  Eventually, all that logic will be
  // pushed down into here and made more efficient.
  bool prevWS = false;
  for (uint32_t i = 0; i <= lastCharIndex; i++) {
    if (nsCRT::IsAsciiSpace(theString[i])) {
      if (prevWS) {
        // i - 1 can't be negative because prevWS starts out false
        theString.SetCharAt(kNBSP, i - 1);
      } else {
        prevWS = true;
      }
    } else {
      prevWS = false;
    }
  }

  // XXX If the point is not editable, InsertTextWithTransaction() returns
  //     error, but we keep handling it.  But I think that it wastes the
  //     runtime cost.  So, perhaps, we should return error code which couldn't
  //     modify it and make each caller of this method decide whether it should
  //     keep or stop handling the edit action.
  nsresult rv =
      MOZ_KnownLive(mHTMLEditor)
          .InsertTextWithTransaction(aDocument, theString, pointToInsert,
                                     aPointAfterInsertedString);
  if (NS_SUCCEEDED(rv)) {
    return NS_OK;
  }

  NS_WARNING("HTMLEditor::InsertTextWithTransaction() failed, but ignored");

  // XXX Temporarily, set new insertion point to the original point.
  if (aPointAfterInsertedString) {
    *aPointAfterInsertedString = pointToInsert;
  }
  return NS_OK;
}

nsresult WSRunObject::DeleteWSBackward() {
  EditorDOMPointInText atPreviousCharOfStart =
      GetPreviousCharPoint(mScanStartPoint);
  if (!atPreviousCharOfStart.IsSet() ||
      atPreviousCharOfStart.IsEndOfContainer()) {
    return NS_OK;
  }

  // Easy case, preformatted ws.
  if (mPRE) {
    if (!atPreviousCharOfStart.IsCharASCIISpace() &&
        !atPreviousCharOfStart.IsCharNBSP()) {
      return NS_OK;
    }
    nsresult rv =
        DeleteRange(atPreviousCharOfStart, atPreviousCharOfStart.NextPoint());
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "WSRunObject::DeleteRange() failed");
    return rv;
  }

  // Caller's job to ensure that previous char is really ws.  If it is normal
  // ws, we need to delete the whole run.
  if (atPreviousCharOfStart.IsCharASCIISpace()) {
    EditorDOMPointInText start, end;
    Tie(start, end) =
        GetASCIIWhitespacesBounds(eBoth, atPreviousCharOfStart.NextPoint());
    NS_WARNING_ASSERTION(start.IsSet(),
                         "WSRunObject::GetASCIIWhitespacesBounds() didn't "
                         "return start position, but ignored");
    NS_WARNING_ASSERTION(end.IsSet(),
                         "WSRunObject::GetASCIIWhitespacesBounds() didn't "
                         "return end position, but ignored");

    // adjust surrounding ws
    EditorDOMPoint startToDelete(start), endToDelete(end);
    nsresult rv = WSRunObject::PrepareToDeleteRange(
        MOZ_KnownLive(mHTMLEditor), &startToDelete, &endToDelete);
    if (NS_FAILED(rv)) {
      NS_WARNING("WSRunObject::PrepareToDeleteRange() failed");
      return rv;
    }

    // finally, delete that ws
    rv = DeleteRange(startToDelete, endToDelete);
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "WSRunObject::DeleteRange() failed");
    return rv;
  }

  if (atPreviousCharOfStart.IsCharNBSP()) {
    EditorDOMPoint startToDelete(atPreviousCharOfStart);
    EditorDOMPoint endToDelete(startToDelete.NextPoint());
    nsresult rv = WSRunObject::PrepareToDeleteRange(
        MOZ_KnownLive(mHTMLEditor), &startToDelete, &endToDelete);
    if (NS_FAILED(rv)) {
      NS_WARNING("WSRunObject::PrepareToDeleteRange() failed");
      return rv;
    }

    // finally, delete that ws
    rv = DeleteRange(startToDelete, endToDelete);
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "WSRunObject::DeleteRange() failed");
    return rv;
  }

  return NS_OK;
}

nsresult WSRunObject::DeleteWSForward() {
  EditorDOMPointInText atNextCharOfStart = GetNextCharPoint(mScanStartPoint);
  if (!atNextCharOfStart.IsSet() || atNextCharOfStart.IsEndOfContainer()) {
    return NS_OK;
  }

  // Easy case, preformatted ws.
  if (mPRE) {
    if (!atNextCharOfStart.IsCharASCIISpace() &&
        !atNextCharOfStart.IsCharNBSP()) {
      return NS_OK;
    }
    nsresult rv = DeleteRange(atNextCharOfStart, atNextCharOfStart.NextPoint());
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "WSRunObject::DeleteRange() failed");
    return rv;
  }

  // Caller's job to ensure that next char is really ws.  If it is normal ws,
  // we need to delete the whole run.
  if (atNextCharOfStart.IsCharASCIISpace()) {
    EditorDOMPointInText start, end;
    Tie(start, end) =
        GetASCIIWhitespacesBounds(eBoth, atNextCharOfStart.NextPoint());
    NS_WARNING_ASSERTION(start.IsSet(),
                         "WSRunObject::GetASCIIWhitespacesBounds() didn't "
                         "return start position, but ignored");
    NS_WARNING_ASSERTION(end.IsSet(),
                         "WSRunObject::GetASCIIWhitespacesBounds() didn't "
                         "return end position, but ignored");
    // Adjust surrounding ws
    EditorDOMPoint startToDelete(start), endToDelete(end);
    nsresult rv = WSRunObject::PrepareToDeleteRange(
        MOZ_KnownLive(mHTMLEditor), &startToDelete, &endToDelete);
    if (NS_FAILED(rv)) {
      NS_WARNING("WSRunObject::PrepareToDeleteRange() failed");
      return rv;
    }

    // Finally, delete that ws
    rv = DeleteRange(startToDelete, endToDelete);
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "WSRunObject::DeleteRange() failed");
    return rv;
  }

  if (atNextCharOfStart.IsCharNBSP()) {
    EditorDOMPoint startToDelete(atNextCharOfStart);
    EditorDOMPoint endToDelete(startToDelete.NextPoint());
    nsresult rv = WSRunObject::PrepareToDeleteRange(
        MOZ_KnownLive(mHTMLEditor), &startToDelete, &endToDelete);
    if (NS_FAILED(rv)) {
      NS_WARNING("WSRunObject::PrepareToDeleteRange() failed");
      return rv;
    }

    // Finally, delete that ws
    rv = DeleteRange(startToDelete, endToDelete);
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "WSRunObject::DeleteRange() failed");
    return rv;
  }

  return NS_OK;
}

template <typename PT, typename CT>
WSScanResult WSRunScanner::ScanPreviousVisibleNodeOrBlockBoundaryFrom(
    const EditorDOMPointBase<PT, CT>& aPoint) const {
  // Find first visible thing before the point.  Position
  // outVisNode/outVisOffset just _after_ that thing.  If we don't find
  // anything return start of ws.
  MOZ_ASSERT(aPoint.IsSet());

  WSFragment* run = FindNearestRun(aPoint, false);

  // Is there a visible run there or earlier?
  for (; run; run = run->mLeft) {
    if (run->IsVisibleAndMiddleOfHardLine()) {
      EditorDOMPointInText atPreviousChar = GetPreviousCharPoint(aPoint);
      // When it's a non-empty text node, return it.
      if (atPreviousChar.IsSet() && !atPreviousChar.IsContainerEmpty()) {
        MOZ_ASSERT(!atPreviousChar.IsEndOfContainer());
        return WSScanResult(
            atPreviousChar.NextPoint(),
            atPreviousChar.IsCharASCIISpace() || atPreviousChar.IsCharNBSP()
                ? WSType::NormalWhiteSpaces
                : WSType::NormalText);
      }
      // If no text node, keep looking.  We should eventually fall out of loop
    }
  }

  if (mStartReasonContent != mStartNode) {
    // In this case, mStartOffset is not meaningful.
    return WSScanResult(mStartReasonContent, mStartReason);
  }
  return WSScanResult(EditorDOMPoint(mStartReasonContent, mStartOffset),
                      mStartReason);
}

template <typename PT, typename CT>
WSScanResult WSRunScanner::ScanNextVisibleNodeOrBlockBoundaryFrom(
    const EditorDOMPointBase<PT, CT>& aPoint) const {
  // Find first visible thing after the point.  Position
  // outVisNode/outVisOffset just _before_ that thing.  If we don't find
  // anything return end of ws.
  MOZ_ASSERT(aPoint.IsSet());

  WSFragment* run = FindNearestRun(aPoint, true);

  // Is there a visible run there or later?
  for (; run; run = run->mRight) {
    if (run->IsVisibleAndMiddleOfHardLine()) {
      EditorDOMPointInText atNextChar = GetNextCharPoint(aPoint);
      // When it's a non-empty text node, return it.
      if (atNextChar.IsSet() && !atNextChar.IsContainerEmpty()) {
        return WSScanResult(
            atNextChar,
            !atNextChar.IsEndOfContainer() &&
                    (atNextChar.IsCharASCIISpace() || atNextChar.IsCharNBSP())
                ? WSType::NormalWhiteSpaces
                : WSType::NormalText);
      }
      // If no text node, keep looking.  We should eventually fall out of loop
    }
  }

  if (mEndReasonContent != mEndNode) {
    // In this case, mEndOffset is not meaningful.
    return WSScanResult(mEndReasonContent, mEndReason);
  }
  return WSScanResult(EditorDOMPoint(mEndReasonContent, mEndOffset),
                      mEndReason);
}

nsresult WSRunObject::AdjustWhitespace() {
  // this routine examines a run of ws and tries to get rid of some unneeded
  // nbsp's, replacing them with regualr ascii space if possible.  Keeping
  // things simple for now and just trying to fix up the trailing ws in the run.
  if (!mLastNBSPNode) {
    // nothing to do!
    return NS_OK;
  }
  for (WSFragment* run = mStartRun; run; run = run->mRight) {
    if (!run->IsVisibleAndMiddleOfHardLine()) {
      continue;
    }
    nsresult rv = CheckTrailingNBSPOfRun(run);
    if (NS_FAILED(rv)) {
      NS_WARNING("WSRunObject::CheckTrailingNBSPOfRun() failed");
      return rv;
    }
  }
  return NS_OK;
}

//--------------------------------------------------------------------------------------------
//   protected methods
//--------------------------------------------------------------------------------------------

nsIContent* WSRunScanner::GetEditableBlockParentOrTopmotEditableInlineContent(
    nsIContent* aContent) const {
  if (NS_WARN_IF(!aContent)) {
    return nullptr;
  }
  NS_ASSERTION(mHTMLEditor->IsEditable(aContent),
               "Given content is not editable");
  // XXX What should we do if scan range crosses block boundary?  Currently,
  //     it's not collapsed only when inserting composition string so that
  //     it's possible but shouldn't occur actually.
  nsIContent* editableBlockParentOrTopmotEditableInlineContent = nullptr;
  for (nsIContent* content = aContent;
       content && mHTMLEditor->IsEditable(content);
       content = content->GetParent()) {
    editableBlockParentOrTopmotEditableInlineContent = content;
    if (IsBlockNode(editableBlockParentOrTopmotEditableInlineContent)) {
      break;
    }
  }
  return editableBlockParentOrTopmotEditableInlineContent;
}

nsresult WSRunScanner::GetWSNodes() {
  // collect up an array of nodes that are contiguous with the insertion point
  // and which contain only whitespace.  Stop if you reach non-ws text or a new
  // block boundary.
  EditorDOMPoint start(mScanStartPoint), end(mScanStartPoint);
  nsIContent* scanStartContent = mScanStartPoint.GetContainerAsContent();
  if (NS_WARN_IF(!scanStartContent)) {
    // Meaning container of mScanStartPoint is a Document or DocumentFragment.
    // I.e., we're try to modify outside of root element.  We don't need to
    // support such odd case because web apps cannot append text nodes as
    // direct child of Document node.
    return NS_ERROR_FAILURE;
  }
  nsIContent* editableBlockParentOrTopmotEditableInlineContent =
      GetEditableBlockParentOrTopmotEditableInlineContent(scanStartContent);
  if (NS_WARN_IF(!editableBlockParentOrTopmotEditableInlineContent)) {
    // Meaning that the container of `mScanStartPoint` is not editable.
    editableBlockParentOrTopmotEditableInlineContent = scanStartContent;
  }

  // first look backwards to find preceding ws nodes
  if (Text* textNode = mScanStartPoint.GetContainerAsText()) {
    const nsTextFragment* textFrag = &textNode->TextFragment();
    mNodeArray.InsertElementAt(0, textNode);
    if (!mScanStartPoint.IsStartOfContainer()) {
      for (uint32_t i = mScanStartPoint.Offset(); i; i--) {
        // sanity bounds check the char position.  bug 136165
        if (i > textFrag->GetLength()) {
          MOZ_ASSERT_UNREACHABLE("looking beyond end of text fragment");
          continue;
        }
        char16_t theChar = textFrag->CharAt(i - 1);
        if (!nsCRT::IsAsciiSpace(theChar)) {
          if (theChar != kNBSP) {
            mStartNode = textNode;
            mStartOffset = i;
            mStartReason = WSType::NormalText;
            mStartReasonContent = textNode;
            break;
          }
          // as we look backwards update our earliest found nbsp
          mFirstNBSPNode = textNode;
          mFirstNBSPOffset = i - 1;
          // also keep track of latest nbsp so far
          if (!mLastNBSPNode) {
            mLastNBSPNode = textNode;
            mLastNBSPOffset = i - 1;
          }
        }
        start.Set(textNode, i - 1);
      }
    }
  }

  while (!mStartNode) {
    // we haven't found the start of ws yet.  Keep looking
    nsCOMPtr<nsIContent> priorNode = GetPreviousWSNode(
        start, editableBlockParentOrTopmotEditableInlineContent);
    if (priorNode) {
      if (IsBlockNode(priorNode)) {
        mStartNode = start.GetContainer();
        mStartOffset = start.Offset();
        mStartReason = WSType::OtherBlockBoundary;
        mStartReasonContent = priorNode;
      } else if (priorNode->IsText() && priorNode->IsEditable()) {
        RefPtr<Text> textNode = priorNode->AsText();
        mNodeArray.InsertElementAt(0, textNode);
        const nsTextFragment* textFrag = &textNode->TextFragment();
        uint32_t len = textNode->TextLength();

        if (len < 1) {
          // Zero length text node. Set start point to it
          // so we can get past it!
          start.Set(priorNode, 0);
        } else {
          for (int32_t pos = len - 1; pos >= 0; pos--) {
            // sanity bounds check the char position.  bug 136165
            if (uint32_t(pos) >= textFrag->GetLength()) {
              MOZ_ASSERT_UNREACHABLE("looking beyond end of text fragment");
              continue;
            }
            char16_t theChar = textFrag->CharAt(pos);
            if (!nsCRT::IsAsciiSpace(theChar)) {
              if (theChar != kNBSP) {
                mStartNode = textNode;
                mStartOffset = pos + 1;
                mStartReason = WSType::NormalText;
                mStartReasonContent = textNode;
                break;
              }
              // as we look backwards update our earliest found nbsp
              mFirstNBSPNode = textNode;
              mFirstNBSPOffset = pos;
              // also keep track of latest nbsp so far
              if (!mLastNBSPNode) {
                mLastNBSPNode = textNode;
                mLastNBSPOffset = pos;
              }
            }
            start.Set(textNode, pos);
          }
        }
      } else {
        // it's a break or a special node, like <img>, that is not a block and
        // not a break but still serves as a terminator to ws runs.
        mStartNode = start.GetContainer();
        mStartOffset = start.Offset();
        if (priorNode->IsHTMLElement(nsGkAtoms::br)) {
          mStartReason = WSType::BRElement;
        } else {
          mStartReason = WSType::SpecialContent;
        }
        mStartReasonContent = priorNode;
      }
    } else {
      // no prior node means we exhausted
      // editableBlockParentOrTopmotEditableInlineContent
      mStartNode = start.GetContainer();
      mStartOffset = start.Offset();
      mStartReason = WSType::CurrentBlockBoundary;
      // mStartReasonContent can be either a block element or any non-editable
      // content in this case.
      mStartReasonContent = editableBlockParentOrTopmotEditableInlineContent;
    }
  }

  // then look ahead to find following ws nodes
  if (Text* textNode = end.GetContainerAsText()) {
    // don't need to put it on list. it already is from code above
    const nsTextFragment* textFrag = &textNode->TextFragment();
    if (!end.IsEndOfContainer()) {
      for (uint32_t i = end.Offset(); i < textNode->TextLength(); i++) {
        // sanity bounds check the char position.  bug 136165
        if (i >= textFrag->GetLength()) {
          MOZ_ASSERT_UNREACHABLE("looking beyond end of text fragment");
          continue;
        }
        char16_t theChar = textFrag->CharAt(i);
        if (!nsCRT::IsAsciiSpace(theChar)) {
          if (theChar != kNBSP) {
            mEndNode = textNode;
            mEndOffset = i;
            mEndReason = WSType::NormalText;
            mEndReasonContent = textNode;
            break;
          }
          // as we look forwards update our latest found nbsp
          mLastNBSPNode = textNode;
          mLastNBSPOffset = i;
          // also keep track of earliest nbsp so far
          if (!mFirstNBSPNode) {
            mFirstNBSPNode = textNode;
            mFirstNBSPOffset = i;
          }
        }
        end.Set(textNode, i + 1);
      }
    }
  }

  while (!mEndNode) {
    // we haven't found the end of ws yet.  Keep looking
    nsCOMPtr<nsIContent> nextNode =
        GetNextWSNode(end, editableBlockParentOrTopmotEditableInlineContent);
    if (nextNode) {
      if (IsBlockNode(nextNode)) {
        // we encountered a new block.  therefore no more ws.
        mEndNode = end.GetContainer();
        mEndOffset = end.Offset();
        mEndReason = WSType::OtherBlockBoundary;
        mEndReasonContent = nextNode;
      } else if (nextNode->IsText() && nextNode->IsEditable()) {
        RefPtr<Text> textNode = nextNode->AsText();
        mNodeArray.AppendElement(textNode);
        const nsTextFragment* textFrag = &textNode->TextFragment();
        uint32_t len = textNode->TextLength();

        if (len < 1) {
          // Zero length text node. Set end point to it
          // so we can get past it!
          end.Set(textNode, 0);
        } else {
          for (uint32_t pos = 0; pos < len; pos++) {
            // sanity bounds check the char position.  bug 136165
            if (pos >= textFrag->GetLength()) {
              MOZ_ASSERT_UNREACHABLE("looking beyond end of text fragment");
              continue;
            }
            char16_t theChar = textFrag->CharAt(pos);
            if (!nsCRT::IsAsciiSpace(theChar)) {
              if (theChar != kNBSP) {
                mEndNode = textNode;
                mEndOffset = pos;
                mEndReason = WSType::NormalText;
                mEndReasonContent = textNode;
                break;
              }
              // as we look forwards update our latest found nbsp
              mLastNBSPNode = textNode;
              mLastNBSPOffset = pos;
              // also keep track of earliest nbsp so far
              if (!mFirstNBSPNode) {
                mFirstNBSPNode = textNode;
                mFirstNBSPOffset = pos;
              }
            }
            end.Set(textNode, pos + 1);
          }
        }
      } else {
        // we encountered a break or a special node, like <img>,
        // that is not a block and not a break but still
        // serves as a terminator to ws runs.
        mEndNode = end.GetContainer();
        mEndOffset = end.Offset();
        if (nextNode->IsHTMLElement(nsGkAtoms::br)) {
          mEndReason = WSType::BRElement;
        } else {
          mEndReason = WSType::SpecialContent;
        }
        mEndReasonContent = nextNode;
      }
    } else {
      // no next node means we exhausted
      // editableBlockParentOrTopmotEditableInlineContent
      mEndNode = end.GetContainer();
      mEndOffset = end.Offset();
      mEndReason = WSType::CurrentBlockBoundary;
      // mEndReasonContent can be either a block element or any non-editable
      // content in this case.
      mEndReasonContent = editableBlockParentOrTopmotEditableInlineContent;
    }
  }

  return NS_OK;
}

void WSRunScanner::GetRuns() {
  ClearRuns();

  // Handle preformatted case first since it's simple.  Note that if end of
  // the scan range isn't in preformatted element, we need to check only the
  // style at mScanStartPoint since the range would be replaced and the start
  // style will be applied to all new string.
  mPRE = EditorBase::IsPreformatted(mScanStartPoint.GetContainer());
  // if it's preformatedd, or if we are surrounded by text or special, it's all
  // one big normal ws run
  if (mPRE ||
      ((StartsFromNormalText() || StartsFromSpecialContent()) &&
       (EndsByNormalText() || EndsBySpecialContent() || EndsByBRElement()))) {
    InitializeWithSingleFragment(WSFragment::Visible::Yes,
                                 WSFragment::StartOfHardLine::No,
                                 WSFragment::EndOfHardLine::No);
    return;
  }

  // if we are before or after a block (or after a break), and there are no
  // nbsp's, then it's all non-rendering ws.
  if (!mFirstNBSPNode && !mLastNBSPNode &&
      (StartsFromHardLineBreak() || EndsByBlockBoundary())) {
    InitializeWithSingleFragment(
        WSFragment::Visible::No,
        StartsFromHardLineBreak() ? WSFragment::StartOfHardLine::Yes
                                  : WSFragment::StartOfHardLine::No,
        EndsByBlockBoundary() ? WSFragment::EndOfHardLine::Yes
                              : WSFragment::EndOfHardLine::No);
    return;
  }

  // otherwise a little trickier.  shucks.
  mStartRun = new WSFragment();
  mStartRun->mStartNode = mStartNode;
  mStartRun->mStartOffset = mStartOffset;

  if (StartsFromHardLineBreak()) {
    // set up mStartRun
    mStartRun->MarkAsStartOfHardLine();
    mStartRun->mEndNode = mFirstNBSPNode;
    mStartRun->mEndOffset = mFirstNBSPOffset;
    mStartRun->SetStartFrom(mStartReason);
    mStartRun->SetEndByNormalWiteSpaces();

    // set up next run
    WSFragment* normalRun = new WSFragment();
    mStartRun->mRight = normalRun;
    normalRun->MarkAsVisible();
    normalRun->mStartNode = mFirstNBSPNode;
    normalRun->mStartOffset = mFirstNBSPOffset;
    normalRun->SetStartFromLeadingWhiteSpaces();
    normalRun->mLeft = mStartRun;
    if (!EndsByBlockBoundary()) {
      // then no trailing ws.  this normal run ends the overall ws run.
      normalRun->SetEndBy(mEndReason);
      normalRun->mEndNode = mEndNode;
      normalRun->mEndOffset = mEndOffset;
      mEndRun = normalRun;
    } else {
      // we might have trailing ws.
      // it so happens that *if* there is an nbsp at end,
      // {mEndNode,mEndOffset-1} will point to it, even though in general
      // start/end points not guaranteed to be in text nodes.
      if (mLastNBSPNode == mEndNode && mLastNBSPOffset == mEndOffset - 1) {
        // normal ws runs right up to adjacent block (nbsp next to block)
        normalRun->SetEndBy(mEndReason);
        normalRun->mEndNode = mEndNode;
        normalRun->mEndOffset = mEndOffset;
        mEndRun = normalRun;
      } else {
        normalRun->mEndNode = mLastNBSPNode;
        normalRun->mEndOffset = mLastNBSPOffset + 1;
        normalRun->SetEndByTrailingWhiteSpaces();

        // set up next run
        WSFragment* lastRun = new WSFragment();
        lastRun->MarkAsEndOfHardLine();
        lastRun->mStartNode = mLastNBSPNode;
        lastRun->mStartOffset = mLastNBSPOffset + 1;
        lastRun->mEndNode = mEndNode;
        lastRun->mEndOffset = mEndOffset;
        lastRun->SetStartFromNormalWhiteSpaces();
        lastRun->mLeft = normalRun;
        lastRun->SetEndBy(mEndReason);
        mEndRun = lastRun;
        normalRun->mRight = lastRun;
      }
    }
  } else {
    MOZ_ASSERT(!StartsFromHardLineBreak());
    mStartRun->MarkAsVisible();
    mStartRun->mEndNode = mLastNBSPNode;
    mStartRun->mEndOffset = mLastNBSPOffset + 1;
    mStartRun->SetStartFrom(mStartReason);

    // we might have trailing ws.
    // it so happens that *if* there is an nbsp at end, {mEndNode,mEndOffset-1}
    // will point to it, even though in general start/end points not
    // guaranteed to be in text nodes.
    if (mLastNBSPNode == mEndNode && mLastNBSPOffset == (mEndOffset - 1)) {
      mStartRun->SetEndBy(mEndReason);
      mStartRun->mEndNode = mEndNode;
      mStartRun->mEndOffset = mEndOffset;
      mEndRun = mStartRun;
    } else {
      // set up next run
      WSFragment* lastRun = new WSFragment();
      lastRun->MarkAsEndOfHardLine();
      lastRun->mStartNode = mLastNBSPNode;
      lastRun->mStartOffset = mLastNBSPOffset + 1;
      lastRun->SetStartFromNormalWhiteSpaces();
      lastRun->mLeft = mStartRun;
      lastRun->SetEndBy(mEndReason);
      mEndRun = lastRun;
      mStartRun->mRight = lastRun;
      mStartRun->SetEndByTrailingWhiteSpaces();
    }
  }
}

void WSRunScanner::ClearRuns() {
  WSFragment *tmp, *run;
  run = mStartRun;
  while (run) {
    tmp = run->mRight;
    delete run;
    run = tmp;
  }
  mStartRun = 0;
  mEndRun = 0;
}

void WSRunScanner::InitializeWithSingleFragment(
    WSFragment::Visible aIsVisible,
    WSFragment::StartOfHardLine aIsStartOfHardLine,
    WSFragment::EndOfHardLine aIsEndOfHardLine) {
  MOZ_ASSERT(!mStartRun);
  MOZ_ASSERT(!mEndRun);

  mStartRun = new WSFragment();

  mStartRun->mStartNode = mStartNode;
  mStartRun->mStartOffset = mStartOffset;
  if (aIsVisible == WSFragment::Visible::Yes) {
    mStartRun->MarkAsVisible();
  }
  if (aIsStartOfHardLine == WSFragment::StartOfHardLine::Yes) {
    mStartRun->MarkAsStartOfHardLine();
  }
  if (aIsEndOfHardLine == WSFragment::EndOfHardLine::Yes) {
    mStartRun->MarkAsEndOfHardLine();
  }
  mStartRun->mEndNode = mEndNode;
  mStartRun->mEndOffset = mEndOffset;
  mStartRun->SetStartFrom(mStartReason);
  mStartRun->SetEndBy(mEndReason);

  mEndRun = mStartRun;
}

nsIContent* WSRunScanner::GetPreviousWSNodeInner(nsINode* aStartNode,
                                                 nsINode* aBlockParent) const {
  // Can't really recycle various getnext/prior routines because we have
  // special needs here.  Need to step into inline containers but not block
  // containers.
  MOZ_ASSERT(aStartNode && aBlockParent);

  if (aStartNode == mEditingHost) {
    NS_WARNING(
        "WSRunScanner::GetPreviousWSNodeInner() was called with editing host");
    return nullptr;
  }

  nsCOMPtr<nsIContent> priorNode = aStartNode->GetPreviousSibling();
  OwningNonNull<nsINode> curNode = *aStartNode;
  while (!priorNode) {
    // We have exhausted nodes in parent of aStartNode.
    nsCOMPtr<nsINode> curParent = curNode->GetParentNode();
    if (!curParent) {
      NS_WARNING("Reached orphan node while climbing up the DOM tree");
      return nullptr;
    }
    if (curParent == aBlockParent) {
      // We have exhausted nodes in the block parent.  The convention here is
      // to return null.
      return nullptr;
    }
    if (curParent == mEditingHost) {
      NS_WARNING("Reached editing host while climbing up the DOM tree");
      return nullptr;
    }
    // We have a parent: look for previous sibling
    priorNode = curParent->GetPreviousSibling();
    curNode = curParent;
  }
  // We have a prior node.  If it's a block, return it.
  if (IsBlockNode(priorNode)) {
    return priorNode;
  }
  if (mHTMLEditor->IsContainer(priorNode)) {
    // Else if it's a container, get deep rightmost child
    nsCOMPtr<nsIContent> child = mHTMLEditor->GetRightmostChild(priorNode);
    if (child) {
      return child;
    }
  }
  // Else return the node itself
  return priorNode;
}

nsIContent* WSRunScanner::GetPreviousWSNode(const EditorDOMPoint& aPoint,
                                            nsINode* aBlockParent) const {
  // Can't really recycle various getnext/prior routines because we
  // have special needs here.  Need to step into inline containers but
  // not block containers.
  MOZ_ASSERT(aPoint.IsSet() && aBlockParent);

  if (aPoint.IsInTextNode()) {
    return GetPreviousWSNodeInner(aPoint.GetContainer(), aBlockParent);
  }
  if (!mHTMLEditor->IsContainer(aPoint.GetContainer())) {
    return GetPreviousWSNodeInner(aPoint.GetContainer(), aBlockParent);
  }

  if (!aPoint.Offset()) {
    if (aPoint.GetContainer() == aBlockParent) {
      // We are at start of the block.
      return nullptr;
    }

    // We are at start of non-block container
    return GetPreviousWSNodeInner(aPoint.GetContainer(), aBlockParent);
  }

  if (NS_WARN_IF(!aPoint.GetContainerAsContent())) {
    return nullptr;
  }

  nsCOMPtr<nsIContent> priorNode = aPoint.GetPreviousSiblingOfChild();
  if (NS_WARN_IF(!priorNode)) {
    return nullptr;
  }

  // We have a prior node.  If it's a block, return it.
  if (IsBlockNode(priorNode)) {
    return priorNode;
  }
  if (mHTMLEditor->IsContainer(priorNode)) {
    // Else if it's a container, get deep rightmost child
    nsCOMPtr<nsIContent> child = mHTMLEditor->GetRightmostChild(priorNode);
    if (child) {
      return child;
    }
  }
  // Else return the node itself
  return priorNode;
}

nsIContent* WSRunScanner::GetNextWSNodeInner(nsINode* aStartNode,
                                             nsINode* aBlockParent) const {
  // Can't really recycle various getnext/prior routines because we have
  // special needs here.  Need to step into inline containers but not block
  // containers.
  MOZ_ASSERT(aStartNode && aBlockParent);

  if (aStartNode == mEditingHost) {
    NS_WARNING(
        "WSRunScanner::GetNextWSNodeInner() was called with editing host");
    return nullptr;
  }

  nsCOMPtr<nsIContent> nextNode = aStartNode->GetNextSibling();
  nsCOMPtr<nsINode> curNode = aStartNode;
  while (!nextNode) {
    // We have exhausted nodes in parent of aStartNode.
    nsCOMPtr<nsINode> curParent = curNode->GetParentNode();
    if (!curParent) {
      NS_WARNING("Reached orphan node while climbing up the DOM tree");
      return nullptr;
    }
    if (curParent == aBlockParent) {
      // We have exhausted nodes in the block parent.  The convention here is
      // to return null.
      return nullptr;
    }
    if (curParent == mEditingHost) {
      NS_WARNING("Reached editing host while climbing up the DOM tree");
      return nullptr;
    }
    // We have a parent: look for next sibling
    nextNode = curParent->GetNextSibling();
    curNode = curParent;
  }
  // We have a next node.  If it's a block, return it.
  if (IsBlockNode(nextNode)) {
    return nextNode;
  }
  if (mHTMLEditor->IsContainer(nextNode)) {
    // Else if it's a container, get deep leftmost child
    nsCOMPtr<nsIContent> child = mHTMLEditor->GetLeftmostChild(nextNode);
    if (child) {
      return child;
    }
  }
  // Else return the node itself
  return nextNode;
}

nsIContent* WSRunScanner::GetNextWSNode(const EditorDOMPoint& aPoint,
                                        nsINode* aBlockParent) const {
  // Can't really recycle various getnext/prior routines because we have
  // special needs here.  Need to step into inline containers but not block
  // containers.
  MOZ_ASSERT(aPoint.IsSet() && aBlockParent);

  if (aPoint.IsInTextNode()) {
    return GetNextWSNodeInner(aPoint.GetContainer(), aBlockParent);
  }
  if (!mHTMLEditor->IsContainer(aPoint.GetContainer())) {
    return GetNextWSNodeInner(aPoint.GetContainer(), aBlockParent);
  }

  if (NS_WARN_IF(!aPoint.GetContainerAsContent())) {
    return nullptr;
  }

  nsCOMPtr<nsIContent> nextNode = aPoint.GetChild();
  if (!nextNode) {
    if (aPoint.GetContainer() == aBlockParent) {
      // We are at end of the block.
      return nullptr;
    }

    // We are at end of non-block container
    return GetNextWSNodeInner(aPoint.GetContainer(), aBlockParent);
  }

  // We have a next node.  If it's a block, return it.
  if (IsBlockNode(nextNode)) {
    return nextNode;
  }
  if (mHTMLEditor->IsContainer(nextNode)) {
    // else if it's a container, get deep leftmost child
    nsCOMPtr<nsIContent> child = mHTMLEditor->GetLeftmostChild(nextNode);
    if (child) {
      return child;
    }
  }
  // Else return the node itself
  return nextNode;
}

nsresult WSRunObject::PrepareToDeleteRangePriv(WSRunObject* aEndObject) {
  // this routine adjust whitespace before *this* and after aEndObject
  // in preperation for the two areas to become adjacent after the
  // intervening content is deleted.  It's overly agressive right
  // now.  There might be a block boundary remaining between them after
  // the deletion, in which case these adjstments are unneeded (though
  // I don't think they can ever be harmful?)

  if (NS_WARN_IF(!aEndObject)) {
    return NS_ERROR_INVALID_ARG;
  }

  // get the runs before and after selection
  WSFragment* beforeRun = FindNearestRun(mScanStartPoint, false);
  WSFragment* afterRun =
      aEndObject->FindNearestRun(aEndObject->mScanStartPoint, true);

  if (!beforeRun && !afterRun) {
    return NS_OK;
  }

  if (afterRun) {
    // trim after run of any leading ws
    if (afterRun->IsStartOfHardLine()) {
      // mScanStartPoint will be referred bellow so that we need to keep
      // it a valid point.
      AutoEditorDOMPointChildInvalidator forgetChild(mScanStartPoint);
      nsresult rv = aEndObject->DeleteRange(aEndObject->mScanStartPoint,
                                            afterRun->EndPoint());
      if (NS_FAILED(rv)) {
        NS_WARNING("WSRunObject::DeleteRange() failed");
        return rv;
      }
    }
    // adjust normal ws in afterRun if needed
    else if (afterRun->IsVisibleAndMiddleOfHardLine() && !aEndObject->mPRE) {
      if ((beforeRun && beforeRun->IsStartOfHardLine()) ||
          (!beforeRun && StartsFromHardLineBreak())) {
        // make sure leading char of following ws is an nbsp, so that it will
        // show up
        EditorDOMPointInText nextCharOfStartOfEnd =
            aEndObject->GetNextCharPoint(aEndObject->mScanStartPoint);
        if (nextCharOfStartOfEnd.IsSet() &&
            !nextCharOfStartOfEnd.IsEndOfContainer() &&
            nextCharOfStartOfEnd.IsCharASCIISpace()) {
          // mScanStartPoint will be referred bellow so that we need to keep
          // it a valid point.
          AutoEditorDOMPointChildInvalidator forgetChild(mScanStartPoint);
          nsresult rv =
              aEndObject->InsertNBSPAndRemoveFollowingASCIIWhitespaces(
                  nextCharOfStartOfEnd);
          if (NS_FAILED(rv)) {
            NS_WARNING(
                "WSRunObject::InsertNBSPAndRemoveFollowingASCIIWhitespaces() "
                "failed");
            return rv;
          }
        }
      }
    }
  }

  if (!beforeRun) {
    return NS_OK;
  }

  // trim before run of any trailing ws
  if (beforeRun->IsEndOfHardLine()) {
    nsresult rv = DeleteRange(beforeRun->StartPoint(), mScanStartPoint);
    if (NS_FAILED(rv)) {
      NS_WARNING("WSRunObject::DeleteRange() failed");
      return rv;
    }
    return NS_OK;
  }

  if (beforeRun->IsVisibleAndMiddleOfHardLine() && !mPRE) {
    if ((afterRun && (afterRun->IsEndOfHardLine() || afterRun->IsVisible())) ||
        (!afterRun && aEndObject->EndsByBlockBoundary())) {
      // make sure trailing char of starting ws is an nbsp, so that it will show
      // up
      EditorDOMPointInText atPreviousCharOfStart =
          GetPreviousCharPoint(mScanStartPoint);
      if (atPreviousCharOfStart.IsSet() &&
          !atPreviousCharOfStart.IsEndOfContainer() &&
          atPreviousCharOfStart.IsCharASCIISpace()) {
        EditorDOMPointInText start, end;
        Tie(start, end) = GetASCIIWhitespacesBounds(eBoth, mScanStartPoint);
        NS_WARNING_ASSERTION(start.IsSet(),
                             "WSRunObject::GetASCIIWhitespacesBounds() didn't "
                             "return start point, but ignored");
        NS_WARNING_ASSERTION(end.IsSet(),
                             "WSRunObject::GetASCIIWhitespacesBounds() didn't "
                             "return end point, but ignored");
        nsresult rv = InsertNBSPAndRemoveFollowingASCIIWhitespaces(start);
        if (NS_FAILED(rv)) {
          NS_WARNING(
              "WSRunObject::InsertNBSPAndRemoveFollowingASCIIWhitespaces() "
              "failed");
          return rv;
        }
      }
    }
  }
  return NS_OK;
}

nsresult WSRunObject::PrepareToSplitAcrossBlocksPriv() {
  // used to prepare ws to be split across two blocks.  The main issue
  // here is make sure normalWS doesn't end up becoming non-significant
  // leading or trailing ws after the split.

  // get the runs before and after selection
  WSFragment* beforeRun = FindNearestRun(mScanStartPoint, false);
  WSFragment* afterRun = FindNearestRun(mScanStartPoint, true);

  // adjust normal ws in afterRun if needed
  if (afterRun && afterRun->IsVisibleAndMiddleOfHardLine()) {
    // make sure leading char of following ws is an nbsp, so that it will show
    // up
    EditorDOMPointInText atNextCharOfStart = GetNextCharPoint(mScanStartPoint);
    if (atNextCharOfStart.IsSet() && !atNextCharOfStart.IsEndOfContainer() &&
        atNextCharOfStart.IsCharASCIISpace()) {
      // mScanStartPoint will be referred bellow so that we need to keep
      // it a valid point.
      AutoEditorDOMPointChildInvalidator forgetChild(mScanStartPoint);
      nsresult rv =
          InsertNBSPAndRemoveFollowingASCIIWhitespaces(atNextCharOfStart);
      if (NS_FAILED(rv)) {
        NS_WARNING(
            "WSRunObject::InsertNBSPAndRemoveFollowingASCIIWhitespaces() "
            "failed");
        return rv;
      }
    }
  }

  // adjust normal ws in beforeRun if needed
  if (beforeRun && beforeRun->IsVisibleAndMiddleOfHardLine()) {
    // make sure trailing char of starting ws is an nbsp, so that it will show
    // up
    EditorDOMPointInText atPreviousCharOfStart =
        GetPreviousCharPoint(mScanStartPoint);
    if (atPreviousCharOfStart.IsSet() &&
        !atPreviousCharOfStart.IsEndOfContainer() &&
        atPreviousCharOfStart.IsCharASCIISpace()) {
      EditorDOMPointInText start, end;
      Tie(start, end) = GetASCIIWhitespacesBounds(eBoth, mScanStartPoint);
      NS_WARNING_ASSERTION(start.IsSet(),
                           "WSRunObject::GetASCIIWhitespacesBounds() didn't "
                           "return start point, but ignored");
      NS_WARNING_ASSERTION(end.IsSet(),
                           "WSRunObject::GetASCIIWhitespacesBounds() didn't "
                           "return end point, but ignored");
      nsresult rv = InsertNBSPAndRemoveFollowingASCIIWhitespaces(start);
      if (NS_FAILED(rv)) {
        NS_WARNING(
            "WSRunObject::InsertNBSPAndRemoveFollowingASCIIWhitespaces() "
            "failed");
        return rv;
      }
    }
  }
  return NS_OK;
}

nsresult WSRunObject::DeleteRange(const EditorDOMPoint& aStartPoint,
                                  const EditorDOMPoint& aEndPoint) {
  if (NS_WARN_IF(!aStartPoint.IsSet()) || NS_WARN_IF(!aEndPoint.IsSet())) {
    return NS_ERROR_INVALID_ARG;
  }
  MOZ_ASSERT(aStartPoint.IsSetAndValid());
  MOZ_ASSERT(aEndPoint.IsSetAndValid());

  // MOOSE: this routine needs to be modified to preserve the integrity of the
  // wsFragment info.

  if (aStartPoint == aEndPoint) {
    // Nothing to delete
    return NS_OK;
  }

  if (aStartPoint.GetContainer() == aEndPoint.GetContainer() &&
      aStartPoint.IsInTextNode()) {
    RefPtr<Text> textNode = aStartPoint.ContainerAsText();
    nsresult rv = MOZ_KnownLive(mHTMLEditor)
                      .DeleteTextWithTransaction(
                          *textNode, aStartPoint.Offset(),
                          aEndPoint.Offset() - aStartPoint.Offset());
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                         "HTMLEditor::DeleteTextWithTransaction() failed");
    return rv;
  }

  RefPtr<nsRange> range;
  int32_t count = mNodeArray.Length();
  int32_t idx = mNodeArray.IndexOf(aStartPoint.GetContainer());
  if (idx == -1) {
    // If our starting point wasn't one of our ws text nodes, then just go
    // through them from the beginning.
    idx = 0;
  }
  for (; idx < count; idx++) {
    RefPtr<Text> node = mNodeArray[idx];
    if (!node) {
      // We ran out of ws nodes; must have been deleting to end
      return NS_OK;
    }
    if (node == aStartPoint.GetContainer()) {
      if (!aStartPoint.IsEndOfContainer()) {
        nsresult rv = MOZ_KnownLive(mHTMLEditor)
                          .DeleteTextWithTransaction(
                              *node, aStartPoint.Offset(),
                              aStartPoint.GetContainer()->Length() -
                                  aStartPoint.Offset());
        if (NS_FAILED(rv)) {
          NS_WARNING("HTMLEditor::DeleteTextWithTransaction() failed");
          return rv;
        }
      }
    } else if (node == aEndPoint.GetContainer()) {
      if (!aEndPoint.IsStartOfContainer()) {
        nsresult rv =
            MOZ_KnownLive(mHTMLEditor)
                .DeleteTextWithTransaction(*node, 0, aEndPoint.Offset());
        if (NS_FAILED(rv)) {
          NS_WARNING("HTMLEditor::DeleteTextWithTransaction() failed");
          return rv;
        }
      }
      break;
    } else {
      if (!range) {
        ErrorResult error;
        range = nsRange::Create(aStartPoint.ToRawRangeBoundary(),
                                aEndPoint.ToRawRangeBoundary(), error);
        if (!range) {
          NS_WARNING("nsRange::Create() failed");
          return error.StealNSResult();
        }
      }
      bool nodeBefore, nodeAfter;
      nsresult rv =
          RangeUtils::CompareNodeToRange(node, range, &nodeBefore, &nodeAfter);
      if (NS_FAILED(rv)) {
        NS_WARNING("RangeUtils::CompareNodeToRange() failed");
        return rv;
      }
      if (nodeAfter) {
        break;
      }
      if (!nodeBefore) {
        nsresult rv =
            MOZ_KnownLive(mHTMLEditor).DeleteNodeWithTransaction(*node);
        if (NS_FAILED(rv)) {
          NS_WARNING("HTMLEditor::DeleteNodeWithTransaction() failed");
          return rv;
        }
        mNodeArray.RemoveElement(node);
        --count;
        --idx;
      }
    }
  }
  return NS_OK;
}

template <typename PT, typename CT>
EditorDOMPointInText WSRunScanner::GetNextCharPoint(
    const EditorDOMPointBase<PT, CT>& aPoint) const {
  MOZ_ASSERT(aPoint.IsSetAndValid());

  size_t index = aPoint.IsInTextNode()
                     ? mNodeArray.IndexOf(aPoint.GetContainer())
                     : decltype(mNodeArray)::NoIndex;
  if (index == decltype(mNodeArray)::NoIndex) {
    // Use range comparisons to get next text node which is in mNodeArray.
    return LookForNextCharPointWithinAllTextNodes(aPoint);
  }
  return GetNextCharPointFromPointInText(
      EditorDOMPointInText(mNodeArray[index], aPoint.Offset()));
}

template <typename PT, typename CT>
EditorDOMPointInText WSRunScanner::GetPreviousCharPoint(
    const EditorDOMPointBase<PT, CT>& aPoint) const {
  MOZ_ASSERT(aPoint.IsSetAndValid());

  size_t index = aPoint.IsInTextNode()
                     ? mNodeArray.IndexOf(aPoint.GetContainer())
                     : decltype(mNodeArray)::NoIndex;
  if (index == decltype(mNodeArray)::NoIndex) {
    // Use range comparisons to get previous text node which is in mNodeArray.
    return LookForPreviousCharPointWithinAllTextNodes(aPoint);
  }
  return GetPreviousCharPointFromPointInText(
      EditorDOMPointInText(mNodeArray[index], aPoint.Offset()));
}

EditorDOMPointInText WSRunScanner::GetNextCharPointFromPointInText(
    const EditorDOMPointInText& aPoint) const {
  MOZ_ASSERT(aPoint.IsSet());

  size_t index = mNodeArray.IndexOf(aPoint.GetContainer());
  if (index == decltype(mNodeArray)::NoIndex) {
    // Can't find point, but it's not an error
    return EditorDOMPointInText();
  }

  if (aPoint.IsSetAndValid() && !aPoint.IsEndOfContainer()) {
    // XXX This may return empty text node.
    return aPoint;
  }

  if (index + 1 == mNodeArray.Length()) {
    return EditorDOMPointInText();
  }

  // XXX This may return empty text node.
  return EditorDOMPointInText(mNodeArray[index + 1], 0);
}

EditorDOMPointInText WSRunScanner::GetPreviousCharPointFromPointInText(
    const EditorDOMPointInText& aPoint) const {
  MOZ_ASSERT(aPoint.IsSet());

  size_t index = mNodeArray.IndexOf(aPoint.GetContainer());
  if (index == decltype(mNodeArray)::NoIndex) {
    // Can't find point, but it's not an error
    return EditorDOMPointInText();
  }

  if (!aPoint.IsStartOfContainer()) {
    return aPoint.PreviousPoint();
  }

  if (!index) {
    return EditorDOMPointInText();
  }

  // XXX This may return empty text node.
  return EditorDOMPointInText(mNodeArray[index - 1],
                              mNodeArray[index - 1]->TextLength()
                                  ? mNodeArray[index - 1]->TextLength() - 1
                                  : 0);
}

nsresult WSRunObject::InsertNBSPAndRemoveFollowingASCIIWhitespaces(
    const EditorDOMPointInText& aPoint) {
  // MOOSE: this routine needs to be modified to preserve the integrity of the
  // wsFragment info.
  if (NS_WARN_IF(!aPoint.IsSet())) {
    return NS_ERROR_NULL_POINTER;
  }

  // First, insert an NBSP.
  AutoTransactionsConserveSelection dontChangeMySelection(mHTMLEditor);
  nsresult rv = MOZ_KnownLive(mHTMLEditor)
                    .InsertTextIntoTextNodeWithTransaction(
                        nsDependentSubstring(&kNBSP, 1), aPoint, true);
  if (NS_FAILED(rv)) {
    NS_WARNING("EditorBase::InsertTextIntoTextNodeWithTransaction() failed");
    return rv;
  }

  // Now, the text node may have been modified by mutation observer.
  // So, the NBSP may have gone.
  if (!aPoint.IsSetAndValid() || aPoint.IsEndOfContainer() ||
      !aPoint.IsCharNBSP()) {
    // This is just preparation of an edit action.  Let's return NS_OK.
    // XXX Perhaps, we should return another success code which indicates
    //     mutation observer touched the DOM tree.  However, that should
    //     be returned from each transaction's DoTransaction.
    return NS_OK;
  }

  // Next, find range of whitespaces it will be replaced.
  EditorDOMPointInText start, end;
  Tie(start, end) = GetASCIIWhitespacesBounds(eAfter, aPoint.NextPoint());
  if (!start.IsSet()) {
    return NS_OK;
  }
  NS_WARNING_ASSERTION(end.IsSet(),
                       "WSRunObject::GetASCIIWhitespacesBounds() didn't return "
                       "end point, but ignored");

  // Finally, delete that replaced ws, if any
  rv = DeleteRange(start, end);
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "WSRunObject::DeleteRange() failed");
  return rv;
}

template <typename PT, typename CT>
Tuple<EditorDOMPointInText, EditorDOMPointInText>
WSRunObject::GetASCIIWhitespacesBounds(
    int16_t aDir, const EditorDOMPointBase<PT, CT>& aPoint) const {
  MOZ_ASSERT(aPoint.IsSet());

  EditorDOMPointInText start, end;

  if (aDir & eAfter) {
    EditorDOMPointInText atNextChar = GetNextCharPoint(aPoint);
    if (atNextChar.IsSet()) {
      // We found a text node, at least.
      start = end = atNextChar;
      // Scan ahead to end of ASCII whitespaces.
      // XXX Looks like that this is too expensive in most cases.  While we
      //     are scanning a text node, we should do it without
      //     GetNextCharPointInText().
      // XXX This loop ends at end of a text node.  Shouldn't we keep looking
      //     next text node?
      for (; atNextChar.IsSet() && !atNextChar.IsEndOfContainer() &&
             atNextChar.IsCharASCIISpace();
           atNextChar = GetNextCharPointFromPointInText(atNextChar)) {
        // End of the range should be after the whitespace.
        end = atNextChar = atNextChar.NextPoint();
      }
    }
  }

  if (aDir & eBefore) {
    EditorDOMPointInText atPreviousChar = GetPreviousCharPoint(aPoint);
    if (atPreviousChar.IsSet()) {
      // We found a text node, at least.
      start = atPreviousChar.NextPoint();
      if (!end.IsSet()) {
        end = start;
      }
      // Scan back to start of ASCII whitespaces.
      // XXX Looks like that this is too expensive in most cases.  While we
      //     are scanning a text node, we should do it without
      //     GetPreviousCharPointFromPointInText().
      // XXX This loop ends at end of a text node.  Shouldn't we keep looking
      //     the text node?
      for (; atPreviousChar.IsSet() && !atPreviousChar.IsEndOfContainer() &&
             atPreviousChar.IsCharASCIISpace();
           atPreviousChar =
               GetPreviousCharPointFromPointInText(atPreviousChar)) {
        start = atPreviousChar;
      }
    }
  }

  return MakeTuple(start, end);
}

template <typename PT, typename CT>
WSRunScanner::WSFragment* WSRunScanner::FindNearestRun(
    const EditorDOMPointBase<PT, CT>& aPoint, bool aForward) const {
  MOZ_ASSERT(aPoint.IsSetAndValid());

  for (WSFragment* run = mStartRun; run; run = run->mRight) {
    int32_t comp = run->mStartNode ? *nsContentUtils::ComparePoints(
                                         aPoint.ToRawRangeBoundary(),
                                         run->StartPoint().ToRawRangeBoundary())
                                   : -1;
    if (comp <= 0) {
      // aPoint equals or before start of the run.  Return the run if we're
      // scanning forward, otherwise, nullptr.
      return aForward ? run : nullptr;
    }

    comp = run->mEndNode ? *nsContentUtils::ComparePoints(
                               aPoint.ToRawRangeBoundary(),
                               run->EndPoint().ToRawRangeBoundary())
                         : -1;
    if (comp < 0) {
      // If aPoint is in the run, return the run.
      return run;
    }

    if (!comp) {
      // If aPoint is at end of the run, return next run if we're scanning
      // forward, otherwise, return the run.
      return aForward ? run->mRight : run;
    }

    if (!run->mRight) {
      // If the run is the last run and aPoint is after end of the last run,
      // return nullptr if we're scanning forward, otherwise, return this
      // last run.
      return aForward ? nullptr : run;
    }
  }

  return nullptr;
}

char16_t WSRunScanner::GetCharAt(Text* aTextNode, int32_t aOffset) const {
  // return 0 if we can't get a char, for whatever reason
  if (NS_WARN_IF(!aTextNode) || NS_WARN_IF(aOffset < 0) ||
      NS_WARN_IF(aOffset >=
                 static_cast<int32_t>(aTextNode->TextDataLength()))) {
    return 0;
  }
  return aTextNode->TextFragment().CharAt(aOffset);
}

template <typename PT, typename CT>
EditorDOMPointInText WSRunScanner::LookForNextCharPointWithinAllTextNodes(
    const EditorDOMPointBase<PT, CT>& aPoint) const {
  // Note: only to be called if aPoint.GetContainer() is not a ws node.

  MOZ_ASSERT(aPoint.IsSetAndValid());

  // Binary search on wsnodes
  uint32_t numNodes = mNodeArray.Length();

  if (!numNodes) {
    // Do nothing if there are no nodes to search
    return EditorDOMPointInText();
  }

  // Begin binary search.  We do this because we need to minimize calls to
  // ComparePoints(), which is expensive.
  uint32_t firstNum = 0, curNum = numNodes / 2, lastNum = numNodes;
  while (curNum != lastNum) {
    Text* curNode = mNodeArray[curNum];
    int16_t cmp = *nsContentUtils::ComparePoints(aPoint.ToRawRangeBoundary(),
                                                 RawRangeBoundary(curNode, 0u));
    if (cmp < 0) {
      lastNum = curNum;
    } else {
      firstNum = curNum + 1;
    }
    curNum = (lastNum - firstNum) / 2 + firstNum;
    MOZ_ASSERT(firstNum <= curNum && curNum <= lastNum, "Bad binary search");
  }

  // When the binary search is complete, we always know that the current node
  // is the same as the end node, which is always past our range.  Therefore,
  // we've found the node immediately after the point of interest.
  if (curNum == mNodeArray.Length()) {
    // hey asked for past our range (it's after the last node).
    // GetNextCharPoint() will do the work for us when we pass it the last
    // index of the last node.
    return GetNextCharPointFromPointInText(
        EditorDOMPointInText::AtEndOf(mNodeArray[curNum - 1]));
  }

  // The char after the point is the first character of our range.
  return GetNextCharPointFromPointInText(
      EditorDOMPointInText(mNodeArray[curNum], 0));
}

template <typename PT, typename CT>
EditorDOMPointInText WSRunScanner::LookForPreviousCharPointWithinAllTextNodes(
    const EditorDOMPointBase<PT, CT>& aPoint) const {
  // Note: only to be called if aNode is not a ws node.

  MOZ_ASSERT(aPoint.IsSetAndValid());

  // Binary search on wsnodes
  uint32_t numNodes = mNodeArray.Length();

  if (!numNodes) {
    // Do nothing if there are no nodes to search
    return EditorDOMPointInText();
  }

  uint32_t firstNum = 0, curNum = numNodes / 2, lastNum = numNodes;
  int16_t cmp = 0;

  // Begin binary search.  We do this because we need to minimize calls to
  // ComparePoints(), which is expensive.
  while (curNum != lastNum) {
    Text* curNode = mNodeArray[curNum];
    cmp = *nsContentUtils::ComparePoints(aPoint.ToRawRangeBoundary(),
                                         RawRangeBoundary(curNode, 0u));
    if (cmp < 0) {
      lastNum = curNum;
    } else {
      firstNum = curNum + 1;
    }
    curNum = (lastNum - firstNum) / 2 + firstNum;
    MOZ_ASSERT(firstNum <= curNum && curNum <= lastNum, "Bad binary search");
  }

  // When the binary search is complete, we always know that the current node
  // is the same as the end node, which is always past our range. Therefore,
  // we've found the node immediately after the point of interest.
  if (curNum == mNodeArray.Length()) {
    // Get the point before the end of the last node, we can pass the length of
    // the node into GetPreviousCharPoint(), and it will return the last
    // character.
    return GetPreviousCharPointFromPointInText(
        EditorDOMPointInText::AtEndOf(mNodeArray[curNum - 1]));
  }

  // We can just ask the current node for the point immediately before it,
  // it will handle moving to the previous node (if any) and returning the
  // appropriate character
  return GetPreviousCharPointFromPointInText(
      EditorDOMPointInText(mNodeArray[curNum], 0));
}

nsresult WSRunObject::CheckTrailingNBSPOfRun(WSFragment* aRun) {
  if (NS_WARN_IF(!aRun)) {
    return NS_ERROR_INVALID_ARG;
  }

  // Try to change an nbsp to a space, if possible, just to prevent nbsp
  // proliferation.  Examine what is before and after the trailing nbsp, if
  // any.
  bool leftCheck = false;
  bool spaceNBSP = false;
  bool rightCheck = false;

  // Check if it's a visible fragment in a hard line.
  if (!aRun->IsVisibleAndMiddleOfHardLine()) {
    return NS_ERROR_FAILURE;
  }

  // first check for trailing nbsp
  EditorDOMPointInText atPreviousCharOfEndOfRun =
      GetPreviousCharPoint(aRun->EndPoint());
  if (atPreviousCharOfEndOfRun.IsSet() &&
      !atPreviousCharOfEndOfRun.IsEndOfContainer() &&
      atPreviousCharOfEndOfRun.IsCharNBSP()) {
    // now check that what is to the left of it is compatible with replacing
    // nbsp with space
    EditorDOMPointInText atPreviousCharOfPreviousCharOfEndOfRun =
        GetPreviousCharPointFromPointInText(atPreviousCharOfEndOfRun);
    if (atPreviousCharOfPreviousCharOfEndOfRun.IsSet()) {
      if (atPreviousCharOfPreviousCharOfEndOfRun.IsEndOfContainer() ||
          !atPreviousCharOfPreviousCharOfEndOfRun.IsCharASCIISpace()) {
        leftCheck = true;
      } else {
        spaceNBSP = true;
      }
    } else if (aRun->StartsFromNormalText() ||
               aRun->StartsFromSpecialContent()) {
      leftCheck = true;
    }
    if (leftCheck || spaceNBSP) {
      // now check that what is to the right of it is compatible with replacing
      // nbsp with space
      if (aRun->EndsByNormalText() || aRun->EndsBySpecialContent() ||
          aRun->EndsByBRElement()) {
        rightCheck = true;
      }
      if ((aRun->EndsByBlockBoundary()) &&
          (IsBlockNode(GetEditableBlockParentOrTopmotEditableInlineContent(
               mScanStartPoint.GetContainerAsContent())) ||
           IsBlockNode(mScanStartPoint.GetContainerAsContent()))) {
        // We are at a block boundary.  Insert a <br>.  Why?  Well, first note
        // that the br will have no visible effect since it is up against a
        // block boundary.  |foo<br><p>bar| renders like |foo<p>bar| and
        // similarly |<p>foo<br></p>bar| renders like |<p>foo</p>bar|.  What
        // this <br> addition gets us is the ability to convert a trailing nbsp
        // to a space.  Consider: |<body>foo. '</body>|, where ' represents
        // selection.  User types space attempting to put 2 spaces after the
        // end of their sentence.  We used to do this as: |<body>foo.
        // &nbsp</body>|  This caused problems with soft wrapping: the nbsp
        // would wrap to the next line, which looked attrocious.  If you try to
        // do: |<body>foo.&nbsp </body>| instead, the trailing space is
        // invisible because it is against a block boundary.  If you do:
        // |<body>foo.&nbsp&nbsp</body>| then you get an even uglier soft
        // wrapping problem, where foo is on one line until you type the final
        // space, and then "foo  " jumps down to the next line.  Ugh.  The best
        // way I can find out of this is to throw in a harmless <br> here,
        // which allows us to do: |<body>foo.&nbsp <br></body>|, which doesn't
        // cause foo to jump lines, doesn't cause spaces to show up at the
        // beginning of soft wrapped lines, and lets the user see 2 spaces when
        // they type 2 spaces.

        RefPtr<Element> brElement =
            MOZ_KnownLive(mHTMLEditor)
                .InsertBRElementWithTransaction(aRun->EndPoint());
        if (!brElement) {
          NS_WARNING("HTMLEditor::InsertBRElementWithTransaction() failed");
          return NS_ERROR_FAILURE;
        }

        atPreviousCharOfEndOfRun = GetPreviousCharPoint(aRun->EndPoint());
        atPreviousCharOfPreviousCharOfEndOfRun =
            GetPreviousCharPointFromPointInText(atPreviousCharOfEndOfRun);
        rightCheck = true;
      }
    }
    if (leftCheck && rightCheck) {
      // Now replace nbsp with space.  First, insert a space
      AutoTransactionsConserveSelection dontChangeMySelection(mHTMLEditor);
      nsresult rv =
          MOZ_KnownLive(mHTMLEditor)
              .InsertTextIntoTextNodeWithTransaction(
                  NS_LITERAL_STRING(" "), atPreviousCharOfEndOfRun, true);
      if (NS_FAILED(rv)) {
        NS_WARNING(
            "EditorBase::InsertTextIntoTextNodeWithTransaction() failed");
        return rv;
      }

      // Finally, delete that nbsp
      NS_ASSERTION(!atPreviousCharOfEndOfRun.IsEndOfContainer() &&
                       !atPreviousCharOfEndOfRun.IsAtLastContent(),
                   "The text node was modified by mutation event listener");
      if (!atPreviousCharOfEndOfRun.IsEndOfContainer() &&
          !atPreviousCharOfEndOfRun.IsAtLastContent()) {
        NS_ASSERTION(atPreviousCharOfEndOfRun.IsNextCharNBSP(),
                     "Trying to remove an NBSP, but it's gone from the "
                     "expected position");
        EditorDOMPointInText atNextCharOfPreviousCharOfEndOfRun =
            atPreviousCharOfEndOfRun.NextPoint();
        nsresult rv =
            DeleteRange(atNextCharOfPreviousCharOfEndOfRun,
                        atNextCharOfPreviousCharOfEndOfRun.NextPoint());
        if (NS_FAILED(rv)) {
          NS_WARNING("WSRunObject::DeleteRange() failed");
          return rv;
        }
      }
    } else if (!mPRE && spaceNBSP && rightCheck) {
      // Don't mess with this preformatted for now.  We have a run of ASCII
      // whitespace (which will render as one space) followed by an nbsp (which
      // is at the end of the whitespace run).  Let's switch their order.  This
      // will ensure that if someone types two spaces after a sentence, and the
      // editor softwraps at this point, the spaces won't be split across lines,
      // which looks ugly and is bad for the moose.
      MOZ_ASSERT(!atPreviousCharOfPreviousCharOfEndOfRun.IsEndOfContainer());
      EditorDOMPointInText start, end;
      // XXX end won't be used, whey `eBoth`?
      Tie(start, end) = GetASCIIWhitespacesBounds(
          eBoth, atPreviousCharOfPreviousCharOfEndOfRun.NextPoint());
      NS_WARNING_ASSERTION(
          start.IsSet(),
          "WSRunObject::GetASCIIWhitespacesBounds() didn't return start point");
      NS_WARNING_ASSERTION(end.IsSet(),
                           "WSRunObject::GetASCIIWhitespacesBounds() didn't "
                           "return end point, but ignored");

      // Delete that nbsp
      NS_ASSERTION(!atPreviousCharOfEndOfRun.IsEndOfContainer(),
                   "The text node was modified by mutation event listener");
      if (!atPreviousCharOfEndOfRun.IsEndOfContainer()) {
        NS_ASSERTION(atPreviousCharOfEndOfRun.IsCharNBSP(),
                     "Trying to remove an NBSP, but it's gone from the "
                     "expected position");
        nsresult rv = DeleteRange(atPreviousCharOfEndOfRun,
                                  atPreviousCharOfEndOfRun.NextPoint());
        if (NS_FAILED(rv)) {
          NS_WARNING("WSRunObject::DeleteRange() failed");
          return rv;
        }
      }

      // Finally, insert that nbsp before the ASCII ws run
      NS_ASSERTION(start.IsSetAndValid(),
                   "The text node was modified by mutation event listener");
      if (start.IsSetAndValid()) {
        AutoTransactionsConserveSelection dontChangeMySelection(mHTMLEditor);
        nsresult rv = MOZ_KnownLive(mHTMLEditor)
                          .InsertTextIntoTextNodeWithTransaction(
                              nsDependentSubstring(&kNBSP, 1), start, true);
        if (NS_FAILED(rv)) {
          NS_WARNING(
              "EditorBase::InsertTextIntoTextNodeWithTransaction() failed");
          return rv;
        }
      }
    }
  }
  return NS_OK;
}

nsresult WSRunObject::ReplacePreviousNBSPIfUnnecessary(
    WSFragment* aRun, const EditorDOMPoint& aPoint) {
  if (NS_WARN_IF(!aRun) || NS_WARN_IF(!aPoint.IsSet())) {
    return NS_ERROR_INVALID_ARG;
  }
  MOZ_ASSERT(aPoint.IsSetAndValid());

  // Try to change an NBSP to a space, if possible, just to prevent NBSP
  // proliferation.  This routine is called when we are about to make this
  // point in the ws abut an inserted break or text, so we don't have to worry
  // about what is after it.  What is after it now will end up after the
  // inserted object.
  bool canConvert = false;
  EditorDOMPointInText atPreviousChar = GetPreviousCharPoint(aPoint);
  if (atPreviousChar.IsSet() && !atPreviousChar.IsEndOfContainer() &&
      atPreviousChar.IsCharNBSP()) {
    EditorDOMPointInText atPreviousCharOfPreviousChar =
        GetPreviousCharPointFromPointInText(atPreviousChar);
    if (atPreviousCharOfPreviousChar.IsSet()) {
      if (atPreviousCharOfPreviousChar.IsEndOfContainer() ||
          !atPreviousCharOfPreviousChar.IsCharASCIISpace()) {
        // If previous character is a NBSP and its previous character isn't
        // ASCII space, we can replace the NBSP with ASCII space.
        canConvert = true;
      }
    } else if (aRun->StartsFromNormalText() ||
               aRun->StartsFromSpecialContent()) {
      // If previous character is a NBSP and it's the first character of the
      // text node, additionally, if its previous node is a text node including
      // non-whitespace characters or <img> node or something inline
      // non-container element node, we can replace the NBSP with ASCII space.
      canConvert = true;
    }
  }

  if (!canConvert) {
    return NS_OK;
  }

  // First, insert a space before the previous NBSP.
  AutoTransactionsConserveSelection dontChangeMySelection(mHTMLEditor);
  nsresult rv = MOZ_KnownLive(mHTMLEditor)
                    .InsertTextIntoTextNodeWithTransaction(
                        NS_LITERAL_STRING(" "), atPreviousChar, true);
  if (NS_FAILED(rv)) {
    NS_WARNING("EditorBase::InsertTextIntoTextNodeWithTransaction() failed");
    return rv;
  }

  // Finally, delete the previous NBSP.
  NS_ASSERTION(
      !atPreviousChar.IsEndOfContainer() && !atPreviousChar.IsAtLastContent(),
      "The text node was modified by mutation event listener");
  if (!atPreviousChar.IsEndOfContainer() && !atPreviousChar.IsAtLastContent()) {
    NS_ASSERTION(
        atPreviousChar.IsNextCharNBSP(),
        "Trying to remove an NBSP, but it's gone from the expected position");
    EditorDOMPointInText atNextCharOfPreviousChar = atPreviousChar.NextPoint();
    nsresult rv = DeleteRange(atNextCharOfPreviousChar,
                              atNextCharOfPreviousChar.NextPoint());
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "WSRunObject::DeleteRange() failed");
    return rv;
  }

  return NS_OK;
}

nsresult WSRunObject::CheckLeadingNBSP(WSFragment* aRun, nsINode* aNode,
                                       int32_t aOffset) {
  // Try to change an nbsp to a space, if possible, just to prevent nbsp
  // proliferation This routine is called when we are about to make this point
  // in the ws abut an inserted text, so we don't have to worry about what is
  // before it.  What is before it now will end up before the inserted text.
  bool canConvert = false;
  EditorDOMPointInText atNextChar =
      GetNextCharPoint(EditorRawDOMPoint(aNode, aOffset));
  if (!atNextChar.IsSet() || NS_WARN_IF(atNextChar.IsEndOfContainer())) {
    return NS_OK;
  }

  if (atNextChar.IsCharNBSP()) {
    EditorDOMPointInText atNextCharOfNextCharOfNBSP =
        GetNextCharPointFromPointInText(atNextChar.NextPoint());
    if (atNextCharOfNextCharOfNBSP.IsSet()) {
      if (atNextCharOfNextCharOfNBSP.IsEndOfContainer() ||
          !atNextCharOfNextCharOfNBSP.IsCharASCIISpace()) {
        canConvert = true;
      }
    } else if (aRun->EndsByNormalText() || aRun->EndsBySpecialContent() ||
               aRun->EndsByBRElement()) {
      canConvert = true;
    }
  }
  if (canConvert) {
    // First, insert a space
    AutoTransactionsConserveSelection dontChangeMySelection(mHTMLEditor);
    nsresult rv = MOZ_KnownLive(mHTMLEditor)
                      .InsertTextIntoTextNodeWithTransaction(
                          NS_LITERAL_STRING(" "), atNextChar, true);
    if (NS_FAILED(rv)) {
      NS_WARNING("EditorBase::InsertTextIntoTextNodeWithTransaction() failed");
      return rv;
    }

    // Finally, delete that nbsp
    NS_ASSERTION(
        !atNextChar.IsEndOfContainer() && !atNextChar.IsAtLastContent(),
        "The text node was modified by mutation event listener");
    if (!atNextChar.IsEndOfContainer() && !atNextChar.IsAtLastContent()) {
      NS_ASSERTION(
          atNextChar.IsNextCharNBSP(),
          "Trying to remove an NBSP, but it's gone from the expected position");
      EditorDOMPointInText atNextCharOfNextChar = atNextChar.NextPoint();
      rv = DeleteRange(atNextCharOfNextChar, atNextCharOfNextChar.NextPoint());
      NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                           "WSRunObject::DeleteRange() failed");
      return rv;
    }
  }
  return NS_OK;
}

nsresult WSRunObject::Scrub() {
  for (WSFragment* run = mStartRun; run; run = run->mRight) {
    if (run->IsMiddleOfHardLine()) {
      continue;
    }
    nsresult rv = DeleteRange(run->StartPoint(), run->EndPoint());
    if (NS_FAILED(rv)) {
      NS_WARNING("WSRunObject::DeleteRange() failed");
      return rv;
    }
  }
  return NS_OK;
}

}  // namespace mozilla