All files / src/dm ve.dm.LinearData.js

98.36% Statements 543/552
96.98% Branches 450/464
100% Functions 91/91
98.29% Lines 519/528

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                1x 3550x 3550x         1x     1x 1x                                                         1x       1x                           1x 34898x                               1x   259036x                 1x 114372x                 1x 62169x                                 1x 2152x 2152x   2152x 62x     2090x 278x   2090x 286x   2090x 341x     1749x   46x       1703x 837x         866x   782x 782x   782x 782x   782x     84x                                 1x 2785x 220x     2565x   2565x   515x   2050x   1154x   896x 238x       658x 65x   658x 65x   658x 593x   658x 593x     658x 658x   658x                 1x 12909x 7612x 5297x 27x 5270x 2097x   3173x                         1x 825x 825x 825x 825x 672x   33x     639x 639x     153x   67x     86x     825x                 1x 22627x 22627x                     1x 371650x                 1x 6906x                         1x   5995x   5995x   5995x                 1x 27960x                 1x 79218x                 1x 44257x                 1x 27180x                 1x 1x               1x 44513x               1x 2703x               1x 16565x                   1x 6968x                   1x 13x                     1x 3850x                     1x 1x                       1x 822x                       1x 1x                         1x 4270x   4270x 4270x 4121x 4121x   4270x   4270x               1x 1x                                               1x   10262x 719x   9543x 9543x 9543x 9543x                                                                                                                                                         1x   716x 60x     656x 656x 656x 656x                                                                                                                                               1x 4x 4x 11x 11x       1x     3x                     1x 637x 118x 36x   82x     82x     519x                       1x 12649x 2x         12647x         86x 86x         12647x 12647x                               1x 22x 22x 22x 22x 51x 51x   22x 51x 51x 51x         22x 149x 149x             22x 22x         43x 22x                         1x 11864x                     1x 285x                     1x 563x 563x 563x                   1x 51x     51x 51x   2x 2x       49x       49x                     1x 21902x 21902x                   1x 3x     20x                   1x 113x       1x                     1x 922x   922x     922x 5607x 2244x 4x     2244x 2127x       3480x 4x   3476x   869x   869x 117x   752x     2607x 2607x 539x 2068x   231x 82x     149x   149x 4x       723x                             1x     2672x   1899x       773x         2672x 1867x   805x         2672x 2435x     237x         2672x 256x                     1x 2x                 1x 65x                         1x 82x     82x 57x     82x 347x   169x 178x   63x 43x   20x       13x   115x   113x 113x 2x   111x 108x     12x                         1x 22x 22x 1054x 874x 180x 24x   156x 78x   156x     22x                       1x 2407x   2407x 2407x 13502x 10631x 2871x 1125x     2407x                       1x 4x                                                     1x     852x 47x 18x   29x         834x           834x 834x 834x 834x 834x 834x 834x   834x       2020x 2020x       47x     47x 21x   26x 26x 5x       2015x 862x 794x 794x 794x 781x     1153x                 70x   25x     45x 45x 45x 45x 45x   1209x   23x                         1x 605x                               1x 702x 370x   332x 73x 73x 73x   259x                             1x   164x 1x   163x                                     1x 247x 170x   77x 4x 4x 4x   73x                               1x 365x   365x     365x           163x       163x         163x   13x       150x   45x             105x       202x           260x 4x   256x                       1x 8x 30x 5x 5x 5x                         1x 64x 671x 213x 213x 213x                       1x     17x 21x 17x   4x       7x 52x   2x   50x 50x 16x 34x 1x   50x 7x 7x 2x                                                 1x 178x 178x 178x     178x 6x   172x   8x 7x 7x         7x 7x 7x 7x 7x             7x             172x                 178x 1559x 942x 942x 942x   942x 477x   465x     942x 2x 2x 2x         942x 8x 8x           942x         16x 16x   16x 8x 8x       16x 16x       926x 7x     2x 2x   5x     7x 7x       919x           5x 5x   5x 5x     914x 908x 908x       914x 1x 1x 1x 11x   1x 1x       913x 447x                 617x         5x       2x 2x   2x 2x     3x 2x   1x 1x               615x         6x   4x 3x   1x 1x           1528x 1528x 105x 7x 98x   22x 22x     1528x 457x 121x   121x 121x     457x 22x   22x       457x 451x 451x                           1x 92x 92x 1002x 334x 334x 334x                       1x 16x 16x 16x 64x 64x 18x 9x   9x   46x 40x 40x 7x       9x               1x     13x                               1x 197x 44x    
/*!
 * VisualEditor LinearData class.
 *
 * Class containing linear data and an hash-value store.
 *
 * @copyright See AUTHORS.txt
 */
 
/**
 * Generic linear data storage
 *
 * @class
 * @constructor
 * @param {ve.dm.HashValueStore} store Hash-value store
 * @param {ve.dm.LinearData.Item[]} [data] Linear data
 */
ve.dm.LinearData = function VeDmLinearData( store, data ) {
	this.store = store;
	this.data = data ? ve.deepFreeze( data, true ) : [];
};
 
/* Inheritance */
 
OO.initClass( ve.dm.LinearData );
 
// Deprecated aliases
ve.dm.FlatLinearData = ve.dm.LinearData;
ve.dm.ElementLinearData = ve.dm.LinearData;
 
/**
 * @typedef {Object} Element
 * @memberof ve.dm.LinearData
 * @property {string} type The type of the element
 * @property {Object} [attributes] Optional additional attributes specific to the element type
 * @property {string} [originalDomElementsHash] Hash of the original DOM elements found by the converter
 * @property {Object} [internal] Internal attributes used by the converter
 */
 
/**
 * @typedef {Array} AnnotatedCharacter
 * @memberof ve.dm.LinearData
 * @property {string} 0 Character data
 * @property {string[]} 1 Annotation hashses
 */
 
/**
 * @typedef {ve.dm.LinearData.Element|string|ve.dm.LinearData.AnnotatedCharacter} Item
 * @memberof ve.dm.LinearData
 * A single item in the linear model data array, which can be:
 * - An element object
 * - A single character string
 * - A tuple of character and annotation hashes
 */
 
/* Static Properties */
 
ve.dm.LinearData.static.startWordRegExp = new RegExp(
	'^(' + unicodeJS.characterclass.patterns.word + ')'
);
 
ve.dm.LinearData.static.endWordRegExp = new RegExp(
	'(' + unicodeJS.characterclass.patterns.word + ')$'
);
 
/* Static Methods */
 
/**
 * Get the type of an element
 *
 * This will return the same string for close and open elements.
 *
 * @param {ve.dm.LinearData.Element} element Element item
 * @return {string} Type of the element
 */
ve.dm.LinearData.static.getType = function ( element ) {
	return this.isCloseElementData( element ) ? element.type.slice( 1 ) : element.type;
};
 
/**
 * Check if data item is an element.
 *
 * This method assumes that any value that has a type property that's a string is an element object.
 *
 * Element data:
 *
 *      <heading> a </heading> <paragraph> b c <img></img> </paragraph>
 *     ^         . ^          ^           . . ^     ^     ^            .
 *
 * @param {ve.dm.LinearData.Item} item Linear data item
 * @return {boolean} Item is an element
 */
ve.dm.LinearData.static.isElementData = function ( item ) {
	// Data exists and appears to be an element
	return item !== undefined && typeof item.type === 'string';
};
 
/**
 * Checks if data item is an open element.
 *
 * @param {ve.dm.LinearData.Item} item Element item
 * @return {boolean} Item is an open element
 */
ve.dm.LinearData.static.isOpenElementData = function ( item ) {
	return this.isElementData( item ) && !item.type.startsWith( '/' );
};
 
/**
 * Checks if data item is a close element.
 *
 * @param {ve.dm.LinearData.Item} item Element item
 * @return {boolean} Item is a close element
 */
ve.dm.LinearData.static.isCloseElementData = function ( item ) {
	return this.isElementData( item ) && item.type.startsWith( '/' );
};
 
/**
 * Compare two items' basic properties
 *
 * Items are comparable if they have the same type and attributes, or
 * have the same text data. Anything semantically irrelevant is filtered
 * out first.
 *
 * When changing, ensure that ve.dm.Transaction.static.compareElementsForTranslate
 * is also updated.
 *
 * @param {ve.dm.LinearData.Item} a First item
 * @param {ve.dm.LinearData.Item} b Second item
 * @return {boolean} Items are comparable
 */
ve.dm.LinearData.static.compareElementsUnannotated = function ( a, b ) {
	let aPlain = a,
		bPlain = b;
 
	if ( a === b ) {
		return true;
	}
 
	if ( Array.isArray( a ) ) {
		aPlain = a[ 0 ];
	}
	if ( Array.isArray( b ) ) {
		bPlain = b[ 0 ];
	}
	if ( typeof aPlain === 'string' && typeof bPlain === 'string' ) {
		return aPlain === bPlain;
	}
 
	if ( typeof a !== typeof b ) {
		// Different types
		return false;
	}
 
	// By this point, both must be objects, so must have equal types
	if ( a.type !== b.type ) {
		return false;
	}
 
	// Both objects are open elements, so compare hashes.
	// (NB we only need to check one as they have equal .type)
	if ( ve.dm.LinearData.static.isOpenElementData( a ) ) {
		// As we are using hashes, we don't need to worry about annotations
		aPlain = ve.dm.modelRegistry.lookup( a.type ).static.getHashObject( a );
		delete aPlain.originalDomElementsHash;
 
		bPlain = ve.dm.modelRegistry.lookup( b.type ).static.getHashObject( b );
		delete bPlain.originalDomElementsHash;
 
		return ve.compare( aPlain, bPlain );
	} else {
		// Both objects are close elements, no need to compare attributes
		return true;
	}
};
 
/**
 * Compare two items' basic properties and annotations
 *
 * Items are comparable if they have the same type, attributes,
 * text data and annotations, as determined by
 * ve.dm.AnnotationSet#compareTo .
 *
 * @param {ve.dm.LinearData.Item} a First item
 * @param {ve.dm.LinearData.Item} b Second item
 * @param {ve.dm.HashValueStore} aStore First item's store
 * @param {ve.dm.HashValueStore} [bStore] Second item's store, if different
 * @return {boolean} Items are comparable
 */
ve.dm.LinearData.static.compareElements = function ( a, b, aStore, bStore ) {
	if ( a === b ) {
		return true;
	}
 
	const typeofA = typeof a;
 
	if ( typeofA !== typeof b ) {
		// Different types
		return false;
	}
	if ( typeofA === 'string' ) {
		// Both strings, and not equal
		return false;
	}
	if ( !this.compareElementsUnannotated( a, b ) ) {
		return false;
	}
	let aAnnotations, bAnnotations;
	// Items are equal without annotations, now compare annotations:
	if ( Array.isArray( a ) ) {
		aAnnotations = a[ 1 ];
	}
	if ( Array.isArray( b ) ) {
		bAnnotations = b[ 1 ];
	}
	if ( a && a.type ) {
		aAnnotations = a.annotations;
	}
	if ( b && b.type ) {
		bAnnotations = b.annotations;
	}
 
	const aSet = new ve.dm.AnnotationSet( aStore, aAnnotations || [] );
	const bSet = new ve.dm.AnnotationSet( bStore || aStore, bAnnotations || [] );
 
	return aSet.compareTo( bSet );
};
 
/**
 * Read the array of annotation store hashes from an item of linear data
 *
 * @param {ve.dm.LinearData.Item} item Item of linear data
 * @return {string[]} An array of annotation store hashes
 */
ve.dm.LinearData.static.getAnnotationHashesFromItem = function ( item ) {
	if ( typeof item === 'string' ) {
		return [];
	} else if ( item.annotations ) {
		return item.annotations.slice();
	} else if ( item[ 1 ] ) {
		return item[ 1 ].slice();
	} else {
		return [];
	}
};
 
/**
 * Set annotations' store hashes at a specified offset.
 *
 * Cleans up data structure if hashes array is empty.
 *
 * @param {ve.dm.LinearData.Item} item Item of linear data
 * @param {string[]} hashes Annotations' store hashes
 * @return {ve.dm.LinearData.Item} Deep-copied, modified item
 */
ve.dm.LinearData.static.replaceAnnotationHashesForItem = function ( item, hashes ) {
	const isElement = ve.dm.LinearData.static.isElementData( item );
	item = ve.copy( item );
	hashes = hashes.slice();
	if ( hashes.length > 0 ) {
		if ( isElement ) {
			// New element annotation
			item.annotations = hashes;
		} else {
			// New character annotation
			const character = ve.dm.LinearData.static.getCharacterDataFromItem( item );
			item = [ character, hashes ];
		}
	} else {
		if ( isElement ) {
			// Cleanup empty element annotation
			delete item.annotations;
		} else {
			// Cleanup empty character annotation
			item = ve.dm.LinearData.static.getCharacterDataFromItem( item );
		}
	}
	return item;
};
 
/**
 * Get character data from an item
 *
 * @param {ve.dm.LinearData.Item} item Item to get character data from
 * @return {string} Character data, or '' if no character data
 */
ve.dm.LinearData.static.getCharacterDataFromItem = function ( item ) {
	const data = Array.isArray( item ) ? item[ 0 ] : item;
	return typeof data === 'string' ? data : '';
};
 
/* Methods */
 
/**
 * Gets linear data from a specified index, or all data if no index specified
 *
 * @param {number} [offset] Offset to get data from
 * @return {ve.dm.LinearData.Item|ve.dm.LinearData.Item[]} Data from index, or all data (by reference)
 */
ve.dm.LinearData.prototype.getData = function ( offset ) {
	return offset === undefined ? this.data : this.data[ offset ];
};
 
/**
 * Sets linear data at a specified index
 *
 * @param {number} offset Offset to set data at
 * @param {ve.dm.LinearData.Item} item Value to store
 */
ve.dm.LinearData.prototype.setData = function ( offset, item ) {
	this.data[ offset ] = typeof item === 'object' ? ve.deepFreeze( item ) : item;
};
 
/**
 * Modify an existing object in the linear model
 *
 * As objects in the model and immutable, this creates
 * a clone which is passed to a callback function for
 * modification, then the clone is inserted into the model.
 *
 * @param {number} offset Offset to modify data at
 * @param {Function} modify Modification function. First argument is the data element to modify.
 */
ve.dm.LinearData.prototype.modifyData = function ( offset, modify ) {
	// Unfreeze object by creating a new copy
	const newItem = ve.copy( this.getData( offset ) );
	// Modify via callback
	modify( newItem );
	// Insert into linear model, re-freezing it
	this.setData( offset, newItem );
};
 
/**
 * Get the type of the element at a specified offset.
 *
 * @param {number} offset Data offset
 * @return {string} Type of the element
 */
ve.dm.LinearData.prototype.getType = function ( offset ) {
	return this.constructor.static.getType( this.getData( offset ) );
};
 
/**
 * Check if data at a given offset is an element.
 *
 * @param {number} offset Data offset
 * @return {boolean} Data at offset is an element
 */
ve.dm.LinearData.prototype.isElementData = function ( offset ) {
	return this.constructor.static.isElementData( this.getData( offset ) );
};
 
/**
 * Checks if data at a given offset is an open element.
 *
 * @param {number} offset Data offset
 * @return {boolean} Data at offset is an open element
 */
ve.dm.LinearData.prototype.isOpenElementData = function ( offset ) {
	return this.constructor.static.isOpenElementData( this.getData( offset ) );
};
 
/**
 * Checks if data at a given offset is a close element.
 *
 * @param {number} offset Data offset
 * @return {boolean} Data at offset is a close element
 */
ve.dm.LinearData.prototype.isCloseElementData = function ( offset ) {
	return this.constructor.static.isCloseElementData( this.getData( offset ) );
};
 
/**
 * Push data to the end of the array
 *
 * @param {...ve.dm.LinearData.Item} [values] Values to store
 * @return {number} The new length of the linear data
 */
ve.dm.LinearData.prototype.push = function ( ...values ) {
	return this.data.push( ...values );
};
 
/**
 * Gets length of the linear data
 *
 * @return {number} Length of the linear data
 */
ve.dm.LinearData.prototype.getLength = function () {
	return this.getData().length;
};
 
/**
 * Gets a range covering the entire linear data
 *
 * @return {ve.Range} Range covering the entire linear data
 */
ve.dm.LinearData.prototype.getRange = function () {
	return new ve.Range( 0, this.getLength() );
};
 
/**
 * Gets the hash-value store
 *
 * @return {ve.dm.HashValueStore} The hash-value store
 */
ve.dm.LinearData.prototype.getStore = function () {
	return this.store;
};
 
/**
 * Slice linear data
 *
 * @param {number} begin Index to begin at
 * @param {number} [end] Index to end at
 * @return {ve.dm.LinearData.Item[]} One-level deep copy of sliced range
 */
ve.dm.LinearData.prototype.slice = function ( begin, end ) {
	return this.data.slice( begin, end );
};
 
/**
 * Slice linear data and return new LinearData object containing result
 *
 * @param {number} begin Index to begin at
 * @param {number} [end] Index to end at
 * @return {ve.dm.LinearData} LinearData object containing one-level deep copy of sliced range
 */
ve.dm.LinearData.prototype.sliceObject = function ( begin, end ) {
	return new this.constructor( this.getStore(), this.slice( begin, end ) );
};
 
/**
 * Splice linear data
 *
 * @param {number} index Splice from
 * @param {number} deleteCount Items to be removed
 * @param {...ve.dm.LinearData.Item} [elements] Items to be inserted
 * @return {ve.dm.LinearData.Item[]} Elements removed
 */
ve.dm.LinearData.prototype.splice = function ( index, deleteCount, ...elements ) {
	return this.data.splice( index, deleteCount, ...elements );
};
 
/**
 * Splice linear data and return new LinearData object containing result
 *
 * @param {number} index Splice from
 * @param {number} deleteCount Items to be removed
 * @param {...ve.dm.LinearData.Item} [elements] Items to be inserted
 * @return {ve.dm.LinearData} LinearData object containing elements removed
 */
ve.dm.LinearData.prototype.spliceObject = function ( index, deleteCount, ...elements ) {
	return new this.constructor( this.getStore(), this.splice( index, deleteCount, ...elements ) );
};
 
/**
 * Returns ve.batchSplice of linear data
 *
 * @see ve.batchSplice
 * @param {number} offset
 * @param {number} remove
 * @param {ve.dm.LinearData.Item[]} data
 * @return {ve.dm.LinearData.Item[]}
 */
ve.dm.LinearData.prototype.batchSplice = function ( offset, remove, data ) {
	return ve.batchSplice( this.getData(), offset, remove, data );
};
 
/**
 * Returns ve.batchSplice of linear data, wrapped in a LinearData object
 *
 * @see ve.batchSplice
 * @param {number} offset
 * @param {number} remove
 * @param {ve.dm.LinearData.Item[]} data
 * @return {ve.dm.LinearData}
 */
ve.dm.LinearData.prototype.batchSpliceObject = function ( offset, remove, data ) {
	return new this.constructor(
		this.getStore(),
		this.batchSplice( offset, remove, data )
	);
};
 
/**
 * Get a slice or copy of the provided data.
 *
 * @param {ve.Range} [range] Range of data to get, all data will be given by default
 * @param {boolean} [deep=false] Whether to return a deep copy (WARNING! This may be very slow)
 * @return {ve.dm.LinearData.Item[]} Slice or copy of data
 */
ve.dm.LinearData.prototype.getDataSlice = function ( range, deep ) {
	const length = this.getLength();
	let end,
		start = 0;
	if ( range !== undefined ) {
		start = Math.max( 0, Math.min( length, range.start ) );
		end = Math.max( 0, Math.min( length, range.end ) );
	}
	const data = this.slice( start, end );
	// Return either the slice or a deep copy of the slice
	return deep ? ve.copy( data ) : data;
};
 
/**
 * Clone the data, with a deep copy of the data.
 *
 * @return {ve.dm.LinearData} Clone of this object
 */
ve.dm.LinearData.prototype.clone = function () {
	return new this.constructor(
		this.getStore(),
		ve.copy( this.data )
	);
};
 
/**
 * Check if content can be inserted at an offset in document data.
 *
 * This method assumes that any value that has a type property that's a string is an element object.
 *
 * Content offsets:
 *
 *      <heading> a </heading> <paragraph> b c <img> </img> </paragraph>
 *     .         ^ ^          .           ^ ^ ^     .      ^            .
 *
 * Content offsets:
 *
 *      <list> <listItem> </listItem> <list>
 *     .      .          .           .      .
 *
 * @param {number} offset Document offset
 * @return {boolean} Content can be inserted at offset
 */
ve.dm.LinearData.prototype.isContentOffset = function ( offset ) {
	// Edges are never content
	if ( offset === 0 || offset === this.getLength() ) {
		return false;
	}
	const left = this.getData( offset - 1 );
	const right = this.getData( offset );
	const factory = ve.dm.nodeFactory;
	return (
		// Data exists at offsets
		( left !== undefined && right !== undefined ) &&
		(
			// If there's content on the left or the right of the offset than we are good
			// <paragraph>|a|</paragraph>
			( typeof left === 'string' || typeof right === 'string' ) ||
			// Same checks but for annotated characters - isArray is slower, try it next
			( Array.isArray( left ) || Array.isArray( right ) ) ||
			// The most expensive test are last, these deal with elements
			(
				// Right of a leaf
				// <paragraph><image></image>|</paragraph>
				(
					// Is an element
					typeof left.type === 'string' &&
					// Is a closing
					left.type.startsWith( '/' ) &&
					// Is a leaf
					factory.isNodeContent( left.type.slice( 1 ) )
				) ||
				// Left of a leaf
				// <paragraph>|<image></image></paragraph>
				(
					// Is an element
					typeof right.type === 'string' &&
					// Is not a closing
					!right.type.startsWith( '/' ) &&
					// Is a leaf
					factory.isNodeContent( right.type )
				) ||
				// Inside empty content branch
				// <paragraph>|</paragraph>
				(
					// Inside empty element
					'/' + left.type === right.type &&
					// Both are content branches (right is the same type)
					factory.canNodeContainContent( left.type )
				)
			)
		)
	);
};
 
/**
 * Check if structure can be inserted at an offset in document data.
 *
 * If the {unrestricted} param is true than only offsets where any kind of element can be inserted
 * will return true. This can be used to detect the difference between a location that a paragraph
 * can be inserted, such as between two tables but not directly inside a table.
 *
 * This method assumes that any value that has a type property that's a string is an element object.
 *
 * Structural offsets (unrestricted = false):
 *
 *      <heading> a </heading> <paragraph> b c <img> </img> </paragraph>
 *     ^         . .          ^           . . .     .      .            ^
 *
 * Structural offsets (unrestricted = true):
 *
 *      <heading> a </heading> <paragraph> b c <img> </img> </paragraph>
 *     ^         . .          ^           . . .     .      .            ^
 *
 * Structural offsets (unrestricted = false):
 *
 *      <list> <listItem> </listItem> <list>
 *     ^      ^          ^           ^      ^
 *
 * Content branch offsets (unrestricted = true):
 *
 *      <list> <listItem> </listItem> <list>
 *     ^      .          ^           .      ^
 *
 * @param {number} offset Document offset
 * @param {boolean} [unrestricted=false] Only return true if any kind of element can be inserted at offset
 * @return {boolean} Structure can be inserted at offset
 */
ve.dm.LinearData.prototype.isStructuralOffset = function ( offset, unrestricted ) {
	// Edges are always structural
	if ( offset === 0 || offset === this.getLength() ) {
		return true;
	}
	// Offsets must be within range and both sides must be elements
	const left = this.getData( offset - 1 );
	const right = this.getData( offset );
	const factory = ve.dm.nodeFactory;
	return (
		(
			left !== undefined &&
			right !== undefined &&
			typeof left.type === 'string' &&
			typeof right.type === 'string'
		) &&
		(
			// Right of a branch
			// <list><listItem><paragraph>a</paragraph>|</listItem>|</list>|
			(
				// Is a closing
				left.type.charAt( 0 ) === '/' &&
				// Is a branch or non-content leaf
				(
					factory.canNodeHaveChildren( left.type.slice( 1 ) ) ||
					!factory.isNodeContent( left.type.slice( 1 ) )
				) &&
				(
					// Only apply this rule in unrestricted mode
					!unrestricted ||
					// Right of an unrestricted branch
					// <list><listItem><paragraph>a</paragraph>|</listItem></list>|
					// Both are non-content branches that can have any kind of child
					factory.getParentNodeTypes( left.type.slice( 1 ) ) === null
				)
			) ||
			// Left of a branch
			// |<list>|<listItem>|<paragraph>a</paragraph></listItem></list>
			(
				// Is not a closing
				right.type.charAt( 0 ) !== '/' &&
				// Is a branch or non-content leaf
				(
					factory.canNodeHaveChildren( right.type ) ||
					!factory.isNodeContent( right.type )
				) &&
				(
					// Only apply this rule in unrestricted mode
					!unrestricted ||
					// Left of an unrestricted branch
					// |<list><listItem>|<paragraph>a</paragraph></listItem></list>
					// Both are non-content branches that can have any kind of child
					factory.getParentNodeTypes( right.type ) === null
				)
			) ||
			// Inside empty non-content branch
			// <list>|</list> or <list><listItem>|</listItem></list>
			(
				// Inside empty element
				'/' + left.type === right.type &&
				// Both are non-content branches (right is the same type)
				factory.canNodeHaveChildrenNotContent( left.type ) &&
				(
					// Only apply this rule in unrestricted mode
					!unrestricted ||
					// Both are non-content branches that can have any kind of child
					factory.getChildNodeTypes( left.type ) === null
				)
			)
		)
	);
};
 
/**
 * Check for non-content elements in data.
 *
 * This method assumes that any value that has a type property that's a string is an element object.
 * Elements are discovered by iterating through the entire data array.
 *
 * @return {boolean} True if all elements in data are content elements
 */
ve.dm.LinearData.prototype.isContentData = function () {
	let i = this.getLength();
	while ( i-- ) {
		const item = this.getData( i );
		if ( item.type !== undefined &&
			item.type.charAt( 0 ) !== '/' &&
			!ve.dm.nodeFactory.isNodeContent( item.type )
		) {
			return false;
		}
	}
	return true;
};
 
/**
 * Check if an annotation can be applied at a specific offset
 *
 * @param {number} offset
 * @param {ve.dm.Annotation} annotation
 * @param {boolean} [ignoreClose=false] Ignore close elements, otherwise check if their open element is annotatable
 * @return {boolean} Annotation can be applied at this offset
 */
ve.dm.LinearData.prototype.canTakeAnnotationAtOffset = function ( offset, annotation, ignoreClose ) {
	if ( this.isElementData( offset ) ) {
		if ( ignoreClose && this.isCloseElementData( offset ) ) {
			return false;
		}
		const type = this.getType( offset );
		// Structural nodes are never annotatable
		// Disallowed annotations can't be set
		return ve.dm.nodeFactory.isNodeContent( type ) && ve.dm.nodeFactory.canNodeTakeAnnotation( type, annotation );
	} else {
		// Text is always annotatable
		return true;
	}
};
 
/**
 * Get annotations' store hashes covered by an offset.
 *
 * @param {number} offset Offset to get annotations for
 * @param {boolean} [ignoreClose=false] Ignore annotations on close elements
 * @return {string[]} An array of annotation store hashes the offset is covered by
 * @throws {Error} offset out of bounds
 */
ve.dm.LinearData.prototype.getAnnotationHashesFromOffset = function ( offset, ignoreClose ) {
	if ( offset < 0 || offset > this.getLength() ) {
		throw new Error( 'offset ' + offset + ' out of bounds' );
	}
 
	// Since annotations are not stored on a closing leaf node,
	// rewind offset by 1 to return annotations for that structure
	if (
		!ignoreClose &&
		this.isCloseElementData( offset ) &&
		!ve.dm.nodeFactory.canNodeHaveChildren( this.getType( offset ) ) // Leaf node
	) {
		offset = this.getRelativeContentOffset( offset, -1 );
		Iif ( offset === -1 ) {
			return [];
		}
	}
 
	const item = this.getData( offset );
	return this.constructor.static.getAnnotationHashesFromItem( item ) || [];
};
 
/**
 * @typedef {Object} AnnotationRange
 * @memberof ve.dm.LinearData
 * @property {ve.dm.Annotation} annotation
 * @property {ve.dm.Range} range
 */
 
/**
 * Get contiguous ranges covered by annotations
 *
 * @param {ve.Range} range Range to search
 * @return {ve.dm.LinearData.AnnotationRange[]} Contiguous annotation ranges, ordered by start then end
 */
ve.dm.LinearData.prototype.getAnnotationRanges = function ( range ) {
	const annotationRanges = [];
	const startOffsets = {};
	const annotationStack = new ve.dm.AnnotationSet( this.getStore() );
	const open = ( i, ann ) => {
		const key = JSON.stringify( ann.getComparableObject() );
		startOffsets[ key ] = i;
	};
	const close = ( i, ann ) => {
		const key = JSON.stringify( ann.getComparableObject() );
		const startOffset = startOffsets[ key ];
		annotationRanges.push( {
			annotation: ann,
			range: new ve.Range( startOffset, i )
		} );
	};
	range.forEach( ( i ) => {
		const annotations = this.getAnnotationsFromOffset( i );
		ve.dm.Converter.static.openAndCloseAnnotations(
			annotationStack, annotations,
			open.bind( this, i ),
			close.bind( this, i )
		);
	} );
	// Close remaining annotations
	const emptySet = new ve.dm.AnnotationSet( this.getStore() );
	ve.dm.Converter.static.openAndCloseAnnotations(
		annotationStack, emptySet,
		open.bind( this, range.end ),
		close.bind( this, range.end )
	);
	annotationRanges.sort( ( a, b ) => a.range.start - b.range.start || a.range.end - b.range.end );
	return annotationRanges;
};
 
/**
 * Get annotations covered by an offset.
 *
 * The returned AnnotationSet is a clone of the one in the data.
 *
 * @param {number} offset Offset to get annotations for
 * @param {boolean} [ignoreClose=false] Ignore annotations on close elements
 * @return {ve.dm.AnnotationSet} A set of all annotation objects offset is covered by
 * @throws {Error} offset out of bounds
 */
ve.dm.LinearData.prototype.getAnnotationsFromOffset = function ( offset, ignoreClose ) {
	return new ve.dm.AnnotationSet( this.getStore(), this.getAnnotationHashesFromOffset( offset, ignoreClose ) );
};
 
/**
 * Set annotations of data at a specified offset.
 *
 * Cleans up data structure if annotation set is empty.
 *
 * @param {number} offset Offset to set annotations at
 * @param {ve.dm.AnnotationSet} annotations Annotations to set
 */
ve.dm.LinearData.prototype.setAnnotationsAtOffset = function ( offset, annotations ) {
	this.setAnnotationHashesAtOffset( offset, this.getStore().hashAll( annotations.get() ) );
};
 
/**
 * Set annotations' store hashes at a specified offset.
 *
 * Cleans up data structure if hashes array is empty.
 *
 * @param {number} offset Offset to set annotation hashes at
 * @param {string[]} hashes Annotations' store hashes
 */
ve.dm.LinearData.prototype.setAnnotationHashesAtOffset = function ( offset, hashes ) {
	let item = this.getData( offset );
	item = this.constructor.static.replaceAnnotationHashesForItem( item, hashes );
	this.setData( offset, item );
};
 
/**
 * Set or unset an attribute at a specified offset.
 *
 * @param {number} offset Offset to set/unset attribute at
 * @param {string} key Attribute name
 * @param {any} value Value to set, or undefined to unset
 */
ve.dm.LinearData.prototype.setAttributeAtOffset = function ( offset, key, value ) {
	Iif ( !this.isElementData( offset ) ) {
		return;
	}
	this.modifyData( offset, ( item ) => {
		if ( value === undefined ) {
			// Clear
			Eif ( item.attributes ) {
				delete item.attributes[ key ];
			}
		} else {
			// Automatically initialize attributes object
			Iif ( !item.attributes ) {
				item.attributes = {};
			}
			// Set
			item.attributes[ key ] = value;
		}
	} );
};
 
/**
 * Get character data at a specified offset
 *
 * @param {number} offset Offset to get character data from
 * @return {string} Character data
 */
ve.dm.LinearData.prototype.getCharacterData = function ( offset ) {
	const item = this.getData( offset );
	return ve.dm.LinearData.static.getCharacterDataFromItem( item );
};
 
/**
 * Gets the range of content surrounding a given offset that's covered by a given annotation.
 *
 * @param {number} offset Offset to begin looking forward and backward from
 * @param {ve.dm.Annotation} annotation Annotation to test for coverage with
 * @return {ve.Range|null} Range of content covered by annotation, or null if offset is not covered
 */
ve.dm.LinearData.prototype.getAnnotatedRangeFromOffset = function ( offset, annotation ) {
	Iif ( this.getAnnotationsFromOffset( offset ).contains( annotation ) === false ) {
		return null;
	}
	return new ve.Range( offset ).expandCallback( ( i ) => this.getAnnotationsFromOffset( i ).contains( annotation ), this.getRange() );
};
 
/**
 * Get the range of an annotation found within a range.
 *
 * @param {ve.Range} range Range to begin looking forward and backward from
 * @param {ve.dm.Annotation} annotation Annotation to test for coverage with
 * @return {ve.Range|null} Range of content covered by annotation, or a copy of the range
 */
ve.dm.LinearData.prototype.getAnnotatedRangeFromRange = function ( range, annotation ) {
	return range.expandCallback( ( i ) => this.getAnnotationsFromOffset( i ).contains( annotation ), this.getRange() );
};
 
// Deprecated alias
ve.dm.LinearData.prototype.getAnnotatedRangeFromSelection = ve.dm.LinearData.prototype.getAnnotatedRangeFromRange;
 
/**
 * Get annotations common to all content in a range.
 *
 * @param {ve.Range} [range] Range to get annotations for. The whole data set if not specified.
 * @param {boolean} [all=false] Get all annotations found within the range, not just those that cover it
 * @param {boolean} [nullIfContentEmpty=false] Returns null (instead of an empty ve.dm.AnnotationSet) if
 *  there is no content in the range.
 * @return {ve.dm.AnnotationSet|null} All annotation objects range is covered by.
 */
ve.dm.LinearData.prototype.getAnnotationsFromRange = function ( range, all, nullIfContentEmpty ) {
	range = range || this.getRange();
 
	let ignoreChildrenDepth = 0;
	let left, right;
	// Iterator over the range, looking for annotations, starting at the 2nd character
	for ( let i = range.start; i < range.end; i++ ) {
		if ( this.isElementData( i ) ) {
			if ( ve.dm.nodeFactory.shouldIgnoreChildren( this.getType( i ) ) ) {
				ignoreChildrenDepth += this.isOpenElementData( i ) ? 1 : -1;
			}
			// Skip non-content data
			if ( !ve.dm.nodeFactory.isNodeContent( this.getType( i ) ) ) {
				continue;
			}
		}
		// Ignore things inside ignoreChildren nodes
		if ( ignoreChildrenDepth > 0 ) {
			continue;
		}
		if ( !left ) {
			// Look at left side of range for annotations
			left = this.getAnnotationsFromOffset( i );
			// Shortcut for single character and zero-length ranges
			if ( range.getLength() === 0 || range.getLength() === 1 ) {
				return left;
			}
			continue;
		}
		// Current character annotations
		right = this.getAnnotationsFromOffset( i );
		if ( all && !right.isEmpty() ) {
			left.addSet( right );
		} else if ( !all ) {
			// A non annotated character indicates there's no full coverage
			if ( right.isEmpty() ) {
				return new ve.dm.AnnotationSet( this.getStore() );
			}
			// Exclude comparable annotations that are in left but not right
			left = left.getComparableAnnotationsFromSet( right );
			// If we've reduced left down to nothing, just stop looking
			if ( left.isEmpty() ) {
				break;
			}
		}
	}
	return left || ( nullIfContentEmpty ? null : new ve.dm.AnnotationSet( this.getStore() ) );
};
 
/**
 * Get the insertion annotations that should apply to a range.
 *
 * The semantics are intended to match Chromium's behaviour.
 * TODO: This cannot match Firefox behaviour, which depends on the cursor's annotation
 * boundary side, and performs a union of the annotations at each end of the selection;
 * see https://phabricator.wikimedia.org/T113869 .
 *
 * @param {ve.Range} range The range into which text would be inserted
 * @param {boolean} [startAfterAnnotations=false] Use annotations after cursor if collapsed
 * @return {ve.dm.AnnotationSet} The insertion annotations that should apply
 */
ve.dm.LinearData.prototype.getInsertionAnnotationsFromRange = function ( range, startAfterAnnotations ) {
	let start;
	// Get position for start annotations
	if ( range.isCollapsed() && !startAfterAnnotations ) {
		// Use the position just before the cursor
		start = Math.max( 0, range.start - 1 );
	} else {
		// If uncollapsed, use the first character of the selection
		// If collapsed, use the first position after the cursor
		start = range.start;
	}
 
	let startAnnotations;
	// Get startAnnotations: the annotations that apply at the selection start
	if ( this.isContentOffset( start ) ) {
		startAnnotations = this.getAnnotationsFromOffset( start );
	} else {
		startAnnotations = new ve.dm.AnnotationSet( this.getStore() );
	}
 
	let afterAnnotations;
	// Get afterAnnotations: the annotations that apply straight after the selection
	if ( this.isContentOffset( range.end ) ) {
		afterAnnotations = this.getAnnotationsFromOffset( range.end );
	} else {
		// Use the empty set
		afterAnnotations = new ve.dm.AnnotationSet( this.getStore() );
	}
 
	// Return those startAnnotations that either continue in afterAnnotations or
	// should get added to appended content
	return startAnnotations.filter(
		( annotation ) => annotation.constructor.static.applyToInsertedContent &&
			( annotation.constructor.static.applyToAppendedContent || afterAnnotations.containsComparable( annotation ) )
	);
};
 
/**
 * Check if the range has any annotations
 *
 * @param {ve.Range} range Range to check for annotations
 * @return {boolean} The range contains at least one annotation
 */
ve.dm.LinearData.prototype.hasAnnotationsInRange = function ( range ) {
	return range.some( ( i ) => this.getAnnotationHashesFromOffset( i, true ).length );
};
 
/**
 * Get a range without any whitespace content at the beginning and end.
 *
 * @param {ve.Range} range Range to trim
 * @return {Object} Trimmed range
 */
ve.dm.LinearData.prototype.trimOuterSpaceFromRange = function ( range ) {
	return range.trimCallback( ( i ) => /^\s+$/.test( this.getCharacterData( i ) ) );
};
 
/**
 * Check if the data is just text
 *
 * @param {ve.Range} [range] Range to get the data for. The whole data set if not specified.
 * @param {boolean} [ignoreNonContentNodes=false] Ignore all non-content nodes, e.g. paragraphs, headings, lists
 * @param {string[]} [ignoredTypes] Only ignore specific non-content types
 * @param {boolean} [ignoreCoveringAnnotations=false] Ignore covering annotations
 * @param {boolean} [ignoreAllAnnotations=false] Ignore all annotations
 * @return {boolean} The data is plain text
 */
ve.dm.LinearData.prototype.isPlainText = function ( range, ignoreNonContentNodes, ignoredTypes, ignoreCoveringAnnotations, ignoreAllAnnotations ) {
	range = range || this.getRange();
 
	let annotations;
	if ( ignoreCoveringAnnotations ) {
		annotations = this.getAnnotationsFromRange( range );
	}
 
	return range.every( ( i ) => {
		if ( typeof this.data[ i ] === 'string' ) {
			// Un-annotated text
			return true;
		} else if ( Array.isArray( this.data[ i ] ) ) {
			// Annotated text
			if ( ignoreAllAnnotations ) {
				return true;
			}
			if (
				ignoreCoveringAnnotations &&
				annotations.containsAllOf( this.getAnnotationsFromOffset( i ) )
			) {
				return true;
			}
		} else if ( ignoreNonContentNodes || ignoredTypes ) {
			// Element data
			const type = this.getType( i );
			if ( ignoredTypes && ignoredTypes.includes( type ) ) {
				return true;
			}
			if ( ignoreNonContentNodes && !ve.dm.nodeFactory.isNodeContent( type ) ) {
				return true;
			}
		}
		return false;
	} );
};
 
/**
 * Execute a callback function for each group of consecutive content data (text or content element).
 *
 * @param {ve.Range} range Range in which to search
 * @param {Function} callback Function called with the following parameters:
 * @param {number} callback.offset Offset of the first datum of the run.
 * @param {string} callback.text Text of the run (with content element opening/closing data
 *   replaced with U+FFFC).
 */
ve.dm.LinearData.prototype.forEachRunOfContent = function ( range, callback ) {
	let text = '';
	range.forEach( ( i ) => {
		if ( !this.isElementData( i ) ) {
			text += this.getCharacterData( i );
		} else if ( ve.dm.nodeFactory.isNodeContent( this.getType( i ) ) ) {
			text += '\uFFFC'; // U+FFFC OBJECT REPLACEMENT CHARACTER
		} else {
			if ( text ) {
				callback( i - text.length, text );
			}
			text = '';
		}
	} );
	Iif ( text ) {
		callback( range.end - text.length, text );
	}
};
 
/**
 * Get the data as plain text
 *
 * @param {boolean} [maintainIndices=false] Maintain data offset to string index alignment by replacing elements with line breaks
 * @param {ve.Range} [range] Range to get the data for. The whole data set if not specified.
 * @return {string} Data as plain text
 */
ve.dm.LinearData.prototype.getText = function ( maintainIndices, range ) {
	range = range || this.getRange();
 
	let text = '';
	range.forEach( ( i ) => {
		if ( !this.isElementData( i ) ) {
			text += this.getCharacterData( i );
		} else if ( maintainIndices ) {
			text += '\n';
		}
	} );
	return text;
};
 
/**
 * Get the data as original source text (source mode only)
 *
 * Split paragraphs are converted to single line breaks. It is assumed the
 * document contains nothing but plain text and paragraph elements.
 *
 * @param {ve.Range} [range] Range to get the data for. The whole data set if not specified.
 * @return {string} Data as original source text
 */
ve.dm.LinearData.prototype.getSourceText = function ( range ) {
	return ve.dm.sourceConverter.getSourceTextFromDataRange( this.data, range );
};
 
/**
 * Get an offset at a distance to an offset that passes a validity test.
 *
 * - If {offset} is not already valid, one step will be used to move it to a valid one.
 * - If {offset} is already valid and cannot be moved in the direction of {distance} and still be
 *   valid, it will be left where it is
 * - If {distance} is zero the result will either be {offset} if it's already valid or the
 *   nearest valid offset to the right if possible and to the left otherwise.
 * - If {offset} is after the last valid offset and {distance} is >= 1, or if {offset} if
 *   before the first valid offset and {distance} <= 1 than the result will be the nearest
 *   valid offset in the opposite direction.
 * - If the data does not contain a single valid offset the result will be -1
 *
 * Nodes that want their children to be ignored (see ve.dm.Node#static-ignoreChildren) are not
 * descended into. Giving a starting offset inside an ignoreChildren node will give unpredictable
 * results.
 *
 * @param {number} offset Offset to start from
 * @param {number} distance Number of valid offsets to move
 * @param {Function} callback Function to call to check if an offset is valid which will be
 * given initial argument of offset
 * @param {...any} [args] Additional arguments to pass to the callback
 * @return {number} Relative valid offset or -1 if there are no valid offsets in data
 */
ve.dm.LinearData.prototype.getRelativeOffset = function ( offset, distance, callback, ...args ) {
	// If offset is already a structural offset and distance is zero than no further work is needed,
	// otherwise distance should be 1 so that we can get out of the invalid starting offset
	if ( distance === 0 ) {
		if ( callback.call( this, offset, ...args ) ) {
			return offset;
		} else {
			distance = 1;
		}
	}
	// Initial values
	let direction = (
		offset <= 0 ? 1 : (
			offset >= this.getLength() ? -1 : (
				distance > 0 ? 1 : -1
			)
		)
	);
	distance = Math.abs( distance );
	const start = offset;
	let i = start + direction;
	offset = -1;
	let steps = 0;
	let ignoreChildrenDepth = 0;
	let turnedAround = false;
	// Iteration
	while ( i >= 0 && i <= this.getLength() ) {
		// Detect when the search for a valid offset enters a node whose children should be
		// ignored, and don't return an offset inside such a node. This clearly won't work
		// if you start inside such a node, but you shouldn't be doing that to being with
		const dataOffset = i + ( direction > 0 ? -1 : 0 );
		if (
			this.isElementData( dataOffset ) &&
			ve.dm.nodeFactory.shouldIgnoreChildren( this.getType( dataOffset ) )
		) {
			const isOpen = this.isOpenElementData( dataOffset );
			// We have entered a node if we step right over an open, or left over a close.
			// Otherwise we have left a node
			if ( ( direction > 0 && isOpen ) || ( direction < 0 && !isOpen ) ) {
				ignoreChildrenDepth++;
			} else {
				ignoreChildrenDepth--;
				if ( ignoreChildrenDepth < 0 ) {
					return -1;
				}
			}
		}
		if ( callback.call( this, i, ...args ) ) {
			if ( !ignoreChildrenDepth ) {
				steps++;
				offset = i;
				if ( distance === steps ) {
					return offset;
				}
			}
		} else if (
			// Don't keep turning around over and over
			!turnedAround &&
			// Only turn around if not a single step could be taken
			steps === 0 &&
			// Only turn around if we're about to reach the edge
			( ( direction < 0 && i === 0 ) || ( direction > 0 && ( i === this.getLength() || this.getType( i - 1 ) === 'internalList' ) ) )
		) {
			// Before we turn around, let's see if we are at a valid position
			if ( callback.call( this, start, ...args ) ) {
				// Stay where we are
				return start;
			}
			// Start over going in the opposite direction
			direction *= -1;
			i = start;
			distance = 1;
			turnedAround = true;
			ignoreChildrenDepth = 0;
		}
		i += direction;
	}
	return offset;
};
 
/**
 * Get a content offset at a distance from an offset.
 *
 * This method is a wrapper around {getRelativeOffset}, using {isContentOffset} as
 * the offset validation callback.
 *
 * @param {number} offset Offset to start from
 * @param {number} distance Number of content offsets to move
 * @return {number} Relative content offset or -1 if there are no valid offsets in data
 */
ve.dm.LinearData.prototype.getRelativeContentOffset = function ( offset, distance ) {
	return this.getRelativeOffset( offset, distance, this.constructor.prototype.isContentOffset );
};
 
/**
 * Get the nearest content offset to an offset.
 *
 * If the offset is already a valid offset, it will be returned unchanged. This method differs from
 * calling {getRelativeContentOffset} with a zero length difference because the direction can be
 * controlled without necessarily moving the offset if it's already valid. Also, if the direction
 * is 0 or undefined than nearest offsets will be found to the left and right and the one with the
 * shortest distance will be used.
 *
 * @param {number} offset Offset to start from
 * @param {number} [direction] Direction to prefer matching offset in, -1 for left and 1 for right
 * @return {number} Nearest content offset or -1 if there are no valid offsets in data
 */
ve.dm.LinearData.prototype.getNearestContentOffset = function ( offset, direction ) {
	if ( this.isContentOffset( offset ) ) {
		return offset;
	}
	if ( direction === undefined ) {
		const left = this.getRelativeContentOffset( offset, -1 );
		const right = this.getRelativeContentOffset( offset, 1 );
		return offset - left < right - offset ? left : right;
	} else {
		return this.getRelativeContentOffset( offset, direction > 0 ? 1 : -1 );
	}
};
 
/**
 * Get a structural offset at a distance from an offset.
 *
 * This method is a wrapper around {getRelativeOffset}, using {this.isStructuralOffset} as
 * the offset validation callback.
 *
 * @param {number} offset Offset to start from
 * @param {number} distance Number of structural offsets to move
 * @param {boolean} [unrestricted=false] Only consider offsets where any kind of element can be inserted
 * @return {number} Relative structural offset
 */
ve.dm.LinearData.prototype.getRelativeStructuralOffset = function ( offset, distance, unrestricted ) {
	// Optimization: start and end are always unrestricted structural offsets
	if ( distance === 0 && ( offset === 0 || offset === this.getLength() ) ) {
		return offset;
	}
	return this.getRelativeOffset(
		offset, distance, this.constructor.prototype.isStructuralOffset, unrestricted
	);
};
 
/**
 * Get the nearest structural offset to an offset.
 *
 * If the offset is already a valid offset, it will be returned unchanged. This method differs from
 * calling {getRelativeStructuralOffset} with a zero length difference because the direction can be
 * controlled without necessarily moving the offset if it's already valid. Also, if the direction
 * is 0 or undefined than nearest offsets will be found to the left and right and the one with the
 * shortest distance will be used.
 *
 * @param {number} offset Offset to start from
 * @param {number} [direction] Direction to prefer matching offset in, -1 for left and 1 for right
 * @param {boolean} [unrestricted=false] Only consider offsets where any kind of element can be inserted
 * @return {number} Nearest structural offset
 */
ve.dm.LinearData.prototype.getNearestStructuralOffset = function ( offset, direction, unrestricted ) {
	if ( this.isStructuralOffset( offset, unrestricted ) ) {
		return offset;
	}
	if ( !direction ) {
		const left = this.getRelativeStructuralOffset( offset, -1, unrestricted );
		const right = this.getRelativeStructuralOffset( offset, 1, unrestricted );
		return offset - left < right - offset ? left : right;
	} else {
		return this.getRelativeStructuralOffset( offset, direction > 0 ? 1 : -1, unrestricted );
	}
};
 
/**
 * Get the range of the word at offset (else a collapsed range)
 *
 * First, if the offset is not a content offset then it will be moved to the nearest one.
 * Then, if the offset is inside a word, it will be expanded to that word;
 * else if the offset is at the end of a word, it will be expanded to that word;
 * else if the offset is at the start of a word, it will be expanded to that word;
 * else the offset is not adjacent to any word and is returned as a collapsed range.
 *
 * @param {number} offset Offset to start from; must not be inside a surrogate pair
 * @return {ve.Range} Boundaries of the adjacent word (else offset as collapsed range)
 */
ve.dm.LinearData.prototype.getWordRange = function ( offset ) {
	const dataString = new ve.dm.DataString( this.getData() );
 
	offset = this.getNearestContentOffset( offset );
 
	let range;
	if ( unicodeJS.wordbreak.isBreak( dataString, offset ) ) {
		// The cursor offset is not inside a word. See if there is an adjacent word
		// codepoint (checking two chars to allow surrogate pairs). If so, expand in that
		// direction only (preferring backwards if there are word codepoints on both
		// sides).
 
		const isAfterWord = this.constructor.static.endWordRegExp.exec(
			( dataString.read( offset - 2 ) || ' ' ) +
			( dataString.read( offset - 1 ) || ' ' )
		);
		const isBeforeWord = this.constructor.static.startWordRegExp.exec(
			( dataString.read( offset ) || ' ' ) +
			( dataString.read( offset + 1 ) || ' ' )
		);
 
		if ( isAfterWord && !isBeforeWord ) {
			// Cursor is immediately after a word codepoint: expand backwards
			range = new ve.Range(
				unicodeJS.wordbreak.prevBreakOffset( dataString, offset ),
				offset
			);
		} else if ( isBeforeWord && !isAfterWord ) {
			// Cursor is immediately before a word codepoint: expand forwards
			range = new ve.Range(
				offset,
				unicodeJS.wordbreak.nextBreakOffset( dataString, offset )
			);
		} else {
			// Cursor is not adjacent to a word codepoint, or there
			// are words either side (T382144): do not expand
			return new ve.Range( offset );
		}
	} else {
		// Cursor is inside a word: expand both backwards and forwards
		range = new ve.Range(
			unicodeJS.wordbreak.prevBreakOffset( dataString, offset ),
			unicodeJS.wordbreak.nextBreakOffset( dataString, offset )
		);
	}
	// Range expanded to all whitespace: collapse
	if ( this.getText( false, range ).trim().length === 0 ) {
		return new ve.Range( offset );
	}
	return range;
};
 
/**
 * Remap the internal list indexes used in this linear data.
 *
 * Calls remapInternalListIndexes() for each node.
 *
 * @param {Object} mapping Mapping from internal list indexes to internal list indexes
 * @param {ve.dm.InternalList} internalList Internal list the indexes are being mapped into.
 *  Used for refreshing attribute values that were computed with getNextUniqueNumber().
 */
ve.dm.LinearData.prototype.remapInternalListIndexes = function ( mapping, internalList ) {
	for ( let i = 0, ilen = this.data.length; i < ilen; i++ ) {
		if ( this.isOpenElementData( i ) ) {
			const nodeClass = ve.dm.nodeFactory.lookup( this.getType( i ) );
			this.modifyData( i, ( item ) => {
				nodeClass.static.remapInternalListIndexes( item, mapping, internalList );
			} );
		}
	}
};
 
/**
 * Remap the internal list keys used in this linear data.
 *
 * Calls remapInternalListKeys() for each node.
 *
 * @param {ve.dm.InternalList} internalList Internal list the keys are being mapped into.
 */
ve.dm.LinearData.prototype.remapInternalListKeys = function ( internalList ) {
	for ( let i = 0, ilen = this.data.length; i < ilen; i++ ) {
		if ( this.isOpenElementData( i ) ) {
			const nodeClass = ve.dm.nodeFactory.lookup( this.getType( i ) );
			this.modifyData( i, ( item ) => {
				nodeClass.static.remapInternalListKeys( item, internalList );
			} );
		}
	}
};
 
/**
 * Remap an annotation hash when it changes
 *
 * @param {string} oldHash Old hash to replace
 * @param {string} newHash New hash to replace it with
 */
ve.dm.LinearData.prototype.remapAnnotationHash = function ( oldHash, newHash ) {
	function remap( annotations ) {
		let spliceAt;
		while ( ( spliceAt = annotations.indexOf( oldHash ) ) !== -1 ) {
			if ( !annotations.includes( newHash ) ) {
				annotations.splice( spliceAt, 1, newHash );
			} else {
				annotations.splice( spliceAt, 1 );
			}
		}
	}
	for ( let i = 0, ilen = this.data.length; i < ilen; i++ ) {
		if ( this.data[ i ] === undefined || typeof this.data[ i ] === 'string' ) {
			// Common case, cheap, avoid the isArray check
			continue;
		} else {
			this.modifyData( i, ( item ) => {
				if ( Array.isArray( item ) ) {
					remap( item[ 1 ] );
				} else if ( item.annotations !== undefined ) {
					remap( item.annotations );
				}
				if ( ve.getProp( item, 'internal', 'metaItems' ) ) {
					const data = ve.getProp( item, 'internal', 'metaItems' );
					for ( let j = 0, jlen = data.length; j < jlen; j++ ) {
						Iif ( data[ j ].annotations !== undefined ) {
							remap( data[ j ].annotations );
						}
					}
				}
			} );
		}
	}
};
 
/**
 * Sanitize data according to a set of rules.
 *
 * @param {Object} rules Sanitization rules
 * @param {string[]} [rules.blacklist] Blacklist of model types which aren't allowed
 * @param {Object} [rules.conversions] Model type conversions to apply, e.g. { heading: 'paragraph' }
 * @param {boolean} [rules.removeOriginalDomElements=false] Remove references to DOM elements data was converted from
 * @param {boolean} [rules.plainText=false] Remove all formatting for plain text import
 * @param {boolean} [rules.allowBreaks=false] Allow <br> line breaks, otherwise the node will be split
 * @param {boolean} [rules.preserveHtmlWhitespace=false] Preserve non-semantic HTML whitespace
 * @param {boolean} [rules.nodeSanitization=false] Apply per-type node sanitizations via ve.dm.Node#sanitize
 * @param {boolean} [rules.keepEmptyContentBranches=false] Preserve empty content branch nodes
 * @param {boolean} [rules.singleLine=false] Don't allow more that one ContentBranchNode
 * @param {boolean} [rules.allowMetaData] Don't strip metadata
 */
ve.dm.LinearData.prototype.sanitize = function ( rules ) {
	const elementStack = [],
		store = this.getStore(),
		allAnnotations = this.getAnnotationsFromRange( this.getRange(), true );
 
	let emptySet, setToRemove;
	if ( rules.plainText ) {
		emptySet = new ve.dm.AnnotationSet( store );
	} else {
		if ( rules.removeOriginalDomElements ) {
			// Remove originalDomElements from annotations
			for ( let i = 0, len = allAnnotations.getLength(); i < len; i++ ) {
				const ann = allAnnotations.get( i );
				Eif ( ann.element.originalDomElementsHash !== undefined ) {
					// This changes the hash of the value, so we have to
					// update that. If we don't do this, other assumptions
					// that values fetched from the store are actually in the
					// store will fail.
					const oldHash = store.hashOfValue( ann );
					delete allAnnotations.get( i ).element.originalDomElementsHash;
					const newHash = store.replaceHash( oldHash, ann );
					this.remapAnnotationHash( oldHash, newHash );
					Iif ( allAnnotations.storeHashes.includes( newHash ) ) {
						// New annotation-value was already in the set, which
						// just reduces the effective-length of the set.
						allAnnotations.storeHashes.splice( i, 1 );
						i--;
						len--;
					} else {
						allAnnotations.storeHashes.splice( i, 1, newHash );
					}
				}
			}
		}
 
		// Create annotation set to remove from blacklist
		setToRemove = allAnnotations.filter( ( annotation ) => (
			rules.blacklist && rules.blacklist[ annotation.name ]
		) || (
		// If original DOM element references are being removed, remove spans
			annotation.name === 'textStyle/span' && rules.removeOriginalDomElements
		) );
	}
 
	let contentElement;
	for ( let i = 0, len = this.getLength(); i < len; i++ ) {
		if ( this.isElementData( i ) ) {
			let type = this.getType( i );
			const canContainContent = ve.dm.nodeFactory.canNodeContainContent( type );
			const isOpen = this.isOpenElementData( i );
 
			if ( isOpen ) {
				elementStack.push( this.getData( i ) );
			} else {
				elementStack.pop();
			}
			// Apply type conversions
			if ( rules.conversions && rules.conversions[ type ] ) {
				type = rules.conversions[ type ];
				this.modifyData( i, ( item ) => {
					item.type = ( !isOpen ? '/' : '' ) + type;
				} );
			}
 
			// Convert content-containing non-paragraph nodes to paragraphs in plainText mode
			if ( rules.plainText && type !== 'paragraph' && canContainContent ) {
				type = 'paragraph';
				this.setData( i, {
					type: ( this.isCloseElementData( i ) ? '/' : '' ) + type
				} );
			}
 
			// Remove blacklisted nodes, and metadata if disallowed
			if (
				( rules.blacklist && rules.blacklist[ type ] ) ||
				( rules.plainText && type !== 'paragraph' && type !== 'internalList' ) ||
				( !rules.allowMetadata && ve.dm.nodeFactory.isMetaData( type ) )
			) {
				this.splice( i, 1 );
				len--;
				// Make sure you haven't just unwrapped a wrapper paragraph
				if ( isOpen ) {
					this.modifyData( i, ( item ) => {
						ve.deleteProp( item, 'internal', 'generated' );
					} );
				}
				// Move pointer back and continue
				i--;
				continue;
			}
 
			// Split on breaks
			if ( !rules.allowBreaks && type === 'break' && contentElement ) {
				if ( this.isOpenElementData( i - 1 ) && this.isCloseElementData( i + 2 ) ) {
					// If the break is the only element in another element it was likely added
					// to force it open, so remove it.
					this.splice( i, 2 );
					len -= 2;
				} else {
					this.splice( i, 2, { type: '/' + contentElement.type }, ve.copy( contentElement ) );
				}
				// Move pointer back and continue
				i--;
				continue;
			}
 
			// If a node is empty but can contain content, then just remove it
			if (
				!rules.keepEmptyContentBranches &&
				isOpen && this.isCloseElementData( i + 1 ) &&
				!ve.getProp( this.getData( i ), 'internal', 'generated' ) &&
				canContainContent
			) {
				this.splice( i, 2 );
				len -= 2;
				// Move pointer back and continue
				i--;
				continue;
			}
 
			if ( !rules.preserveHtmlWhitespace ) {
				this.modifyData( i, ( item ) => {
					ve.deleteProp( item, 'internal', 'whitespace' );
				} );
			}
 
			if ( canContainContent && !isOpen && rules.singleLine ) {
				i++;
				const start = i;
				while ( i < len && !( this.isOpenElementData( i ) && this.getType( i ) === 'internalList' ) ) {
					i++;
				}
				this.splice( start, i - start );
				break;
			}
 
			// Store the current contentElement for splitting
			if ( canContainContent ) {
				contentElement = isOpen ? this.getData( i ) : null;
			}
		} else {
			// Support: Firefox
			// Remove plain newline characters, as they are semantically meaningless
			// and will confuse the user. Firefox adds these automatically when copying
			// line-wrapped HTML. T104790
			// However, don't remove them if we're in a situation where they might
			// actually be meaningful -- i.e. if we're inside a <pre>. T132006
			if (
				this.getCharacterData( i ) === '\n' &&
				// Get last open type from the stack
				!ve.dm.nodeFactory.doesNodeHaveSignificantWhitespace( elementStack[ elementStack.length - 1 ].type )
			) {
				if ( /^\s+$/.test( this.getCharacterData( i + 1 ) ) ||
					/^\s+$/.test( this.getCharacterData( i - 1 ) )
				) {
					// If whitespace-adjacent, remove the newline to avoid double spaces
					this.splice( i, 1 );
					len--;
					// Move pointer back and continue
					i--;
					continue;
				} else {
					// …otherwise replace it with a space
					if ( typeof this.getData( i ) === 'string' ) {
						this.setData( i, ' ' );
					} else {
						this.modifyData( i, ( item ) => {
							item[ 0 ] = ' ';
						} );
					}
				}
			}
			// Support: Chrome, Safari
			// Sometimes all spaces are replaced with NBSP by the browser, so replace those
			// which aren't adjacent to plain spaces. T183647
			if (
				this.getCharacterData( i ) === '\u00a0' &&
				// Get last open type from the stack
				!ve.dm.nodeFactory.doesNodeHaveSignificantWhitespace( elementStack[ elementStack.length - 1 ].type )
			) {
				if ( !( this.getCharacterData( i + 1 ) === ' ' || this.getCharacterData( i - 1 ) === ' ' ) ) {
					// Replace with a space
					if ( typeof this.getData( i ) === 'string' ) {
						this.setData( i, ' ' );
					} else {
						this.modifyData( i, ( item ) => {
							item[ 0 ] = ' ';
						} );
					}
				}
			}
		}
		const annotations = this.getAnnotationsFromOffset( i, true );
		if ( !annotations.isEmpty() ) {
			if ( rules.plainText ) {
				this.setAnnotationsAtOffset( i, emptySet );
			} else if ( setToRemove.getLength() ) {
				// Remove blacklisted annotations
				annotations.removeSet( setToRemove );
				this.setAnnotationsAtOffset( i, annotations );
			}
		}
		if ( this.isOpenElementData( i ) ) {
			if ( rules.nodeSanitization ) {
				const nodeClass = ve.dm.modelRegistry.lookup( this.getType( i ) );
				// Perform per-class sanitizations:
				this.modifyData( i, ( item ) => {
					nodeClass.static.sanitize( item, rules );
				} );
			}
			if ( rules.removeOriginalDomElements ) {
				this.modifyData( i, ( item ) => {
					// Remove originalDomElements from nodes
					delete item.originalDomElementsHash;
				} );
			}
			// Remove metadata if disallowed (moved metadata)
			if ( !rules.allowMetadata ) {
				this.modifyData( i, ( item ) => {
					ve.deleteProp( item, 'internal', 'metaItems' );
				} );
			}
		}
	}
};
 
/**
 * Run all elements through getClonedElement(). This should be done if
 * you intend to insert the sliced data back into the document as a copy
 * of the original data (e.g. for copy and paste).
 *
 * @param {boolean} preserveGenerated Preserve internal.generated properties of elements
 */
ve.dm.LinearData.prototype.cloneElements = function ( preserveGenerated ) {
	const store = this.getStore();
	for ( let i = 0, len = this.getLength(); i < len; i++ ) {
		if ( this.isOpenElementData( i ) ) {
			const nodeClass = ve.dm.nodeFactory.lookup( this.getType( i ) );
			Eif ( nodeClass ) {
				this.setData( i, nodeClass.static.cloneElement( this.getData( i ), store, preserveGenerated ) );
			}
		}
	}
};
 
/**
 * Counts all elements that aren't between internalList and /internalList
 *
 * @param {number} [limit] Number of elements after which to stop counting
 * @return {number} Number of elements that aren't in an internalList
 */
ve.dm.LinearData.prototype.countNonInternalElements = function ( limit ) {
	let internalDepth = 0,
		count = 0;
	for ( let i = 0, l = this.getLength(); i < l; i++ ) {
		const type = this.getType( i );
		if ( type && ve.dm.nodeFactory.isNodeInternal( type ) ) {
			if ( this.isOpenElementData( i ) ) {
				internalDepth++;
			} else {
				internalDepth--;
			}
		} else if ( !internalDepth ) {
			count++;
			if ( limit && count >= limit ) {
				return count;
			}
		}
	}
	return count;
};
 
/**
 * Checks if the document has content that's not part of an internalList.
 *
 * @return {boolean} The document has content
 */
ve.dm.LinearData.prototype.hasContent = function () {
	// Two or less elements (<p>, </p>) is considered an empty document
	// For performance, abort the count when we reach 3.
	return this.countNonInternalElements( 3 ) > 2 ||
		// Also check that the element is not a content branch node, e.g. a blockImage
		// and also that is not the internal list
		(
			this.isElementData( 0 ) &&
			!ve.dm.nodeFactory.canNodeContainContent( this.getType( 0 ) ) &&
			!ve.dm.nodeFactory.isNodeInternal( this.getType( 0 ) )
		);
};
 
/**
 * Get the length of the common start sequence of annotations that applies to a whole range
 *
 * @param {ve.Range} range The document range
 * @return {number} Common start sequence length (0 if the range is empty)
 */
ve.dm.LinearData.prototype.getCommonAnnotationArrayLength = function ( range ) {
	const annotationHashesForOffset = range.map( ( i ) => this.getAnnotationHashesFromOffset( i ) );
	return ve.getCommonStartSequenceLength( annotationHashesForOffset );
};