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

97.06% Statements 429/442
92.88% Branches 248/267
100% Functions 42/42
97.06% Lines 429/442
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                                                                                                                                                                                    1150× 1150× 2430×                   1056×     13230×             704×   12526×     1056× 1056×   1056×                       2430×     1279×     1279× 376×   903× 903× 903×     371×   532× 274×     258×     258× 258× 258×     35×     35× 34×                   1314×   1314× 632×     682× 682× 703× 703×     703× 703× 703× 682×     682× 305×   377×     2660×           2660× 4686×   2660×   1314× 1279×   35×     1346×     2660× 2081×   579×   2660×           2660×       2660× 7871× 7871×           5343×   2528×   461× 440× 440×       2528×       2660× 2660× 2660× 2660× 2660×       1121×     1121×   277× 277×   1121×       2430× 2430× 2430× 2430×       2430×     549× 549× 549× 549× 549×   504× 504× 504× 455×   504× 504×   164× 164× 164× 164× 164× 164×   506× 506× 506× 506× 506×   641× 641× 641×   66× 66× 66× 66× 66× 66× 66×                       1155× 1155×   1150×                 1160× 1160×     1160× 1160× 1160× 1160× 1160× 1160× 1160× 1160×               1155×   1155× 3580×   1151×                   3591× 3591× 2308× 2308× 7366×   1283× 1242× 1599× 1599× 1091× 1091×     508× 508× 574× 574×   508× 508×   1242× 1654× 1654× 1011× 1009×     643× 643× 707× 707×   643× 643×                     1152× 1152× 1530× 1530×       1151×   379×     86× 293×     293× 293×   379×                 16767× 16767× 266×   16501×         16501× 16501× 16501× 16501×                                       7745×       7745× 7540×   7745×           7423× 7423× 7423×     7423×     7423×     7423×       322× 322×   25× 24× 17×   24×   212× 46× 45× 36×     166× 166× 165× 94×       210×           78× 51× 51× 51× 14×       27×   27× 27×         78× 78×   319×               1599×       1599× 366×     1599× 279× 1320× 230× 1090× 546× 544× 544×                 1654×     1654× 1011× 1011×   643× 643×     1654× 506×         506× 506× 505×     505× 1148× 643× 643× 83×   505× 505× 460× 460× 460× 214×             45× 14×   45× 45×                   781× 781× 230×   551×             622× 622× 551×                 513×     513×   512×           512× 284×                 643×   643×   643×           643× 560×                 166×       166×   165×           165× 165× 71×                 71×           71×   69×             69× 69× 16×                 551×   551×           551×               509×   509× 279× 279×   230× 230×   509×           509×                 2225×   2225× 5715× 5715× 3386×   5715×   2225×                   2225×   2225× 931×   1294×   2225× 716× 1342× 791×   551×                     17802×               17898×                 17799×                 17894×                     35700× 35700× 3339× 3339× 3339× 55×   3339× 32361× 5257× 5257× 1913×   5257×   27104×                     35693×     35693×   35693× 51365× 51365× 134004× 134004× 94112×   39892× 39892×   39892×   36735×       3157×     3157×   458×       51365× 51365× 32536×     35693×                 1552×               835×               2228×                   714×   714× 241×   473×                   679×         679×     678×     677× 621×       621×                
/*!
 * VisualEditor DataModel TreeModifier class.
 *
 * @copyright 2011-2019 VisualEditor Team and others; see http://ve.mit-license.org
 */
 
/**
 * DataModel tree modifier, following the algorithm in T162762.
 *
 * The top-level process() method applies a transaction to the document in two stages. First,
 * calculateTreeOperations() translates the linear transaction into tree operations; then,
 * applyTreeOperations() updates both the linear model and the document tree simultaneously.
 *
 * Each tree operation takes one of the following forms:
 *
 * { type: 'insertNode', isContent: {boolean}, at: {Path}, element: {OpenElementLinModItem} }
 * { type: 'removeNode', isContent: {boolean}, at: {Path}, element: {OpenElementLinModItem} }
 * { type: 'moveNode', isContent: {boolean}, from: {Path}, to: {Path} }
 * { type: 'insertText', isContent: true, at: {Path}, data: {TextLinModItem[]} }
 * { type: 'removeText', isContent: true, at: {Path}, data: {TextLinModItem[]} }
 * { type: 'moveText', isContent: true, from: {Path}, to: {Path}, length: {number} }
 *
 * Note that moveNode/moveText do not specify what content is being moved, and all the Node
 * operations always operate on a single node at a time.
 *
 * {Path} is number[] representing the tree path from the DocumentNode to the position, except
 * that within ContentBranchNodes, the offset is the linearized offset of the position.
 *
 * {OpenElementLinModItem} is the linear model value representing the node being inserted or
 * removed, like { type: 'paragraph' } .
 *
 * {TextLinModItem[]} is the linear model values representing the text, like
 * [ 'y', 'o', 'u', ' ', [ 'm', [ 'he4e7c54e2204d10b ] ], [ 'e' 'he4e7c54e2204d10b ] ] .
 *
 * The isContent flag is true if the operation is taking place inside a ContentBranchNode
 * (so it is always true for text).
 *
 * NOTE: Instances of this class are not recyclable: you can only call .process( tx ) on them once.
 *
 * @class
 * @constructor
 */
ve.dm.TreeModifier = function VeDmTreeModifier() {
	// XXX we only need these two for dump() in tests
	this.document = null;
	this.insertions = null;
 
	/**
	 * @property {Array} data Live document linear data
	 */
	this.data = null;
 
	/**
	 * @property {ve.dm.Node[]} deletions Array (acting as set) of removed nodes
	 */
	this.deletions = null;
 
	/**
	 * @property {ve.dm.TreeCursor} remover Tree cursor for removals
	 */
	this.remover = null;
 
	/**
	 * @property {ve.dm.TreeCursor} inserter Tree cursor for insertions
	 */
	this.inserter = null;
 
	/**
	 * @property {Object[]} treeOps Array of tree ops being built
	 */
	this.treeOps = null;
 
	/**
	 * @property {number[]} insertedNodes Nodes to be inserted at context
	 */
	this.insertedNodes = null;
 
	/**
	 * @property {number[]} insertedPositions Position within nodes to be inserted
	 */
	this.insertedPositions = null;
 
	/**
	 * @property {Object} adjustmentTree Sparse tree, paths as indexes
	 * @property {number} adjustmentTree.inserted Child items inserted at this position
	 * @property {number} adjustmentTree.removed Child items removed at this position
	 * @property {Object} adjustmentTree.i Subtree at position i
	 */
	this.adjustmentTree = null;
};
 
OO.initClass( ve.dm.TreeModifier );
 
// Static methods
 
/**
 * Apply tree operations to document tree and linear data simultaneously
 *
 * @param {boolean} isReversed Whether the transaction is an undo
 * @param {ve.dm.Document} document The document to modify
 * @param {Object[]} treeOps The tree operations
 */
ve.dm.TreeModifier.static.applyTreeOperations = function ( isReversed, document, treeOps ) {
	var i, iLen;
	for ( i = 0, iLen = treeOps.length; i < iLen; i++ ) {
		this.applyTreeOperation( isReversed, document, treeOps[ i ] );
	}
};
 
/**
 * Throw an exception if two pieces of linear data are not equal
 *
 * @param {Array} actual Document linear data to test
 * @param {Array} expected Expected linear data to test against
 */
ve.dm.TreeModifier.static.checkEqualData = function ( actual, expected ) {
	var jActual, jExpected;
 
	function replacer( name, value ) {
		// TODO: replace this check with data equality class method checks
		if (
			name === 'changesSinceLoad' ||
			name === 'originalDomElementsHash' ||
			name === 'originalMw' ||
			name === 'mw' ||
			name === 'contentsUsed'
		) {
			return undefined;
		}
		return value;
	}
 
	jActual = JSON.stringify( actual, replacer );
	jExpected = JSON.stringify( expected, replacer );
 
	Iif ( jActual !== jExpected ) {
		throw new Error( 'Expected ' + jExpected + ' but got ' + jActual );
	}
};
 
/**
 * Apply a tree operation to document tree and linear data simultaneously
 *
 * @param {boolean} isReversed Whether the transaction is an undo
 * @param {ve.dm.Document} document The document to modify
 * @param {Object} treeOp The tree operation
 */
ve.dm.TreeModifier.static.applyTreeOperation = function ( isReversed, document, treeOp ) {
	var wantText, f, t, a, data, node, adjustment, nodeToInsert,
		changedBranchNodes = [];
 
	function ensureText( position ) {
		var pre, post, newNode,
			node = position.node,
			offset = position.offset;
		if ( node.type === 'text' ) {
			return position;
		}
		pre = node.children[ offset - 1 ];
		post = node.children[ offset ];
		if ( post && post.type === 'text' ) {
			// Prefer post to pre, because we might want to remove text. (We shouldn't
			// really have two adjacent text nodes, though)
			return { node: post, offset: 0 };
		}
		if ( pre && pre.type === 'text' ) {
			return { node: pre, offset: pre.length };
		}
		// There are no adjacent text nodes; insert one
		Iif ( !node.hasChildren() ) {
			throw new Error( 'Cannot add a child to ' + node.type + ' node' );
		}
		newNode = new ve.dm.TextNode( 0 );
		node.splice( offset, 0, newNode );
		return { node: newNode, offset: 0 };
	}
 
	function ensureNotText( position ) {
		var parentNode, parentOffset, length, newNode,
			node = position.node,
			offset = position.offset;
		if ( node.type !== 'text' ) {
			return position;
		}
		parentNode = node.parent;
		parentOffset = node.parent.children.indexOf( node );
		Iif ( offset === 0 ) {
			// Position before the text node
			return { node: parentNode, offset: parentOffset };
		}
		Iif ( offset === node.length ) {
			return { node: parentNode, offset: parentOffset + 1 };
		}
		// Else we must split the text node
		length = node.length - offset;
		node.adjustLength( -length );
		newNode = new ve.dm.TextNode( length );
		parentNode.splice( parentOffset + 1, 0, newNode );
		return { node: parentNode, offset: parentOffset + 1 };
	}
 
	function findContentPosition( node, contentOffset ) {
		var i, offset, childLength, child;
 
		if ( contentOffset === 0 ) {
			return { node: node, offset: 0 };
		}
		// Find the child that will take us up to or past the contentOffset
		offset = 0;
		for ( i = 0; ; i++ ) {
			child = node.children[ i ];
			Iif ( !child ) {
				throw new Error( 'Node does not reach offset' );
			}
			childLength = child.getOuterLength();
			offset += childLength;
			if ( offset >= contentOffset ) {
				break;
			}
		}
		if ( offset === contentOffset ) {
			return { node: node, offset: i + 1 };
		}
		return { node: child, offset: contentOffset - offset + childLength };
	}
 
	function prepareSplice( pathAndOffset, isContent, wantText ) {
		var i, iLen, position,
			path = pathAndOffset.slice( 0, -1 ),
			offset = pathAndOffset[ pathAndOffset.length - 1 ],
			node = document.documentNode;
 
		// Find node
		for ( i = 0, iLen = path.length; i < iLen; i++ ) {
			node = node.children[ path[ i ] ];
		}
		if ( isContent ) {
			// Determine position from (linearized) content offset
			if ( wantText ) {
				position = ensureText( findContentPosition( node, offset ) );
			} else {
				position = ensureNotText( findContentPosition( node, offset ) );
			}
		} else {
			position = { node: node, offset: offset };
		}
		// Get linear offset
		if ( position.node.type === 'text' || position.offset === 0 ) {
			position.linearOffset = position.node.getRange().start + position.offset;
		} else {
			position.linearOffset = position.node.children[ position.offset - 1 ].getOuterRange().end;
		}
		return position;
	}
 
	// Increment the change counter on the closest containing branch node at this offset
	// (This is used when converting to/from HTML, to decide whether loaded metadata offsets
	// need round tripping)
	function markBranchNodeChanged( offset ) {
		var item,
			adjustment = isReversed ? -1 : 1,
			i = offset - 1;
 
		while ( i >= 0 ) {
			item = document.data.getData( i-- );
			if ( !(
				ve.dm.LinearData.static.isOpenElementData( item ) &&
				ve.dm.nodeFactory.lookup(
					ve.dm.LinearData.static.getType( item )
				).prototype instanceof ve.dm.BranchNode
			) ) {
				continue;
			}
			if ( item.internal && item.internal.changesSinceLoad !== undefined ) {
				// Guard against marking the same node twice
				if ( changedBranchNodes.indexOf( item ) === -1 ) {
					changedBranchNodes.push( item );
					item.internal.changesSinceLoad += adjustment;
				}
			}
			// This is a branch node boundary, so go no further
			break;
		}
	}
 
	function spliceLinear( offset, remove, data ) {
		var content;
		data = data || [];
		content = ve.batchSplice( document.data, offset, remove, data );
		markBranchNodeChanged( offset );
		return content;
	}
 
	// Removes empty text node, or joins consecutive text nodes, at offset
	function healTextNodes( node, offset ) {
		var pre = node.children[ offset - 1 ],
			post = node.children[ offset ];
 
		if ( post && post.type === 'text' && post.length === 0 ) {
			// Remove empty text node
			node.splice( offset, 1 );
			post = node.children[ offset ];
		}
		if ( pre && post && pre.type === 'text' && post.type === 'text' ) {
			pre.adjustLength( post.length );
			node.splice( offset, 1 );
		}
	}
 
	wantText = treeOp.type.slice( -4 ) === 'Text';
	f = treeOp.from && prepareSplice( treeOp.from, treeOp.isContent, wantText );
	t = treeOp.to && prepareSplice( treeOp.to, treeOp.isContent, wantText );
	a = treeOp.at && prepareSplice( treeOp.at, treeOp.isContent, wantText );
 
	// Always adjust linear data before tree, to ensure consistency when node events
	// are emitted.
	switch ( treeOp.type ) {
		case 'removeNode':
			// The node should have no contents, so its outer length should be 2
			data = spliceLinear( a.linearOffset, 2 );
			this.checkEqualData( data, [ treeOp.element, { type: '/' + treeOp.element.type } ] );
			a.node.splice( a.offset, 1 );
			healTextNodes( a.node, a.offset );
			break;
		case 'insertNode':
			spliceLinear( a.linearOffset, 0, [ treeOp.element, { type: '/' + treeOp.element.type } ] );
			nodeToInsert = ve.dm.nodeFactory.createFromElement( treeOp.element );
			if ( nodeToInsert instanceof ve.dm.BranchNode ) {
				nodeToInsert.setupBlockSlugs();
			}
			a.node.splice( a.offset, 0, nodeToInsert );
			break;
		case 'moveNode':
			data = spliceLinear( f.linearOffset, f.node.children[ f.offset ].getOuterLength() );
			node = f.node.splice( f.offset, 1 )[ 0 ];
			adjustment = t.linearOffset > f.linearOffset ? data.length : 0;
			spliceLinear( t.linearOffset - adjustment, 0, data );
			t.node.splice( t.offset, 0, node );
			break;
		case 'removeText':
			data = spliceLinear( a.linearOffset, treeOp.data.length );
			this.checkEqualData( data, treeOp.data );
			a.node.adjustLength( -treeOp.data.length );
			healTextNodes( a.node.parent, a.node.parent.children.indexOf( a.node ) );
			break;
		case 'insertText':
			spliceLinear( a.linearOffset, 0, treeOp.data );
			a.node.adjustLength( treeOp.data.length );
			break;
		case 'moveText':
			data = spliceLinear( f.linearOffset, treeOp.length );
			f.node.adjustLength( -treeOp.length );
			healTextNodes( f.node.parent, f.node.parent.children.indexOf( f.node ) );
			adjustment = t.linearOffset > f.linearOffset ? data.length : 0;
			spliceLinear( t.linearOffset - adjustment, 0, data );
			t.node.adjustLength( treeOp.length );
			break;
		default:
			throw new Error( 'Unknown tree op type: ' + treeOp.type );
	}
};
 
/**
 * The top level method: modify document tree according to transaction
 *
 * @param {ve.dm.Document} document The document
 * @param {ve.dm.Transaction} transaction The transaction
 */
ve.dm.TreeModifier.prototype.process = function ( document, transaction ) {
	this.setup( document );
	this.calculateTreeOperations( transaction );
	// Prior rollback logic removed: treeOps is now guaranteed to work
	this.constructor.static.applyTreeOperations( transaction.isReversed, document, this.treeOps );
};
 
/**
 * Setup state variables
 *
 * @param {ve.dm.Document} document The document to be processed
 */
ve.dm.TreeModifier.prototype.setup = function ( document ) {
	// XXX we only need these two properties for dump() in tests
	this.document = document;
	this.insertions = [];
 
	// Initialize state
	this.data = document.data;
	this.deletions = [];
	this.remover = new ve.dm.TreeCursor( document.getDocumentNode(), [] );
	this.inserter = new ve.dm.TreeCursor( document.getDocumentNode(), this.deletions );
	this.treeOps = [];
	this.insertedNodes = [];
	this.insertedPositions = [];
	this.adjustmentTree = {};
};
 
/**
 * Transform linear operations into tree operations
 *
 * @param {ve.dm.Transaction} transaction The transaction
 */
ve.dm.TreeModifier.prototype.calculateTreeOperations = function ( transaction ) {
	var i, iLen,
		linearOps = transaction.operations;
	for ( i = 0, iLen = linearOps.length; i < iLen; i++ ) {
		this.processLinearOperation( linearOps[ i ] );
	}
	this.processImplicitFinalRetain();
};
 
/**
 * Translate a linear operation into tree operations
 *
 * #processImplicitFinalRetain should be called once all operations have been processed
 *
 * @param {Object} linearOp The linear operation
 */
ve.dm.TreeModifier.prototype.processLinearOperation = function ( linearOp ) {
	var retainLength, i, iLen, item, data;
	if ( linearOp.type === 'retain' ) {
		retainLength = linearOp.length;
		while ( retainLength > 0 ) {
			retainLength -= this.processRetain( retainLength );
		}
	} else if ( linearOp.type === 'replace' ) {
		for ( i = 0, iLen = linearOp.remove.length; i < iLen; i++ ) {
			item = linearOp.remove[ i ];
			if ( item.type ) {
				this.processRemove( item );
				continue;
			}
			// Group the whole current run of text, and process it
			data = [ item ];
			while ( ++i < iLen && !linearOp.remove[ i ].type ) {
				item = linearOp.remove[ i ];
				data.push( item );
			}
			i--;
			this.processRemove( data );
		}
		for ( i = 0, iLen = linearOp.insert.length; i < iLen; i++ ) {
			item = linearOp.insert[ i ];
			if ( item.type ) {
				this.processInsert( item );
				continue;
			}
			// Group the whole current run of text, and process it
			data = [ item ];
			while ( ++i < iLen && !linearOp.insert[ i ].type ) {
				item = linearOp.insert[ i ];
				data.push( item );
			}
			i--;
			this.processInsert( data );
		}
	}
	// Else the linear operation type must be 'attribute': do nothing
};
 
/**
 * Retain to the end of the content
 */
ve.dm.TreeModifier.prototype.processImplicitFinalRetain = function () {
	// Pretend there is an implicit retain to the end of the document
	// TODO: fix our tests so this is unnecessary, then check for exhaustion instead
	var node, retainLength, item;
	while ( true ) {
		node = this.remover.node;
		if ( !node || (
			node === this.remover.root &&
			this.remover.offset === node.children.length
		) ) {
			return;
		}
		if ( node.type === 'text' ) {
			// Retain all remaining text; if there is no remaining text then
			// retain a single offset.
			retainLength = Math.max( 1, node.length - this.remover.offset );
		} else Iif ( !node.hasChildren() ) {
			retainLength = 1;
		} else {
			item = node.children[ this.remover.offset ];
			retainLength = item ? item.getOuterLength() : 1;
		}
		this.processRetain( retainLength );
	}
};
 
/**
 * Test whether both pointers point to the same location
 *
 * @return {boolean} True if the paths and offsets are identical
 */
ve.dm.TreeModifier.prototype.cursorsMatch = function () {
	var rawRemoverPosition, rawInserterPosition, adjustedRemoverPosition, adjustedInserterPosition;
	if ( this.insertedPositions.length > 0 ) {
		return false;
	}
	rawRemoverPosition = this.getRawRemoverPosition( {
		path: this.remover.path,
		offset: this.remover.offset,
		node: this.remover.node
	} );
	rawInserterPosition = this.getRawInserterPosition();
	adjustedRemoverPosition = this.adjustRemoverPosition( rawRemoverPosition );
	adjustedInserterPosition = this.adjustInserterPosition( rawInserterPosition );
	return JSON.stringify( adjustedRemoverPosition ) ===
		JSON.stringify( adjustedInserterPosition );
};
 
/**
 * Process the retention of content passed by one step of the remover
 *
 * If the inserter and remover are at the same place, just skip content.
 *
 * Else the remover *feeds* the inserter:
 * - The inserter plans insertions in the (imagined, hypothetical) document
 * - But the only move it can make in the (immutable) real document is to step out of nodes
 * - It cannot skip past nodes (other than skipping remaining siblings when stepping out)
 * - If the remover steps into a node, the inserter creates a node of the same type
 * - If the remover crosses content, it is moved to the inserter
 * - If the remover steps out of a node, the inserter steps out of its node
 *
 * @param {number} maxLength The maximum amount of content to retain
 * @return {number} The amount of content retained
 */
ve.dm.TreeModifier.prototype.processRetain = function ( maxLength ) {
	var removerStep, inserterStep, element,
		remover = this.remover,
		inserter = this.inserter;
 
	if ( this.insertedPositions.length === 0 ) {
		this.inserter.crossIgnoredNodes();
	}
	if ( this.cursorsMatch() ) {
		// Pointers are in the same location, so advance them together.
		// This is the only way both pointers can ever enter the same node;
		// in any other case, a node entered at an 'open' tag by one pointer
		// is marked as either as a deletion or a creation, so the other
		// pointer will not follow.
		removerStep = remover.stepAtMost( maxLength );
		inserterStep = inserter.stepAtMost( maxLength );
		Iif ( !removerStep ) {
			throw new Error( 'Remover past end' );
		}
		Iif ( !inserterStep ) {
			throw new Error( 'Inserter past end' );
		}
		Iif ( !this.cursorsMatch() ) {
			throw new Error( 'Remover and inserter unexpectedly diverged' );
		}
		return removerStep.length;
	}
	// Else pointers are not in the same location (in fact they cannot lie in the
	// same node)
	removerStep = remover.stepAtMost( maxLength );
	switch ( removerStep.type ) {
		case 'crosstext':
			this.pushMoveTextOp( removerStep );
			if ( this.insertedPositions.length ) {
				this.insertedPositions[ this.insertedPositions.length - 1 ] += removerStep.length;
			}
			break;
		case 'cross':
			if ( removerStep.item.type === 'text' ) {
				this.pushMoveTextOp( removerStep );
				if ( this.insertedPositions.length ) {
					this.insertedPositions[ this.insertedPositions.length - 1 ] += removerStep.item.length;
				}
			} else {
				this.deletions.push( removerStep.item );
				this.pushMoveNodeOp( removerStep );
				if ( this.insertedPositions.length ) {
					this.insertedPositions[ this.insertedPositions.length - 1 ] +=
						this.isInsertionContent() ? 2 : 1;
				}
			}
			break;
		case 'open':
			this.deletions.push( removerStep.item );
			// Clone last open and step in
			element = removerStep.item.getClonedElement( true );
			this.pushInsertNodeOp( element );
			this.insertedNodes.push( element );
			// This 0 position is invalid if element is content (because the offset should be
			// linearized), but it will get popped immediately
			this.insertedPositions.push( 0 );
			break;
		case 'close':
			if ( this.insertedPositions.length ) {
				this.insertedNodes.pop();
				this.insertedPositions.pop();
				if ( this.insertedPositions.length ) {
					this.insertedPositions[ this.insertedPositions.length - 1 ] +=
						this.isInsertionContent() ? 2 : 1;
				}
			} else {
				if ( inserter.node.type === 'text' ) {
					inserter.stepOut();
				}
				inserterStep = inserter.stepOut();
				Iif ( inserterStep.item.type !== removerStep.item.type ) {
					throw new Error( 'Expected ' + removerStep.item.type + ', not ' +
		inserterStep.item.type );
				}
			}
			this.pushRemoveLastIfInDeletions();
			break;
	}
	return removerStep.length;
};
 
/**
 * Process the removal of some items
 *
 * @param {Object|Array} itemOrData An open tag, a close tag, or an array of text items
 */
ve.dm.TreeModifier.prototype.processRemove = function ( itemOrData ) {
	var cursorsMatch = this.cursorsMatch(),
		length = itemOrData.length || 1,
		step = this.remover.stepAtMost( length );
 
	if ( cursorsMatch && ( step.type === 'cross' || step.type === 'crosstext' ) ) {
		this.inserter.stepAtMost( length );
	}
 
	if ( step.type === 'crosstext' ) {
		this.pushRemoveTextOp( step );
	} else if ( step.type === 'cross' ) {
		this.pushRemoveLast();
	} else if ( step.type === 'open' ) {
		this.deletions.push( step.item );
	} else Eif ( step.type === 'close' ) {
		this.pushRemoveLastIfInDeletions();
	}
};
 
/**
 * Process the insertion an open tag, a close tag, or an array of text items
 *
 * @param {Object|Array} itemOrData An open tag, a close tag, or an array of text items
 */
ve.dm.TreeModifier.prototype.processInsert = function ( itemOrData ) {
	var item, type, data, element, step,
		inserter = this.inserter;
 
	if ( itemOrData.type ) {
		item = itemOrData;
		type = item.type.charAt( 0 ) === '/' ? 'close' : 'open';
	} else {
		data = itemOrData;
		type = 'crosstext';
	}
 
	if ( type === 'open' ) {
		if ( inserter.node.type === 'text' ) {
			// Step past the end of the text node, even if that skips past some
			// content (in which case the remover logically must later cross that
			// content in either processRemove or processRetain).
			inserter.stepOut();
		}
		element = ve.copy( item );
		this.pushInsertNodeOp( element );
		this.insertedNodes.push( element );
		// This 0 position is invalid if element is content (because the offset should be
		// linearized), but it will get popped immediately
		this.insertedPositions.push( 0 );
	} else if ( type === 'crosstext' ) {
		this.pushInsertTextOp( ve.copy( data ) );
		if ( this.insertedPositions.length ) {
			this.insertedPositions[ this.insertedPositions.length - 1 ] += data.length;
		}
	} else Eif ( type === 'close' ) {
		if ( this.insertedPositions.length ) {
			this.insertedNodes.pop();
			this.insertedPositions.pop();
			if ( this.insertedPositions.length ) {
				this.insertedPositions[ this.insertedPositions.length - 1 ] +=
					this.isInsertionContent() ? 2 : 1;
			}
		} else {
			// Step past the next close tag, even if that skips past some content (in which
			// case the remover logically must later cross that content in either
			// processRemove or processRetain).
			if ( inserter.node.type === 'text' ) {
				inserter.stepOut();
			}
			step = inserter.stepOut();
			if ( step.item.type !== item.type.slice( 1 ) ) {
				throw new Error( 'Expected closing for ' + step.item.type +
					' but got closing for ' + item.type.slice( 1 ) );
			}
		}
	}
};
 
/**
 * Push into treeOps the removal of the last remover step, which must be 'cross' or 'close'
 */
ve.dm.TreeModifier.prototype.pushRemoveLast = function () {
	var step = this.remover.lastStep;
	if ( step.item.type === 'text' ) {
		this.pushRemoveTextOp( step );
	} else {
		this.pushRemoveNodeOp( step );
	}
};
 
/**
 * Push into treeOps the removal of the last remover step, if that item marked as deleted
 */
ve.dm.TreeModifier.prototype.pushRemoveLastIfInDeletions = function () {
	var i = this.deletions.indexOf( this.remover.lastStep.item );
	if ( i !== -1 ) {
		this.pushRemoveLast();
	}
};
 
/**
 * Push into treeOps the node insertion at the current inserter position
 *
 * @param {ve.dm.Node} element The element to insert (inserted into treeOps without copying)
 */
ve.dm.TreeModifier.prototype.pushInsertNodeOp = function ( element ) {
	var isContent = this.isInsertionContent(),
		rawInserterPosition = this.getRawInserterPosition();
 
	this.checkCanInsertNodeType( element.type );
 
	this.treeOps.push( {
		type: 'insertNode',
		isContent: isContent,
		at: this.adjustInserterPosition( rawInserterPosition ),
		element: element
	} );
	if ( this.insertedPositions.length === 0 ) {
		this.modifyAdjustmentTree( rawInserterPosition, isContent ? 2 : 1, false );
	}
};
 
/**
 * Push into treeOps the text insertion at the current inserter position
 *
 * @param {Array} data The text data to insert
 */
ve.dm.TreeModifier.prototype.pushInsertTextOp = function ( data ) {
	var rawInserterPosition = this.getRawInserterPosition();
 
	this.checkCanInsertText();
 
	this.treeOps.push( {
		type: 'insertText',
		isContent: true,
		at: this.adjustInserterPosition( rawInserterPosition ),
		data: data
	} );
	if ( this.insertedPositions.length === 0 ) {
		this.modifyAdjustmentTree( rawInserterPosition, data.length, false );
	}
};
 
/**
 * Push into treeOps a move of a node to the current inserter position
 *
 * @param {Object} removerStep the remover step over the node; see ve.dm.TreeCursor#stepAtMost
 */
ve.dm.TreeModifier.prototype.pushMoveNodeOp = function ( removerStep ) {
	var rawRemoverPosition = this.getRawRemoverPosition( removerStep ),
		rawInserterPosition = this.getRawInserterPosition(),
		isContent = this.doesTypeTakeContent( removerStep.node.type );
 
	this.checkCanInsertNodeType( removerStep.item.type );
 
	this.treeOps.push( {
		type: 'moveNode',
		isContent: isContent,
		from: this.adjustRemoverPosition( rawRemoverPosition ),
		to: this.adjustInserterPosition( rawInserterPosition )
	} );
	this.modifyAdjustmentTree( rawRemoverPosition, isContent ? -2 : -1, true );
	if ( this.insertedPositions.length === 0 ) {
		this.modifyAdjustmentTree( rawInserterPosition, isContent ? 2 : 1, false );
	}
};
 
/**
 * Push into treeOps a move of some text to the current inserter position
 *
 * @param {Object} removerStep the remover step over the text; see ve.dm.TreeCursor#stepAtMost
 */
ve.dm.TreeModifier.prototype.pushMoveTextOp = function ( removerStep ) {
	var length = removerStep.type === 'crosstext' ?
			removerStep.length :
			removerStep.item.getLength(),
		rawRemoverPosition = this.getRawRemoverPosition( removerStep ),
		rawInserterPosition = this.getRawInserterPosition();
 
	this.checkCanInsertText();
 
	this.treeOps.push( {
		type: 'moveText',
		isContent: true,
		from: this.adjustRemoverPosition( rawRemoverPosition ),
		to: this.adjustInserterPosition( rawInserterPosition ),
		length: length
	} );
	this.modifyAdjustmentTree( rawRemoverPosition, -length, false );
	if ( this.insertedPositions.length === 0 ) {
		this.modifyAdjustmentTree( rawInserterPosition, length, false );
	}
};
 
/**
 * Push into treeOps a removal of a node
 *
 * @param {Object} removerStep the remover step over the node; see ve.dm.TreeCursor#stepAtMost
 */
ve.dm.TreeModifier.prototype.pushRemoveNodeOp = function ( removerStep ) {
	var rawRemoverPosition = this.getRawRemoverPosition( removerStep ),
		isContent = this.doesTypeTakeContent( removerStep.node.type );
	this.treeOps.push( {
		type: 'removeNode',
		isContent: isContent,
		at: this.adjustRemoverPosition( rawRemoverPosition ),
		element: removerStep.item.getClonedElement( true )
	} );
	this.modifyAdjustmentTree( rawRemoverPosition, isContent ? -2 : -1, true );
};
 
/**
 * Push into treeOps a removal of some text
 *
 * @param {Object} removerStep the remover step over the text; see ve.dm.TreeCursor#stepAtMost
 */
ve.dm.TreeModifier.prototype.pushRemoveTextOp = function ( removerStep ) {
	var start, end,
		rawRemoverPosition = this.getRawRemoverPosition( removerStep );
	if ( removerStep.type === 'crosstext' ) {
		start = removerStep.node.getRange().start + removerStep.offset;
		end = start + removerStep.length;
	} else {
		start = removerStep.item.getRange().start;
		end = removerStep.item.getRange().end;
	}
	this.treeOps.push( {
		type: 'removeText',
		isContent: true,
		at: this.adjustRemoverPosition( rawRemoverPosition ),
		data: ve.copy( this.data.slice( start, end ) )
	} );
	this.modifyAdjustmentTree( rawRemoverPosition, start - end, false );
};
 
/**
 * Return adjustment tree node at a given offset path, inserting it if necessary
 *
 * @param {number[]} position Offset path in the adjustment tree
 * @return {Object} The adjustment tree node
 */
ve.dm.TreeModifier.prototype.findOrCreateAdjustmentNode = function ( position ) {
	var i, len, offset,
		adjustmentNode = this.adjustmentTree;
	for ( i = 0, len = position.length; i < len; i++ ) {
		offset = position[ i ];
		if ( !adjustmentNode[ offset ] ) {
			adjustmentNode[ offset ] = {};
		}
		adjustmentNode = adjustmentNode[ offset ];
	}
	return adjustmentNode;
};
 
/**
 * Modify the adjustment in the adjustment tree at a given offset path
 *
 * @param {number[]} rawPosition Unadjusted offset path
 * @param {number} diff Adjustment at rawPosition
 * @param {boolean} deleteDescendants If true, delete all adjustments at paths descending from here
 */
ve.dm.TreeModifier.prototype.modifyAdjustmentTree = function ( rawPosition, diff, deleteDescendants ) {
	var i,
		adjustmentNode = this.findOrCreateAdjustmentNode( rawPosition );
	if ( diff > 0 ) {
		adjustmentNode.inserted = ( adjustmentNode.inserted || 0 ) + diff;
	} else {
		adjustmentNode.removed = ( adjustmentNode.removed || 0 ) - diff;
	}
	if ( deleteDescendants ) {
		for ( i in adjustmentNode ) {
			if ( i === 'inserted' || i === 'removed' ) {
				continue;
			}
			delete adjustmentNode[ i ];
		}
	}
};
 
/**
 * Get the raw position of a node stepped over by the remover
 *
 * @param {Object} step Remover step; see ve.dm.TreeCursor#stepAtMost
 * @return {number[]} The pathAndOffset, with offsets inside a ContentBranchNode linearized
 */
ve.dm.TreeModifier.prototype.getRawRemoverPosition = function ( step ) {
	return this.getRawPosition( step.path, step.offset, step.node );
};
 
/**
 * Get the raw position at the inserter
 *
 * @return {number[]} The pathAndOffset, with offsets inside a ContentBranchNode linearized
 */
ve.dm.TreeModifier.prototype.getRawInserterPosition = function () {
	return this.getRawPosition( this.inserter.path, this.inserter.offset, this.inserter.node );
};
 
/**
 * Get the adjusted position of a raw remover position
 *
 * @param {number[]} rawPosition The raw remover position
 * @return {number[]} Adjusted pathAndOffset, with offsets inside a ContentBranchNode linearized
 */
ve.dm.TreeModifier.prototype.adjustRemoverPosition = function ( rawPosition ) {
	return this.getAdjustedPosition( rawPosition, false );
};
 
/**
 * Get the adjusted position of a raw inserter position, XXX
 *
 * @param {number[]} rawPosition The raw inserter position (must be its current position)
 * @return {number[]} Adjusted pathAndOffset, with offsets inside a ContentBranchNode linearized, and including current position within nodes to be inserted, if any
 */
ve.dm.TreeModifier.prototype.adjustInserterPosition = function ( rawPosition ) {
	return this.getAdjustedPosition( rawPosition, true ).concat( this.insertedPositions );
};
 
/**
 * Get the raw position of a node, with offsets inside a ContentBranchNode linearized
 *
 * @param {number[]} path Path to a node
 * @param {number} offset Offset within the node
 * @param {ve.dm.Node} node The node
 * @return {number[]} The pathAndOffset, with offsets inside a ContentBranchNode linearized
 */
ve.dm.TreeModifier.prototype.getRawPosition = function ( path, offset, node ) {
	var i, numNodesBefore, linearizedOffset;
	if ( node.parent instanceof ve.dm.ContentBranchNode ) {
		numNodesBefore = path[ path.length - 1 ];
		linearizedOffset = offset;
		for ( i = 0; i < numNodesBefore; i++ ) {
			linearizedOffset += node.parent.children[ i ].getOuterLength();
		}
		return path.slice( 0, -1 ).concat( linearizedOffset );
	} else if ( node instanceof ve.dm.ContentBranchNode ) {
		linearizedOffset = 0;
		for ( i = 0; i < offset; i++ ) {
			linearizedOffset += node.children[ i ].getOuterLength();
		}
		return path.concat( linearizedOffset );
	} else {
		return path.concat( offset );
	}
};
 
/**
 * Get the adjusted position of a raw position
 *
 * @param {number[]} position The raw position
 * @param {boolean} isInserter True for an inserter position; false for a remover position
 * @return {number[]} Adjusted pathAndOffset, with offsets inside a ContentBranchNode linearized
 */
ve.dm.TreeModifier.prototype.getAdjustedPosition = function ( position, isInserter ) {
	var i, iLen, j, jLen, positionI, childNode, inserted, removed,
		node = this.adjustmentTree;
 
	position = position.slice();
	// Adjust each offset in the path so inserted nodes are counted
	for ( i = 0, iLen = position.length; i < iLen; i++ ) {
		positionI = position[ i ];
		for ( j = 0, jLen = positionI + 1; j < jLen; j++ ) {
			childNode = node[ j ];
			if ( !childNode ) {
				continue;
			}
			inserted = childNode.inserted || 0;
			removed = childNode.removed || 0;
 
			if ( i < iLen - 1 || j < jLen - 1 ) {
				// This offset is strictly before position
				position[ i ] += inserted - removed;
			} else {
				// This offset is exactly at position
				// Don't adjust for removals
				position[ i ] += inserted;
				// Adjust for insertions, except if we are the inserter and the insertion is incomplete
				// (note if insertedNodes.length > 0, then also inserted > 0)
				if ( isInserter && this.insertedNodes.length > 0 ) {
					// Incomplete means we are inside a (non text) node
					position[ i ]--;
				}
			}
		}
		node = node[ positionI ];
		if ( !node ) {
			break;
		}
	}
	return position;
};
 
/**
 * Test whether a node type takes content
 *
 * @param {string} type The name of a ve.dm.Node type
 * @return {boolean} Whether that type takes content
 */
ve.dm.TreeModifier.prototype.doesTypeTakeContent = function ( type ) {
	return !!ve.dm.nodeFactory.canNodeContainContent( type );
};
 
/**
 * Test whether the inserter is at a content position
 *
 * @return {boolean} Whether the inserter is at a content position
 */
ve.dm.TreeModifier.prototype.isInsertionContent = function () {
	return this.doesTypeTakeContent( this.getTypeAtInserter() );
};
 
/**
 * Get the type of the node in which the inserter lies
 *
 * @return {string} The node type
 */
ve.dm.TreeModifier.prototype.getTypeAtInserter = function () {
	return this.insertedNodes.length > 0 ?
		this.insertedNodes[ this.insertedNodes.length - 1 ].type :
		this.inserter.node.type;
};
 
/**
 * Throw an error if the inserter is not in a content position
 *
 * @throws {Error} Cannot insert text into a foo node
 */
ve.dm.TreeModifier.prototype.checkCanInsertText = function () {
	var parentType = this.getTypeAtInserter();
 
	if ( parentType === 'text' ) {
		return;
	}
	if ( !ve.dm.nodeFactory.canNodeContainContent( parentType ) ) {
		throw new Error( 'Cannot insert text into a ' + parentType + ' node' );
	}
};
 
/**
 * Throw an error if the inserter node cannot take a child of a specified type
 *
 * @param {string} nodeType The node type
 * @throws {Error} Cannot add child
 */
ve.dm.TreeModifier.prototype.checkCanInsertNodeType = function ( nodeType ) {
	var parentType = this.getTypeAtInserter(),
		nodeClass = ve.dm.nodeFactory.lookup( nodeType ),
		parentClass = ve.dm.nodeFactory.lookup( parentType ),
		childNodeTypes = parentClass.static.childNodeTypes;
 
	if ( Array.isArray( childNodeTypes ) && childNodeTypes.length === 0 ) {
		throw new Error( 'Cannot add a child to ' + parentType + ' node' );
	}
 
	if ( nodeClass.static.isContent && !parentClass.static.canContainContent ) {
		throw new Error( 'Cannot add content node (' + nodeType + ') to a ' + parentType + ' node' );
	}
 
	if ( !nodeClass.static.isMetaData ) {
		Iif ( !nodeClass.static.isContent && parentClass.static.canContainContent ) {
			throw new Error( 'Cannot add structure node (' + nodeType + ') to a ' + parentType + ' node' );
		}
 
		Iif ( Array.isArray( childNodeTypes ) && childNodeTypes.indexOf( nodeType ) === -1 ) {
			throw new Error( 'Cannot add a ' + nodeType + ' node to ' + parentType + ' node' );
		}
	}
};
 
/* Initialization */
 
ve.dm.treeModifier = new ve.dm.TreeModifier();