all files / src/dm/lineardata/ ve.dm.ElementLinearData.js

97.9% Statements 467/477
96.4% Branches 429/445
100% Functions 43/43
97.9% Lines 467/477
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                                    1891×                                                     362×     362× 97×   362× 90×   362× 155×     207×   26×       181×         176×   133× 133×   133× 133×   133×     43×                                 933×   933×     932×   932×   226×   706×   530×   176× 42×     134× 53×   134× 53×   134× 81×   134× 81×     134× 134×   134×                 10804× 6645× 4159× 14× 4145× 1277×   2868×                         490×   490× 490× 490× 415×   21×     394× 394×     75×   27×     48×     490×                 19887× 19887×                                             8660×   8660× 697×   7963× 7963× 7963× 7963×                                                                                                                                                         593×   593× 57×     536× 536× 536× 536×                                                                                                                                               11× 11×                               433× 433× 56× 14×   42×     42×     377×                       10595× 10595×         10593×         72× 72×         10593× 10593×                         10092×                     167×                     279× 279× 279×                   41× 41×     41×         39×       39×                   19445× 19445×                             13×   10×                     28×   28× 40× 40× 28× 28×     28× 47× 28×   19×   28×                   693×   693× 4591× 1865× 28×     1865× 1750×       2841× 88×   2753×   645×   645× 75×   570×     2108× 2108× 307× 1801×   181× 67×     114×   114×       551×                             2439×     2439×   1746×       693×       2439× 1702×   737×       2439× 2238×     201×         2439× 190×                                         16×   16× 19×   16×   16×                         66×   66×   66× 44×     66× 279×   130× 149×   50× 32×   18×       13×   99×   97× 97×   95× 91×     11×   55×                       26×     26× 1390× 1162× 228× 24×   204× 102×   204×     26×                       2269× 2269×   2269× 12698× 9966× 2732× 986×     2269×                                                                           688×                 688× 40× 17×   23×       671×             671× 671× 671×   671×       1391× 1391×       19×     19×   13× 13×       1384× 660× 644× 644× 644× 631×     724×                 46×   20×     26× 26× 26× 26× 26×   733×   13×                         484×                               594×   594× 315×   279× 38× 38× 38×   241×                               144×   143×                                     204× 204× 134×   70×   66×                               331×     331×   331×           139×         93×       46×         40×                 192×           325×   322×                                 72× 72× 72×     72×                             119× 119× 296× 59× 59×                       50× 50× 531× 172× 172×                     21×   19× 10×                                             135×           135×   129×                                   129× 23×                 135× 1250× 760× 760× 760×   760× 391×   369×     760×       760×           760×         14× 14×   14×     14× 14×       746× 12×       10×     12× 12×       734×           10× 10×   10× 10×     724× 718×     724× 11×         723× 355×                 490×                                 488×                     1211× 1211× 64× 57×       1211× 362× 91×   91×   362×   12×                         65×   65× 678× 226× 226× 226×                       15×     15× 61× 61× 18×     43× 37× 37×                         12×                               37×   37× 178×   37×    
/*!
 * VisualEditor ElementLinearData classes.
 *
 * Class containing element linear data and an hash-value store.
 *
 * @copyright 2011-2019 VisualEditor Team and others; see http://ve.mit-license.org
 */
 
/**
 * Element linear data storage
 *
 * @class
 * @extends ve.dm.FlatLinearData
 * @constructor
 * @param {ve.dm.HashValueStore} store Hash-value store
 * @param {Array} [data] Linear data
 */
ve.dm.ElementLinearData = function VeDmElementLinearData() {
	// Parent constructor
	ve.dm.ElementLinearData.super.apply( this, arguments );
};
 
/* Inheritance */
 
OO.inheritClass( ve.dm.ElementLinearData, ve.dm.FlatLinearData );
 
/* Static Members */
 
ve.dm.ElementLinearData.static.startWordRegExp = new RegExp(
	'^(' + unicodeJS.characterclass.patterns.word + ')'
);
 
ve.dm.ElementLinearData.static.endWordRegExp = new RegExp(
	'(' + unicodeJS.characterclass.patterns.word + ')$'
);
 
/* Static Methods */
 
/**
 * Compare two elements' basic properties
 *
 * Elements are comparable if they have the same type and attributes, or
 * have the same text data. Anything semantically irrelevant is filtered
 * out first.
 *
 * @param {Object|Array|string} a First element
 * @param {Object|Array|string} b Second element
 * @return {boolean} Elements are comparable
 */
ve.dm.ElementLinearData.static.compareElementsUnannotated = function ( a, b ) {
	var aPlain = a,
		bPlain = b;
 
	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 elements' basic properties and annotations
 *
 * Elements are comparable if they have the same type, attributes,
 * text data and annotations, as determined by
 * ve.dm.AnnotationSet#compareTo .
 *
 * @param {Object|Array|string} a First element
 * @param {Object|Array|string} b Second element
 * @param {ve.dm.HashValueStore} aStore First element's store
 * @param {ve.dm.HashValueStore} [bStore] Second element's store, if different
 * @return {boolean} Elements are comparable
 */
ve.dm.ElementLinearData.static.compareElements = function ( a, b, aStore, bStore ) {
	var typeofA, aSet, bSet, aAnnotations, bAnnotations;
 
	if ( a === b ) {
		return true;
	}
 
	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;
	}
	// Elements 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;
	}
 
	aSet = new ve.dm.AnnotationSet( aStore, aAnnotations || [] );
	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 {string|Array|Object} item Item of linear data
 * @return {string[]} An array of annotation store hashes
 */
ve.dm.ElementLinearData.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 {string|Array|Object} item Item of linear data
 * @param {string[]} hashes Annotations' store hashes
 * @return {string|Array|Object} Deep-copied, modified item
 */
ve.dm.ElementLinearData.static.replaceAnnotationHashesForItem = function ( item, hashes ) {
	var character,
		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
			character = ve.dm.ElementLinearData.static.getCharacterDataFromItem( item );
			item = [ character, hashes ];
		}
	} else {
		if ( isElement ) {
			// Cleanup empty element annotation
			delete item.annotations;
		} else {
			// Cleanup empty character annotation
			item = ve.dm.ElementLinearData.static.getCharacterDataFromItem( item );
		}
	}
	return item;
};
 
/**
 * Get character data from an item
 *
 * @param {string|Array|Object} item Item to get character data from
 * @return {string} Character data, or '' if no character data
 */
ve.dm.ElementLinearData.static.getCharacterDataFromItem = function ( item ) {
	var data = Array.isArray( item ) ? item[ 0 ] : item;
	return typeof data === 'string' ? data : '';
};
 
/* Methods */
 
/**
 * 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.ElementLinearData.prototype.isContentOffset = function ( offset ) {
	var left, right, factory;
	// Edges are never content
	if ( offset === 0 || offset === this.getLength() ) {
		return false;
	}
	left = this.getData( offset - 1 );
	right = this.getData( offset );
	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.charAt( 0 ) === '/' &&
					// 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.charAt( 0 ) !== '/' &&
					// 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] Only return true if any kind of element can be inserted at offset
 * @return {boolean} Structure can be inserted at offset
 */
ve.dm.ElementLinearData.prototype.isStructuralOffset = function ( offset, unrestricted ) {
	var left, right, factory;
	// Edges are always structural
	if ( offset === 0 || offset === this.getLength() ) {
		return true;
	}
	// Offsets must be within range and both sides must be elements
	left = this.getData( offset - 1 );
	right = this.getData( offset );
	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.ElementLinearData.prototype.isContentData = function () {
	var item, i = this.getLength();
	while ( i-- ) {
		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 Offset
 * @param {ve.dm.Annotation} annotation Annotation
 * @param {boolean} [ignoreClose] Ignore close elements, otherwise check if their open element is annotatable
 * @return {boolean} Annotation can be applied at this offset
 */
ve.dm.ElementLinearData.prototype.canTakeAnnotationAtOffset = function ( offset, annotation, ignoreClose ) {
	var type;
	if ( this.isElementData( offset ) ) {
		if ( ignoreClose && this.isCloseElementData( offset ) ) {
			return false;
		}
		type = this.getType( offset );
		// Structural nodes are never annotatable
		// Blacklisted 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] 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.ElementLinearData.prototype.getAnnotationHashesFromOffset = function ( offset, ignoreClose ) {
	var item;
	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 [];
		}
	}
 
	item = this.getData( offset );
	return this.constructor.static.getAnnotationHashesFromItem( item ) || [];
};
 
/**
 * 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] 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.ElementLinearData.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.ElementLinearData.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.ElementLinearData.prototype.setAnnotationHashesAtOffset = function ( offset, hashes ) {
	var 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 {Mixed} value Value to set, or undefined to unset
 */
ve.dm.ElementLinearData.prototype.setAttributeAtOffset = function ( offset, key, value ) {
	var item = this.getData( offset );
	Iif ( !this.isElementData( offset ) ) {
		return;
	}
	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.ElementLinearData.prototype.getCharacterData = function ( offset ) {
	var item = this.getData( offset );
	return ve.dm.ElementLinearData.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 {Object} 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.ElementLinearData.prototype.getAnnotatedRangeFromOffset = function ( offset, annotation ) {
	var start = offset,
		end = offset;
	Iif ( this.getAnnotationsFromOffset( offset ).contains( annotation ) === false ) {
		return null;
	}
	while ( start > 0 ) {
		start--;
		if ( this.getAnnotationsFromOffset( start ).contains( annotation ) === false ) {
			start++;
			break;
		}
	}
	while ( end < this.getLength() ) {
		if ( this.getAnnotationsFromOffset( end ).contains( annotation ) === false ) {
			break;
		}
		end++;
	}
	return new ve.Range( start, end );
};
 
/**
 * 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.ElementLinearData.prototype.getAnnotatedRangeFromSelection = function ( range, annotation ) {
	var start = range.start,
		end = range.end;
	while ( start > 0 ) {
		start--;
		if ( this.getAnnotationsFromOffset( start ).contains( annotation ) === false ) {
			start++;
			break;
		}
	}
	while ( end < this.getLength() ) {
		if ( this.getAnnotationsFromOffset( end ).contains( annotation ) === false ) {
			break;
		}
		end++;
	}
	return new ve.Range( start, end );
};
 
/**
 * Get annotations common to all content in a range.
 *
 * @param {ve.Range} range Range to get annotations for
 * @param {boolean} [all=false] Get all annotations found within the range, not just those that cover it
 * @return {ve.dm.AnnotationSet} All annotation objects range is covered by
 */
ve.dm.ElementLinearData.prototype.getAnnotationsFromRange = function ( range, all ) {
	var i, left, right, ignoreChildrenDepth = 0;
	// Iterator over the range, looking for annotations, starting at the 2nd character
	for ( 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 || 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] Use annotations after cursor if collapsed
 * @return {ve.dm.AnnotationSet} The insertion annotations that should apply
 */
ve.dm.ElementLinearData.prototype.getInsertionAnnotationsFromRange = function ( range, startAfterAnnotations ) {
	var start, startAnnotations, afterAnnotations;
 
	// 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;
	}
 
	// 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() );
	}
 
	// 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( function ( annotation ) {
		return 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.ElementLinearData.prototype.hasAnnotationsInRange = function ( range ) {
	var i;
	for ( i = range.start; i < range.end; i++ ) {
		if ( this.getAnnotationHashesFromOffset( i, true ).length ) {
			return true;
		}
	}
	return false;
};
 
/**
 * 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.ElementLinearData.prototype.trimOuterSpaceFromRange = function ( range ) {
	var start = range.start,
		end = range.end;
	while ( this.getCharacterData( end - 1 ).match( /\s/ ) ) {
		end--;
	}
	while ( start < end && this.getCharacterData( start ).match( /\s/ ) ) {
		start++;
	}
	return range.to < range.end ? new ve.Range( end, start ) : new ve.Range( start, end );
};
 
/**
 * 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] Ignore all non-content nodes, e.g. paragraphs, headings, lists
 * @param {string[]} [ignoredTypes] Only ignore specific non-content types
 * @param {boolean} [ignoreCoveringAnnotations] Ignore covering annotations
 * @param {boolean} [ignoreAllAnnotations] Ignore all annotations
 * @return {boolean} The data is plain text
 */
ve.dm.ElementLinearData.prototype.isPlainText = function ( range, ignoreNonContentNodes, ignoredTypes, ignoreCoveringAnnotations, ignoreAllAnnotations ) {
	var i, type, annotations;
 
	range = range || new ve.Range( 0, this.getLength() );
 
	if ( ignoreCoveringAnnotations ) {
		annotations = this.getAnnotationsFromRange( range );
	}
 
	for ( i = range.start; i < range.end; i++ ) {
		if ( typeof this.data[ i ] === 'string' ) {
			// Un-annotated text
			continue;
		} else if ( Array.isArray( this.data[ i ] ) ) {
			// Annotated text
			if ( ignoreAllAnnotations ) {
				continue;
			}
			if (
				ignoreCoveringAnnotations &&
				annotations.containsAllOf( this.getAnnotationsFromOffset( i ) )
			) {
				continue;
			}
		} else if ( ignoreNonContentNodes || ignoredTypes ) {
			// Element data
			type = this.getType( i );
			if ( ignoredTypes && ignoredTypes.indexOf( type ) !== -1 ) {
				continue;
			}
			if ( ignoreNonContentNodes && !ve.dm.nodeFactory.isNodeContent( type ) ) {
				continue;
			}
		}
		return false;
	}
	return true;
};
 
/**
 * 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.ElementLinearData.prototype.forEachRunOfContent = function ( range, callback ) {
	var i,
		text = '';
 
	for ( i = range.start; i < range.end; 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] 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.ElementLinearData.prototype.getText = function ( maintainIndices, range ) {
	var i, text = '';
	range = range || new ve.Range( 0, this.getLength() );
 
	for ( i = range.start; i < range.end; 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.ElementLinearData.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 {...Mixed} [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.ElementLinearData.prototype.getRelativeOffset = function ( offset, distance, callback ) {
	var i, direction,
		dataOffset, isOpen,
		args = Array.prototype.slice.call( arguments, 3 ),
		start = offset,
		steps = 0,
		turnedAround = false,
		ignoreChildrenDepth = 0;
	// 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.apply( this, [ offset ].concat( args ) ) ) {
			return offset;
		} else {
			distance = 1;
		}
	}
	// Initial values
	direction = (
		offset <= 0 ? 1 : (
			offset >= this.getLength() ? -1 : (
				distance > 0 ? 1 : -1
			)
		)
	);
	distance = Math.abs( distance );
	i = start + direction;
	offset = -1;
	// 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
		dataOffset = i + ( direction > 0 ? -1 : 0 );
		if (
			this.isElementData( dataOffset ) &&
			ve.dm.nodeFactory.shouldIgnoreChildren( this.getType( dataOffset ) )
		) {
			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.apply( this, [ i ].concat( 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.apply( this, [ start ].concat( 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.ElementLinearData.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.ElementLinearData.prototype.getNearestContentOffset = function ( offset, direction ) {
	var left, right;
 
	if ( this.isContentOffset( offset ) ) {
		return offset;
	}
	if ( direction === undefined ) {
		left = this.getRelativeContentOffset( offset, -1 );
		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] Only consider offsets where any kind of element can be inserted
 * @return {number} Relative structural offset
 */
ve.dm.ElementLinearData.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] Only consider offsets where any kind of element can be inserted
 * @return {number} Nearest structural offset
 */
ve.dm.ElementLinearData.prototype.getNearestStructuralOffset = function ( offset, direction, unrestricted ) {
	var left, right;
	if ( this.isStructuralOffset( offset, unrestricted ) ) {
		return offset;
	}
	if ( !direction ) {
		left = this.getRelativeStructuralOffset( offset, -1, unrestricted );
		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.ElementLinearData.prototype.getWordRange = function ( offset ) {
	var range,
		dataString = new ve.dm.DataString( this.getData() );
 
	offset = this.getNearestContentOffset( offset );
 
	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).
 
		if ( this.constructor.static.endWordRegExp.exec(
			( dataString.read( offset - 2 ) || ' ' ) +
			( dataString.read( offset - 1 ) || ' ' )
		) ) {
			// Cursor is immediately after a word codepoint: expand backwards
			range = new ve.Range(
				unicodeJS.wordbreak.prevBreakOffset( dataString, offset ),
				offset
			);
		} else if ( this.constructor.static.startWordRegExp.exec(
			( dataString.read( offset ) || ' ' ) +
			( dataString.read( offset + 1 ) || ' ' )
		) ) {
			// 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: 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;
};
 
/**
 * Finds all instances of items being stored in the hash-value store for this data store
 *
 * Currently this is just all annotations still in use.
 *
 * @param {ve.Range} [range] Optional range to get store values for
 * @return {Object} Object containing all store values, keyed by store hash
 */
ve.dm.ElementLinearData.prototype.getUsedStoreValues = function ( range ) {
	var i, hash, hashes, j,
		store = this.getStore(),
		valueStore = {};
 
	range = range || new ve.Range( 0, this.data.length );
 
	for ( i = range.start; i < range.end; i++ ) {
		// Annotations
		// Use ignoreClose to save time; no need to count every element annotation twice
		hashes = this.getAnnotationHashesFromOffset( i, true );
		j = hashes.length;
		while ( j-- ) {
			hash = hashes[ j ];
			Eif ( !Object.prototype.hasOwnProperty.call( valueStore, hash ) ) {
				valueStore[ hash ] = store.value( hash );
			}
		}
		Iif ( this.data[ i ].originalDomElementsHash !== undefined ) {
			valueStore[ this.data[ i ].originalDomElementsHash ] = store.value( this.data[ i ].originalDomElementsHash );
		}
	}
	return valueStore;
};
 
/**
 * 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.ElementLinearData.prototype.remapInternalListIndexes = function ( mapping, internalList ) {
	var i, ilen, nodeClass;
	for ( i = 0, ilen = this.data.length; i < ilen; i++ ) {
		if ( this.isOpenElementData( i ) ) {
			nodeClass = ve.dm.nodeFactory.lookup( this.getType( i ) );
			nodeClass.static.remapInternalListIndexes( this.data[ i ], 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.ElementLinearData.prototype.remapInternalListKeys = function ( internalList ) {
	var i, ilen, nodeClass;
	for ( i = 0, ilen = this.data.length; i < ilen; i++ ) {
		if ( this.isOpenElementData( i ) ) {
			nodeClass = ve.dm.nodeFactory.lookup( this.getType( i ) );
			nodeClass.static.remapInternalListKeys( this.data[ i ], 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.ElementLinearData.prototype.remapAnnotationHash = function ( oldHash, newHash ) {
	var i, ilen, spliceAt;
	for ( 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 if ( Array.isArray( this.data[ i ] ) ) {
			while ( ( spliceAt = this.data[ i ][ 1 ].indexOf( oldHash ) ) !== -1 ) {
				if ( this.data[ i ][ 1 ].indexOf( newHash ) === -1 ) {
					this.data[ i ][ 1 ].splice( spliceAt, 1, newHash );
				} else {
					this.data[ i ][ 1 ].splice( spliceAt, 1, newHash );
				}
			}
		}
	}
};
 
/**
 * 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] Remove references to DOM elements data was converted from
 * @param {boolean} [rules.plainText] Remove all formatting for plain text import
 * @param {boolean} [rules.allowBreaks] Allow <br> line breaks, otherwise the node will be split
 * @param {boolean} [rules.preserveHtmlWhitespace] Preserve non-semantic HTML whitespace
 * @param {boolean} [rules.nodeSanitization] Apply per-type node sanitizations via ve.dm.Node#sanitize
 * @param {boolean} [rules.keepEmptyContentBranches] Preserve empty content branch nodes
 * @param {boolean} [rules.singleLine] Don't allow more that one ContentBranchNode
 * @param {boolean} [rules.allowMetaData] Don't strip metadata
 */
ve.dm.ElementLinearData.prototype.sanitize = function ( rules ) {
	var i, len, annotations, emptySet, setToRemove, type, oldHash, newHash,
		canContainContent, contentElement, isOpen, nodeClass, ann, start,
		elementStack = [],
		store = this.getStore(),
		allAnnotations = this.getAnnotationsFromRange( new ve.Range( 0, this.getLength() ), true );
 
	if ( rules.plainText ) {
		emptySet = new ve.dm.AnnotationSet( store );
	} else {
		if ( rules.removeOriginalDomElements ) {
			// Remove originalDomElements from annotations
			for ( i = 0, len = allAnnotations.getLength(); i < len; i++ ) {
				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.
					oldHash = store.hashOfValue( ann );
					delete allAnnotations.get( i ).element.originalDomElementsHash;
					newHash = store.replaceHash( oldHash, ann );
					this.remapAnnotationHash( oldHash, newHash );
					Iif ( allAnnotations.storeHashes.indexOf( newHash ) !== -1 ) {
						// 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( function ( annotation ) {
			return (
				rules.blacklist && rules.blacklist[ annotation.name ]
			) || (
				// If original DOM element references are being removed, remove spans
				annotation.name === 'textStyle/span' && rules.removeOriginalDomElements
			);
		} );
	}
 
	for ( i = 0, len = this.getLength(); i < len; i++ ) {
		if ( this.isElementData( i ) ) {
			type = this.getType( i );
			canContainContent = ve.dm.nodeFactory.canNodeContainContent( type );
			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.getData( i ).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 ) {
					ve.deleteProp( this.getData( i ), '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 ) {
				ve.deleteProp( this.getData( i ), 'internal', 'whitespace' );
			}
 
			if ( canContainContent && !isOpen && rules.singleLine ) {
				i++;
				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 ( this.getCharacterData( i + 1 ).match( /\s/ ) || this.getCharacterData( i - 1 ).match( /\s/ ) ) {
					// 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
					Eif ( typeof this.getData( i ) === 'string' ) {
						this.data[ i ] = ' ';
					} else {
						this.data[ i ][ 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.data[ i ] = ' ';
					} else {
						this.data[ i ][ 0 ] = ' ';
					}
				}
			}
		}
		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 ) {
				nodeClass = ve.dm.modelRegistry.lookup( this.getType( i ) );
				// Perform per-class sanitizations:
				nodeClass.static.sanitize( this.getData( i ), rules );
			}
			if ( rules.removeOriginalDomElements ) {
				// Remove originalDomElements from nodes
				delete this.getData( i ).originalDomElementsHash;
			}
		}
	}
};
 
/**
 * 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.ElementLinearData.prototype.cloneElements = function ( preserveGenerated ) {
	var i, len, nodeClass,
		store = this.getStore();
	for ( i = 0, len = this.getLength(); i < len; i++ ) {
		if ( this.isOpenElementData( i ) ) {
			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.ElementLinearData.prototype.countNonInternalElements = function ( limit ) {
	var i, l, type,
		internalDepth = 0,
		count = 0;
	for ( i = 0, l = this.getLength(); i < l; i++ ) {
		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.ElementLinearData.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.ElementLinearData.prototype.getCommonAnnotationArrayLength = function ( range ) {
	var i,
		annotationHashesForOffset = [];
	for ( i = range.start; i < range.end; i++ ) {
		annotationHashesForOffset.push( this.getAnnotationHashesFromOffset( i ) );
	}
	return ve.getCommonStartSequenceLength( annotationHashesForOffset );
};