all files / src/dm/ ve.dm.SurfaceFragment.js

83.16% Statements 395/475
72.56% Branches 201/277
90.2% Functions 46/51
83.16% Lines 395/475
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                                    968×         968× 968× 968× 968× 968× 968× 968×     968×                           73×   73×       73×     73×               72× 72× 72× 10×       73×                   1812×   1812×     1811× 130× 130× 130× 1681×   152× 152× 152× 152×   1811×                       336×       336× 279×   336×       336×   138×                 214×               595×                   1499× 1499×               2137×                                                     134×                         15×                       30× 30×   30×   30×   30×                                                                       59×                                                             62× 62×       62×   62×                 28×   28×   10×       18×   28×                         11×   11×   10× 10× 17× 17×   10×   10×             62×                                             49× 49×     49×                 13× 13×     13×                       154×       154× 34×   120× 120× 127× 127×   120×               120×                                               49× 49×         49×   49× 49×   49×               40×     40× 62× 52×     40×                     96×     96× 96×                                 18× 18×     18×                       20× 20×     20×                   24×     24× 24× 24× 24× 24× 10× 10×                           24×                                         53×                 103× 103×                                                                                         23×         23×   23× 17×             23× 24× 24×   24× 27× 27×                     23×   23×                                   63×       63×       63× 25×     13×   25×     63×   63× 29×   29×       28×     63× 63×           63×                 63×     62× 62×     62×                                                               46×       46×       46×           46× 46×   42×       46× 40×           46× 46×     45× 45×   46×                 42× 42×       42× 42×     42×                   31×     31×               31× 31× 31×   31×                   11× 11×                                             16× 16×                                 31×         31× 29×                 31×   31×                     11× 11×       11×       11×                                                                                         38×         38×       38×     37× 26×   37× 17×     37×       37×                                                                                                                                         15× 15×       15× 12×     15×   15×     15×       15×                                                                                                                 15×                                                                   15×       15× 15×     15× 15× 15×                               15× 15× 15×                                 15× 15×   15×       15×       15×           15×   15×   15×    
/*!
 * VisualEditor DataModel Fragment class.
 *
 * @copyright 2011-2019 VisualEditor Team and others; see http://ve.mit-license.org
 */
 
/**
 * DataModel surface fragment.
 *
 * @class
 *
 * @constructor
 * @param {ve.dm.Surface} surface Target surface
 * @param {ve.dm.Selection} [selection] Selection within target document, current selection used by default
 * @param {boolean} [noAutoSelect] Don't update the surface's selection when making changes
 * @param {boolean} [excludeInsertions] Exclude inserted content at the boundaries when updating range
 */
ve.dm.SurfaceFragment = function VeDmSurfaceFragment( surface, selection, noAutoSelect, excludeInsertions ) {
	// Short-circuit for missing-surface null fragment
	Iif ( !surface ) {
		return this;
	}
 
	// Properties
	this.document = surface.getDocument();
	this.noAutoSelect = !!noAutoSelect;
	this.excludeInsertions = !!excludeInsertions;
	this.surface = surface;
	this.selection = selection || surface.getSelection();
	this.leafNodes = null;
	this.pending = [];
 
	// Initialization
	this.historyPointer = this.document.getCompleteHistoryLength();
};
 
/* Inheritance */
 
OO.initClass( ve.dm.SurfaceFragment );
 
/* Methods */
 
/**
 * Get list of selected nodes and annotations.
 *
 * @param {boolean} [all] Include nodes and annotations which only cover some of the fragment
 * @return {ve.dm.Model[]} Selected models
 */
ve.dm.SurfaceFragment.prototype.getSelectedModels = function ( all ) {
	var i, len, nodes, selectedNode, annotations;
	// Handle null selection
	Iif ( this.isNull() ) {
		return [];
	}
 
	annotations = this.getAnnotations( all );
 
	// Filter out nodes with collapsed ranges
	if ( all ) {
		nodes = this.getCoveredNodes();
		for ( i = 0, len = nodes.length; i < len; i++ ) {
			Iif ( nodes[ i ].range && nodes[ i ].range.isCollapsed() ) {
				nodes.splice( i, 1 );
				len--;
				i--;
			} else {
				nodes[ i ] = nodes[ i ].node;
			}
		}
	} else {
		nodes = [];
		selectedNode = this.getSelectedNode();
		if ( selectedNode ) {
			nodes.push( selectedNode );
		}
	}
 
	return nodes.concat( !annotations.isEmpty() ? annotations.get() : [] );
};
 
/**
 * Update selection based on un-applied transactions in the surface, or specified selection.
 *
 * @param {ve.dm.Selection} [selection] Optional selection to set
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.update = function ( selection ) {
	var txs;
	// Handle null selection
	if ( this.isNull() ) {
		return this;
	}
 
	if ( selection && !selection.equals( this.selection ) ) {
		this.selection = selection;
		this.leafNodes = null;
		this.historyPointer = this.document.getCompleteHistoryLength();
	} else if ( this.historyPointer < this.document.getCompleteHistoryLength() ) {
		// Small optimisation: check history pointer is in the past
		txs = this.document.getCompleteHistorySince( this.historyPointer );
		this.selection = this.selection.translateByTransactions( txs, this.excludeInsertions );
		this.leafNodes = null;
		this.historyPointer += txs.length;
	}
	return this;
};
 
/**
 * Process a set of transactions on the surface, and update the selection if the fragment
 * is auto-selecting.
 *
 * @param {ve.dm.Transaction|ve.dm.Transaction[]} txs Transaction(s) to process
 * @param {ve.dm.Selection} [selection] Selection to set, if different from translated selection, required if the
 *   fragment is null
 * @throws {Error} If fragment is null and selection is omitted
 */
ve.dm.SurfaceFragment.prototype.change = function ( txs, selection ) {
	Iif ( !selection && this.isNull() ) {
		throw new Error( 'Cannot change null fragment without selection' );
	}
 
	if ( !Array.isArray( txs ) ) {
		txs = [ txs ];
	}
	this.surface.change(
		txs,
		!this.noAutoSelect && ( selection || this.getSelection().translateByTransactions( txs, this.excludeInsertions ) )
	);
	if ( selection ) {
		// Overwrite the selection
		this.update( selection );
	}
};
 
/**
 * Get the surface the fragment is a part of.
 *
 * @return {ve.dm.Surface|null} Surface of fragment
 */
ve.dm.SurfaceFragment.prototype.getSurface = function () {
	return this.surface;
};
 
/**
 * Get the document of the surface the fragment is a part of.
 *
 * @return {ve.dm.Document|null} Document of surface of fragment
 */
ve.dm.SurfaceFragment.prototype.getDocument = function () {
	return this.document;
};
 
/**
 * Get the selection of the fragment within the surface.
 *
 * This method also calls update to make sure the selection returned is current.
 *
 * @return {ve.dm.Selection} The selection
 */
ve.dm.SurfaceFragment.prototype.getSelection = function () {
	this.update();
	return this.selection;
};
 
/**
 * Check if the fragment is null.
 *
 * @return {boolean} Fragment is a null fragment
 */
ve.dm.SurfaceFragment.prototype.isNull = function () {
	return this.selection.isNull();
};
 
/**
 * Check if the surface's selection will be updated automatically when changes are made.
 *
 * @return {boolean} Will automatically update surface selection
 */
ve.dm.SurfaceFragment.prototype.willAutoSelect = function () {
	return !this.noAutoSelect;
};
 
/**
 * Change whether to automatically update the surface selection when making changes.
 *
 * @param {boolean} [autoSelect=true] Automatically update surface selection
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.setAutoSelect = function ( autoSelect ) {
	this.noAutoSelect = !autoSelect;
	return this;
};
 
/**
 * Get a clone of this SurfaceFragment, optionally with a different selection.
 *
 * @param {ve.dm.Selection} [selection] If set, use this selection rather than the old fragment's selection
 * @return {ve.dm.SurfaceFragment} Clone of this fragment
 */
ve.dm.SurfaceFragment.prototype.clone = function ( selection ) {
	return new this.constructor(
		this.surface,
		selection || this.getSelection(),
		this.noAutoSelect,
		this.excludeInsertions
	);
};
 
/**
 * Check whether updates to this fragment's selection will exclude content inserted at the boundaries.
 *
 * @return {boolean} Selection updates will exclude insertions
 */
ve.dm.SurfaceFragment.prototype.willExcludeInsertions = function () {
	return this.excludeInsertions;
};
 
/**
 * Tell this fragment whether it should exclude insertions. If this option is enabled, updates to
 * this fragment's selection in response to transactions will not include content inserted at the
 * boundaries of the selection; if it is disabled, insertions will be included.
 *
 * @param {boolean} excludeInsertions Whether to exclude insertions
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.setExcludeInsertions = function ( excludeInsertions ) {
	excludeInsertions = !!excludeInsertions;
	Eif ( this.excludeInsertions !== excludeInsertions ) {
		// Process any deferred updates with the old value
		this.update();
		// Set the new value
		this.excludeInsertions = excludeInsertions;
	}
	return this;
};
 
/**
 * Get a new fragment with an adjusted position
 *
 * @param {number} [start] Adjustment for start position
 * @param {number} [end] Adjustment for end position
 * @return {ve.dm.SurfaceFragment} Adjusted fragment
 */
ve.dm.SurfaceFragment.prototype.adjustLinearSelection = function ( start, end ) {
	var newRange, oldRange;
	Iif ( !( this.selection instanceof ve.dm.LinearSelection ) ) {
		return this.clone();
	}
	oldRange = this.getSelection().getRange();
	newRange = oldRange && new ve.Range( oldRange.start + ( start || 0 ), oldRange.end + ( end || 0 ) );
	return this.clone( new ve.dm.LinearSelection( newRange ) );
};
 
/**
 * Get a new fragment with a truncated length.
 *
 * @param {number} limit Maximum length of new range (negative for left-side truncation)
 * @return {ve.dm.SurfaceFragment} Truncated fragment
 */
ve.dm.SurfaceFragment.prototype.truncateLinearSelection = function ( limit ) {
	var range;
	Iif ( !( this.selection instanceof ve.dm.LinearSelection ) ) {
		return this.clone();
	}
	range = this.getSelection().getRange();
	return this.clone( new ve.dm.LinearSelection( range.truncate( limit ) ) );
};
 
/**
 * Get a new fragment with a zero-length selection at the start offset.
 *
 * @return {ve.dm.SurfaceFragment} Collapsed fragment
 */
ve.dm.SurfaceFragment.prototype.collapseToStart = function () {
	return this.clone( this.getSelection().collapseToStart() );
};
 
/**
 * Get a new fragment with a zero-length selection at the end offset.
 *
 * @return {ve.dm.SurfaceFragment} Collapsed fragment
 */
ve.dm.SurfaceFragment.prototype.collapseToEnd = function () {
	return this.clone( this.getSelection().collapseToEnd() );
};
 
/**
 * Get a new fragment with a range that no longer includes leading and trailing whitespace.
 *
 * @return {ve.dm.SurfaceFragment} Trimmed fragment
 */
ve.dm.SurfaceFragment.prototype.trimLinearSelection = function () {
	var oldRange, newRange;
	Iif ( !( this.selection instanceof ve.dm.LinearSelection ) ) {
		return this.clone();
	}
	oldRange = this.getSelection().getRange();
	newRange = oldRange;
 
	Iif ( this.getText().trim().length === 0 ) {
		// oldRange is only whitespace
		newRange = new ve.Range( oldRange.start );
	} else {
		newRange = this.document.data.trimOuterSpaceFromRange( oldRange );
	}
 
	return this.clone( new ve.dm.LinearSelection( newRange ) );
};
 
/**
 * Get a new fragment that covers an expanded range of the document.
 *
 * @param {string} [scope='parent'] Method of expansion:
 *  - `word`: Expands to cover the nearest word by looking for word breaks (see UnicodeJS.wordbreak)
 *  - `annotation`: Expands to cover a given annotation type (ve.dm.Annotation) within the current range
 *  - `root`: Expands to cover the entire document
 *  - `siblings`: Expands to cover all sibling nodes
 *  - `closest`: Expands to cover the closest common ancestor node of a give type (ve.dm.Node)
 *  - `parent`: Expands to cover the closest common parent node
 * @param {ve.dm.Annotation|ve.dm.Node} [type] Parameter to use with scope method if needed
 * @return {ve.dm.SurfaceFragment} Expanded fragment
 */
ve.dm.SurfaceFragment.prototype.expandLinearSelection = function ( scope, type ) {
	var node, nodes, parent, newRange, oldRange;
	Iif ( !( this.selection instanceof ve.dm.LinearSelection ) ) {
		return this.clone();
	}
 
	oldRange = this.getSelection().getRange();
 
	switch ( scope || 'parent' ) {
		case 'word':
			if ( !oldRange.isCollapsed() ) {
				newRange = ve.Range.static.newCoveringRange( [
					this.document.data.getWordRange( oldRange.start ),
					this.document.data.getWordRange( oldRange.end )
				], oldRange.isBackwards() );
			} else {
				// Optimisation for zero-length ranges
				newRange = this.document.data.getWordRange( oldRange.start );
			}
			break;
		case 'annotation':
			newRange = this.document.data.getAnnotatedRangeFromSelection( oldRange, type );
			// Adjust selection if it does not contain the annotated range
			if ( oldRange.start > newRange.start || oldRange.end < newRange.end ) {
				// Maintain range direction
				if ( oldRange.from > oldRange.to ) {
					newRange = newRange.flip();
				}
			} else {
				// Otherwise just keep the range as is
				newRange = oldRange;
			}
			break;
		case 'root':
			newRange = this.getDocument().getDocumentRange();
			break;
		case 'siblings':
			// Grow range to cover all siblings
			nodes = this.document.selectNodes( oldRange, 'siblings' );
			if ( nodes.length === 1 ) {
				newRange = nodes[ 0 ].node.getOuterRange();
			} else {
				newRange = new ve.Range(
					nodes[ 0 ].node.getOuterRange().start,
					nodes[ nodes.length - 1 ].node.getOuterRange().end
				);
			}
			break;
		case 'closest':
			// Grow range to cover closest common ancestor node of given type
			nodes = this.document.selectNodes( oldRange, 'siblings' );
			// If the range covered the entire node check that node
			if ( nodes[ 0 ].nodeRange.equalsSelection( oldRange ) && nodes[ 0 ].node instanceof type ) {
				newRange = nodes[ 0 ].nodeOuterRange;
				break;
			}
			parent = nodes[ 0 ].node.getParent();
			while ( parent && !( parent instanceof type ) ) {
				node = parent;
				parent = parent.getParent();
			}
			if ( parent ) {
				newRange = parent.getOuterRange();
			}
			break;
		case 'parent':
			// Grow range to cover the closest common parent node
			node = this.document.selectNodes( oldRange, 'siblings' )[ 0 ].node;
			parent = node.getParent();
			Eif ( parent ) {
				newRange = parent.getOuterRange();
			}
			break;
		default:
			throw new Error( 'Invalid scope argument: ' + scope );
	}
	return this.clone(
		newRange ?
			new ve.dm.LinearSelection( newRange ) :
			new ve.dm.NullSelection()
	);
};
 
/**
 * Get data for the fragment.
 *
 * @param {boolean} [deep] Get a deep copy of the data
 * @return {Array} Fragment data
 */
ve.dm.SurfaceFragment.prototype.getData = function ( deep ) {
	var range = this.getSelection().getCoveringRange();
	Iif ( !range ) {
		return [];
	}
	return this.document.getData( range, deep );
};
 
/**
 * Get plain text for the fragment.
 *
 * @param {boolean} [maintainIndices] Maintain data offset to string index alignment by replacing elements with line breaks
 * @return {string} Fragment text
 */
ve.dm.SurfaceFragment.prototype.getText = function ( maintainIndices ) {
	var range = this.getSelection().getCoveringRange();
	Iif ( !range ) {
		return '';
	}
	return this.document.data.getText( maintainIndices, range );
};
 
/**
 * Whether the fragment contains only text, allowing annotations
 *
 * @method
 * @return {boolean} Whether there's only text
 */
ve.dm.SurfaceFragment.prototype.containsOnlyText = function () {
	var range = this.getSelection().getCoveringRange();
	Iif ( !range ) {
		return true;
	}
	return this.document.data.isPlainText( range, false, false, false, true );
};
 
/**
 * Get annotations in fragment.
 *
 * By default, this will only get annotations that completely cover the fragment. Use the {all}
 * argument to get all annotations that occur within the fragment.
 *
 * @param {boolean} [all] Get annotations which only cover some of the fragment
 * @return {ve.dm.AnnotationSet} All annotation objects range is covered by
 */
ve.dm.SurfaceFragment.prototype.getAnnotations = function ( all ) {
	var i, l, ranges, rangeAnnotations, matchingAnnotations,
		selection = this.getSelection(),
		annotations = new ve.dm.AnnotationSet( this.getDocument().getStore() );
 
	if ( selection.isCollapsed() ) {
		return this.surface.getInsertionAnnotations();
	} else {
		ranges = selection.getRanges( this.getDocument() );
		for ( i = 0, l = ranges.length; i < l; i++ ) {
			rangeAnnotations = this.getDocument().data.getAnnotationsFromRange( ranges[ i ], all );
			if ( !i ) {
				// First range, annotations must be empty
				annotations = rangeAnnotations;
			} else if ( all ) {
				annotations.addSet( rangeAnnotations );
			} else {
				matchingAnnotations = rangeAnnotations.getComparableAnnotationsFromSet( annotations );
				if ( matchingAnnotations.isEmpty() ) {
					// Nothing matched so our intersection is empty
					annotations = matchingAnnotations;
					break;
				} else {
					// Match in the other direction, to keep all distinct compatible annotations (e.g. both b and strong)
					annotations = annotations.getComparableAnnotationsFromSet( rangeAnnotations );
					annotations.addSet( matchingAnnotations );
				}
			}
		}
		return annotations;
	}
};
 
/**
 * Check if the fragment has any annotations
 *
 * Quicker than doing !fragment.getAnnotations( true ).isEmpty() as
 * it stops at the first sight of an annotation.
 *
 * @return {boolean} The fragment contains at least one annotation
 */
ve.dm.SurfaceFragment.prototype.hasAnnotations = function () {
	var i, l, ranges = this.getSelection().getRanges( this.getDocument() );
 
	for ( i = 0, l = ranges.length; i < l; i++ ) {
		if ( this.getDocument().data.hasAnnotationsInRange( ranges[ i ] ) ) {
			return true;
		}
	}
	return false;
};
 
/**
 * Get all leaf nodes covered by the fragment.
 *
 * @see ve.Document#selectNodes Used to get the return value
 *
 * @return {Array} List of nodes and related information
 */
ve.dm.SurfaceFragment.prototype.getLeafNodes = function () {
	var range = this.getSelection().getCoveringRange();
	Iif ( !range ) {
		return [];
	}
 
	// Update in case the cache needs invalidating
	this.update();
	// Cache leafNodes because it's expensive to compute
	Eif ( !this.leafNodes ) {
		this.leafNodes = this.document.selectNodes( range, 'leaves' );
	}
	return this.leafNodes;
};
 
/**
 * Get all leaf nodes excluding nodes where the selection is empty.
 *
 * @return {Array} List of nodes and related information
 */
ve.dm.SurfaceFragment.prototype.getSelectedLeafNodes = function () {
	var i, len,
		selectedLeafNodes = [],
		leafNodes = this.getLeafNodes();
	for ( i = 0, len = leafNodes.length; i < len; i++ ) {
		if ( len === 1 || !leafNodes[ i ].range || leafNodes[ i ].range.getLength() ) {
			selectedLeafNodes.push( leafNodes[ i ].node );
		}
	}
	return selectedLeafNodes;
};
 
/**
 * Get the node selected by a range, i.e. the range matches the node's range exactly.
 *
 * Note that this method operates on the fragment's range, not the document's current selection.
 * This fragment does not need to be selected for this method to work.
 *
 * @return {ve.dm.Node|null} The node selected by the range, or null if a node is not selected
 */
ve.dm.SurfaceFragment.prototype.getSelectedNode = function () {
	var surface = this.getSurface();
 
	// Ensure the fragment is up to date
	this.update();
	return this.selection.equals( surface.getSelection() ) ?
		// If the selection is equal to the surface's use the cached node
		surface.getSelectedNode() :
		surface.getSelectedNodeFromSelection( this.selection );
};
 
/**
 * Get nodes covered by the fragment.
 *
 * Does not descend into nodes that are entirely covered by the range. The result is
 * similar to that of {ve.dm.SurfaceFragment.prototype.getLeafNodes} except that if a node is
 * entirely covered, its children aren't returned separately.
 *
 * @see ve.Document#selectNodes for more information about the return value
 *
 * @return {Array} List of nodes and related information
 */
ve.dm.SurfaceFragment.prototype.getCoveredNodes = function () {
	var range = this.getSelection().getCoveringRange();
	Iif ( !range ) {
		return [];
	}
	return this.document.selectNodes( range, 'covered' );
};
 
/**
 * Get nodes covered by the fragment.
 *
 * Includes adjacent siblings covered by the range, descending if the range is in a single node.
 *
 * @see ve.Document#selectNodes for more information about the return value.
 *
 * @return {Array} List of nodes and related information
 */
ve.dm.SurfaceFragment.prototype.getSiblingNodes = function () {
	var range = this.getSelection().getCoveringRange();
	Iif ( !range ) {
		return [];
	}
	return this.document.selectNodes( range, 'siblings' );
};
 
/**
 * Check if the nodes at the current fragment have an ancestor with matching type and attribute values.
 *
 * @param {string} type Node type to match
 * @param {Object} [attributes] Node attributes to match
 * @return {boolean} Nodes have a matching ancestor
 */
ve.dm.SurfaceFragment.prototype.hasMatchingAncestor = function ( type, attributes ) {
	var i, len, nodes, cells, all,
		selection = this.getSelection();
 
	Eif ( selection instanceof ve.dm.LinearSelection ) {
		nodes = this.getSelectedLeafNodes();
		all = !!nodes.length;
		for ( i = 0, len = nodes.length; i < len; i++ ) {
			if ( !nodes[ i ].hasMatchingAncestor( type, attributes ) ) {
				all = false;
				break;
			}
		}
	} else if ( selection instanceof ve.dm.TableSelection ) {
		cells = selection.getMatrixCells( this.getDocument() );
		all = true;
		for ( i = cells.length - 1; i >= 0; i-- ) {
			if ( !cells[ i ].node.matches( type, attributes ) ) {
				all = false;
				break;
			}
		}
	}
 
	return all;
};
 
/**
 * Clear a fragment's pending list
 */
ve.dm.SurfaceFragment.prototype.clearPending = function () {
	this.pending = [];
};
 
/**
 * Push a promise to the fragment's pending list
 *
 * @param {jQuery.Promise} promise Promise
 */
ve.dm.SurfaceFragment.prototype.pushPending = function ( promise ) {
	this.pending.push( promise );
};
 
/**
 * Get a promise that resolves when the pending list is complete
 *
 * @return {jQuery.Promise} Promise
 */
ve.dm.SurfaceFragment.prototype.getPending = function () {
	return ve.promiseAll( this.pending );
};
 
/**
 * Apply the fragment's range to the surface as a selection.
 *
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.select = function () {
	this.surface.setSelection( this.getSelection() );
	return this;
};
 
/**
 * Change one or more attributes on covered nodes.
 *
 * @param {Object} attr List of attributes to change, use undefined to remove an attribute
 * @param {string} [type] Node type to restrict changes to
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.changeAttributes = function ( attr, type ) {
	var i, len, result,
		txs = [],
		covered = this.getCoveredNodes();
 
	for ( i = 0, len = covered.length; i < len; i++ ) {
		result = covered[ i ];
		if (
			// Non-wrapped nodes have no attributes
			!result.node.isWrapped() ||
			// Filtering by node type
			( type && result.node.getType() !== type ) ||
			// Ignore zero-length results
			( result.range && result.range.isCollapsed() )
		) {
			continue;
		}
		txs.push(
			ve.dm.TransactionBuilder.static.newFromAttributeChanges(
				this.document, result.nodeOuterRange.start, attr
			)
		);
	}
	Eif ( txs.length ) {
		this.change( txs );
	}
	return this;
};
 
/**
 * Apply an annotation to content in the fragment.
 *
 * To avoid problems identified in T35108, use the {ve.dm.SurfaceFragment.trimLinearSelection} method.
 *
 * TODO: Optionally take an annotation set instead of name and data arguments and set/clear multiple
 * annotations in a single transaction.
 *
 * @param {string} method Mode of annotation, either 'set' or 'clear'
 * @param {string|ve.dm.Annotation|ve.dm.AnnotationSet} nameOrAnnotations Annotation name, for example: 'textStyle/bold',
 *  Annotation object or AnnotationSet
 * @param {Object} [data] Additional annotation data (not used if annotation object is given)
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.annotateContent = function ( method, nameOrAnnotations, data ) {
	var annotation, i, ilen, j, jlen, tx, range,
		annotations = new ve.dm.AnnotationSet( this.getDocument().getStore() ),
		ranges = this.getSelection().getRanges( this.getDocument() ),
		txs = [];
 
	Iif ( nameOrAnnotations instanceof ve.dm.AnnotationSet ) {
		annotations = nameOrAnnotations;
	} else if ( nameOrAnnotations instanceof ve.dm.Annotation ) {
		annotations.push( nameOrAnnotations );
	} else {
		annotation = ve.dm.annotationFactory.create( nameOrAnnotations, data );
		if ( method === 'set' ) {
			annotations.push( annotation );
		} else Eif ( method === 'clear' ) {
			for ( i = 0, ilen = ranges.length; i < ilen; i++ ) {
				annotations.addSet(
					this.document.data.getAnnotationsFromRange( ranges[ i ], true ).getAnnotationsByName( annotation.name )
				);
			}
		}
	}
	for ( i = 0, ilen = ranges.length; i < ilen; i++ ) {
		range = ranges[ i ];
		Eif ( !range.isCollapsed() ) {
			// Apply to selection
			for ( j = 0, jlen = annotations.getLength(); j < jlen; j++ ) {
				tx = ve.dm.TransactionBuilder.static.newFromAnnotation( this.document, range, method, annotations.get( j ) );
				txs.push( tx );
			}
		} else {
			// Apply annotation to stack
			if ( method === 'set' ) {
				this.surface.addInsertionAnnotations( annotations );
			} else if ( method === 'clear' ) {
				this.surface.removeInsertionAnnotations( annotations );
			}
		}
	}
	this.change( txs );
 
	return this;
};
 
/**
 * Remove content in the fragment and insert content before it.
 *
 * This will move the fragment's range to cover the inserted content. Note that this may be
 * different from what a normal range translation would do: the insertion might occur
 * at a different offset if that is needed to make the document balanced.
 *
 * If the content is a plain text string containing linebreaks, each line will be wrapped
 * in a paragraph.
 *
 * @param {string|Array} content Content to insert, can be either a string or array of data
 * @param {boolean} [annotate] Content should be automatically annotated to match surrounding content
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.insertContent = function ( content, annotate ) {
	var i, l, lines, annotations, tx, offset, newRange,
		range = this.getSelection().getCoveringRange(),
		doc = this.getDocument();
 
	Iif ( !range ) {
		return this;
	}
 
	if ( !range.isCollapsed() ) {
		if ( annotate ) {
			// If we're replacing content, use the annotations selected
			// instead of continuing from the left
			annotations = this.getAnnotations();
		}
		this.removeContent();
	}
 
	offset = range.start;
	// Auto-convert content to array of plain text characters
	if ( typeof content === 'string' ) {
		lines = content.split( /[\r\n]+/ );
 
		if ( lines.length > 1 ) {
			content = [];
			for ( i = 0, l = lines.length; i < l; i++ ) {
				Eif ( lines[ i ].length ) {
					content.push( { type: 'paragraph' } );
					ve.batchPush( content, lines[ i ].split( '' ) );
					content.push( { type: '/paragraph' } );
				}
			}
		} else {
			content = content.split( '' );
		}
	}
	Eif ( content.length ) {
		if ( annotate && !annotations ) {
			// TODO T126021: Don't reach into properties of document
			// FIXME T126022: the logic we actually need for annotating inserted content
			// correctly is much more complicated
			annotations = doc.data
				.getAnnotationsFromOffset( offset === 0 ? 0 : offset - 1 );
		}
		if ( annotations && annotations.getLength() > 0 ) {
			// Add the annotations to the content, passing the
			// replaceComparable argument which will remove any comparable
			// annotations from content so that they can be replaced with
			// those in annotations. This has the effect of not double-
			// wrapping any annotations which are identical apart from their
			// original DOM element so we don't generate markup like
			// <b>f<b>o</b>o</b> when pasting.
			ve.dm.Document.static.addAnnotationsToData( content, annotations, true, doc.store );
		}
		tx = ve.dm.TransactionBuilder.static.newFromInsertion( doc, offset, content );
		// Set the range to cover the inserted content; the offset translation will be wrong
		// if newFromInsertion() decided to move the insertion point
		newRange = tx.getModifiedRange( doc );
		this.change( tx, newRange ? new ve.dm.LinearSelection( newRange ) : new ve.dm.NullSelection() );
	}
 
	return this;
};
 
/**
 * Insert HTML in the fragment.
 *
 * This will move the fragment's range to cover the inserted content. Note that this may be
 * different from what a normal range translation would do: the insertion might occur
 * at a different offset if that is needed to make the document balanced.
 *
 * @param {string} html HTML to insert
 * @param {Object} [importRules] The import rules for the target surface, if importing
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.insertHtml = function ( html, importRules ) {
	this.insertDocument( this.getDocument().newFromHtml( html, importRules ) );
	return this;
};
 
/**
 * Insert a ve.dm.Document in the fragment.
 *
 * This will move the fragment's range to cover the inserted content. Note that this may be
 * different from what a normal range translation would do: the insertion might occur
 * at a different offset if that is needed to make the document balanced.
 *
 * @param {ve.dm.Document} newDoc Document to insert
 * @param {ve.Range} [newDocRange] Range from the new document to insert (defaults to entire document)
 * @param {boolean} [annotate] Content should be automatically annotated to match surrounding content
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.insertDocument = function ( newDoc, newDocRange, annotate ) {
	var tx, newRange, annotations, offset, annotatedData, annotatedDoc,
		range = this.getSelection().getCoveringRange(),
		doc = this.getDocument();
 
	Iif ( !range ) {
		return this;
	}
 
	if ( !range.isCollapsed() ) {
		Eif ( annotate ) {
			// If we're replacing content, use the annotations selected
			// instead of continuing from the left
			annotations = this.getAnnotations();
		}
		this.removeContent();
	}
 
	offset = range.start;
	if ( annotate && !annotations ) {
		// TODO T126021: Don't reach into properties of document
		annotations = doc.data
			.getAnnotationsFromOffset( offset === 0 ? 0 : offset - 1 );
	}
 
	if ( !annotations || annotations.getLength() === 0 ) {
		annotatedDoc = newDoc;
	} else {
		// Build shallow-cloned annotatedData array, copying on write as we go
		// FIXME T126022: the logic we actually need for annotating inserted content
		// correctly is much more complicated
		annotatedData = newDoc.data.slice();
		ve.dm.Document.static.addAnnotationsToData( annotatedData, annotations, true, newDoc.store, true );
		annotatedDoc = newDoc.cloneWithData( annotatedData );
	}
	tx = ve.dm.TransactionBuilder.static.newFromDocumentInsertion( doc, offset, annotatedDoc, newDocRange );
	if ( !tx.isNoOp() ) {
		// Set the range to cover the inserted content; the offset translation will be wrong
		// if newFromInsertion() decided to move the insertion point
		newRange = tx.getModifiedRange( doc );
		this.change( tx, newRange ? new ve.dm.LinearSelection( newRange ) : new ve.dm.NullSelection() );
	}
	return this;
};
 
/**
 * Remove content in the fragment.
 *
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.removeContent = function () {
	var range = this.getSelection().getCoveringRange();
	Iif ( !range ) {
		return this;
	}
 
	Eif ( !range.isCollapsed() ) {
		this.change( ve.dm.TransactionBuilder.static.newFromRemoval( this.document, range ) );
	}
 
	return this;
};
 
/**
 * Delete content and correct selection
 *
 * @param {number} [directionAfterDelete=-1] Direction to move after delete: 1 or -1 or 0
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.delete = function ( directionAfterDelete ) {
	var rangeAfterRemove, tx, startNode, endNode, endNodeData, nodeToDelete, nearestOffset,
		rangeToRemove = this.getSelection().getCoveringRange();
 
	Iif ( !rangeToRemove || rangeToRemove.isCollapsed() ) {
		return this;
	}
 
	// Try to build a removal transaction. At the moment the transaction processor is only
	// capable of merging nodes of the same type and at the same depth level, so some or all
	// of rangeToRemove may be left untouched (and in some cases tx may not remove anything
	// at all).
	tx = ve.dm.TransactionBuilder.static.newFromRemoval( this.document, rangeToRemove );
	this.change( tx );
	rangeAfterRemove = tx.translateRange( rangeToRemove );
 
	if (
		!rangeAfterRemove.isCollapsed() &&
		( endNode = this.document.getBranchNodeFromOffset( rangeAfterRemove.end, false ) ) &&
		// If endNode is within our rangeAfterRemove, then we shouldn't delete it
		endNode.getRange().start >= rangeAfterRemove.end
	) {
		// If after processing removal transaction range is not collapsed it means that
		// not everything got merged nicely, so we process further to deal with
		// remaining content.
 
		startNode = this.document.getBranchNodeFromOffset( rangeAfterRemove.start, false );
		if ( startNode.getRange().isCollapsed() ) {
			// If startNode has no content then just delete that node instead of
			// moving content from endNode to startNode. This prevents content being
			// inserted into empty structure, e.g. and empty heading will be deleted
			// rather than "converting" the paragraph beneath to a heading.
			while ( true ) {
				tx = ve.dm.TransactionBuilder.static.newFromRemoval( this.document, startNode.getOuterRange() );
				startNode = startNode.getParent();
				this.change( tx );
 
				// If the removal resulted in the parent node being empty (e.g.
				// when startNode was a paragraph inside a list item), loop to
				// delete the parent node. Else break.
				if ( !( startNode && startNode.children.length === 0 && (
					startNode.hasSlugAtOffset( startNode.getRange().start ) ||
					// These would be uneditable when empty, so remove
					startNode instanceof ve.dm.DefinitionListNode ||
					startNode instanceof ve.dm.ListNode
				) && startNode.canHaveChildrenNotContent() ) ) {
					break;
				}
				// Only fix up the range if we're going to loop (if we're not, the
				// range collapse using getNearestContentOffset below will already
				// do the fix up).
				rangeAfterRemove = tx.translateRange( rangeAfterRemove );
			}
		} else {
			// If startNode has content then take remaining content from endNode and
			// append it into startNode. Then remove endNode (and recursively any
			// ancestor that the removal causes to be empty).
			endNodeData = this.document.getData( endNode.getRange() );
			nodeToDelete = endNode;
			nodeToDelete.traverseUpstream( function ( node ) {
				var parent = node.getParent();
				if ( parent.children.length === 1 ) {
					nodeToDelete = parent;
					return true;
				} else {
					return false;
				}
			} );
			tx = ve.dm.TransactionBuilder.static.newFromRemoval(
				this.document,
				nodeToDelete.getOuterRange()
			);
			Eif ( !tx.isNoOp() ) {
				// Move contents of endNode into startNode, and delete nodeToDelete
				this.change( tx );
				this.change( ve.dm.TransactionBuilder.static.newFromInsertion(
					this.document,
					rangeAfterRemove.start,
					endNodeData
				) );
			}
		}
	}
 
	// Use a collapsed range at a content offset beside rangeAfterRemove.start
	nearestOffset = this.document.data.getNearestContentOffset(
		rangeAfterRemove.start,
		// If undefined (e.g. cut), default to backwards movement
		directionAfterDelete || -1
	);
	if ( nearestOffset > -1 ) {
		rangeAfterRemove = new ve.Range( nearestOffset );
	} else {
		// There isn't a valid content offset. This probably means that we're
		// in a strange document which consists entirely of aliens, with no
		// text entered. This is unusual, but not impossible. As such, just
		// collapse the selection and accept that it won't really be
		// meaningful in most cases.
		rangeAfterRemove = new ve.Range( rangeAfterRemove.start );
	}
 
	this.change( [], new ve.dm.LinearSelection( rangeAfterRemove ) );
 
	return this;
};
 
/**
 * Convert each content branch in the fragment from one type to another.
 *
 * @param {string} type Element type to convert to
 * @param {Object} [attr] Initial attributes for new element
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.convertNodes = function ( type, attr ) {
	var range = this.getSelection().getCoveringRange();
	Iif ( !range ) {
		return this;
	}
 
	this.change( ve.dm.TransactionBuilder.static.newFromContentBranchConversion(
		this.document, range, type, attr
	) );
 
	return this;
};
 
/**
 * Wrap each node in the fragment with one or more elements.
 *
 * A wrapper object is a linear model element; a plain object containing a type property and an
 * optional attributes property.
 *
 * Example:
 *     // fragment is a selection of: <p>a</p><p>b</p>
 *     fragment.wrapNodes(
 *         [{ type: 'list', attributes: { style: 'bullet' } }, { type: 'listItem' }]
 *     )
 *     // fragment is now a selection of: <ul><li><p>a</p></li></ul><ul><li><p>b</p></li></ul>
 *
 * @param {Object|Object[]} wrapper Wrapper object, or array of wrapper objects (see above)
 * @param {string} wrapper.type Node type of wrapper
 * @param {Object} [wrapper.attributes] Attributes of wrapper
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.wrapNodes = function ( wrapper ) {
	var range = this.getSelection().getCoveringRange();
	Iif ( !range ) {
		return this;
	}
 
	Iif ( !Array.isArray( wrapper ) ) {
		wrapper = [ wrapper ];
	}
	this.change(
		ve.dm.TransactionBuilder.static.newFromWrap( this.document, range, [], [], [], wrapper )
	);
 
	return this;
};
 
/**
 * Unwrap nodes in the fragment out of one or more elements.
 *
 * Example:
 *     // fragment is a selection of: <ul>「<li><p>a</p></li><li><p>b</p></li>」</ul>
 *     fragment.unwrapNodes( 1, 1 )
 *     // fragment is now a selection of: 「<p>a</p><p>b</p>」
 *
 * @param {number} outerDepth Number of nodes outside the selection to unwrap
 * @param {number} innerDepth Number of nodes inside the selection to unwrap
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.unwrapNodes = function ( outerDepth, innerDepth ) {
	var i,
		range = this.getSelection().getCoveringRange(),
		innerUnwrapper = [],
		outerUnwrapper = [];
 
	Iif ( !range ) {
		return this;
	}
 
	if ( range.getLength() < innerDepth * 2 ) {
		throw new Error( 'cannot unwrap by greater depth than maximum theoretical depth of selection' );
	}
 
	for ( i = 0; i < innerDepth; i++ ) {
		innerUnwrapper.push( this.document.data.getData( range.start + i ) );
	}
	for ( i = outerDepth; i > 0; i-- ) {
		outerUnwrapper.push( this.document.data.getData( range.start - i ) );
	}
 
	this.change( ve.dm.TransactionBuilder.static.newFromWrap(
		this.document, range, outerUnwrapper, [], innerUnwrapper, []
	) );
 
	return this;
};
 
/**
 * Change the wrapping of each node in the fragment from one type to another.
 *
 * A wrapper object is a linear model element; a plain object containing a type property and an
 * optional attributes property.
 *
 * Example:
 *     // fragment is a selection of: <dl><dt><p>a</p></dt></dl><dl><dt><p>b</p></dt></dl>
 *     fragment.rewrapNodes(
 *         2,
 *         [{ type: 'list', attributes: { style: 'bullet' } }, { type: 'listItem' }]
 *     )
 *     // fragment is now a selection of: <ul><li><p>a</p></li></ul><ul><li><p>b</p></li></ul>
 *
 * @param {number} depth Number of nodes to unwrap
 * @param {Object|Object[]} wrapper Wrapper object, or array of wrapper objects (see above)
 * @param {string} wrapper.type Node type of wrapper
 * @param {Object} [wrapper.attributes] Attributes of wrapper
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.rewrapNodes = function ( depth, wrapper ) {
	var i,
		range = this.getSelection().getCoveringRange(),
		unwrapper = [];
 
	Iif ( !range ) {
		return this;
	}
 
	Iif ( !Array.isArray( wrapper ) ) {
		wrapper = [ wrapper ];
	}
 
	Iif ( range.getLength() < depth * 2 ) {
		throw new Error( 'cannot unwrap by greater depth than maximum theoretical depth of selection' );
	}
 
	for ( i = 0; i < depth; i++ ) {
		unwrapper.push( this.document.data.getData( range.start + i ) );
	}
 
	this.change(
		ve.dm.TransactionBuilder.static.newFromWrap( this.document, range, [], [], unwrapper, wrapper )
	);
 
	return this;
};
 
/**
 * Wrap nodes in the fragment with one or more elements.
 *
 * A wrapper object is a linear model element; a plain object containing a type property and an
 * optional attributes property.
 *
 * Example:
 *     // fragment is a selection of: <p>a</p><p>b</p>
 *     fragment.wrapAllNodes(
 *         { type: 'list', attributes: { style: 'bullet' } },
 *         { type: 'listItem' }
 *     )
 *     // fragment is now a selection of: <ul><li><p>a</p></li><li><p>b</p></li></ul>
 *
 * Example:
 *     // fragment is a selection of: <p>a</p><p>b</p>
 *     fragment.wrapAllNodes(
 *         [{ type: 'list', attributes: { style: 'bullet' } }, { type: 'listItem' }]
 *     )
 *     // fragment is now a selection of: <ul><li><p>a</p><p>b</p></li></ul>
 *
 * @param {Object|Object[]} wrapOuter Opening element(s) to wrap around the range
 * @param {Object|Object[]} wrapEach Opening element(s) to wrap around each top-level element in the range
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.wrapAllNodes = function ( wrapOuter, wrapEach ) {
	var range = this.getSelection().getCoveringRange();
	Iif ( !range ) {
		return this;
	}
 
	if ( !Array.isArray( wrapOuter ) ) {
		wrapOuter = [ wrapOuter ];
	}
 
	wrapEach = wrapEach || [];
 
	if ( !Array.isArray( wrapEach ) ) {
		wrapEach = [ wrapEach ];
	}
 
	this.change(
		ve.dm.TransactionBuilder.static.newFromWrap( this.document, range, [], wrapOuter, [], wrapEach )
	);
 
	return this;
};
 
/**
 * Change the wrapping of nodes in the fragment from one type to another.
 *
 * A wrapper object is a linear model element; a plain object containing a type property and an
 * optional attributes property.
 *
 * Example:
 *     // fragment is a selection of: <h1><p>a</p><p>b</p></h1>
 *     fragment.rewrapAllNodes( 1, { type: 'heading', attributes: { level: 2 } } );
 *     // fragment is now a selection of: <h2><p>a</p><p>b</p></h2>
 *
 * @param {number} depth Number of nodes to unwrap
 * @param {Object|Object[]} wrapper Wrapper object, or array of wrapper objects (see above)
 * @param {string} wrapper.type Node type of wrapper
 * @param {Object} [wrapper.attributes] Attributes of wrapper
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.rewrapAllNodes = function ( depth, wrapper ) {
	var i, innerRange,
		range = this.getSelection().getCoveringRange(),
		unwrapper = [];
 
	Iif ( !range ) {
		return this;
	}
 
	// TODO: preserve direction
	innerRange = new ve.Range(
		range.start + depth,
		range.end - depth
	);
 
	Iif ( !Array.isArray( wrapper ) ) {
		wrapper = [ wrapper ];
	}
 
	Iif ( range.getLength() < depth * 2 ) {
		throw new Error( 'cannot unwrap by greater depth than maximum theoretical depth of selection' );
	}
 
	for ( i = 0; i < depth; i++ ) {
		unwrapper.push( this.document.data.getData( range.start + i ) );
	}
 
	this.change(
		ve.dm.TransactionBuilder.static.newFromWrap( this.document, innerRange, unwrapper, wrapper, [], [] )
	);
 
	return this;
};
 
/**
 * Isolates the nodes in a fragment then unwraps them.
 *
 * The node selection is expanded to siblings. These are isolated such that they are the
 * sole children of the nearest parent element which can 'type' can exist in.
 *
 * The new isolated selection is then safely unwrapped.
 *
 * @param {string} isolateForType Node type to isolate for
 * @return {ve.dm.SurfaceFragment}
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.isolateAndUnwrap = function ( isolateForType ) {
	var nodes, startSplitNode, endSplitNode, startOffset, endOffset, oldExclude,
		allowedParents,
		insertions = [],
		outerDepth = 0,
		factory = ve.dm.nodeFactory,
		startSplitRequired = false,
		endSplitRequired = false,
		startSplitNodes = [],
		endSplitNodes = [],
		fragment = this;
 
	function createSplits( splitNodes, insertBefore ) {
		var i, length,
			adjustment = 0,
			data = [];
 
		for ( i = 0, length = splitNodes.length; i < length; i++ ) {
			data.unshift( { type: '/' + splitNodes[ i ].type } );
			data.push( splitNodes[ i ].getClonedElement() );
 
			if ( insertBefore ) {
				adjustment += 2;
			}
		}
 
		// Queue up transaction data
		insertions.push( {
			offset: insertBefore ? startOffset : endOffset,
			data: data
		} );
 
		startOffset += adjustment;
		endOffset += adjustment;
	}
 
	Iif ( !( this.selection instanceof ve.dm.LinearSelection ) ) {
		return this;
	}
 
	allowedParents = factory.getSuggestedParentNodeTypes( isolateForType );
	nodes = this.getSiblingNodes();
 
	// Find start split point, if required
	startSplitNode = nodes[ 0 ].node;
	startOffset = startSplitNode.getOuterRange().start;
	Iif ( allowedParents !== null ) {
		while ( allowedParents.indexOf( startSplitNode.getParent().type ) === -1 ) {
			if ( startSplitNode.getParent().indexOf( startSplitNode ) > 0 ) {
				startSplitRequired = true;
			}
			startSplitNode = startSplitNode.getParent();
			if ( startSplitRequired ) {
				startSplitNodes.unshift( startSplitNode );
			} else {
				startOffset = startSplitNode.getOuterRange().start;
			}
			outerDepth++;
		}
	}
 
	// Find end split point, if required
	endSplitNode = nodes[ nodes.length - 1 ].node;
	endOffset = endSplitNode.getOuterRange().end;
	Iif ( allowedParents !== null ) {
		while ( allowedParents.indexOf( endSplitNode.getParent().type ) === -1 ) {
			if ( endSplitNode.getParent().indexOf( endSplitNode ) < endSplitNode.getParent().getChildren().length - 1 ) {
				endSplitRequired = true;
			}
			endSplitNode = endSplitNode.getParent();
			if ( endSplitRequired ) {
				endSplitNodes.unshift( endSplitNode );
			} else {
				endOffset = endSplitNode.getOuterRange().end;
			}
		}
	}
 
	// We have to exclude insertions while doing splits, because we want the range to be
	// exactly what we're isolating, we don't want it to grow to include the separators
	// we're inserting (which would happen if one of them is immediately adjacent to the range)
	oldExclude = this.willExcludeInsertions();
	this.setExcludeInsertions( true );
 
	Iif ( startSplitRequired ) {
		createSplits( startSplitNodes, true );
	}
 
	Iif ( endSplitRequired ) {
		createSplits( endSplitNodes, false );
	}
 
	insertions.forEach( function ( insertion ) {
		fragment.change(
			ve.dm.TransactionBuilder.static.newFromInsertion( fragment.getDocument(), insertion.offset, insertion.data )
		);
	} );
 
	this.setExcludeInsertions( oldExclude );
 
	this.unwrapNodes( outerDepth, 0 );
 
	return this;
};