1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674
|
/* -*- 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 "WhiteSpaceVisibilityKeeper.h"
#include "EditorDOMPoint.h"
#include "EditorUtils.h"
#include "ErrorList.h"
#include "HTMLEditHelpers.h" // for MoveNodeResult, SplitNodeResult
#include "HTMLEditor.h"
#include "HTMLEditorNestedClasses.h" // for AutoMoveOneLineHandler
#include "HTMLEditUtils.h"
#include "SelectionState.h"
#include "mozilla/Assertions.h"
#include "mozilla/SelectionState.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/StaticPrefs_editor.h" // for StaticPrefs::editor_*
#include "mozilla/dom/AncestorIterator.h"
#include "nsCRT.h"
#include "nsContentUtils.h"
#include "nsDebug.h"
#include "nsError.h"
#include "nsIContent.h"
#include "nsIContentInlines.h"
#include "nsString.h"
namespace mozilla {
using namespace dom;
using LeafNodeType = HTMLEditUtils::LeafNodeType;
using WalkTreeOption = HTMLEditUtils::WalkTreeOption;
Result<EditorDOMPoint, nsresult>
WhiteSpaceVisibilityKeeper::PrepareToSplitBlockElement(
HTMLEditor& aHTMLEditor, const EditorDOMPoint& aPointToSplit,
const Element& aSplittingBlockElement) {
if (NS_WARN_IF(!aPointToSplit.IsInContentNodeAndValidInComposedDoc()) ||
NS_WARN_IF(!HTMLEditUtils::IsSplittableNode(aSplittingBlockElement)) ||
NS_WARN_IF(!EditorUtils::IsEditableContent(
*aPointToSplit.ContainerAs<nsIContent>(), EditorType::HTML))) {
return Err(NS_ERROR_FAILURE);
}
// The container of aPointToSplit may be not splittable, e.g., selection
// may be collapsed **in** a `<br>` element or a comment node. So, look
// for splittable point with climbing the tree up.
EditorDOMPoint pointToSplit(aPointToSplit);
for (nsIContent* content : aPointToSplit.ContainerAs<nsIContent>()
->InclusiveAncestorsOfType<nsIContent>()) {
if (content == &aSplittingBlockElement) {
break;
}
if (HTMLEditUtils::IsSplittableNode(*content)) {
break;
}
pointToSplit.Set(content);
}
// NOTE: Chrome does not normalize white-spaces at splitting `Text` when
// inserting a paragraph at least when the surrounding white-spaces being or
// end with an NBSP.
Result<EditorDOMPoint, nsresult> pointToSplitOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitAt(
aHTMLEditor, pointToSplit,
{NormalizeOption::StopIfFollowingWhiteSpacesStartsWithNBSP,
NormalizeOption::StopIfPrecedingWhiteSpacesEndsWithNBP});
if (MOZ_UNLIKELY(pointToSplitOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitAt() failed");
return pointToSplitOrError.propagateErr();
}
pointToSplit = pointToSplitOrError.unwrap();
if (NS_WARN_IF(!pointToSplit.IsInContentNode()) ||
NS_WARN_IF(
!pointToSplit.ContainerAs<nsIContent>()->IsInclusiveDescendantOf(
&aSplittingBlockElement)) ||
NS_WARN_IF(!HTMLEditUtils::IsSplittableNode(aSplittingBlockElement)) ||
NS_WARN_IF(!HTMLEditUtils::IsSplittableNode(
*pointToSplit.ContainerAs<nsIContent>()))) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return pointToSplit;
}
// static
Result<MoveNodeResult, nsresult> WhiteSpaceVisibilityKeeper::
MergeFirstLineOfRightBlockElementIntoDescendantLeftBlockElement(
HTMLEditor& aHTMLEditor, Element& aLeftBlockElement,
Element& aRightBlockElement, const EditorDOMPoint& aAtRightBlockChild,
const Maybe<nsAtom*>& aListElementTagName,
const HTMLBRElement* aPrecedingInvisibleBRElement,
const Element& aEditingHost) {
MOZ_ASSERT(
EditorUtils::IsDescendantOf(aLeftBlockElement, aRightBlockElement));
MOZ_ASSERT(&aRightBlockElement == aAtRightBlockChild.GetContainer());
OwningNonNull<Element> rightBlockElement = aRightBlockElement;
EditorDOMPoint afterRightBlockChild = aAtRightBlockChild.NextPoint();
{
AutoTrackDOMPoint trackAfterRightBlockChild(aHTMLEditor.RangeUpdaterRef(),
&afterRightBlockChild);
// First, delete invisible white-spaces at start of the right block and
// normalize the leading visible white-spaces.
nsresult rv = WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesAfter(
aHTMLEditor, afterRightBlockChild);
if (NS_FAILED(rv)) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesAfter() "
"failed");
return Err(rv);
}
// Next, delete invisible white-spaces at end of the left block and
// normalize the trailing visible white-spaces.
rv = WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesBefore(
aHTMLEditor, EditorDOMPoint::AtEndOf(aLeftBlockElement));
if (NS_FAILED(rv)) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesBefore() "
"failed");
return Err(rv);
}
trackAfterRightBlockChild.FlushAndStopTracking();
if (NS_WARN_IF(afterRightBlockChild.GetContainer() !=
&aRightBlockElement)) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
// Finally, make sure that we won't create new invisible white-spaces.
{
AutoTrackDOMPoint trackAfterRightBlockChild(aHTMLEditor.RangeUpdaterRef(),
&afterRightBlockChild);
Result<EditorDOMPoint, nsresult> atFirstVisibleThingOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAfter(
aHTMLEditor, afterRightBlockChild,
{NormalizeOption::StopIfFollowingWhiteSpacesStartsWithNBSP});
if (MOZ_UNLIKELY(atFirstVisibleThingOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAfter() failed");
return atFirstVisibleThingOrError.propagateErr();
}
Result<EditorDOMPoint, nsresult> afterLastVisibleThingOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesBefore(
aHTMLEditor, EditorDOMPoint::AtEndOf(aLeftBlockElement), {});
if (MOZ_UNLIKELY(afterLastVisibleThingOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAfter() failed");
return afterLastVisibleThingOrError.propagateErr();
}
}
// XXX And afterRightBlockChild.GetContainerAs<Element>() always returns
// an element pointer so that probably here should not use
// accessors of EditorDOMPoint, should use DOM API directly instead.
if (afterRightBlockChild.GetContainerAs<Element>()) {
rightBlockElement = *afterRightBlockChild.ContainerAs<Element>();
} else if (NS_WARN_IF(
!afterRightBlockChild.GetContainerParentAs<Element>())) {
return Err(NS_ERROR_UNEXPECTED);
} else {
rightBlockElement = *afterRightBlockChild.GetContainerParentAs<Element>();
}
auto atStartOfRightText = [&]() MOZ_NEVER_INLINE_DEBUG -> EditorDOMPoint {
const WSRunScanner scanner({}, EditorRawDOMPoint(&aRightBlockElement, 0u));
for (EditorRawDOMPointInText atFirstChar =
scanner.GetInclusiveNextCharPoint<EditorRawDOMPointInText>(
EditorRawDOMPoint(&aRightBlockElement, 0u));
atFirstChar.IsSet();
atFirstChar =
scanner.GetInclusiveNextCharPoint<EditorRawDOMPointInText>(
atFirstChar.AfterContainer<EditorRawDOMPoint>())) {
if (atFirstChar.IsContainerEmpty()) {
continue; // Ignore empty text node.
}
if (atFirstChar.IsCharASCIISpaceOrNBSP() &&
HTMLEditUtils::IsSimplyEditableNode(
*atFirstChar.ContainerAs<Text>())) {
return atFirstChar.To<EditorDOMPoint>();
}
break;
}
return EditorDOMPoint();
}();
AutoTrackDOMPoint trackStartOfRightText(aHTMLEditor.RangeUpdaterRef(),
&atStartOfRightText);
// Do br adjustment.
// XXX Why don't we delete the <br> first? If so, we can skip to track the
// MoveNodeResult at last.
const RefPtr<HTMLBRElement> invisibleBRElementAtEndOfLeftBlockElement =
WSRunScanner::GetPrecedingBRElementUnlessVisibleContentFound(
{WSRunScanner::Option::OnlyEditableNodes},
EditorDOMPoint::AtEndOf(aLeftBlockElement));
NS_ASSERTION(
aPrecedingInvisibleBRElement == invisibleBRElementAtEndOfLeftBlockElement,
"The preceding invisible BR element computation was different");
auto moveContentResult = [&]() MOZ_NEVER_INLINE_DEBUG MOZ_CAN_RUN_SCRIPT
-> Result<MoveNodeResult, nsresult> {
// NOTE: Keep syncing with CanMergeLeftAndRightBlockElements() of
// AutoInclusiveAncestorBlockElementsJoiner.
if (NS_WARN_IF(aListElementTagName.isSome())) {
// Since 2002, here was the following comment:
// > The idea here is to take all children in rightListElement that are
// > past offset, and pull them into leftlistElement.
// However, this has never been performed because we are here only when
// neither left list nor right list is a descendant of the other but
// in such case, getting a list item in the right list node almost
// always failed since a variable for offset of
// rightListElement->GetChildAt() was not initialized. So, it might be
// a bug, but we should keep this traditional behavior for now. If you
// find when we get here, please remove this comment if we don't need to
// do it. Otherwise, please move children of the right list node to the
// end of the left list node.
// XXX Although, we do nothing here, but for keeping traditional
// behavior, we should mark as handled.
return MoveNodeResult::HandledResult(
EditorDOMPoint::AtEndOf(aLeftBlockElement));
}
AutoTransactionsConserveSelection dontChangeMySelection(aHTMLEditor);
// XXX Why do we ignore the result of AutoMoveOneLineHandler::Run()?
NS_ASSERTION(rightBlockElement == afterRightBlockChild.GetContainer(),
"The relation is not guaranteed but assumed");
#ifdef DEBUG
Result<bool, nsresult> firstLineHasContent =
HTMLEditor::AutoMoveOneLineHandler::CanMoveOrDeleteSomethingInLine(
EditorDOMPoint(rightBlockElement, afterRightBlockChild.Offset()),
aEditingHost);
#endif // #ifdef DEBUG
HTMLEditor::AutoMoveOneLineHandler lineMoverToEndOfLeftBlock(
aLeftBlockElement);
nsresult rv = lineMoverToEndOfLeftBlock.Prepare(
aHTMLEditor,
EditorDOMPoint(rightBlockElement, afterRightBlockChild.Offset()),
aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING("AutoMoveOneLineHandler::Prepare() failed");
return Err(rv);
}
MoveNodeResult moveResult = MoveNodeResult::IgnoredResult(
EditorDOMPoint::AtEndOf(aLeftBlockElement));
AutoTrackDOMMoveNodeResult trackMoveResult(aHTMLEditor.RangeUpdaterRef(),
&moveResult);
Result<MoveNodeResult, nsresult> moveFirstLineResult =
lineMoverToEndOfLeftBlock.Run(aHTMLEditor, aEditingHost);
if (MOZ_UNLIKELY(moveFirstLineResult.isErr())) {
NS_WARNING("AutoMoveOneLineHandler::Run() failed");
return moveFirstLineResult.propagateErr();
}
trackMoveResult.FlushAndStopTracking();
#ifdef DEBUG
MOZ_ASSERT(!firstLineHasContent.isErr());
if (firstLineHasContent.inspect()) {
NS_ASSERTION(moveFirstLineResult.inspect().Handled(),
"Failed to consider whether moving or not something");
} else {
NS_ASSERTION(moveFirstLineResult.inspect().Ignored(),
"Failed to consider whether moving or not something");
}
#endif // #ifdef DEBUG
moveResult |= moveFirstLineResult.unwrap();
// Now, all children of rightBlockElement were moved to leftBlockElement.
// So, afterRightBlockChild is now invalid.
afterRightBlockChild.Clear();
return std::move(moveResult);
}();
if (MOZ_UNLIKELY(moveContentResult.isErr())) {
return moveContentResult;
}
MoveNodeResult unwrappedMoveContentResult = moveContentResult.unwrap();
trackStartOfRightText.FlushAndStopTracking();
if (atStartOfRightText.IsInTextNode() &&
atStartOfRightText.IsSetAndValidInComposedDoc() &&
atStartOfRightText.IsMiddleOfContainer()) {
AutoTrackDOMMoveNodeResult trackMoveContentResult(
aHTMLEditor.RangeUpdaterRef(), &unwrappedMoveContentResult);
Result<EditorDOMPoint, nsresult> startOfRightTextOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAt(
aHTMLEditor, atStartOfRightText.AsInText());
if (MOZ_UNLIKELY(startOfRightTextOrError.isErr())) {
NS_WARNING("WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAt() failed");
return startOfRightTextOrError.propagateErr();
}
}
if (!invisibleBRElementAtEndOfLeftBlockElement ||
!invisibleBRElementAtEndOfLeftBlockElement->IsInComposedDoc()) {
return std::move(unwrappedMoveContentResult);
}
{
AutoTransactionsConserveSelection dontChangeMySelection(aHTMLEditor);
AutoTrackDOMMoveNodeResult trackMoveContentResult(
aHTMLEditor.RangeUpdaterRef(), &unwrappedMoveContentResult);
nsresult rv = aHTMLEditor.DeleteNodeWithTransaction(
*invisibleBRElementAtEndOfLeftBlockElement);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed, but ignored");
unwrappedMoveContentResult.IgnoreCaretPointSuggestion();
return Err(rv);
}
}
return std::move(unwrappedMoveContentResult);
}
// static
Result<MoveNodeResult, nsresult> WhiteSpaceVisibilityKeeper::
MergeFirstLineOfRightBlockElementIntoAncestorLeftBlockElement(
HTMLEditor& aHTMLEditor, Element& aLeftBlockElement,
Element& aRightBlockElement, const EditorDOMPoint& aAtLeftBlockChild,
nsIContent& aLeftContentInBlock,
const Maybe<nsAtom*>& aListElementTagName,
const HTMLBRElement* aPrecedingInvisibleBRElement,
const Element& aEditingHost) {
MOZ_ASSERT(
EditorUtils::IsDescendantOf(aRightBlockElement, aLeftBlockElement));
MOZ_ASSERT(
&aLeftBlockElement == &aLeftContentInBlock ||
EditorUtils::IsDescendantOf(aLeftContentInBlock, aLeftBlockElement));
MOZ_ASSERT(&aLeftBlockElement == aAtLeftBlockChild.GetContainer());
OwningNonNull<Element> originalLeftBlockElement = aLeftBlockElement;
OwningNonNull<Element> leftBlockElement = aLeftBlockElement;
EditorDOMPoint atLeftBlockChild(aAtLeftBlockChild);
// First, delete invisible white-spaces before the right block.
{
AutoTrackDOMPoint tracker(aHTMLEditor.RangeUpdaterRef(), &atLeftBlockChild);
nsresult rv =
WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesBefore(
aHTMLEditor, EditorDOMPoint(&aRightBlockElement));
if (NS_FAILED(rv)) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesBefore() "
"failed");
return Err(rv);
}
// Next, delete invisible white-spaces at start of the right block.
rv = WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesAfter(
aHTMLEditor, EditorDOMPoint(&aRightBlockElement, 0u));
if (NS_FAILED(rv)) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesAfter() "
"failed");
return Err(rv);
}
tracker.FlushAndStopTracking();
if (NS_WARN_IF(!atLeftBlockChild.IsInContentNodeAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
// Finally, make sure that we won't create new invisible white-spaces.
AutoTrackDOMPoint tracker(aHTMLEditor.RangeUpdaterRef(), &atLeftBlockChild);
Result<EditorDOMPoint, nsresult> afterLastVisibleThingOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAfter(
aHTMLEditor, EditorDOMPoint(&aRightBlockElement, 0u),
{NormalizeOption::StopIfPrecedingWhiteSpacesEndsWithNBP});
if (MOZ_UNLIKELY(afterLastVisibleThingOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAfter() failed");
return afterLastVisibleThingOrError.propagateErr();
}
Result<EditorDOMPoint, nsresult> atFirstVisibleThingOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesBefore(
aHTMLEditor, atLeftBlockChild, {});
if (MOZ_UNLIKELY(atFirstVisibleThingOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAfter() failed");
return atFirstVisibleThingOrError.propagateErr();
}
tracker.FlushAndStopTracking();
if (NS_WARN_IF(!atLeftBlockChild.IsInContentNodeAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// XXX atLeftBlockChild.GetContainerAs<Element>() should always return
// an element pointer so that probably here should not use
// accessors of EditorDOMPoint, should use DOM API directly instead.
if (Element* nearestAncestor =
atLeftBlockChild.GetContainerOrContainerParentElement()) {
leftBlockElement = *nearestAncestor;
} else {
return Err(NS_ERROR_UNEXPECTED);
}
auto atStartOfRightText = [&]() MOZ_NEVER_INLINE_DEBUG -> EditorDOMPoint {
const WSRunScanner scanner({}, EditorRawDOMPoint(&aRightBlockElement, 0u));
for (EditorRawDOMPointInText atFirstChar =
scanner.GetInclusiveNextCharPoint<EditorRawDOMPointInText>(
EditorRawDOMPoint(&aRightBlockElement, 0u));
atFirstChar.IsSet();
atFirstChar =
scanner.GetInclusiveNextCharPoint<EditorRawDOMPointInText>(
atFirstChar.AfterContainer<EditorRawDOMPoint>())) {
if (atFirstChar.IsContainerEmpty()) {
continue; // Ignore empty text node.
}
if (atFirstChar.IsCharASCIISpaceOrNBSP() &&
HTMLEditUtils::IsSimplyEditableNode(
*atFirstChar.ContainerAs<Text>())) {
return atFirstChar.To<EditorDOMPoint>();
}
break;
}
return EditorDOMPoint();
}();
AutoTrackDOMPoint trackStartOfRightText(aHTMLEditor.RangeUpdaterRef(),
&atStartOfRightText);
// Do br adjustment.
// XXX Why don't we delete the <br> first? If so, we can skip to track the
// MoveNodeResult at last.
const RefPtr<HTMLBRElement> invisibleBRElementBeforeLeftBlockElement =
WSRunScanner::GetPrecedingBRElementUnlessVisibleContentFound(
{WSRunScanner::Option::OnlyEditableNodes}, atLeftBlockChild);
NS_ASSERTION(
aPrecedingInvisibleBRElement == invisibleBRElementBeforeLeftBlockElement,
"The preceding invisible BR element computation was different");
auto moveContentResult = [&]() MOZ_NEVER_INLINE_DEBUG MOZ_CAN_RUN_SCRIPT
-> Result<MoveNodeResult, nsresult> {
// NOTE: Keep syncing with CanMergeLeftAndRightBlockElements() of
// AutoInclusiveAncestorBlockElementsJoiner.
if (aListElementTagName.isSome()) {
// XXX Why do we ignore the error from MoveChildrenWithTransaction()?
MOZ_ASSERT(originalLeftBlockElement == atLeftBlockChild.GetContainer(),
"This is not guaranteed, but assumed");
#ifdef DEBUG
Result<bool, nsresult> rightBlockHasContent =
aHTMLEditor.CanMoveChildren(aRightBlockElement, aLeftBlockElement);
#endif // #ifdef DEBUG
MoveNodeResult moveResult = MoveNodeResult::IgnoredResult(EditorDOMPoint(
atLeftBlockChild.GetContainer(), atLeftBlockChild.Offset()));
AutoTrackDOMMoveNodeResult trackMoveResult(aHTMLEditor.RangeUpdaterRef(),
&moveResult);
// TODO: Stop using HTMLEditor::PreserveWhiteSpaceStyle::No due to no
// tests.
AutoTransactionsConserveSelection dontChangeMySelection(aHTMLEditor);
Result<MoveNodeResult, nsresult> moveChildrenResult =
aHTMLEditor.MoveChildrenWithTransaction(
aRightBlockElement, moveResult.NextInsertionPointRef(),
HTMLEditor::PreserveWhiteSpaceStyle::No,
HTMLEditor::RemoveIfCommentNode::Yes);
if (MOZ_UNLIKELY(moveChildrenResult.isErr())) {
if (NS_WARN_IF(moveChildrenResult.inspectErr() ==
NS_ERROR_EDITOR_DESTROYED)) {
return moveChildrenResult;
}
NS_WARNING(
"HTMLEditor::MoveChildrenWithTransaction() failed, but ignored");
} else {
#ifdef DEBUG
MOZ_ASSERT(!rightBlockHasContent.isErr());
if (rightBlockHasContent.inspect()) {
NS_ASSERTION(moveChildrenResult.inspect().Handled(),
"Failed to consider whether moving or not children");
} else {
NS_ASSERTION(moveChildrenResult.inspect().Ignored(),
"Failed to consider whether moving or not children");
}
#endif // #ifdef DEBUG
trackMoveResult.FlushAndStopTracking();
moveResult |= moveChildrenResult.unwrap();
}
// atLeftBlockChild was moved to rightListElement. So, it's invalid now.
atLeftBlockChild.Clear();
return std::move(moveResult);
}
// Left block is a parent of right block, and the parent of the previous
// visible content. Right block is a child and contains the contents we
// want to move.
EditorDOMPoint pointToMoveFirstLineContent;
if (&aLeftContentInBlock == leftBlockElement) {
// We are working with valid HTML, aLeftContentInBlock is a block
// element, and is therefore allowed to contain aRightBlockElement. This
// is the simple case, we will simply move the content in
// aRightBlockElement out of its block.
pointToMoveFirstLineContent = atLeftBlockChild;
MOZ_ASSERT(pointToMoveFirstLineContent.GetContainer() ==
&aLeftBlockElement);
} else {
if (NS_WARN_IF(!aLeftContentInBlock.IsInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// We try to work as well as possible with HTML that's already invalid.
// Although "right block" is a block, and a block must not be contained
// in inline elements, reality is that broken documents do exist. The
// DIRECT parent of "left NODE" might be an inline element. Previous
// versions of this code skipped inline parents until the first block
// parent was found (and used "left block" as the destination).
// However, in some situations this strategy moves the content to an
// unexpected position. (see bug 200416) The new idea is to make the
// moving content a sibling, next to the previous visible content.
pointToMoveFirstLineContent.SetAfter(&aLeftContentInBlock);
if (NS_WARN_IF(!pointToMoveFirstLineContent.IsInContentNode())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
MOZ_ASSERT(pointToMoveFirstLineContent.IsSetAndValid());
// Because we don't want the moving content to receive the style of the
// previous content, we split the previous content's style.
#ifdef DEBUG
Result<bool, nsresult> firstLineHasContent =
HTMLEditor::AutoMoveOneLineHandler::CanMoveOrDeleteSomethingInLine(
EditorDOMPoint(&aRightBlockElement, 0u), aEditingHost);
#endif // #ifdef DEBUG
if (&aLeftContentInBlock != &aEditingHost) {
Result<SplitNodeResult, nsresult> splitNodeResult =
aHTMLEditor.SplitAncestorStyledInlineElementsAt(
pointToMoveFirstLineContent, EditorInlineStyle::RemoveAllStyles(),
HTMLEditor::SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(splitNodeResult.isErr())) {
NS_WARNING("HTMLEditor::SplitAncestorStyledInlineElementsAt() failed");
return splitNodeResult.propagateErr();
}
SplitNodeResult unwrappedSplitNodeResult = splitNodeResult.unwrap();
nsresult rv = unwrappedSplitNodeResult.SuggestCaretPointTo(
aHTMLEditor, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
if (NS_FAILED(rv)) {
NS_WARNING("SplitNodeResult::SuggestCaretPointTo() failed");
return Err(rv);
}
if (!unwrappedSplitNodeResult.DidSplit()) {
// If nothing was split, we should move the first line content to
// after the parent inline elements.
for (EditorDOMPoint parentPoint = pointToMoveFirstLineContent;
pointToMoveFirstLineContent.IsEndOfContainer() &&
pointToMoveFirstLineContent.IsInContentNode();
pointToMoveFirstLineContent = EditorDOMPoint::After(
*pointToMoveFirstLineContent.ContainerAs<nsIContent>())) {
if (pointToMoveFirstLineContent.GetContainer() ==
&aLeftBlockElement ||
NS_WARN_IF(pointToMoveFirstLineContent.GetContainer() ==
&aEditingHost)) {
break;
}
}
if (NS_WARN_IF(!pointToMoveFirstLineContent.IsInContentNode())) {
return Err(NS_ERROR_FAILURE);
}
} else if (unwrappedSplitNodeResult.Handled()) {
// If se split something, we should move the first line contents
// before the right elements.
if (nsIContent* nextContentAtSplitPoint =
unwrappedSplitNodeResult.GetNextContent()) {
pointToMoveFirstLineContent.Set(nextContentAtSplitPoint);
if (NS_WARN_IF(!pointToMoveFirstLineContent.IsInContentNode())) {
return Err(NS_ERROR_FAILURE);
}
} else {
pointToMoveFirstLineContent =
unwrappedSplitNodeResult.AtSplitPoint<EditorDOMPoint>();
if (NS_WARN_IF(!pointToMoveFirstLineContent.IsInContentNode())) {
return Err(NS_ERROR_FAILURE);
}
}
}
MOZ_DIAGNOSTIC_ASSERT(pointToMoveFirstLineContent.IsSetAndValid());
}
MoveNodeResult moveResult =
MoveNodeResult::IgnoredResult(pointToMoveFirstLineContent);
HTMLEditor::AutoMoveOneLineHandler lineMoverToPoint(
pointToMoveFirstLineContent);
nsresult rv = lineMoverToPoint.Prepare(
aHTMLEditor, EditorDOMPoint(&aRightBlockElement, 0u), aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING("AutoMoveOneLineHandler::Prepare() failed");
return Err(rv);
}
AutoTrackDOMMoveNodeResult trackMoveResult(aHTMLEditor.RangeUpdaterRef(),
&moveResult);
AutoTransactionsConserveSelection dontChangeMySelection(aHTMLEditor);
Result<MoveNodeResult, nsresult> moveFirstLineResult =
lineMoverToPoint.Run(aHTMLEditor, aEditingHost);
if (MOZ_UNLIKELY(moveFirstLineResult.isErr())) {
NS_WARNING("AutoMoveOneLineHandler::Run() failed");
return moveFirstLineResult.propagateErr();
}
#ifdef DEBUG
MOZ_ASSERT(!firstLineHasContent.isErr());
if (firstLineHasContent.inspect()) {
NS_ASSERTION(moveFirstLineResult.inspect().Handled(),
"Failed to consider whether moving or not something");
} else {
NS_ASSERTION(moveFirstLineResult.inspect().Ignored(),
"Failed to consider whether moving or not something");
}
#endif // #ifdef DEBUG
trackMoveResult.FlushAndStopTracking();
moveResult |= moveFirstLineResult.unwrap();
return std::move(moveResult);
}();
if (MOZ_UNLIKELY(moveContentResult.isErr())) {
return moveContentResult;
}
MoveNodeResult unwrappedMoveContentResult = moveContentResult.unwrap();
trackStartOfRightText.FlushAndStopTracking();
if (atStartOfRightText.IsInTextNode() &&
atStartOfRightText.IsSetAndValidInComposedDoc() &&
atStartOfRightText.IsMiddleOfContainer()) {
AutoTrackDOMMoveNodeResult trackMoveContentResult(
aHTMLEditor.RangeUpdaterRef(), &unwrappedMoveContentResult);
Result<EditorDOMPoint, nsresult> startOfRightTextOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAt(
aHTMLEditor, atStartOfRightText.AsInText());
if (MOZ_UNLIKELY(startOfRightTextOrError.isErr())) {
NS_WARNING("WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAt() failed");
return startOfRightTextOrError.propagateErr();
}
}
if (!invisibleBRElementBeforeLeftBlockElement ||
!invisibleBRElementBeforeLeftBlockElement->IsInComposedDoc()) {
return std::move(unwrappedMoveContentResult);
}
{
AutoTrackDOMMoveNodeResult trackMoveContentResult(
aHTMLEditor.RangeUpdaterRef(), &unwrappedMoveContentResult);
AutoTransactionsConserveSelection dontChangeMySelection(aHTMLEditor);
nsresult rv = aHTMLEditor.DeleteNodeWithTransaction(
*invisibleBRElementBeforeLeftBlockElement);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed, but ignored");
unwrappedMoveContentResult.IgnoreCaretPointSuggestion();
return Err(rv);
}
}
return std::move(unwrappedMoveContentResult);
}
// static
Result<MoveNodeResult, nsresult> WhiteSpaceVisibilityKeeper::
MergeFirstLineOfRightBlockElementIntoLeftBlockElement(
HTMLEditor& aHTMLEditor, Element& aLeftBlockElement,
Element& aRightBlockElement, const Maybe<nsAtom*>& aListElementTagName,
const HTMLBRElement* aPrecedingInvisibleBRElement,
const Element& aEditingHost) {
MOZ_ASSERT(
!EditorUtils::IsDescendantOf(aLeftBlockElement, aRightBlockElement));
MOZ_ASSERT(
!EditorUtils::IsDescendantOf(aRightBlockElement, aLeftBlockElement));
// First, delete invisible white-spaces at end of the left block
nsresult rv = WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesBefore(
aHTMLEditor, EditorDOMPoint::AtEndOf(aLeftBlockElement));
if (NS_FAILED(rv)) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesBefore() "
"failed");
return Err(rv);
}
// Next, delete invisible white-spaces at start of the right block and
// normalize the leading visible white-spaces.
rv = WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesAfter(
aHTMLEditor, EditorDOMPoint(&aRightBlockElement, 0u));
if (NS_FAILED(rv)) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesAfter() "
"failed");
return Err(rv);
}
// Finally, make sure to that we won't create new invisible white-spaces.
Result<EditorDOMPoint, nsresult> atFirstVisibleThingOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAfter(
aHTMLEditor, EditorDOMPoint(&aRightBlockElement, 0u),
{NormalizeOption::StopIfFollowingWhiteSpacesStartsWithNBSP});
if (MOZ_UNLIKELY(atFirstVisibleThingOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAfter() failed");
return atFirstVisibleThingOrError.propagateErr();
}
Result<EditorDOMPoint, nsresult> afterLastVisibleThingOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesBefore(
aHTMLEditor, EditorDOMPoint::AtEndOf(aLeftBlockElement), {});
if (MOZ_UNLIKELY(afterLastVisibleThingOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesBefore() failed");
return afterLastVisibleThingOrError.propagateErr();
}
auto atStartOfRightText = [&]() MOZ_NEVER_INLINE_DEBUG -> EditorDOMPoint {
const WSRunScanner scanner({}, EditorRawDOMPoint(&aRightBlockElement, 0u));
for (EditorRawDOMPointInText atFirstChar =
scanner.GetInclusiveNextCharPoint<EditorRawDOMPointInText>(
EditorRawDOMPoint(&aRightBlockElement, 0u));
atFirstChar.IsSet();
atFirstChar =
scanner.GetInclusiveNextCharPoint<EditorRawDOMPointInText>(
atFirstChar.AfterContainer<EditorRawDOMPoint>())) {
if (atFirstChar.IsContainerEmpty()) {
continue; // Ignore empty text node.
}
if (atFirstChar.IsCharASCIISpaceOrNBSP() &&
HTMLEditUtils::IsSimplyEditableNode(
*atFirstChar.ContainerAs<Text>())) {
return atFirstChar.To<EditorDOMPoint>();
}
break;
}
return EditorDOMPoint();
}();
AutoTrackDOMPoint trackStartOfRightText(aHTMLEditor.RangeUpdaterRef(),
&atStartOfRightText);
// Do br adjustment.
// XXX Why don't we delete the <br> first? If so, we can skip to track the
// MoveNodeResult at last.
const RefPtr<HTMLBRElement> invisibleBRElementAtEndOfLeftBlockElement =
WSRunScanner::GetPrecedingBRElementUnlessVisibleContentFound(
{WSRunScanner::Option::OnlyEditableNodes},
EditorDOMPoint::AtEndOf(aLeftBlockElement));
NS_ASSERTION(
aPrecedingInvisibleBRElement == invisibleBRElementAtEndOfLeftBlockElement,
"The preceding invisible BR element computation was different");
auto moveContentResult = [&]() MOZ_NEVER_INLINE_DEBUG MOZ_CAN_RUN_SCRIPT
-> Result<MoveNodeResult, nsresult> {
if (aListElementTagName.isSome() ||
// TODO: We should stop merging entire blocks even if they have same
// white-space style because Chrome behave so. However, it's risky to
// change our behavior in the major cases so that we should do it in
// a bug to manage only the change.
(aLeftBlockElement.NodeInfo()->NameAtom() ==
aRightBlockElement.NodeInfo()->NameAtom() &&
EditorUtils::GetComputedWhiteSpaceStyles(aLeftBlockElement) ==
EditorUtils::GetComputedWhiteSpaceStyles(aRightBlockElement))) {
MoveNodeResult moveResult = MoveNodeResult::IgnoredResult(
EditorDOMPoint::AtEndOf(aLeftBlockElement));
AutoTrackDOMMoveNodeResult trackMoveResult(aHTMLEditor.RangeUpdaterRef(),
&moveResult);
AutoTransactionsConserveSelection dontChangeMySelection(aHTMLEditor);
// Nodes are same type. merge them.
EditorDOMPoint atFirstChildOfRightNode;
nsresult rv = aHTMLEditor.JoinNearestEditableNodesWithTransaction(
aLeftBlockElement, aRightBlockElement, &atFirstChildOfRightNode);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::JoinNearestEditableNodesWithTransaction()"
" failed, but ignored");
if (aListElementTagName.isSome() && atFirstChildOfRightNode.IsSet()) {
Result<CreateElementResult, nsresult> convertListTypeResult =
aHTMLEditor.ChangeListElementType(
// XXX Shouldn't be aLeftBlockElement here?
aRightBlockElement, MOZ_KnownLive(*aListElementTagName.ref()),
*nsGkAtoms::li);
if (MOZ_UNLIKELY(convertListTypeResult.isErr())) {
if (NS_WARN_IF(convertListTypeResult.inspectErr() ==
NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING("HTMLEditor::ChangeListElementType() failed, but ignored");
} else {
// There is AutoTransactionConserveSelection above, therefore, we
// don't need to update selection here.
convertListTypeResult.inspect().IgnoreCaretPointSuggestion();
}
}
trackMoveResult.FlushAndStopTracking();
moveResult |= MoveNodeResult::HandledResult(
EditorDOMPoint::AtEndOf(aLeftBlockElement));
return std::move(moveResult);
}
#ifdef DEBUG
Result<bool, nsresult> firstLineHasContent =
HTMLEditor::AutoMoveOneLineHandler::CanMoveOrDeleteSomethingInLine(
EditorDOMPoint(&aRightBlockElement, 0u), aEditingHost);
#endif // #ifdef DEBUG
MoveNodeResult moveResult = MoveNodeResult::IgnoredResult(
EditorDOMPoint::AtEndOf(aLeftBlockElement));
// Nodes are dissimilar types.
HTMLEditor::AutoMoveOneLineHandler lineMoverToEndOfLeftBlock(
aLeftBlockElement);
nsresult rv = lineMoverToEndOfLeftBlock.Prepare(
aHTMLEditor, EditorDOMPoint(&aRightBlockElement, 0u), aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING("AutoMoveOneLineHandler::Prepare() failed");
return Err(rv);
}
AutoTrackDOMMoveNodeResult trackMoveResult(aHTMLEditor.RangeUpdaterRef(),
&moveResult);
AutoTransactionsConserveSelection dontChangeMySelection(aHTMLEditor);
Result<MoveNodeResult, nsresult> moveFirstLineResult =
lineMoverToEndOfLeftBlock.Run(aHTMLEditor, aEditingHost);
if (MOZ_UNLIKELY(moveFirstLineResult.isErr())) {
NS_WARNING("AutoMoveOneLineHandler::Run() failed");
return moveFirstLineResult.propagateErr();
}
#ifdef DEBUG
MOZ_ASSERT(!firstLineHasContent.isErr());
if (firstLineHasContent.inspect()) {
NS_ASSERTION(moveFirstLineResult.inspect().Handled(),
"Failed to consider whether moving or not something");
} else {
NS_ASSERTION(moveFirstLineResult.inspect().Ignored(),
"Failed to consider whether moving or not something");
}
#endif // #ifdef DEBUG
trackMoveResult.FlushAndStopTracking();
moveResult |= moveFirstLineResult.unwrap();
return std::move(moveResult);
}();
if (MOZ_UNLIKELY(moveContentResult.isErr())) {
return moveContentResult;
}
MoveNodeResult unwrappedMoveContentResult = moveContentResult.unwrap();
trackStartOfRightText.FlushAndStopTracking();
if (atStartOfRightText.IsInTextNode() &&
atStartOfRightText.IsSetAndValidInComposedDoc() &&
atStartOfRightText.IsMiddleOfContainer()) {
AutoTrackDOMMoveNodeResult trackMoveContentResult(
aHTMLEditor.RangeUpdaterRef(), &unwrappedMoveContentResult);
Result<EditorDOMPoint, nsresult> startOfRightTextOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAt(
aHTMLEditor, atStartOfRightText.AsInText());
if (MOZ_UNLIKELY(startOfRightTextOrError.isErr())) {
NS_WARNING("WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAt() failed");
return startOfRightTextOrError.propagateErr();
}
}
if (!invisibleBRElementAtEndOfLeftBlockElement ||
!invisibleBRElementAtEndOfLeftBlockElement->IsInComposedDoc()) {
unwrappedMoveContentResult.ForceToMarkAsHandled();
return std::move(unwrappedMoveContentResult);
}
{
AutoTrackDOMMoveNodeResult trackMoveContentResult(
aHTMLEditor.RangeUpdaterRef(), &unwrappedMoveContentResult);
AutoTransactionsConserveSelection dontChangeMySelection(aHTMLEditor);
nsresult rv = aHTMLEditor.DeleteNodeWithTransaction(
*invisibleBRElementAtEndOfLeftBlockElement);
// XXX In other top level if blocks, the result of
// DeleteNodeWithTransaction() is ignored. Why does only this result
// is respected?
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
unwrappedMoveContentResult.IgnoreCaretPointSuggestion();
return Err(rv);
}
}
return std::move(unwrappedMoveContentResult);
}
// static
Result<EditorDOMPoint, nsresult>
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAt(
HTMLEditor& aHTMLEditor, const EditorDOMPointInText& aPoint) {
MOZ_ASSERT(aPoint.IsSet());
MOZ_ASSERT(!aPoint.IsEndOfContainer());
if (!aPoint.IsCharCollapsibleASCIISpaceOrNBSP()) {
return aPoint.To<EditorDOMPoint>();
}
const HTMLEditor::ReplaceWhiteSpacesData normalizedWhiteSpaces =
aHTMLEditor.GetNormalizedStringAt(aPoint).GetMinimizedData(
*aPoint.ContainerAs<Text>());
if (!normalizedWhiteSpaces.ReplaceLength()) {
return aPoint.To<EditorDOMPoint>();
}
const OwningNonNull<Text> textNode = *aPoint.ContainerAs<Text>();
Result<InsertTextResult, nsresult> insertTextResultOrError =
aHTMLEditor.ReplaceTextWithTransaction(textNode, normalizedWhiteSpaces);
if (MOZ_UNLIKELY(insertTextResultOrError.isErr())) {
NS_WARNING("HTMLEditor::ReplaceTextWithTransaction() failed");
return insertTextResultOrError.propagateErr();
}
return insertTextResultOrError.unwrap().UnwrapCaretPoint();
}
// static
Result<EditorDOMPoint, nsresult>
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesBefore(
HTMLEditor& aHTMLEditor, const EditorDOMPoint& aPoint,
NormalizeOptions aOptions // NOLINT(performance-unnecessary-value-param)
) {
MOZ_ASSERT(aPoint.IsSetAndValid());
MOZ_ASSERT_IF(aPoint.IsInTextNode(), !aPoint.IsMiddleOfContainer());
MOZ_ASSERT(
!aOptions.contains(NormalizeOption::HandleOnlyFollowingWhiteSpaces));
const RefPtr<Element> colsetBlockElement =
aPoint.IsInContentNode() ? HTMLEditUtils::GetInclusiveAncestorElement(
*aPoint.ContainerAs<nsIContent>(),
HTMLEditUtils::ClosestEditableBlockElement,
BlockInlineCheck::UseComputedDisplayStyle)
: nullptr;
EditorDOMPoint afterLastVisibleThing(aPoint);
AutoTArray<OwningNonNull<nsIContent>, 32> unnecessaryContents;
for (nsIContent* previousContent =
aPoint.IsInTextNode() && aPoint.IsEndOfContainer()
? aPoint.ContainerAs<Text>()
: HTMLEditUtils::GetPreviousLeafContentOrPreviousBlockElement(
aPoint,
{HTMLEditUtils::LeafNodeType::LeafNodeOrChildBlock},
BlockInlineCheck::UseComputedDisplayStyle,
colsetBlockElement);
previousContent;
previousContent =
HTMLEditUtils::GetPreviousLeafContentOrPreviousBlockElement(
EditorRawDOMPoint(previousContent),
{HTMLEditUtils::LeafNodeType::LeafNodeOrChildBlock},
BlockInlineCheck::UseComputedDisplayStyle, colsetBlockElement)) {
if (!HTMLEditUtils::IsSimplyEditableNode(*previousContent)) {
// XXX Assume non-editable nodes are visible.
break;
}
const RefPtr<Text> precedingTextNode = Text::FromNode(previousContent);
if (!precedingTextNode &&
HTMLEditUtils::IsVisibleElementEvenIfLeafNode(*previousContent)) {
afterLastVisibleThing.SetAfter(previousContent);
break;
}
if (!precedingTextNode || !precedingTextNode->TextDataLength()) {
// If it's an empty inline element like `<b></b>` or an empty `Text`,
// delete it.
nsIContent* emptyInlineContent =
HTMLEditUtils::GetMostDistantAncestorEditableEmptyInlineElement(
*previousContent, BlockInlineCheck::UseComputedDisplayStyle);
if (!emptyInlineContent) {
emptyInlineContent = previousContent;
}
unnecessaryContents.AppendElement(*emptyInlineContent);
continue;
}
const auto atLastChar =
EditorRawDOMPointInText::AtLastContentOf(*precedingTextNode);
if (!atLastChar.IsCharCollapsibleASCIISpaceOrNBSP()) {
afterLastVisibleThing.SetAfter(precedingTextNode);
break;
}
if (aOptions.contains(
NormalizeOption::StopIfPrecedingWhiteSpacesEndsWithNBP) &&
atLastChar.IsCharNBSP()) {
afterLastVisibleThing.SetAfter(precedingTextNode);
break;
}
const HTMLEditor::ReplaceWhiteSpacesData replaceData =
aHTMLEditor.GetNormalizedStringAt(atLastChar.AsInText())
.GetMinimizedData(*precedingTextNode);
if (!replaceData.ReplaceLength()) {
afterLastVisibleThing.SetAfter(precedingTextNode);
break;
}
// If the Text node has only invisible white-spaces, delete the node itself.
if (replaceData.ReplaceLength() == precedingTextNode->TextDataLength() &&
replaceData.mNormalizedString.IsEmpty()) {
nsIContent* emptyInlineContent =
HTMLEditUtils::GetMostDistantAncestorEditableEmptyInlineElement(
*precedingTextNode, BlockInlineCheck::UseComputedDisplayStyle);
if (!emptyInlineContent) {
emptyInlineContent = precedingTextNode;
}
unnecessaryContents.AppendElement(*emptyInlineContent);
continue;
}
Result<InsertTextResult, nsresult> replaceWhiteSpacesResultOrError =
aHTMLEditor.ReplaceTextWithTransaction(*precedingTextNode, replaceData);
if (MOZ_UNLIKELY(replaceWhiteSpacesResultOrError.isErr())) {
NS_WARNING("HTMLEditor::ReplaceTextWithTransaction() failed");
return replaceWhiteSpacesResultOrError.propagateErr();
}
InsertTextResult replaceWhiteSpacesResult =
replaceWhiteSpacesResultOrError.unwrap();
replaceWhiteSpacesResult.IgnoreCaretPointSuggestion();
afterLastVisibleThing = replaceWhiteSpacesResult.EndOfInsertedTextRef();
}
AutoTrackDOMPoint trackAfterLastVisibleThing(aHTMLEditor.RangeUpdaterRef(),
&afterLastVisibleThing);
for (const auto& contentToDelete : unnecessaryContents) {
if (MOZ_UNLIKELY(!contentToDelete->IsInComposedDoc())) {
continue;
}
nsresult rv =
aHTMLEditor.DeleteNodeWithTransaction(MOZ_KnownLive(contentToDelete));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
trackAfterLastVisibleThing.FlushAndStopTracking();
if (NS_WARN_IF(
!afterLastVisibleThing.IsInContentNodeAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return std::move(afterLastVisibleThing);
}
// static
Result<EditorDOMPoint, nsresult>
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAfter(
HTMLEditor& aHTMLEditor, const EditorDOMPoint& aPoint,
NormalizeOptions aOptions // NOLINT(performance-unnecessary-value-param)
) {
MOZ_ASSERT(aPoint.IsSetAndValid());
MOZ_ASSERT_IF(aPoint.IsInTextNode(), !aPoint.IsMiddleOfContainer());
MOZ_ASSERT(
!aOptions.contains(NormalizeOption::HandleOnlyPrecedingWhiteSpaces));
const RefPtr<Element> colsetBlockElement =
aPoint.IsInContentNode() ? HTMLEditUtils::GetInclusiveAncestorElement(
*aPoint.ContainerAs<nsIContent>(),
HTMLEditUtils::ClosestEditableBlockElement,
BlockInlineCheck::UseComputedDisplayStyle)
: nullptr;
EditorDOMPoint atFirstVisibleThing(aPoint);
AutoTArray<OwningNonNull<nsIContent>, 32> unnecessaryContents;
for (nsIContent* nextContent =
aPoint.IsInTextNode() && aPoint.IsStartOfContainer()
? aPoint.ContainerAs<Text>()
: HTMLEditUtils::GetNextLeafContentOrNextBlockElement(
aPoint,
{HTMLEditUtils::LeafNodeType::LeafNodeOrChildBlock},
BlockInlineCheck::UseComputedDisplayStyle,
colsetBlockElement);
nextContent;
nextContent = HTMLEditUtils::GetNextLeafContentOrNextBlockElement(
EditorRawDOMPoint::After(*nextContent),
{HTMLEditUtils::LeafNodeType::LeafNodeOrChildBlock},
BlockInlineCheck::UseComputedDisplayStyle, colsetBlockElement)) {
if (!HTMLEditUtils::IsSimplyEditableNode(*nextContent)) {
// XXX Assume non-editable nodes are visible.
break;
}
const RefPtr<Text> followingTextNode = Text::FromNode(nextContent);
if (!followingTextNode &&
HTMLEditUtils::IsVisibleElementEvenIfLeafNode(*nextContent)) {
atFirstVisibleThing.Set(nextContent);
break;
}
if (!followingTextNode || !followingTextNode->TextDataLength()) {
// If it's an empty inline element like `<b></b>` or an empty `Text`,
// delete it.
nsIContent* emptyInlineContent =
HTMLEditUtils::GetMostDistantAncestorEditableEmptyInlineElement(
*nextContent, BlockInlineCheck::UseComputedDisplayStyle);
if (!emptyInlineContent) {
emptyInlineContent = nextContent;
}
unnecessaryContents.AppendElement(*emptyInlineContent);
continue;
}
const auto atFirstChar = EditorRawDOMPointInText(followingTextNode, 0u);
if (!atFirstChar.IsCharCollapsibleASCIISpaceOrNBSP()) {
atFirstVisibleThing.Set(followingTextNode);
break;
}
if (aOptions.contains(
NormalizeOption::StopIfPrecedingWhiteSpacesEndsWithNBP) &&
atFirstChar.IsCharNBSP()) {
atFirstVisibleThing.Set(followingTextNode);
break;
}
const HTMLEditor::ReplaceWhiteSpacesData replaceData =
aHTMLEditor.GetNormalizedStringAt(atFirstChar.AsInText())
.GetMinimizedData(*followingTextNode);
if (!replaceData.ReplaceLength()) {
atFirstVisibleThing.Set(followingTextNode);
break;
}
// If the Text node has only invisible white-spaces, delete the node itself.
if (replaceData.ReplaceLength() == followingTextNode->TextDataLength() &&
replaceData.mNormalizedString.IsEmpty()) {
nsIContent* emptyInlineContent =
HTMLEditUtils::GetMostDistantAncestorEditableEmptyInlineElement(
*followingTextNode, BlockInlineCheck::UseComputedDisplayStyle);
if (!emptyInlineContent) {
emptyInlineContent = followingTextNode;
}
unnecessaryContents.AppendElement(*emptyInlineContent);
continue;
}
Result<InsertTextResult, nsresult> replaceWhiteSpacesResultOrError =
aHTMLEditor.ReplaceTextWithTransaction(*followingTextNode, replaceData);
if (MOZ_UNLIKELY(replaceWhiteSpacesResultOrError.isErr())) {
NS_WARNING("HTMLEditor::ReplaceTextWithTransaction() failed");
return replaceWhiteSpacesResultOrError.propagateErr();
}
replaceWhiteSpacesResultOrError.unwrap().IgnoreCaretPointSuggestion();
atFirstVisibleThing.Set(followingTextNode, 0u);
break;
}
AutoTrackDOMPoint trackAtFirstVisibleThing(aHTMLEditor.RangeUpdaterRef(),
&atFirstVisibleThing);
for (const auto& contentToDelete : unnecessaryContents) {
if (MOZ_UNLIKELY(!contentToDelete->IsInComposedDoc())) {
continue;
}
nsresult rv =
aHTMLEditor.DeleteNodeWithTransaction(MOZ_KnownLive(contentToDelete));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
trackAtFirstVisibleThing.FlushAndStopTracking();
if (NS_WARN_IF(!atFirstVisibleThing.IsInContentNodeAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return std::move(atFirstVisibleThing);
}
// static
Result<EditorDOMPoint, nsresult>
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitTextNodeAt(
HTMLEditor& aHTMLEditor, const EditorDOMPointInText& aPointToSplit,
NormalizeOptions aOptions // NOLINT(performance-unnecessary-value-param)
) {
MOZ_ASSERT(aPointToSplit.IsSetAndValid());
if (EditorUtils::IsWhiteSpacePreformatted(
*aPointToSplit.ContainerAs<Text>())) {
return aPointToSplit.To<EditorDOMPoint>();
}
const OwningNonNull<Text> textNode = *aPointToSplit.ContainerAs<Text>();
if (!textNode->TextDataLength()) {
// Delete if it's an empty `Text` node and removable.
if (!HTMLEditUtils::IsRemovableNode(*textNode)) {
// It's logically odd to call this for non-editable `Text`, but it may
// happen if surrounding white-space sequence contains empty non-editable
// `Text`. In that case, the caller needs to normalize its preceding
// `Text` nodes too.
return EditorDOMPoint();
}
const nsCOMPtr<nsINode> parentNode = textNode->GetParentNode();
const nsCOMPtr<nsIContent> nextSibling = textNode->GetNextSibling();
nsresult rv = aHTMLEditor.DeleteNodeWithTransaction(textNode);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
if (NS_WARN_IF(nextSibling && nextSibling->GetParentNode() != parentNode)) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return nextSibling ? EditorDOMPoint(nextSibling)
: EditorDOMPoint::AtEndOf(*parentNode);
}
const HTMLEditor::ReplaceWhiteSpacesData replacePrecedingWhiteSpacesData =
aPointToSplit.IsStartOfContainer() ||
aOptions.contains(
NormalizeOption::HandleOnlyFollowingWhiteSpaces) ||
(aOptions.contains(
NormalizeOption::StopIfPrecedingWhiteSpacesEndsWithNBP) &&
aPointToSplit.IsPreviousCharNBSP())
? HTMLEditor::ReplaceWhiteSpacesData()
: aHTMLEditor.GetPrecedingNormalizedStringToSplitAt(aPointToSplit);
const HTMLEditor::ReplaceWhiteSpacesData replaceFollowingWhiteSpaceData =
aPointToSplit.IsEndOfContainer() ||
aOptions.contains(
NormalizeOption::HandleOnlyPrecedingWhiteSpaces) ||
(aOptions.contains(
NormalizeOption::StopIfFollowingWhiteSpacesStartsWithNBSP) &&
aPointToSplit.IsCharNBSP())
? HTMLEditor::ReplaceWhiteSpacesData()
: aHTMLEditor.GetFollowingNormalizedStringToSplitAt(aPointToSplit);
const HTMLEditor::ReplaceWhiteSpacesData replaceWhiteSpacesData =
(replacePrecedingWhiteSpacesData + replaceFollowingWhiteSpaceData)
.GetMinimizedData(*textNode);
if (!replaceWhiteSpacesData.ReplaceLength()) {
return aPointToSplit.To<EditorDOMPoint>();
}
if (replaceWhiteSpacesData.mNormalizedString.IsEmpty() &&
replaceWhiteSpacesData.ReplaceLength() == textNode->TextDataLength()) {
// If there is only invisible white-spaces, mNormalizedString is empty
// string but replace length is same the the `Text` length. In this case, we
// should delete the `Text` to avoid empty `Text` to stay in the DOM tree.
const nsCOMPtr<nsINode> parentNode = textNode->GetParentNode();
const nsCOMPtr<nsIContent> nextSibling = textNode->GetNextSibling();
nsresult rv = aHTMLEditor.DeleteNodeWithTransaction(textNode);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
if (NS_WARN_IF(nextSibling && nextSibling->GetParentNode() != parentNode)) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return nextSibling ? EditorDOMPoint(nextSibling)
: EditorDOMPoint::AtEndOf(*parentNode);
}
Result<InsertTextResult, nsresult> replaceWhiteSpacesResultOrError =
aHTMLEditor.ReplaceTextWithTransaction(textNode, replaceWhiteSpacesData);
if (MOZ_UNLIKELY(replaceWhiteSpacesResultOrError.isErr())) {
NS_WARNING("HTMLEditor::ReplaceTextWithTransaction() failed");
return replaceWhiteSpacesResultOrError.propagateErr();
}
replaceWhiteSpacesResultOrError.unwrap().IgnoreCaretPointSuggestion();
const uint32_t offsetToSplit =
aPointToSplit.Offset() - replacePrecedingWhiteSpacesData.ReplaceLength() +
replacePrecedingWhiteSpacesData.mNormalizedString.Length();
if (NS_WARN_IF(textNode->TextDataLength() < offsetToSplit)) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return EditorDOMPoint(textNode, offsetToSplit);
}
// static
Result<EditorDOMPoint, nsresult>
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitAt(
HTMLEditor& aHTMLEditor, const EditorDOMPoint& aPointToSplit,
NormalizeOptions aOptions // NOLINT(performance-unnecessary-value-param)
) {
MOZ_ASSERT(aPointToSplit.IsSet());
// If the insertion point is not in composed doc, we're probably initializing
// an element which will be inserted. In such case, the caller should own the
// responsibility for normalizing the white-spaces.
if (!aPointToSplit.IsInComposedDoc()) {
return aPointToSplit;
}
EditorDOMPoint pointToSplit(aPointToSplit);
{
AutoTrackDOMPoint trackPointToSplit(aHTMLEditor.RangeUpdaterRef(),
&pointToSplit);
Result<EditorDOMPoint, nsresult> pointToSplitOrError =
WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpaces(aHTMLEditor,
pointToSplit);
if (MOZ_UNLIKELY(pointToSplitOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpaces() failed");
return pointToSplitOrError.propagateErr();
}
}
if (NS_WARN_IF(!pointToSplit.IsInContentNode())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
if (pointToSplit.IsInTextNode()) {
Result<EditorDOMPoint, nsresult> pointToSplitOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitTextNodeAt(
aHTMLEditor, pointToSplit.AsInText(), aOptions);
if (MOZ_UNLIKELY(pointToSplitOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitTextNodeAt() "
"failed");
return pointToSplitOrError.propagateErr();
}
pointToSplit = pointToSplitOrError.unwrap().To<EditorDOMPoint>();
if (NS_WARN_IF(!pointToSplit.IsInContentNode())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// If we normalize white-spaces in middle of the `Text`, we don't need to
// touch surrounding `Text` nodes.
if (pointToSplit.IsMiddleOfContainer()) {
return pointToSplit;
}
}
// Preceding and/or following white-space sequence may be across multiple
// `Text` nodes. Then, they may become unexpectedly visible without
// normalizing the white-spaces. Therefore, we need to list up all possible
// `Text` nodes first. Then, normalize them unless the `Text` is not
const RefPtr<Element> closestBlockElement =
HTMLEditUtils::GetInclusiveAncestorElement(
*pointToSplit.ContainerAs<nsIContent>(),
HTMLEditUtils::ClosestBlockElement,
BlockInlineCheck::UseComputedDisplayStyle);
AutoTArray<OwningNonNull<Text>, 3> precedingTextNodes, followingTextNodes;
if (!pointToSplit.IsInTextNode() || pointToSplit.IsStartOfContainer()) {
for (nsCOMPtr<nsIContent> previousContent =
HTMLEditUtils::GetPreviousLeafContentOrPreviousBlockElement(
pointToSplit, {LeafNodeType::LeafNodeOrChildBlock},
BlockInlineCheck::UseComputedDisplayStyle,
closestBlockElement);
previousContent;
previousContent =
HTMLEditUtils::GetPreviousLeafContentOrPreviousBlockElement(
*previousContent, {LeafNodeType::LeafNodeOrChildBlock},
BlockInlineCheck::UseComputedDisplayStyle,
closestBlockElement)) {
if (auto* const textNode = Text::FromNode(previousContent)) {
if (!HTMLEditUtils::IsSimplyEditableNode(*textNode) &&
textNode->TextDataLength()) {
break;
}
if (aOptions.contains(
NormalizeOption::StopIfPrecedingWhiteSpacesEndsWithNBP) &&
textNode->DataBuffer().SafeLastChar() == HTMLEditUtils::kNBSP) {
break;
}
precedingTextNodes.AppendElement(*textNode);
if (textNode->TextIsOnlyWhitespace()) {
// white-space only `Text` will be removed, so, we need to check
// preceding one too.
continue;
}
break;
}
if (auto* const element = Element::FromNode(previousContent)) {
if (HTMLEditUtils::IsBlockElement(
*element, BlockInlineCheck::UseComputedDisplayStyle) ||
HTMLEditUtils::IsNonEditableReplacedContent(*element)) {
break;
}
// Ignore invisible inline elements
}
}
}
if (!pointToSplit.IsInTextNode() || pointToSplit.IsEndOfContainer()) {
for (nsCOMPtr<nsIContent> nextContent =
HTMLEditUtils::GetNextLeafContentOrNextBlockElement(
pointToSplit, {LeafNodeType::LeafNodeOrChildBlock},
BlockInlineCheck::UseComputedDisplayStyle,
closestBlockElement);
nextContent;
nextContent = HTMLEditUtils::GetNextLeafContentOrNextBlockElement(
*nextContent, {LeafNodeType::LeafNodeOrChildBlock},
BlockInlineCheck::UseComputedDisplayStyle, closestBlockElement)) {
if (auto* const textNode = Text::FromNode(nextContent)) {
if (!HTMLEditUtils::IsSimplyEditableNode(*textNode) &&
textNode->TextDataLength()) {
break;
}
if (aOptions.contains(
NormalizeOption::StopIfFollowingWhiteSpacesStartsWithNBSP) &&
textNode->DataBuffer().SafeFirstChar() == HTMLEditUtils::kNBSP) {
break;
}
followingTextNodes.AppendElement(*textNode);
if (textNode->TextIsOnlyWhitespace() &&
EditorUtils::IsWhiteSpacePreformatted(*textNode)) {
// white-space only `Text` will be removed, so, we need to check next
// one too.
continue;
}
break;
}
if (auto* const element = Element::FromNode(nextContent)) {
if (HTMLEditUtils::IsBlockElement(
*element, BlockInlineCheck::UseComputedDisplayStyle) ||
HTMLEditUtils::IsNonEditableReplacedContent(*element)) {
break;
}
// Ignore invisible inline elements
}
}
}
AutoTrackDOMPoint trackPointToSplit(aHTMLEditor.RangeUpdaterRef(),
&pointToSplit);
for (const auto& textNode : precedingTextNodes) {
Result<EditorDOMPoint, nsresult> normalizeWhiteSpacesResultOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitTextNodeAt(
aHTMLEditor, EditorDOMPointInText::AtEndOf(textNode), aOptions);
if (MOZ_UNLIKELY(normalizeWhiteSpacesResultOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitTextNodeAt() "
"failed");
return normalizeWhiteSpacesResultOrError.propagateErr();
}
if (normalizeWhiteSpacesResultOrError.inspect().IsInTextNode() &&
!normalizeWhiteSpacesResultOrError.inspect().IsStartOfContainer()) {
// The white-space sequence started from middle of this node, so, we need
// to do this for the preceding nodes.
break;
}
}
for (const auto& textNode : followingTextNodes) {
Result<EditorDOMPoint, nsresult> normalizeWhiteSpacesResultOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitTextNodeAt(
aHTMLEditor, EditorDOMPointInText(textNode, 0u), aOptions);
if (MOZ_UNLIKELY(normalizeWhiteSpacesResultOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitTextNodeAt() "
"failed");
return normalizeWhiteSpacesResultOrError.propagateErr();
}
if (normalizeWhiteSpacesResultOrError.inspect().IsInTextNode() &&
!normalizeWhiteSpacesResultOrError.inspect().IsEndOfContainer()) {
// The white-space sequence ended in middle of this node, so, we need
// to do this for the following nodes.
break;
}
}
trackPointToSplit.FlushAndStopTracking();
if (NS_WARN_IF(!pointToSplit.IsInContentNode())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return std::move(pointToSplit);
}
Result<EditorDOMRange, nsresult>
WhiteSpaceVisibilityKeeper::NormalizeSurroundingWhiteSpacesToJoin(
HTMLEditor& aHTMLEditor, const EditorDOMRange& aRangeToDelete) {
MOZ_ASSERT(!aRangeToDelete.Collapsed());
// Special case if the range for deleting text in same `Text`. In the case,
// we need to normalize the white-space sequence which may be joined after
// deletion.
if (aRangeToDelete.StartRef().IsInTextNode() &&
aRangeToDelete.InSameContainer()) {
const RefPtr<Text> textNode = aRangeToDelete.StartRef().ContainerAs<Text>();
Result<EditorDOMRange, nsresult> rangeToDeleteOrError =
WhiteSpaceVisibilityKeeper::
NormalizeSurroundingWhiteSpacesToDeleteCharacters(
aHTMLEditor, *textNode, aRangeToDelete.StartRef().Offset(),
aRangeToDelete.EndRef().Offset() -
aRangeToDelete.StartRef().Offset());
NS_WARNING_ASSERTION(
rangeToDeleteOrError.isOk(),
"WhiteSpaceVisibilityKeeper::"
"NormalizeSurroundingWhiteSpacesToDeleteCharacters() failed");
return rangeToDeleteOrError;
}
EditorDOMRange rangeToDelete(aRangeToDelete);
// First, delete all invisible white-spaces around the end boundary.
// The end boundary may be middle of invisible white-spaces. If so,
// NormalizeWhiteSpacesToSplitTextNodeAt() won't work well for this.
{
AutoTrackDOMRange trackRangeToDelete(aHTMLEditor.RangeUpdaterRef(),
&rangeToDelete);
const WSScanResult nextThing =
WSRunScanner::ScanInclusiveNextVisibleNodeOrBlockBoundary(
{}, rangeToDelete.StartRef());
if (nextThing.ReachedLineBoundary()) {
nsresult rv =
WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesBefore(
aHTMLEditor, nextThing.PointAtReachedContent<EditorDOMPoint>());
if (NS_FAILED(rv)) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesBefore() "
"failed");
return Err(rv);
}
} else {
Result<EditorDOMPoint, nsresult>
deleteInvisibleLeadingWhiteSpaceResultOrError =
WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpaces(
aHTMLEditor, rangeToDelete.EndRef());
if (MOZ_UNLIKELY(deleteInvisibleLeadingWhiteSpaceResultOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpaces() "
"failed");
return deleteInvisibleLeadingWhiteSpaceResultOrError.propagateErr();
}
}
trackRangeToDelete.FlushAndStopTracking();
if (NS_WARN_IF(!rangeToDelete.IsPositionedAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
// Then, normalize white-spaces after the end boundary.
if (rangeToDelete.EndRef().IsInTextNode() &&
rangeToDelete.EndRef().IsMiddleOfContainer()) {
Result<EditorDOMPoint, nsresult> pointToSplitOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitTextNodeAt(
aHTMLEditor, rangeToDelete.EndRef().AsInText(),
{NormalizeOption::HandleOnlyFollowingWhiteSpaces});
if (MOZ_UNLIKELY(pointToSplitOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitTextNodeAt("
") failed");
return pointToSplitOrError.propagateErr();
}
EditorDOMPoint pointToSplit = pointToSplitOrError.unwrap();
if (pointToSplit.IsSet() && pointToSplit != rangeToDelete.EndRef()) {
MOZ_ASSERT(rangeToDelete.StartRef().EqualsOrIsBefore(pointToSplit));
rangeToDelete.SetEnd(std::move(pointToSplit));
}
} else {
AutoTrackDOMRange trackRangeToDelete(aHTMLEditor.RangeUpdaterRef(),
&rangeToDelete);
Result<EditorDOMPoint, nsresult> atFirstVisibleThingOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAfter(
aHTMLEditor, rangeToDelete.EndRef(), {});
if (MOZ_UNLIKELY(atFirstVisibleThingOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAfter() failed");
return atFirstVisibleThingOrError.propagateErr();
}
trackRangeToDelete.FlushAndStopTracking();
if (NS_WARN_IF(!rangeToDelete.IsPositionedAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
// If cleaning up the white-spaces around the end boundary made the range
// collapsed, the range was in invisible white-spaces. So, in the case, we
// don't need to do nothing.
if (MOZ_UNLIKELY(rangeToDelete.Collapsed())) {
return rangeToDelete;
}
// Next, delete the invisible white-spaces around the start boundary.
{
AutoTrackDOMRange trackRangeToDelete(aHTMLEditor.RangeUpdaterRef(),
&rangeToDelete);
Result<EditorDOMPoint, nsresult>
deleteInvisibleTrailingWhiteSpaceResultOrError =
WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpaces(
aHTMLEditor, rangeToDelete.StartRef());
if (MOZ_UNLIKELY(deleteInvisibleTrailingWhiteSpaceResultOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpaces() failed");
return deleteInvisibleTrailingWhiteSpaceResultOrError.propagateErr();
}
trackRangeToDelete.FlushAndStopTracking();
if (NS_WARN_IF(!rangeToDelete.IsPositionedAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
// Finally, normalize white-spaces before the start boundary only when
// the start boundary is middle of a `Text` node. This is compatible with
// the other browsers.
if (rangeToDelete.StartRef().IsInTextNode() &&
rangeToDelete.StartRef().IsMiddleOfContainer()) {
AutoTrackDOMRange trackRangeToDelete(aHTMLEditor.RangeUpdaterRef(),
&rangeToDelete);
Result<EditorDOMPoint, nsresult> afterLastVisibleThingOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitTextNodeAt(
aHTMLEditor, rangeToDelete.StartRef().AsInText(),
{NormalizeOption::HandleOnlyPrecedingWhiteSpaces});
if (MOZ_UNLIKELY(afterLastVisibleThingOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitTextNodeAt() "
"failed");
return afterLastVisibleThingOrError.propagateErr();
}
trackRangeToDelete.FlushAndStopTracking();
EditorDOMPoint pointToSplit = afterLastVisibleThingOrError.unwrap();
if (pointToSplit.IsSet() && pointToSplit != rangeToDelete.StartRef()) {
MOZ_ASSERT(pointToSplit.EqualsOrIsBefore(rangeToDelete.EndRef()));
rangeToDelete.SetStart(std::move(pointToSplit));
}
}
return rangeToDelete;
}
Result<EditorDOMRange, nsresult>
WhiteSpaceVisibilityKeeper::NormalizeSurroundingWhiteSpacesToDeleteCharacters(
HTMLEditor& aHTMLEditor, Text& aTextNode, uint32_t aOffset,
uint32_t aLength) {
MOZ_ASSERT(aOffset <= aTextNode.TextDataLength());
MOZ_ASSERT(aOffset + aLength <= aTextNode.TextDataLength());
const HTMLEditor::ReplaceWhiteSpacesData normalizedWhiteSpacesData =
aHTMLEditor.GetSurroundingNormalizedStringToDelete(aTextNode, aOffset,
aLength);
EditorDOMRange rangeToDelete(EditorDOMPoint(&aTextNode, aOffset),
EditorDOMPoint(&aTextNode, aOffset + aLength));
if (!normalizedWhiteSpacesData.ReplaceLength()) {
return rangeToDelete;
}
// mNewOffsetAfterReplace is set to aOffset after applying replacing the
// range.
MOZ_ASSERT(normalizedWhiteSpacesData.mNewOffsetAfterReplace != UINT32_MAX);
MOZ_ASSERT(normalizedWhiteSpacesData.mNewOffsetAfterReplace >=
normalizedWhiteSpacesData.mReplaceStartOffset);
MOZ_ASSERT(normalizedWhiteSpacesData.mNewOffsetAfterReplace <=
normalizedWhiteSpacesData.mReplaceEndOffset);
#ifdef DEBUG
{
const HTMLEditor::ReplaceWhiteSpacesData
normalizedPrecedingWhiteSpacesData =
normalizedWhiteSpacesData.PreviousDataOfNewOffset(aOffset);
const HTMLEditor::ReplaceWhiteSpacesData
normalizedFollowingWhiteSpacesData =
normalizedWhiteSpacesData.NextDataOfNewOffset(aOffset + aLength);
MOZ_ASSERT(normalizedPrecedingWhiteSpacesData.ReplaceLength() + aLength +
normalizedFollowingWhiteSpacesData.ReplaceLength() ==
normalizedWhiteSpacesData.ReplaceLength());
MOZ_ASSERT(
normalizedPrecedingWhiteSpacesData.mNormalizedString.Length() +
normalizedFollowingWhiteSpacesData.mNormalizedString.Length() ==
normalizedWhiteSpacesData.mNormalizedString.Length());
}
#endif
const HTMLEditor::ReplaceWhiteSpacesData normalizedPrecedingWhiteSpacesData =
normalizedWhiteSpacesData.PreviousDataOfNewOffset(aOffset)
.GetMinimizedData(aTextNode);
const HTMLEditor::ReplaceWhiteSpacesData normalizedFollowingWhiteSpacesData =
normalizedWhiteSpacesData.NextDataOfNewOffset(aOffset + aLength)
.GetMinimizedData(aTextNode);
if (normalizedFollowingWhiteSpacesData.ReplaceLength()) {
AutoTrackDOMRange trackRangeToDelete(aHTMLEditor.RangeUpdaterRef(),
&rangeToDelete);
Result<InsertTextResult, nsresult>
replaceFollowingWhiteSpacesResultOrError =
aHTMLEditor.ReplaceTextWithTransaction(
aTextNode, normalizedFollowingWhiteSpacesData);
if (MOZ_UNLIKELY(replaceFollowingWhiteSpacesResultOrError.isErr())) {
NS_WARNING("HTMLEditor::ReplaceTextWithTransaction() failed");
return replaceFollowingWhiteSpacesResultOrError.propagateErr();
}
trackRangeToDelete.FlushAndStopTracking();
if (NS_WARN_IF(!rangeToDelete.IsPositioned())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
if (normalizedPrecedingWhiteSpacesData.ReplaceLength()) {
AutoTrackDOMRange trackRangeToDelete(aHTMLEditor.RangeUpdaterRef(),
&rangeToDelete);
Result<InsertTextResult, nsresult>
replacePrecedingWhiteSpacesResultOrError =
aHTMLEditor.ReplaceTextWithTransaction(
aTextNode, normalizedPrecedingWhiteSpacesData);
if (MOZ_UNLIKELY(replacePrecedingWhiteSpacesResultOrError.isErr())) {
NS_WARNING("HTMLEditor::ReplaceTextWithTransaction() failed");
return replacePrecedingWhiteSpacesResultOrError.propagateErr();
}
trackRangeToDelete.FlushAndStopTracking();
if (NS_WARN_IF(!rangeToDelete.IsPositioned())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
return std::move(rangeToDelete);
}
// static
Result<CreateLineBreakResult, nsresult>
WhiteSpaceVisibilityKeeper::InsertLineBreak(
LineBreakType aLineBreakType, HTMLEditor& aHTMLEditor,
const EditorDOMPoint& aPointToInsert) {
if (MOZ_UNLIKELY(NS_WARN_IF(!aPointToInsert.IsSet()))) {
return Err(NS_ERROR_INVALID_ARG);
}
EditorDOMPoint pointToInsert(aPointToInsert);
// Chrome does not normalize preceding white-spaces at least when it ends
// with an NBSP.
Result<EditorDOMPoint, nsresult>
normalizeSurroundingWhiteSpacesResultOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitAt(
aHTMLEditor, aPointToInsert,
{NormalizeOption::StopIfPrecedingWhiteSpacesEndsWithNBP});
if (MOZ_UNLIKELY(normalizeSurroundingWhiteSpacesResultOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitAt() failed");
return normalizeSurroundingWhiteSpacesResultOrError.propagateErr();
}
pointToInsert = normalizeSurroundingWhiteSpacesResultOrError.unwrap();
if (NS_WARN_IF(!pointToInsert.IsSet())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
Result<CreateLineBreakResult, nsresult> insertBRElementResultOrError =
aHTMLEditor.InsertLineBreak(WithTransaction::Yes, aLineBreakType,
pointToInsert);
NS_WARNING_ASSERTION(insertBRElementResultOrError.isOk(),
"HTMLEditor::InsertLineBreak(WithTransaction::Yes, "
"aLineBreakType, eNone) failed");
return insertBRElementResultOrError;
}
nsresult WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesAfter(
HTMLEditor& aHTMLEditor, const EditorDOMPoint& aPoint) {
MOZ_ASSERT(aPoint.IsInContentNode());
const RefPtr<Element> colsetBlockElement =
HTMLEditUtils::GetInclusiveAncestorElement(
*aPoint.ContainerAs<nsIContent>(),
HTMLEditUtils::ClosestEditableBlockElement,
BlockInlineCheck::UseComputedDisplayStyle);
EditorDOMPoint atFirstInvisibleWhiteSpace;
AutoTArray<OwningNonNull<nsIContent>, 32> unnecessaryContents;
for (nsIContent* nextContent =
HTMLEditUtils::GetNextLeafContentOrNextBlockElement(
aPoint,
{HTMLEditUtils::LeafNodeType::LeafNodeOrChildBlock,
HTMLEditUtils::LeafNodeType::TreatCommentAsLeafNode},
BlockInlineCheck::UseComputedDisplayStyle, colsetBlockElement);
nextContent;
nextContent = HTMLEditUtils::GetNextLeafContentOrNextBlockElement(
EditorRawDOMPoint::After(*nextContent),
{HTMLEditUtils::LeafNodeType::LeafNodeOrChildBlock,
HTMLEditUtils::LeafNodeType::TreatCommentAsLeafNode},
BlockInlineCheck::UseComputedDisplayStyle, colsetBlockElement)) {
if (!HTMLEditUtils::IsSimplyEditableNode(*nextContent)) {
// XXX Assume non-editable nodes are visible.
break;
}
const RefPtr<Text> followingTextNode = Text::FromNode(nextContent);
if (!followingTextNode &&
HTMLEditUtils::IsVisibleElementEvenIfLeafNode(*nextContent)) {
break;
}
if (!followingTextNode || !followingTextNode->TextDataLength()) {
// If it's an empty inline element like `<b></b>` or an empty `Text`,
// delete it.
nsIContent* emptyInlineContent =
HTMLEditUtils::GetMostDistantAncestorEditableEmptyInlineElement(
*nextContent, BlockInlineCheck::UseComputedDisplayStyle);
if (!emptyInlineContent) {
emptyInlineContent = nextContent;
}
unnecessaryContents.AppendElement(*emptyInlineContent);
continue;
}
const EditorRawDOMPointInText atFirstChar(followingTextNode, 0u);
if (!atFirstChar.IsCharCollapsibleASCIISpace()) {
break;
}
// If the preceding Text is collapsed and invisible, we should delete it
// and keep deleting preceding invisible white-spaces.
if (!HTMLEditUtils::IsVisibleTextNode(*followingTextNode)) {
nsIContent* emptyInlineContent =
HTMLEditUtils::GetMostDistantAncestorEditableEmptyInlineElement(
*followingTextNode, BlockInlineCheck::UseComputedDisplayStyle);
if (!emptyInlineContent) {
emptyInlineContent = followingTextNode;
}
unnecessaryContents.AppendElement(*emptyInlineContent);
continue;
}
Result<EditorDOMPoint, nsresult> startOfTextOrError =
WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpaces(
aHTMLEditor, EditorDOMPoint(followingTextNode, 0u));
if (MOZ_UNLIKELY(startOfTextOrError.isErr())) {
NS_WARNING("HTMLEditor::ReplaceTextWithTransaction() failed");
return startOfTextOrError.unwrapErr();
}
break;
}
for (const auto& contentToDelete : unnecessaryContents) {
if (MOZ_UNLIKELY(!contentToDelete->IsInComposedDoc())) {
continue;
}
nsresult rv =
aHTMLEditor.DeleteNodeWithTransaction(MOZ_KnownLive(contentToDelete));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return rv;
}
}
return NS_OK;
}
nsresult WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesBefore(
HTMLEditor& aHTMLEditor, const EditorDOMPoint& aPoint) {
MOZ_ASSERT(aPoint.IsInContentNode());
const RefPtr<Element> colsetBlockElement =
HTMLEditUtils::GetInclusiveAncestorElement(
*aPoint.ContainerAs<nsIContent>(),
HTMLEditUtils::ClosestEditableBlockElement,
BlockInlineCheck::UseComputedDisplayStyle);
EditorDOMPoint atFirstInvisibleWhiteSpace;
AutoTArray<OwningNonNull<nsIContent>, 32> unnecessaryContents;
for (nsIContent* previousContent =
HTMLEditUtils::GetPreviousLeafContentOrPreviousBlockElement(
aPoint,
{HTMLEditUtils::LeafNodeType::LeafNodeOrChildBlock,
HTMLEditUtils::LeafNodeType::TreatCommentAsLeafNode},
BlockInlineCheck::UseComputedDisplayStyle, colsetBlockElement);
previousContent;
previousContent =
HTMLEditUtils::GetPreviousLeafContentOrPreviousBlockElement(
EditorRawDOMPoint(previousContent),
{HTMLEditUtils::LeafNodeType::LeafNodeOrChildBlock,
HTMLEditUtils::LeafNodeType::TreatCommentAsLeafNode},
BlockInlineCheck::UseComputedDisplayStyle, colsetBlockElement)) {
if (!HTMLEditUtils::IsSimplyEditableNode(*previousContent)) {
// XXX Assume non-editable nodes are visible.
break;
}
const RefPtr<Text> precedingTextNode = Text::FromNode(previousContent);
if (!precedingTextNode &&
HTMLEditUtils::IsVisibleElementEvenIfLeafNode(*previousContent)) {
break;
}
if (!precedingTextNode || !precedingTextNode->TextDataLength()) {
// If it's an empty inline element like `<b></b>` or an empty `Text`,
// delete it.
nsIContent* emptyInlineContent =
HTMLEditUtils::GetMostDistantAncestorEditableEmptyInlineElement(
*previousContent, BlockInlineCheck::UseComputedDisplayStyle);
if (!emptyInlineContent) {
emptyInlineContent = previousContent;
}
unnecessaryContents.AppendElement(*emptyInlineContent);
continue;
}
const auto atLastChar =
EditorRawDOMPointInText::AtLastContentOf(*precedingTextNode);
if (!atLastChar.IsCharCollapsibleASCIISpace()) {
break;
}
// If the preceding Text is collapsed and invisible, we should delete it
// and keep deleting preceding invisible white-spaces.
if (!HTMLEditUtils::IsVisibleTextNode(*precedingTextNode)) {
nsIContent* emptyInlineContent =
HTMLEditUtils::GetMostDistantAncestorEditableEmptyInlineElement(
*precedingTextNode, BlockInlineCheck::UseComputedDisplayStyle);
if (!emptyInlineContent) {
emptyInlineContent = precedingTextNode;
}
unnecessaryContents.AppendElement(*emptyInlineContent);
continue;
}
Result<EditorDOMPoint, nsresult> endOfTextOrResult =
WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpaces(
aHTMLEditor, EditorDOMPoint::AtEndOf(*precedingTextNode));
if (MOZ_UNLIKELY(endOfTextOrResult.isErr())) {
NS_WARNING("HTMLEditor::ReplaceTextWithTransaction() failed");
return endOfTextOrResult.unwrapErr();
}
break;
}
for (const auto& contentToDelete : Reversed(unnecessaryContents)) {
if (MOZ_UNLIKELY(!contentToDelete->IsInComposedDoc())) {
continue;
}
nsresult rv =
aHTMLEditor.DeleteNodeWithTransaction(MOZ_KnownLive(contentToDelete));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return rv;
}
}
return NS_OK;
}
Result<EditorDOMPoint, nsresult>
WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpaces(
HTMLEditor& aHTMLEditor, const EditorDOMPoint& aPoint) {
if (EditorUtils::IsWhiteSpacePreformatted(
*aPoint.ContainerAs<nsIContent>())) {
return EditorDOMPoint();
}
if (aPoint.IsInTextNode() &&
// If there is a previous char and it's not a collapsible ASCII
// white-space, the point is not in the leading white-spaces.
(!aPoint.IsStartOfContainer() && !aPoint.IsPreviousCharASCIISpace()) &&
// If it does not points a collapsible ASCII white-space, the point is not
// in the trailing white-spaces.
(!aPoint.IsEndOfContainer() && !aPoint.IsCharCollapsibleASCIISpace())) {
return EditorDOMPoint();
}
const Element* const maybeNonEditableClosestBlockElement =
HTMLEditUtils::GetInclusiveAncestorElement(
*aPoint.ContainerAs<nsIContent>(), HTMLEditUtils::ClosestBlockElement,
BlockInlineCheck::UseComputedDisplayStyle);
if (MOZ_UNLIKELY(!maybeNonEditableClosestBlockElement)) {
return EditorDOMPoint(); // aPoint is not in a block.
}
const TextFragmentData textFragmentDataForLeadingWhiteSpaces(
{WSRunScanner::Option::OnlyEditableNodes},
aPoint.IsStartOfContainer() &&
(aPoint.GetContainer() == maybeNonEditableClosestBlockElement ||
aPoint.GetContainer()->IsEditingHost())
? aPoint
: aPoint.PreviousPointOrParentPoint<EditorDOMPoint>(),
maybeNonEditableClosestBlockElement);
if (NS_WARN_IF(!textFragmentDataForLeadingWhiteSpaces.IsInitialized())) {
return Err(NS_ERROR_FAILURE);
}
{
const EditorDOMRange& leadingWhiteSpaceRange =
textFragmentDataForLeadingWhiteSpaces
.InvisibleLeadingWhiteSpaceRangeRef();
if (leadingWhiteSpaceRange.IsPositioned() &&
!leadingWhiteSpaceRange.Collapsed()) {
EditorDOMPoint endOfLeadingWhiteSpaces(leadingWhiteSpaceRange.EndRef());
AutoTrackDOMPoint trackEndOfLeadingWhiteSpaces(
aHTMLEditor.RangeUpdaterRef(), &endOfLeadingWhiteSpaces);
Result<CaretPoint, nsresult> caretPointOrError =
aHTMLEditor.DeleteTextAndTextNodesWithTransaction(
leadingWhiteSpaceRange.StartRef(),
leadingWhiteSpaceRange.EndRef(),
HTMLEditor::TreatEmptyTextNodes::
KeepIfContainerOfRangeBoundaries);
if (MOZ_UNLIKELY(caretPointOrError.isErr())) {
NS_WARNING(
"HTMLEditor::DeleteTextAndTextNodesWithTransaction("
"TreatEmptyTextNodes::KeepIfContainerOfRangeBoundaries) failed");
return caretPointOrError.propagateErr();
}
caretPointOrError.unwrap().IgnoreCaretPointSuggestion();
// If the leading white-spaces were split into multiple text node, we need
// only the last `Text` node.
if (!leadingWhiteSpaceRange.InSameContainer() &&
leadingWhiteSpaceRange.StartRef().IsInTextNode() &&
leadingWhiteSpaceRange.StartRef()
.ContainerAs<Text>()
->IsInComposedDoc() &&
leadingWhiteSpaceRange.EndRef().IsInTextNode() &&
leadingWhiteSpaceRange.EndRef()
.ContainerAs<Text>()
->IsInComposedDoc() &&
!leadingWhiteSpaceRange.StartRef()
.ContainerAs<Text>()
->TextDataLength()) {
nsresult rv = aHTMLEditor.DeleteNodeWithTransaction(MOZ_KnownLive(
*leadingWhiteSpaceRange.StartRef().ContainerAs<Text>()));
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
trackEndOfLeadingWhiteSpaces.FlushAndStopTracking();
if (NS_WARN_IF(!endOfLeadingWhiteSpaces.IsSetAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return endOfLeadingWhiteSpaces;
}
}
const TextFragmentData textFragmentData =
textFragmentDataForLeadingWhiteSpaces.ScanStartRef() == aPoint
? textFragmentDataForLeadingWhiteSpaces
: TextFragmentData({WSRunScanner::Option::OnlyEditableNodes}, aPoint,
maybeNonEditableClosestBlockElement);
const EditorDOMRange& trailingWhiteSpaceRange =
textFragmentData.InvisibleTrailingWhiteSpaceRangeRef();
if (trailingWhiteSpaceRange.IsPositioned() &&
!trailingWhiteSpaceRange.Collapsed()) {
EditorDOMPoint startOfTrailingWhiteSpaces(
trailingWhiteSpaceRange.StartRef());
AutoTrackDOMPoint trackStartOfTrailingWhiteSpaces(
aHTMLEditor.RangeUpdaterRef(), &startOfTrailingWhiteSpaces);
Result<CaretPoint, nsresult> caretPointOrError =
aHTMLEditor.DeleteTextAndTextNodesWithTransaction(
trailingWhiteSpaceRange.StartRef(),
trailingWhiteSpaceRange.EndRef(),
HTMLEditor::TreatEmptyTextNodes::KeepIfContainerOfRangeBoundaries);
if (MOZ_UNLIKELY(caretPointOrError.isErr())) {
NS_WARNING(
"HTMLEditor::DeleteTextAndTextNodesWithTransaction("
"TreatEmptyTextNodes::KeepIfContainerOfRangeBoundaries) failed");
return caretPointOrError.propagateErr();
}
caretPointOrError.unwrap().IgnoreCaretPointSuggestion();
// If the leading white-spaces were split into multiple text node, we need
// only the last `Text` node.
if (!trailingWhiteSpaceRange.InSameContainer() &&
trailingWhiteSpaceRange.StartRef().IsInTextNode() &&
trailingWhiteSpaceRange.StartRef()
.ContainerAs<Text>()
->IsInComposedDoc() &&
trailingWhiteSpaceRange.EndRef().IsInTextNode() &&
trailingWhiteSpaceRange.EndRef()
.ContainerAs<Text>()
->IsInComposedDoc() &&
!trailingWhiteSpaceRange.EndRef()
.ContainerAs<Text>()
->TextDataLength()) {
nsresult rv = aHTMLEditor.DeleteNodeWithTransaction(
MOZ_KnownLive(*trailingWhiteSpaceRange.EndRef().ContainerAs<Text>()));
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
trackStartOfTrailingWhiteSpaces.FlushAndStopTracking();
if (NS_WARN_IF(!startOfTrailingWhiteSpaces.IsSetAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return startOfTrailingWhiteSpaces;
}
const auto atCollapsibleASCIISpace =
[&]() MOZ_NEVER_INLINE_DEBUG -> EditorDOMPointInText {
const auto point =
textFragmentData.GetInclusiveNextCharPoint<EditorDOMPointInText>(
textFragmentData.ScanStartRef(), IgnoreNonEditableNodes::Yes);
if (point.IsSet() &&
// XXX Perhaps, we should ignore empty `Text` nodes and keep scanning.
!point.IsEndOfContainer() && point.IsCharCollapsibleASCIISpace()) {
return point;
}
const auto prevPoint =
textFragmentData.GetPreviousCharPoint<EditorDOMPointInText>(
textFragmentData.ScanStartRef(), IgnoreNonEditableNodes::Yes);
return prevPoint.IsSet() &&
// XXX Perhaps, we should ignore empty `Text` nodes and keep
// scanning.
!prevPoint.IsEndOfContainer() &&
prevPoint.IsCharCollapsibleASCIISpace()
? prevPoint
: EditorDOMPointInText();
}();
if (!atCollapsibleASCIISpace.IsSet()) {
return EditorDOMPoint();
}
const auto firstCollapsibleASCIISpacePoint =
textFragmentData
.GetFirstASCIIWhiteSpacePointCollapsedTo<EditorDOMPointInText>(
atCollapsibleASCIISpace, nsIEditor::eNone,
IgnoreNonEditableNodes::No);
const auto endOfCollapsibleASCIISpacePoint =
textFragmentData
.GetEndOfCollapsibleASCIIWhiteSpaces<EditorDOMPointInText>(
atCollapsibleASCIISpace, nsIEditor::eNone,
IgnoreNonEditableNodes::No);
if (firstCollapsibleASCIISpacePoint.NextPoint() ==
endOfCollapsibleASCIISpacePoint) {
// Only one white-space, so that nothing to do.
return EditorDOMPoint();
}
// Okay, there are some collapsed white-spaces. We should delete them with
// keeping first one.
Result<CaretPoint, nsresult> deleteTextResultOrError =
aHTMLEditor.DeleteTextAndTextNodesWithTransaction(
firstCollapsibleASCIISpacePoint.NextPoint(),
endOfCollapsibleASCIISpacePoint,
HTMLEditor::TreatEmptyTextNodes::Remove);
if (MOZ_UNLIKELY(deleteTextResultOrError.isErr())) {
NS_WARNING("HTMLEditor::DeleteTextWithTransaction() failed");
return deleteTextResultOrError.propagateErr();
}
return deleteTextResultOrError.unwrap().UnwrapCaretPoint();
}
// static
Result<InsertTextResult, nsresult>
WhiteSpaceVisibilityKeeper::InsertTextOrInsertOrUpdateCompositionString(
HTMLEditor& aHTMLEditor, const nsAString& aStringToInsert,
const EditorDOMRange& aRangeToBeReplaced, InsertTextTo aInsertTextTo,
InsertTextFor aPurpose) {
MOZ_ASSERT(aRangeToBeReplaced.StartRef().IsInContentNode());
MOZ_ASSERT_IF(!EditorBase::InsertingTextForExtantComposition(aPurpose),
aRangeToBeReplaced.Collapsed());
if (aStringToInsert.IsEmpty()) {
MOZ_ASSERT(aRangeToBeReplaced.Collapsed());
return InsertTextResult();
}
if (NS_WARN_IF(!aRangeToBeReplaced.StartRef().IsInContentNode())) {
return Err(NS_ERROR_FAILURE); // Cannot insert text
}
EditorDOMPoint pointToInsert = aHTMLEditor.ComputePointToInsertText(
aRangeToBeReplaced.StartRef(), aInsertTextTo);
MOZ_ASSERT(pointToInsert.IsInContentNode());
const bool isWhiteSpaceCollapsible = !EditorUtils::IsWhiteSpacePreformatted(
*aRangeToBeReplaced.StartRef().ContainerAs<nsIContent>());
// First, delete invisible leading white-spaces and trailing white-spaces if
// they are there around the replacing range boundaries. However, don't do
// that if we're updating existing composition string to avoid the composition
// transaction is broken by the text change around composition string.
if (!EditorBase::InsertingTextForExtantComposition(aPurpose) &&
isWhiteSpaceCollapsible && pointToInsert.IsInContentNode()) {
AutoTrackDOMPoint trackPointToInsert(aHTMLEditor.RangeUpdaterRef(),
&pointToInsert);
Result<EditorDOMPoint, nsresult>
deletePointOfInvisibleWhiteSpacesAtStartOrError =
WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpaces(
aHTMLEditor, pointToInsert);
if (MOZ_UNLIKELY(deletePointOfInvisibleWhiteSpacesAtStartOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpaces() failed");
return deletePointOfInvisibleWhiteSpacesAtStartOrError.propagateErr();
}
trackPointToInsert.FlushAndStopTracking();
const EditorDOMPoint deletePointOfInvisibleWhiteSpacesAtStart =
deletePointOfInvisibleWhiteSpacesAtStartOrError.unwrap();
if (NS_WARN_IF(deletePointOfInvisibleWhiteSpacesAtStart.IsSet() &&
!pointToInsert.IsSetAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// If we're starting composition, we won't normalizing surrounding
// white-spaces until end of the composition. Additionally, at that time,
// we need to assume all white-spaces of surrounding white-spaces are
// visible because canceling composition may cause previous white-space
// invisible temporarily. Therefore, we should normalize surrounding
// white-spaces to delete invisible white-spaces contained in the sequence.
// E.g., `NBSP SP SP NBSP`, in this case, one of the SP is invisible.
if (EditorBase::InsertingTextForStartingComposition(aPurpose) &&
pointToInsert.IsInTextNode()) {
const auto whiteSpaceOffset = [&]() -> Maybe<uint32_t> {
if (!pointToInsert.IsEndOfContainer() &&
pointToInsert.IsCharCollapsibleASCIISpaceOrNBSP()) {
return Some(pointToInsert.Offset());
}
if (!pointToInsert.IsStartOfContainer() &&
pointToInsert.IsPreviousCharCollapsibleASCIISpaceOrNBSP()) {
return Some(pointToInsert.Offset() - 1u);
}
return Nothing();
}();
if (whiteSpaceOffset.isSome()) {
Maybe<AutoTrackDOMPoint> trackPointToInsert;
if (pointToInsert.Offset() != *whiteSpaceOffset) {
trackPointToInsert.emplace(aHTMLEditor.RangeUpdaterRef(),
&pointToInsert);
}
Result<EditorDOMPoint, nsresult> pointToInsertOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAt(
aHTMLEditor,
EditorDOMPointInText(pointToInsert.ContainerAs<Text>(),
*whiteSpaceOffset));
if (MOZ_UNLIKELY(pointToInsertOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAt() failed");
return pointToInsertOrError.propagateErr();
}
if (trackPointToInsert.isSome()) {
trackPointToInsert.reset();
} else {
pointToInsert = pointToInsertOrError.unwrap();
}
if (NS_WARN_IF(!pointToInsert.IsInContentNodeAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
}
}
if (NS_WARN_IF(!pointToInsert.IsInContentNode())) {
return Err(NS_ERROR_FAILURE);
}
const HTMLEditor::NormalizedStringToInsertText insertTextData =
[&]() MOZ_NEVER_INLINE_DEBUG {
if (!isWhiteSpaceCollapsible) {
return HTMLEditor::NormalizedStringToInsertText(aStringToInsert,
pointToInsert);
}
if (pointToInsert.IsInTextNode() &&
!EditorBase::InsertingTextForComposition(aPurpose)) {
// If normalizing the surrounding white-spaces in the `Text`, we
// should minimize the replacing range to avoid to unnecessary
// replacement.
return aHTMLEditor
.NormalizeWhiteSpacesToInsertText(
pointToInsert, aStringToInsert,
HTMLEditor::NormalizeSurroundingWhiteSpaces::Yes)
.GetMinimizedData(*pointToInsert.ContainerAs<Text>());
}
return aHTMLEditor.NormalizeWhiteSpacesToInsertText(
pointToInsert, aStringToInsert,
// If we're handling composition string, we should not replace
// surrounding white-spaces to avoid to make
// CompositionTransaction confused.
EditorBase::InsertingTextForComposition(aPurpose)
? HTMLEditor::NormalizeSurroundingWhiteSpaces::No
: HTMLEditor::NormalizeSurroundingWhiteSpaces::Yes);
}();
MOZ_ASSERT_IF(insertTextData.ReplaceLength(), pointToInsert.IsInTextNode());
Result<InsertTextResult, nsresult> insertOrReplaceTextResultOrError =
aHTMLEditor.InsertOrReplaceTextWithTransaction(pointToInsert,
insertTextData);
if (MOZ_UNLIKELY(insertOrReplaceTextResultOrError.isErr())) {
NS_WARNING("HTMLEditor::ReplaceTextWithTransaction() failed");
return insertOrReplaceTextResultOrError;
}
// If the composition is committed, we should normalize surrounding
// white-spaces of the commit string.
if (!EditorBase::InsertingTextForCommittingComposition(aPurpose)) {
return insertOrReplaceTextResultOrError;
}
InsertTextResult insertOrReplaceTextResult =
insertOrReplaceTextResultOrError.unwrap();
const EditorDOMPointInText endOfCommitString =
insertOrReplaceTextResult.EndOfInsertedTextRef().GetAsInText();
if (!endOfCommitString.IsSet() || endOfCommitString.IsContainerEmpty()) {
return std::move(insertOrReplaceTextResult);
}
if (NS_WARN_IF(endOfCommitString.Offset() <
insertTextData.mNormalizedString.Length())) {
insertOrReplaceTextResult.IgnoreCaretPointSuggestion();
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
const EditorDOMPointInText startOfCommitString(
endOfCommitString.ContainerAs<Text>(),
endOfCommitString.Offset() - insertTextData.mNormalizedString.Length());
MOZ_ASSERT(insertOrReplaceTextResult.EndOfInsertedTextRef() ==
insertOrReplaceTextResult.CaretPointRef());
EditorDOMPoint pointToPutCaret = insertOrReplaceTextResult.UnwrapCaretPoint();
// First, normalize the trailing white-spaces if there is. Note that its
// sequence may start from before the commit string. In such case, the
// another call of NormalizeWhiteSpacesAt() won't update the DOM.
if (endOfCommitString.IsMiddleOfContainer()) {
nsresult rv = WhiteSpaceVisibilityKeeper::
NormalizeVisibleWhiteSpacesWithoutDeletingInvisibleWhiteSpaces(
aHTMLEditor, endOfCommitString.PreviousPoint());
if (NS_FAILED(rv)) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::"
"NormalizeVisibleWhiteSpacesWithoutDeletingInvisibleWhiteSpaces() "
"failed");
return Err(rv);
}
if (NS_WARN_IF(!pointToPutCaret.IsSetAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
// Finally, normalize the leading white-spaces if there is and not a part of
// the trailing white-spaces.
if (!startOfCommitString.IsStartOfContainer()) {
nsresult rv = WhiteSpaceVisibilityKeeper::
NormalizeVisibleWhiteSpacesWithoutDeletingInvisibleWhiteSpaces(
aHTMLEditor, startOfCommitString.PreviousPoint());
if (NS_FAILED(rv)) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::"
"NormalizeVisibleWhiteSpacesWithoutDeletingInvisibleWhiteSpaces() "
"failed");
return Err(rv);
}
if (NS_WARN_IF(!pointToPutCaret.IsSetAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
EditorDOMPoint endOfCommitStringAfterNormalized = pointToPutCaret;
return InsertTextResult(std::move(endOfCommitStringAfterNormalized),
CaretPoint(std::move(pointToPutCaret)));
}
// static
nsresult WhiteSpaceVisibilityKeeper::
NormalizeVisibleWhiteSpacesWithoutDeletingInvisibleWhiteSpaces(
HTMLEditor& aHTMLEditor, const EditorDOMPointInText& aPoint) {
MOZ_ASSERT(aPoint.IsSet());
MOZ_ASSERT(!aPoint.IsEndOfContainer());
if (EditorUtils::IsWhiteSpacePreformatted(*aPoint.ContainerAs<Text>())) {
return NS_OK;
}
Text& textNode = *aPoint.ContainerAs<Text>();
const bool isNewLinePreformatted =
EditorUtils::IsNewLinePreformatted(textNode);
const auto IsCollapsibleChar = [&](char16_t aChar) {
return aChar == HTMLEditUtils::kNewLine ? !isNewLinePreformatted
: nsCRT::IsAsciiSpace(aChar);
};
const auto IsCollapsibleCharOrNBSP = [&](char16_t aChar) {
return aChar == HTMLEditUtils::kNBSP || IsCollapsibleChar(aChar);
};
const auto whiteSpaceOffset = [&]() -> Maybe<uint32_t> {
if (IsCollapsibleCharOrNBSP(aPoint.Char())) {
return Some(aPoint.Offset());
}
if (!aPoint.IsAtLastContent() &&
IsCollapsibleCharOrNBSP(aPoint.NextChar())) {
return Some(aPoint.Offset() + 1u);
}
return Nothing();
}();
if (whiteSpaceOffset.isNothing()) {
return NS_OK;
}
CharacterDataBuffer::WhitespaceOptions whitespaceOptions{
CharacterDataBuffer::WhitespaceOption::FormFeedIsSignificant,
CharacterDataBuffer::WhitespaceOption::TreatNBSPAsCollapsible};
if (isNewLinePreformatted) {
whitespaceOptions +=
CharacterDataBuffer::WhitespaceOption::NewLineIsSignificant;
}
const uint32_t firstOffset = [&]() {
if (!*whiteSpaceOffset) {
return 0u;
}
const uint32_t offset = textNode.DataBuffer().RFindNonWhitespaceChar(
whitespaceOptions, *whiteSpaceOffset - 1);
return offset == CharacterDataBuffer::kNotFound ? 0u : offset + 1u;
}();
const uint32_t endOffset = [&]() {
const uint32_t offset = textNode.DataBuffer().FindNonWhitespaceChar(
whitespaceOptions, *whiteSpaceOffset + 1);
return offset == CharacterDataBuffer::kNotFound ? textNode.TextDataLength()
: offset;
}();
MOZ_DIAGNOSTIC_ASSERT(firstOffset <= endOffset);
nsAutoString normalizedString;
const char16_t precedingChar =
!firstOffset ? static_cast<char16_t>(0)
: textNode.DataBuffer().CharAt(firstOffset - 1u);
const char16_t followingChar = endOffset == textNode.TextDataLength()
? static_cast<char16_t>(0)
: textNode.DataBuffer().CharAt(endOffset);
HTMLEditor::GenerateWhiteSpaceSequence(
normalizedString, endOffset - firstOffset,
!firstOffset ? HTMLEditor::CharPointData::InSameTextNode(
HTMLEditor::CharPointType::TextEnd)
: HTMLEditor::CharPointData::InSameTextNode(
precedingChar == HTMLEditUtils::kNewLine
? HTMLEditor::CharPointType::PreformattedLineBreak
: HTMLEditor::CharPointType::VisibleChar),
endOffset == textNode.TextDataLength()
? HTMLEditor::CharPointData::InSameTextNode(
HTMLEditor::CharPointType::TextEnd)
: HTMLEditor::CharPointData::InSameTextNode(
followingChar == HTMLEditUtils::kNewLine
? HTMLEditor::CharPointType::PreformattedLineBreak
: HTMLEditor::CharPointType::VisibleChar));
MOZ_ASSERT(normalizedString.Length() == endOffset - firstOffset);
const OwningNonNull<Text> text(textNode);
Result<InsertTextResult, nsresult> normalizeWhiteSpaceSequenceResultOrError =
aHTMLEditor.ReplaceTextWithTransaction(
text, firstOffset, endOffset - firstOffset, normalizedString);
if (MOZ_UNLIKELY(normalizeWhiteSpaceSequenceResultOrError.isErr())) {
NS_WARNING("HTMLEditor::ReplaceTextWithTransaction() failed");
return normalizeWhiteSpaceSequenceResultOrError.unwrapErr();
}
normalizeWhiteSpaceSequenceResultOrError.unwrap()
.IgnoreCaretPointSuggestion();
return NS_OK;
}
// static
Result<CaretPoint, nsresult>
WhiteSpaceVisibilityKeeper::DeleteContentNodeAndJoinTextNodesAroundIt(
HTMLEditor& aHTMLEditor, nsIContent& aContentToDelete,
const EditorDOMPoint& aCaretPoint, const Element& aEditingHost) {
EditorDOMPoint atContent(&aContentToDelete);
if (!atContent.IsSet()) {
NS_WARNING("Deleting content node was an orphan node");
return Err(NS_ERROR_FAILURE);
}
if (!HTMLEditUtils::IsRemovableNode(aContentToDelete)) {
NS_WARNING("Deleting content node wasn't removable");
return Err(NS_ERROR_FAILURE);
}
EditorDOMPoint pointToPutCaret(aCaretPoint);
Maybe<AutoTrackDOMPoint> trackPointToPutCaret;
if (aCaretPoint.IsSet()) {
trackPointToPutCaret.emplace(aHTMLEditor.RangeUpdaterRef(),
&pointToPutCaret);
}
// If we're removing a block, it may be surrounded by invisible
// white-spaces. We should remove them to avoid to make them accidentally
// visible.
if (HTMLEditUtils::IsBlockElement(
aContentToDelete, BlockInlineCheck::UseComputedDisplayOutsideStyle)) {
AutoTrackDOMPoint trackAtContent(aHTMLEditor.RangeUpdaterRef(), &atContent);
{
nsresult rv =
WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesBefore(
aHTMLEditor, EditorDOMPoint(aContentToDelete.AsElement()));
if (NS_FAILED(rv)) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesBefore()"
" failed");
return Err(rv);
}
if (NS_WARN_IF(!aContentToDelete.IsInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
rv = WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesAfter(
aHTMLEditor, EditorDOMPoint::After(*aContentToDelete.AsElement()));
if (NS_FAILED(rv)) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::EnsureNoInvisibleWhiteSpacesAfter() "
"failed");
return Err(rv);
}
if (NS_WARN_IF(!aContentToDelete.IsInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
if (trackPointToPutCaret.isSome()) {
trackPointToPutCaret->Flush(StopTracking::No);
}
}
if (pointToPutCaret.IsInContentNode()) {
// Additionally, we may put caret into the preceding block (this is the
// case when caret was in an empty block and type `Backspace`, or when
// caret is at end of the preceding block and type `Delete`). In such
// case, we need to normalize the white-space of the preceding `Text` of
// the deleting empty block for the compatibility with the other
// browsers.
if (pointToPutCaret.IsBefore(EditorRawDOMPoint(&aContentToDelete))) {
WSScanResult nextThingOfCaretPoint =
WSRunScanner::ScanInclusiveNextVisibleNodeOrBlockBoundary(
{}, pointToPutCaret);
Maybe<EditorLineBreak> lineBreak;
if (nextThingOfCaretPoint.ReachedLineBreak()) {
lineBreak.emplace(
nextThingOfCaretPoint.CreateEditorLineBreak<EditorLineBreak>());
nextThingOfCaretPoint =
WSRunScanner::ScanInclusiveNextVisibleNodeOrBlockBoundary(
{}, lineBreak->After<EditorRawDOMPoint>());
}
if (nextThingOfCaretPoint.ReachedBlockBoundary()) {
const EditorDOMPoint atBlockBoundary =
nextThingOfCaretPoint.ReachedCurrentBlockBoundary()
? EditorDOMPoint::AtEndOf(*nextThingOfCaretPoint.ElementPtr())
: EditorDOMPoint(nextThingOfCaretPoint.ElementPtr());
Result<EditorDOMPoint, nsresult> afterLastVisibleThingOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesBefore(
aHTMLEditor, atBlockBoundary, {});
if (MOZ_UNLIKELY(afterLastVisibleThingOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesBefore() "
"failed");
return afterLastVisibleThingOrError.propagateErr();
}
if (NS_WARN_IF(!aContentToDelete.IsInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// If the previous content ends with an invisible line break, let's
// delete it.
if (lineBreak.isSome() && lineBreak->IsInComposedDoc()) {
const WSScanResult prevThing =
WSRunScanner::ScanPreviousVisibleNodeOrBlockBoundary(
{}, lineBreak->To<EditorRawDOMPoint>(), &aEditingHost);
if (!prevThing.ReachedLineBoundary()) {
Result<EditorDOMPoint, nsresult> pointOrError =
aHTMLEditor.DeleteLineBreakWithTransaction(
lineBreak.ref(), nsIEditor::eStrip, aEditingHost);
if (MOZ_UNLIKELY(pointOrError.isErr())) {
NS_WARNING(
"HTMLEditor::DeleteLineBreakWithTransaction() failed");
return pointOrError.propagateErr();
}
trackPointToPutCaret->Flush(StopTracking::No);
}
}
}
}
// Similarly, we may put caret into the following block (this is the
// case when caret was in an empty block and type `Delete`, or when
// caret is at start of the following block and type `Backspace`). In
// such case, we need to normalize the white-space of the following
// `Text` of the deleting empty block for the compatibility with the
// other browsers.
else if (EditorRawDOMPoint::After(aContentToDelete)
.EqualsOrIsBefore(pointToPutCaret)) {
const WSScanResult previousThingOfCaretPoint =
WSRunScanner::ScanPreviousVisibleNodeOrBlockBoundary(
{}, pointToPutCaret);
if (previousThingOfCaretPoint.ReachedBlockBoundary()) {
const EditorDOMPoint atBlockBoundary =
previousThingOfCaretPoint.ReachedCurrentBlockBoundary()
? EditorDOMPoint(previousThingOfCaretPoint.ElementPtr(), 0u)
: EditorDOMPoint(previousThingOfCaretPoint.ElementPtr());
Result<EditorDOMPoint, nsresult> atFirstVisibleThingOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAfter(
aHTMLEditor, atBlockBoundary, {});
if (MOZ_UNLIKELY(atFirstVisibleThingOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAfter() "
"failed");
return atFirstVisibleThingOrError.propagateErr();
}
if (NS_WARN_IF(!aContentToDelete.IsInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
}
}
trackAtContent.Flush(StopTracking::Yes);
if (NS_WARN_IF(!atContent.IsInContentNodeAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
// If we're deleting inline content which is not followed by visible
// content, i.e., the preceding text will become the last Text node, we
// should normalize the preceding white-spaces for compatibility with the
// other browsers.
else {
const WSScanResult nextThing =
WSRunScanner::ScanInclusiveNextVisibleNodeOrBlockBoundary(
{}, EditorRawDOMPoint::After(aContentToDelete));
if (nextThing.ReachedLineBoundary()) {
AutoTrackDOMPoint trackAtContent(aHTMLEditor.RangeUpdaterRef(),
&atContent);
Result<EditorDOMPoint, nsresult> afterLastVisibleThingOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesBefore(aHTMLEditor,
atContent, {});
if (MOZ_UNLIKELY(afterLastVisibleThingOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesBefore() "
"failed");
return afterLastVisibleThingOrError.propagateErr();
}
trackAtContent.Flush(StopTracking::Yes);
if (NS_WARN_IF(!atContent.IsInContentNodeAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
}
// Finally, we should normalize the following white-spaces for compatibility
// with the other browsers.
{
AutoTrackDOMPoint trackAtContent(aHTMLEditor.RangeUpdaterRef(), &atContent);
Result<EditorDOMPoint, nsresult> atFirstVisibleThingOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesAfter(
aHTMLEditor, atContent.NextPoint(), {});
if (MOZ_UNLIKELY(atFirstVisibleThingOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesBefore() failed");
return atFirstVisibleThingOrError.propagateErr();
}
trackAtContent.Flush(StopTracking::Yes);
if (NS_WARN_IF(!atContent.IsInContentNodeAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
nsCOMPtr<nsIContent> previousEditableSibling =
HTMLEditUtils::GetPreviousSibling(
aContentToDelete, {WalkTreeOption::IgnoreNonEditableNode});
// Delete the node, and join like nodes if appropriate
nsresult rv = aHTMLEditor.DeleteNodeWithTransaction(aContentToDelete);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
if (trackPointToPutCaret.isSome()) {
trackPointToPutCaret->Flush(StopTracking::Yes);
if (NS_WARN_IF(!pointToPutCaret.IsInContentNode())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
// Are they both text nodes? If so, join them!
// XXX This may cause odd behavior if there is non-editable nodes
// around the atomic content.
if (!aCaretPoint.IsInTextNode() || !previousEditableSibling ||
!previousEditableSibling->IsText()) {
return CaretPoint(std::move(pointToPutCaret));
}
nsIContent* nextEditableSibling = HTMLEditUtils::GetNextSibling(
*previousEditableSibling, {WalkTreeOption::IgnoreNonEditableNode});
if (aCaretPoint.GetContainer() != nextEditableSibling) {
return CaretPoint(std::move(pointToPutCaret));
}
Result<JoinNodesResult, nsresult> joinTextNodesResultOrError =
aHTMLEditor.JoinTextNodesWithNormalizeWhiteSpaces(
MOZ_KnownLive(*previousEditableSibling->AsText()),
MOZ_KnownLive(*aCaretPoint.ContainerAs<Text>()));
if (MOZ_UNLIKELY(joinTextNodesResultOrError.isErr())) {
NS_WARNING("HTMLEditor::JoinTextNodesWithNormalizeWhiteSpaces() failed");
return joinTextNodesResultOrError.propagateErr();
}
return CaretPoint(
joinTextNodesResultOrError.unwrap().AtJoinedPoint<EditorDOMPoint>());
}
// static
nsresult WhiteSpaceVisibilityKeeper::ReplaceTextAndRemoveEmptyTextNodes(
HTMLEditor& aHTMLEditor, const EditorDOMRangeInTexts& aRangeToReplace,
const nsAString& aReplaceString) {
MOZ_ASSERT(aRangeToReplace.IsPositioned());
MOZ_ASSERT(aRangeToReplace.StartRef().IsSetAndValid());
MOZ_ASSERT(aRangeToReplace.EndRef().IsSetAndValid());
MOZ_ASSERT(aRangeToReplace.StartRef().IsBefore(aRangeToReplace.EndRef()));
{
Result<InsertTextResult, nsresult> caretPointOrError =
aHTMLEditor.ReplaceTextWithTransaction(
MOZ_KnownLive(*aRangeToReplace.StartRef().ContainerAs<Text>()),
aRangeToReplace.StartRef().Offset(),
aRangeToReplace.InSameContainer()
? aRangeToReplace.EndRef().Offset() -
aRangeToReplace.StartRef().Offset()
: aRangeToReplace.StartRef().ContainerAs<Text>()->TextLength() -
aRangeToReplace.StartRef().Offset(),
aReplaceString);
if (MOZ_UNLIKELY(caretPointOrError.isErr())) {
NS_WARNING("HTMLEditor::ReplaceTextWithTransaction() failed");
return caretPointOrError.unwrapErr();
}
// Ignore caret suggestion because there was
// AutoTransactionsConserveSelection.
caretPointOrError.unwrap().IgnoreCaretPointSuggestion();
}
if (aRangeToReplace.InSameContainer()) {
return NS_OK;
}
Result<CaretPoint, nsresult> caretPointOrError =
aHTMLEditor.DeleteTextAndTextNodesWithTransaction(
EditorDOMPointInText::AtEndOf(
*aRangeToReplace.StartRef().ContainerAs<Text>()),
aRangeToReplace.EndRef(),
HTMLEditor::TreatEmptyTextNodes::KeepIfContainerOfRangeBoundaries);
if (MOZ_UNLIKELY(caretPointOrError.isErr())) {
NS_WARNING("HTMLEditor::DeleteTextAndTextNodesWithTransaction() failed");
return caretPointOrError.unwrapErr();
}
// Ignore caret suggestion because there was
// AutoTransactionsConserveSelection.
caretPointOrError.unwrap().IgnoreCaretPointSuggestion();
return NS_OK;
}
// static
Result<CaretPoint, nsresult>
WhiteSpaceVisibilityKeeper::DeleteInvisibleASCIIWhiteSpaces(
HTMLEditor& aHTMLEditor, const EditorDOMPoint& aPoint) {
MOZ_ASSERT(aPoint.IsSet());
const TextFragmentData textFragmentData(
{WSRunScanner::Option::OnlyEditableNodes}, aPoint);
if (NS_WARN_IF(!textFragmentData.IsInitialized())) {
return Err(NS_ERROR_FAILURE);
}
const EditorDOMRange& leadingWhiteSpaceRange =
textFragmentData.InvisibleLeadingWhiteSpaceRangeRef();
// XXX Getting trailing white-space range now must be wrong because
// mutation event listener may invalidate it.
const EditorDOMRange& trailingWhiteSpaceRange =
textFragmentData.InvisibleTrailingWhiteSpaceRangeRef();
EditorDOMPoint pointToPutCaret;
DebugOnly<bool> leadingWhiteSpacesDeleted = false;
if (leadingWhiteSpaceRange.IsPositioned() &&
!leadingWhiteSpaceRange.Collapsed()) {
Result<CaretPoint, nsresult> caretPointOrError =
aHTMLEditor.DeleteTextAndTextNodesWithTransaction(
leadingWhiteSpaceRange.StartRef(), leadingWhiteSpaceRange.EndRef(),
HTMLEditor::TreatEmptyTextNodes::KeepIfContainerOfRangeBoundaries);
if (MOZ_UNLIKELY(caretPointOrError.isErr())) {
NS_WARNING("HTMLEditor::DeleteTextAndTextNodesWithTransaction() failed");
return caretPointOrError;
}
caretPointOrError.unwrap().MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
leadingWhiteSpacesDeleted = true;
}
if (trailingWhiteSpaceRange.IsPositioned() &&
!trailingWhiteSpaceRange.Collapsed() &&
leadingWhiteSpaceRange != trailingWhiteSpaceRange) {
NS_ASSERTION(!leadingWhiteSpacesDeleted,
"We're trying to remove trailing white-spaces with maybe "
"outdated range");
AutoTrackDOMPoint trackPointToPutCaret(aHTMLEditor.RangeUpdaterRef(),
&pointToPutCaret);
Result<CaretPoint, nsresult> caretPointOrError =
aHTMLEditor.DeleteTextAndTextNodesWithTransaction(
trailingWhiteSpaceRange.StartRef(),
trailingWhiteSpaceRange.EndRef(),
HTMLEditor::TreatEmptyTextNodes::KeepIfContainerOfRangeBoundaries);
if (MOZ_UNLIKELY(caretPointOrError.isErr())) {
NS_WARNING("HTMLEditor::DeleteTextAndTextNodesWithTransaction() failed");
return caretPointOrError.propagateErr();
}
trackPointToPutCaret.FlushAndStopTracking();
caretPointOrError.unwrap().MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
}
return CaretPoint(std::move(pointToPutCaret));
}
} // namespace mozilla
|