Explorar el Código

Merge branch 'master' into t/92

Piotrek Koszuliński hace 10 años
padre
commit
0c462b7a60
Se han modificado 67 ficheros con 6559 adiciones y 2023 borrados
  1. 0 124
      packages/ckeditor5-engine/src/document/delta/transaction-base.js
  2. 0 159
      packages/ckeditor5-engine/src/document/document.js
  3. 0 87
      packages/ckeditor5-engine/src/document/operation/operation.js
  4. 0 177
      packages/ckeditor5-engine/src/document/position.js
  5. 0 85
      packages/ckeditor5-engine/src/document/range.js
  6. 0 21
      packages/ckeditor5-engine/src/document/transaction.js
  7. 3 3
      packages/ckeditor5-engine/src/treemodel/attribute.js
  8. 21 0
      packages/ckeditor5-engine/src/treemodel/batch.js
  9. 3 3
      packages/ckeditor5-engine/src/treemodel/character.js
  10. 47 42
      packages/ckeditor5-engine/src/treemodel/delta/attributedelta.js
  11. 123 0
      packages/ckeditor5-engine/src/treemodel/delta/batch-base.js
  12. 9 9
      packages/ckeditor5-engine/src/treemodel/delta/delta.js
  13. 10 10
      packages/ckeditor5-engine/src/treemodel/delta/insertdelta.js
  14. 18 18
      packages/ckeditor5-engine/src/treemodel/delta/mergedelta.js
  15. 4 4
      packages/ckeditor5-engine/src/treemodel/delta/register.js
  16. 8 8
      packages/ckeditor5-engine/src/treemodel/delta/removedelta.js
  17. 15 15
      packages/ckeditor5-engine/src/treemodel/delta/splitdelta.js
  18. 228 0
      packages/ckeditor5-engine/src/treemodel/document.js
  19. 41 43
      packages/ckeditor5-engine/src/treemodel/element.js
  20. 92 92
      packages/ckeditor5-engine/src/treemodel/node.js
  21. 32 32
      packages/ckeditor5-engine/src/treemodel/nodelist.js
  22. 48 36
      packages/ckeditor5-engine/src/treemodel/operation/attributeoperation.js
  23. 27 14
      packages/ckeditor5-engine/src/treemodel/operation/insertoperation.js
  24. 33 23
      packages/ckeditor5-engine/src/treemodel/operation/moveoperation.js
  25. 37 0
      packages/ckeditor5-engine/src/treemodel/operation/nooperation.js
  26. 80 0
      packages/ckeditor5-engine/src/treemodel/operation/operation.js
  27. 10 6
      packages/ckeditor5-engine/src/treemodel/operation/reinsertoperation.js
  28. 14 12
      packages/ckeditor5-engine/src/treemodel/operation/removeoperation.js
  29. 422 0
      packages/ckeditor5-engine/src/treemodel/operation/transform.js
  30. 490 0
      packages/ckeditor5-engine/src/treemodel/position.js
  31. 17 17
      packages/ckeditor5-engine/src/treemodel/positioniterator.js
  32. 306 0
      packages/ckeditor5-engine/src/treemodel/range.js
  33. 5 5
      packages/ckeditor5-engine/src/treemodel/rootelement.js
  34. 82 0
      packages/ckeditor5-engine/src/treemodel/smartrange.js
  35. 6 6
      packages/ckeditor5-engine/src/treemodel/text.js
  36. 13 17
      packages/ckeditor5-engine/src/utils.js
  37. 0 120
      packages/ckeditor5-engine/tests/document/document.js
  38. 0 229
      packages/ckeditor5-engine/tests/document/position.js
  39. 0 118
      packages/ckeditor5-engine/tests/document/range.js
  40. 0 82
      packages/ckeditor5-engine/tests/document/transaction.js
  41. 3 3
      packages/ckeditor5-engine/tests/treemodel/attribute.js
  42. 83 0
      packages/ckeditor5-engine/tests/treemodel/batch.js
  43. 9 9
      packages/ckeditor5-engine/tests/treemodel/character.js
  44. 145 77
      packages/ckeditor5-engine/tests/treemodel/delta/attributedelta.js
  45. 5 5
      packages/ckeditor5-engine/tests/treemodel/delta/delta.js
  46. 13 13
      packages/ckeditor5-engine/tests/treemodel/delta/insertdelta.js
  47. 19 19
      packages/ckeditor5-engine/tests/treemodel/delta/mergedelta.js
  48. 15 15
      packages/ckeditor5-engine/tests/treemodel/delta/removedelta.js
  49. 18 18
      packages/ckeditor5-engine/tests/treemodel/delta/splitdelta.js
  50. 186 0
      packages/ckeditor5-engine/tests/treemodel/document/change-event.js
  51. 183 0
      packages/ckeditor5-engine/tests/treemodel/document/document.js
  52. 9 9
      packages/ckeditor5-engine/tests/treemodel/element.js
  53. 9 9
      packages/ckeditor5-engine/tests/treemodel/node.js
  54. 9 9
      packages/ckeditor5-engine/tests/treemodel/nodelist.js
  55. 141 75
      packages/ckeditor5-engine/tests/treemodel/operation/attributeoperation.js
  56. 57 20
      packages/ckeditor5-engine/tests/treemodel/operation/insertoperation.js
  57. 75 59
      packages/ckeditor5-engine/tests/treemodel/operation/moveoperation.js
  58. 48 0
      packages/ckeditor5-engine/tests/treemodel/operation/nooperation.js
  59. 19 15
      packages/ckeditor5-engine/tests/treemodel/operation/reinsertoperation.js
  60. 26 16
      packages/ckeditor5-engine/tests/treemodel/operation/removeoperation.js
  61. 2382 0
      packages/ckeditor5-engine/tests/treemodel/operation/transform.js
  62. 501 0
      packages/ckeditor5-engine/tests/treemodel/position.js
  63. 21 21
      packages/ckeditor5-engine/tests/treemodel/positioniterator.js
  64. 325 0
      packages/ckeditor5-engine/tests/treemodel/range.js
  65. 7 7
      packages/ckeditor5-engine/tests/treemodel/rootelement.js
  66. 5 5
      packages/ckeditor5-engine/tests/treemodel/text.js
  67. 2 2
      packages/ckeditor5-engine/tests/utils/utils.js

+ 0 - 124
packages/ckeditor5-engine/src/document/delta/transaction-base.js

@@ -1,124 +0,0 @@
-/**
- * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md.
- */
-
-'use strict';
-
-CKEDITOR.define( [ 'ckeditorerror' ], ( CKEditorError ) => {
-	/**
-	 * The transaction class groups document changes (deltas). All deltas grouped in a single transactions can be
-	 * reverted together, so you can think about the transaction as a single undo step. If you want to extend one
-	 * undo step you can call another method on the same transaction object. If you want to create a separate undo step
-	 * you can create a new transaction.
-	 *
-	 * For example to create two separate undo steps you can call:
-	 *
-	 *		doc.createTransaction().insert( firstPosition, 'foo' );
-	 *		doc.createTransaction().insert( secondPosition, 'bar' );
-	 *
-	 * To create a single undo step:
-	 *
-	 *		const transaction = doc.createTransaction()
-	 *		transaction.insert( firstPosition, 'foo' );
-	 *		transaction.insert( secontPosition, 'bar' );
-	 *
-	 * Note that all document modification methods (insert, remove, split, etc.) are chainable so you can shorten code to:
-	 *
-	 *		doc.createTransaction().insert( firstPosition, 'foo' ).insert( secontPosition, 'bar' );
-	 *
-	 * @class document.Transaction
-	 */
-	class Transaction {
-		/**
-		 * Creates transaction instance. Not recommended to use directly, use {@link document.Document#createTransaction}
-		 * instead.
-		 *
-		 * @constructor
-		 * @param {document.Document} doc Document which this transaction changes.
-		 */
-		constructor( doc ) {
-			/**
-			 * Document which this transaction changes.
-			 *
-			 * @readonly
-			 * @type {document.Document}
-			 */
-			this.doc = doc;
-
-			/**
-			 * Array of deltas which compose transaction.
-			 *
-			 * @readonly
-			 * @type {document.delta.Delta[]}
-			 */
-			this.deltas = [];
-		}
-
-		/**
-		 * Adds delta to the transaction instance. All modification methods (insert, remove, split, etc.) use this method
-		 * to add created deltas.
-		 *
-		 * @param {document.delta.Delta} delta Delta to add.
-		 * @return {document.delta.Delta} Added delta.
-		 */
-		addDelta( delta ) {
-			delta.transaction = this;
-			this.deltas.push( delta );
-
-			return delta;
-		}
-
-		/**
-		 * Static method to register transaction methods. To make code scalable transaction do not have modification
-		 * methods built in. They can be registered using this method.
-		 *
-		 * This method checks if there is no naming collision and throw `transaction-register-taken` if the method name
-		 * is already taken.
-		 *
-		 * Beside that no magic happens here, the method is added to the `Transaction` class prototype.
-		 *
-		 * For example:
-		 *
-		 *		Transaction.register( 'insert', function( position, nodes ) {
-		 *			// You can use a class inherit from Delta if that class should handle OT in the special way.
-		 *			const delta = new Delta();
-		 *
-		 * 			// Create operations which should be components of this delta.
-		 *			const operation = new InsertOperation( position, nodes, this.doc.version );
-		 *
-		 *			// Remember to apply every operation, no magic, you need to do it manually.
-		 *			this.doc.applyOperation( operation );
-		 *
-		 *			// Add operation to the delta.
-		 *			delta.addOperation( operation );
-		 *
-		 *			// Add delta to the transaction instance.
-		 *			this.addDelta( delta );
-		 *
-		 * 			// Make this method chainable.
-		 * 			return this;
-		 *		} );
-		 *
-		 * @param {String} name Method name.
-		 * @param {Fuction} creator Method body.
-		 */
-		static register( name, creator ) {
-			if ( Transaction.prototype[ name ] ) {
-				/**
-				 * This transaction method is already taken.
-				 *
-				 * @error transaction-register-taken
-				 * @param {String} name
-				 */
-				throw new CKEditorError(
-					'transaction-register-taken: This transaction method is already taken.',
-					{ name: name } );
-			}
-
-			Transaction.prototype[ name ] = creator;
-		}
-	}
-
-	return Transaction;
-} );

+ 0 - 159
packages/ckeditor5-engine/src/document/document.js

@@ -1,159 +0,0 @@
-/**
- * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md.
- */
-
-'use strict';
-
-CKEDITOR.define( [
-	'document/element',
-	'document/rootelement',
-	'document/transaction',
-	'emittermixin',
-	'utils',
-	'ckeditorerror'
-], ( Element, RootElement, Tranaction, EmitterMixin, utils, CKEditorError ) => {
-	const graveyardSymbol = Symbol( 'graveyard' );
-
-	/**
-	 * Document tree model describes all editable data in the editor. It may contain multiple {@link #roots root elements},
-	 * for example if the editor have multiple editable areas, each area will be represented by the separate root.
-	 *
-	 * All changes in the document are done by {@link document.operation.Operation operations}. To create operations in
-	 * the simple way use use the {@link document.Transaction transaction} API, for example:
-	 *
-	 *		document.createTransaction().insert( position, nodes ).split( otherPosition );
-	 *
-	 * @see #createTransaction
-	 *
-	 * @class document.Document
-	 */
-	class Document {
-		/**
-		 * Creates an empty document instance with no {@link #roots}.
-		 *
-		 * @constructor
-		 */
-		constructor() {
-			/**
-			 * List of roots that are owned and managed by this document.
-			 *
-			 * @readonly
-			 * @property {Map} roots
-			 */
-			this.roots = new Map();
-
-			// Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
-			this.createRoot( graveyardSymbol );
-
-			/**
-			 * Document version. It starts from `0` and every operation increases the version number. It is used to ensure that
-			 * operations are applied on the proper document version. If the {@link document.operation.Operation#baseVersion} will
-			 * not match document version the {@link document-applyOperation-wrong-version} error is thrown.
-			 *
-			 * @readonly
-			 * @property {Number} version
-			 */
-			this.version = 0;
-		}
-
-		/**
-		 * This is the entry point for all document changes. All changes on the document are done using
-		 * {@link document.operation.Operation operations}. To create operations in the simple way use the
-		 * {@link document.Transaction} API available via {@link #createTransaction} method.
-		 *
-		 * @param {document.operation.Operation} operation Operation to be applied.
-		 */
-		applyOperation( operation ) {
-			if ( operation.baseVersion !== this.version ) {
-				/**
-				 * Only operations with matching versions can be applied.
-				 *
-				 * @error document-applyOperation-wrong-version
-				 * @param {document.operation.Operation} operation
-				 */
-				throw new CKEditorError(
-					'document-applyOperation-wrong-version: Only operations with matching versions can be applied.',
-					{ operation: operation } );
-			}
-
-			operation._execute();
-			this.version++;
-			this.fire( 'operationApplied', operation );
-		}
-
-		/**
-		 * Creates a new top-level root.
-		 *
-		 * @param {String|Symbol} name Unique root name.
-		 * @returns {document.RootElement} Created root.
-		 */
-		createRoot( name ) {
-			if ( this.roots.has( name ) ) {
-				/**
-				 * Root with specified name already exists.
-				 *
-				 * @error document-createRoot-name-exists
-				 * @param {document.Document} doc
-				 * @param {String} name
-				 */
-				throw new CKEditorError(
-					'document-createRoot-name-exists: Root with specified name already exists.',
-					{ name: name }
-				);
-			}
-
-			const root = new RootElement( this );
-			this.roots.set( name, root );
-
-			return root;
-		}
-
-		/**
-		 * Returns top-level root by it's name.
-		 *
-		 * @param {String|Symbol} name Name of the root to get.
-		 * @returns (document.RootElement} Root registered under given name.
-		 */
-		getRoot( name ) {
-			if ( !this.roots.has( name ) ) {
-				/**
-				 * Root with specified name does not exist.
-				 *
-				 * @error document-createRoot-root-not-exist
-				 * @param {String} name
-				 */
-				throw new CKEditorError(
-					'document-createRoot-root-not-exist: Root with specified name does not exist.',
-					{ name: name }
-				);
-			}
-
-			return this.roots.get( name );
-		}
-
-		/**
-		 * Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
-		 *
-		 * @protected
-		 * @readonly
-		 * @property {document.RootElement} _graveyard
-		 */
-		get _graveyard() {
-			return this.getRoot( graveyardSymbol );
-		}
-
-		/**
-		 * Creates a {@link document.Transaction} instance which allows to change the document.
-		 *
-		 * @returns {document.Transaction} Transaction instance.
-		 */
-		createTransaction() {
-			return new Tranaction( this );
-		}
-	}
-
-	utils.extend( Document.prototype, EmitterMixin );
-
-	return Document;
-} );

+ 0 - 87
packages/ckeditor5-engine/src/document/operation/operation.js

@@ -1,87 +0,0 @@
-/**
- * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md.
- */
-
-'use strict';
-
-CKEDITOR.define( [], () => {
-	/**
-	 * Abstract base operation class.
-	 *
-	 * @abstract
-	 * @class document.operation.Operation
-	 */
-	class Operation {
-		/**
-		 * Base operation constructor.
-		 *
-		 * @param {Number} baseVersion {@link document.Document#version} on which the operation can be applied.
-		 * @constructor
-		 */
-		constructor( baseVersion ) {
-			/**
-			 * {@link document.Document#version} on which operation can be applied. If you try to
-			 * {@link document.Document#applyOperation apply} operation with different base version than the
-			 * {@link document.Document#version document version} the {@link document-applyOperation-wrong-version}
-			 * error is thrown.
-			 *
-			 * @property {Number}
-			 */
-			this.baseVersion = baseVersion;
-
-			/**
-			 * {@link Document.Delta Delta} which the operation is a part of. This property is set by the
-			 * {@link Document.Delta delta} when the operations is added to it by the
-			 * {@link Document.Delta#addOperation} method.
-			 *
-			 * @property {Document.Delta} delta
-			 */
-
-			/**
-			 * Executes the operation - modifications described by the operation attributes
-			 * will be applied to the tree model.
-			 *
-			 * @method _execute
-			 * @protected
-			 */
-
-			/**
-			 * Creates and returns a reverse operation. Reverse operation when executed right after
-			 * the original operation will bring back tree model state to the point before the original
-			 * operation execution. In other words, it reverses changes done by the original operation.
-			 *
-			 * Keep in mind that tree model state may change since executing the original operation,
-			 * so reverse operation will be "outdated". In that case you will need to
-			 * {@link #getTransformedBy transform} it by all operations that were executed after the original operation.
-			 *
-			 * @method getReversed
-			 * @returns {document.operation.Operation} Reversed operation.
-			 */
-
-			/**
-			 * Creates and returns a clone of this operation which is transformed by the given operation.
-			 * When operation is transformed its parameters may change accordingly to the operation which it is
-			 * transformed by. If the given operation applied to the tree model any modifications which are
-			 * affecting ranges/positions/nodes connected with this operation, those changes will be reflected
-			 * in the parameters of the returned operation.
-			 *
-			 * Whenever the {@link document.Document document} has different {@link document.Document#baseVersion}
-			 * than an operation you want to {@link document.Document#applyOperation apply}, you need to transform
-			 * all the operations that were executed on the {@link document.Document document} since it has
-			 * {@link document.Document#baseVersion} same as the operation (transform in the same order as those
-			 * operations were executed). This way all modifications done to the tree model will be reflected
-			 * in the operation parameters and the operation will "work" on "up-to-date" version of the tree model.
-			 *
-			 * **TODO**: So far we think that transforming one operation by another one may result in more than one
-			 * operation. This needs to be clarified in this documentation.
-			 *
-			 * @method getTransformedBy
-			 * @param {document.operation.Operation} operation Operation by which this operation will be transformed.
-			 * @returns {document.operation.Operation[]} A result of transformation of this operation by the given operation.
-			 */
-		}
-	}
-
-	return Operation;
-} );

+ 0 - 177
packages/ckeditor5-engine/src/document/position.js

@@ -1,177 +0,0 @@
-/**
- * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md.
- */
-
-'use strict';
-
-CKEDITOR.define( [ 'utils', 'ckeditorerror' ], ( utils, CKEditorError ) => {
-	/**
-	 * Position in the tree. Position is always located before or after a node.
-	 * See {@link #path} property for more information.
-	 *
-	 * @class document.Position
-	 */
-	class Position {
-		/**
-		 * Creates a position.
-		 *
-		 * @param {Array} path Position path. See {@link #path} property for more information.
-		 * @param {document.Element} root Root element for the path. Note that this element can not have a parent.
-		 * @constructor
-		 */
-		constructor( path, root ) {
-			/**
-			 * Position of the node it the tree. For example:
-			 *
-			 * root
-			 *  |- p         Before: [ 0 ]       After: [ 1 ]
-			 *  |- ul        Before: [ 1 ]       After: [ 2 ]
-			 *     |- li     Before: [ 1, 0 ]    After: [ 1, 1 ]
-			 *     |  |- f   Before: [ 1, 0, 0 ] After: [ 1, 0, 1 ]
-			 *     |  |- o   Before: [ 1, 0, 1 ] After: [ 1, 0, 2 ]
-			 *     |  |- o   Before: [ 1, 0, 2 ] After: [ 1, 0, 3 ]
-			 *     |- li     Before: [ 1, 1 ]    After: [ 1, 2 ]
-			 *        |- b   Before: [ 1, 1, 0 ] After: [ 1, 1, 1 ]
-			 *        |- a   Before: [ 1, 1, 1 ] After: [ 1, 1, 2 ]
-			 *        |- r   Before: [ 1, 1, 2 ] After: [ 1, 1, 3 ]
-			 *
-			 * @type {Number[]}
-			 */
-			this.path = path;
-
-			/**
-			 * Root element for the path. Note that this element can not have a parent.
-			 *
-			 * @type {document.Element}
-			 */
-			this.root = root;
-		}
-
-		/**
-		 * Parent element of the position. The position is located at {@link #offset} in this element.
-		 *
-		 * @readonly
-		 * @property {document.Element} parent
-		 */
-		get parent() {
-			let parent = this.root;
-
-			let i, len;
-
-			for ( i = 0, len = this.path.length - 1; i < len; i++ ) {
-				parent = parent.getChild( this.path[ i ] );
-			}
-
-			return parent;
-		}
-
-		/**
-		 * Offset at which the position is located in the {@link #parent}.
-		 *
-		 * @readonly
-		 * @property {Number} offset
-		 */
-		get offset() {
-			return utils.last( this.path );
-		}
-
-		/**
-		 * Node directly before the position.
-		 *
-		 * @readonly
-		 * @type {document.Node}
-		 */
-		get nodeBefore() {
-			return this.parent.getChild( this.offset - 1 ) || null;
-		}
-
-		/**
-		 * Node directly after the position.
-		 *
-		 * @readonly
-		 * @property {document.Node}
-		 */
-		get nodeAfter() {
-			return this.parent.getChild( this.offset ) || null;
-		}
-
-		/**
-		 * Two positions equal if paths are equal.
-		 *
-		 * @param {document.Position} otherPosition Position to compare.
-		 * @returns {Boolean} True if positions equal.
-		 */
-		isEqual( otherPosition ) {
-			return utils.isEqual( this.path, otherPosition.path );
-		}
-
-		/**
-		 * Returns the path to the parent, which is the {@link document.Position#path} without the last element.
-		 *
-		 * This method returns the parent path even if the parent does not exists.
-		 *
-		 * @returns {Number[]} Path to the parent.
-		 */
-		getParentPath() {
-			return this.path.slice( 0, -1 );
-		}
-
-		/**
-		 * Creates a new position from the parent element and the offset in that element.
-		 *
-		 * @param {document.Element} parent Position parent element.
-		 * @param {Number} offset Position offset.
-		 * @returns {document.Position}
-		 */
-		static createFromParentAndOffset( parent, offset ) {
-			const path = parent.getPath();
-
-			path.push( offset );
-
-			return new Position( path, parent.root );
-		}
-
-		/**
-		 * Creates a new position before the given node.
-		 *
-		 * @param {document.node} node Node the position should be directly before.
-		 * @returns {document.Position}
-		 */
-		static createBefore( node ) {
-			if ( !node.parent ) {
-				/**
-				 * You can not make position before root.
-				 *
-				 * @error position-before-root
-				 * @param {document.Node} root
-				 */
-				throw new CKEditorError( 'position-before-root: You can not make position before root.', { root: node } );
-			}
-
-			return Position.createFromParentAndOffset( node.parent, node.getIndex() );
-		}
-
-		/**
-		 * Creates a new position after given node.
-		 *
-		 * @param {document.Node} node Node the position should be directly after.
-		 * @returns {document.Position}
-		 */
-		static createAfter( node ) {
-			if ( !node.parent ) {
-				/**
-				 * You can not make position after root.
-				 *
-				 * @error position-after-root
-				 * @param {document.Node} root
-				 */
-				throw new CKEditorError( 'position-after-root: You can not make position after root.', { root: node } );
-			}
-
-			return Position.createFromParentAndOffset( node.parent, node.getIndex() + 1 );
-		}
-	}
-
-	return Position;
-} );

+ 0 - 85
packages/ckeditor5-engine/src/document/range.js

@@ -1,85 +0,0 @@
-/**
- * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md.
- */
-
-'use strict';
-
-CKEDITOR.define( [ 'document/positioniterator', 'document/position' ], ( PositionIterator, Position ) => {
-	/**
-	 * Range class. Range is iterable.
-	 *
-	 * @class document.Range
-	 */
-	class Range {
-		/**
-		 * Creates a range.
-		 *
-		 * @param {document.Position} start Start position.
-		 * @param {document.Position} end End position.
-		 * @constructor
-		 */
-		constructor( start, end ) {
-			/**
-			 * Start position.
-			 *
-			 * @property {document.Position}
-			 */
-			this.start = start;
-
-			/**
-			 * End position.
-			 *
-			 * @property {document.Position}
-			 */
-			this.end = end;
-		}
-
-		/**
-		 * Creates a range inside an element which starts before the first child and ends after the last child.
-		 *
-		 * @param {document.Element} element Element which is a parent for the range.
-		 * @returns {document.Range} Created range.
-		 */
-		static createFromElement( element ) {
-			return Range.createFromParentsAndOffsets( element, 0, element, element.getChildCount() );
-		}
-
-		/**
-		 * Creates a range from given parents and offsets.
-		 *
-		 * @param {document.Element} startElement Start position parent element.
-		 * @param {Number} startOffset Start position offset.
-		 * @param {document.Element} endElement End position parent element.
-		 * @param {Number} endOffset End position offset.
-		 * @returns {document.Range} Created range.
-		 */
-		static createFromParentsAndOffsets( startElement, startOffset, endElement, endOffset ) {
-			return new Range(
-					Position.createFromParentAndOffset( startElement, startOffset ),
-					Position.createFromParentAndOffset( endElement, endOffset )
-				);
-		}
-
-		/**
-		 * Two ranges equal if their start and end positions equal.
-		 *
-		 * @param {document.Range} otherRange Range to compare with.
-		 * @returns {Boolean} True if ranges equal.
-		 */
-		isEqual( otherRange ) {
-			return this.start.isEqual( otherRange.start ) && this.end.isEqual( otherRange.end );
-		}
-
-		/**
-		 * Range iterator.
-		 *
-		 * @see document.PositionIterator
-		 */
-		[ Symbol.iterator ]() {
-			return new PositionIterator( this );
-		}
-	}
-
-	return Range;
-} );

+ 0 - 21
packages/ckeditor5-engine/src/document/transaction.js

@@ -1,21 +0,0 @@
-/**
- * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md.
- */
-
-'use strict';
-
-// All deltas need to be loaded so they can register themselves as transaction methods.
-//
-// To solve circular dependencies (deltas need to require transaction class), transaction class body is moved
-// to document/delta/transaction-base.
-CKEDITOR.define( [
-	'document/delta/transaction-base',
-	'document/delta/insertdelta',
-	'document/delta/removedelta',
-	'document/delta/changedelta',
-	'document/delta/splitdelta',
-	'document/delta/mergedelta'
-], ( Transaction ) => {
-	return Transaction;
-} );

+ 3 - 3
packages/ckeditor5-engine/src/document/attribute.js → packages/ckeditor5-engine/src/treemodel/attribute.js

@@ -9,7 +9,7 @@ CKEDITOR.define( [ 'utils' ], ( utils ) => {
 	/**
 	 * Attributes can store any additional information for nodes in the data model.
 	 *
-	 * @class document.Attribute
+	 * @class treeModel.Attribute
 	 */
 	class Attribute {
 		/**
@@ -75,7 +75,7 @@ CKEDITOR.define( [ 'utils' ], ( utils ) => {
 		 *		let attr2 = new Attribute( 'foo', { b: 2, a: 1 } );
 		 *		attr1.isEqual( attr2 ); // true
 		 *
-		 * @param {document.Attribute} otherAttr Attribute to compare with.
+		 * @param {treeModel.Attribute} otherAttr Attribute to compare with.
 		 * @returns {Boolean} True if attributes are equal to each other.
 		 */
 		isEqual( otherAttr ) {
@@ -97,7 +97,7 @@ CKEDITOR.define( [ 'utils' ], ( utils ) => {
 		 * @static
 		 * @param {String} key Attribute key.
 		 * @param {Mixed} value Attribute value.
-		 * @returns {document.Attribute} Registered attribute.
+		 * @returns {treeModel.Attribute} Registered attribute.
 		 */
 		static register( key, value ) {
 			const attr = new Attribute( key, value );

+ 21 - 0
packages/ckeditor5-engine/src/treemodel/batch.js

@@ -0,0 +1,21 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+'use strict';
+
+// All deltas need to be loaded so they can register themselves as Batch methods.
+//
+// To solve circular dependencies (deltas need to require Batch class), Batch class body is moved
+// to treemodel/delta/batch-base.
+CKEDITOR.define( [
+	'treemodel/delta/batch-base',
+	'treemodel/delta/insertdelta',
+	'treemodel/delta/removedelta',
+	'treemodel/delta/attributedelta',
+	'treemodel/delta/splitdelta',
+	'treemodel/delta/mergedelta'
+], ( Batch ) => {
+	return Batch;
+} );

+ 3 - 3
packages/ckeditor5-engine/src/document/character.js → packages/ckeditor5-engine/src/treemodel/character.js

@@ -5,18 +5,18 @@
 
 'use strict';
 
-CKEDITOR.define( [ 'document/node' ], ( Node ) => {
+CKEDITOR.define( [ 'treemodel/node' ], ( Node ) => {
 	/**
 	 * Data structure for character stored in the tree data model.
 	 *
-	 * @class Character
+	 * @class treeModel.Character
 	 */
 	class Character extends Node {
 		/**
 		 * Creates character linear item.
 		 *
 		 * @param {String} character Described character.
-		 * @param {Iterable} attrs Iterable collection of {@link document.Attribute attributes}.
+		 * @param {Iterable} attrs Iterable collection of {@link treeModel.Attribute attributes}.
 		 * @constructor
 		 */
 		constructor( character, attrs ) {

+ 47 - 42
packages/ckeditor5-engine/src/document/delta/changedelta.js → packages/ckeditor5-engine/src/treemodel/delta/attributedelta.js

@@ -6,35 +6,36 @@
 'use strict';
 
 CKEDITOR.define( [
-	'document/delta/delta',
-	'document/delta/register',
-	'document/operation/changeoperation',
-	'document/position',
-	'document/range',
-	'document/attribute',
-	'document/element'
-], ( Delta, register, ChangeOperation, Position, Range, Attribute, Element ) => {
+	'treemodel/delta/delta',
+	'treemodel/delta/register',
+	'treemodel/operation/attributeoperation',
+	'treemodel/position',
+	'treemodel/range',
+	'treemodel/positioniterator',
+	'treemodel/attribute',
+	'treemodel/element'
+], ( Delta, register, AttributeOperation, Position, Range, PositionIterator, Attribute, Element ) => {
 	/**
-	 * To provide specific OT behavior and better collisions solving, change methods ({@link document.Transaction#setAttr}
-	 * and {@link document.Transaction#removeAttr}) use `ChangeDelta` class which inherits from the `Delta` class and may
+	 * To provide specific OT behavior and better collisions solving, change methods ({@link treeModel.Batch#setAttr}
+	 * and {@link treeModel.Batch#removeAttr}) use `AttributeDelta` class which inherits from the `Delta` class and may
 	 * overwrite some methods.
 	 *
-	 * @class document.delta.ChangeDelta
+	 * @class treeModel.delta.AttributeDelta
 	 */
-	class ChangeDelta extends Delta {}
+	class AttributeDelta extends Delta {}
 
 	/**
 	 * Sets the value of the attribute of the node or on the range.
 	 *
 	 * @chainable
 	 * @method setAttr
-	 * @memberOf document.Transaction
+	 * @memberOf treeModel.Batch
 	 * @param {String} key Attribute key.
-	 * @param {Mixed} value Attribute new value.
-	 * @param {document.Node|document.Range} nodeOrRange Node or range on which the attribute will be set.
+	 * @param {*} value Attribute new value.
+	 * @param {treeModel.Node|treeModel.Range} nodeOrRange Node or range on which the attribute will be set.
 	 */
 	register( 'setAttr', function( key, value, nodeOrRange ) {
-		change( this, key, value, nodeOrRange );
+		attribute( this, key, value, nodeOrRange );
 
 		return this;
 	} );
@@ -44,26 +45,26 @@ CKEDITOR.define( [
 	 *
 	 * @chainable
 	 * @method removeAttr
-	 * @memberOf document.Transaction
+	 * @memberOf treeModel.Batch
 	 * @param {String} key Attribute key.
-	 * @param {document.Node|document.Range} nodeOrRange Node or range on which the attribute will be removed.
+	 * @param {treeModel.Node|treeModel.Range} nodeOrRange Node or range on which the attribute will be removed.
 	 */
 	register( 'removeAttr', function( key, nodeOrRange ) {
-		change( this, key, null, nodeOrRange );
+		attribute( this, key, null, nodeOrRange );
 
 		return this;
 	} );
 
-	function change( transaction, key, value, nodeOrRange ) {
-		const delta = new ChangeDelta();
+	function attribute( batch, key, value, nodeOrRange ) {
+		const delta = new AttributeDelta();
 
 		if ( nodeOrRange instanceof Range ) {
-			changeRange( transaction.doc, delta, key, value, nodeOrRange );
+			changeRange( batch.doc, delta, key, value, nodeOrRange );
 		} else {
-			changeNode( transaction.doc, delta, key, value, nodeOrRange );
+			changeNode( batch.doc, delta, key, value, nodeOrRange );
 		}
 
-		transaction.addDelta( delta );
+		batch.addDelta( delta );
 	}
 
 	function changeNode( doc, delta, key, value, node ) {
@@ -81,7 +82,7 @@ CKEDITOR.define( [
 				range = new Range( Position.createBefore( node ), Position.createAfter( node ) );
 			}
 
-			const operation = new ChangeOperation(
+			const operation = new AttributeOperation(
 					range,
 					previousValue ? new Attribute( key, previousValue ) : null,
 					value ? new Attribute( key, value ) : null,
@@ -93,7 +94,7 @@ CKEDITOR.define( [
 		}
 	}
 
-	// Because change operation needs to have the same attribute value on the whole range, this function split the range
+	// Because attribute operation needs to have the same attribute value on the whole range, this function split the range
 	// into smaller parts.
 	function changeRange( doc, delta, key, value, range ) {
 		// Position of the last split, the beginning of the new range.
@@ -113,33 +114,37 @@ CKEDITOR.define( [
 		let next = iterator.next();
 
 		while ( !next.done ) {
-			valueAfter = next.value.node.getAttr( key );
-
-			// At the first run of the iterator the position in undefined. We also do not have a valueBefore, but
-			// because valueAfter may be null, valueBefore may be equal valueAfter ( undefined == null ).
-			if ( position && valueBefore != valueAfter ) {
-				// if valueBefore == value there is nothing to change, so we add operation only if these values are different.
-				if ( valueBefore != value ) {
-					addOperation();
+			// We check values only when the range contains given element, that is when the iterator "enters" the element.
+			// To prevent double-checking or not needed checking, we filter-out iterator values for ELEMENT_LEAVE position.
+			if ( next.value.type != PositionIterator.ELEMENT_LEAVE ) {
+				valueAfter = next.value.node.getAttr( key );
+
+				// At the first run of the iterator the position in undefined. We also do not have a valueBefore, but
+				// because valueAfter may be null, valueBefore may be equal valueAfter ( undefined == null ).
+				if ( position && valueBefore != valueAfter ) {
+					// if valueBefore == value there is nothing to change, so we add operation only if these values are different.
+					if ( valueBefore != value ) {
+						addOperation();
+					}
+
+					lastSplitPosition = position;
 				}
 
-				lastSplitPosition = position;
+				position = iterator.position;
+				valueBefore = valueAfter;
 			}
 
-			position = iterator.position;
-			valueBefore = valueAfter;
-
 			next = iterator.next();
 		}
 
 		// Because position in the loop is not the iterator position (see let position comment), the last position in
 		// the while loop will be last but one position in the range. We need to check the last position manually.
-		if ( position != lastSplitPosition && valueBefore != value ) {
+		if ( position instanceof Position && position != lastSplitPosition && valueBefore != value ) {
 			addOperation();
 		}
 
 		function addOperation() {
-			const operation = new ChangeOperation(
+			const operation = new AttributeOperation(
 					new Range( lastSplitPosition, position ),
 					valueBefore ? new Attribute( key, valueBefore ) : null,
 					value ? new Attribute( key, value ) : null,
@@ -151,5 +156,5 @@ CKEDITOR.define( [
 		}
 	}
 
-	return ChangeDelta;
-} );
+	return AttributeDelta;
+} );

+ 123 - 0
packages/ckeditor5-engine/src/treemodel/delta/batch-base.js

@@ -0,0 +1,123 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+'use strict';
+
+CKEDITOR.define( [ 'ckeditorerror' ], ( CKEditorError ) => {
+	/**
+	 * The Batch class groups document changes (deltas). All deltas grouped in a single Batch can be
+	 * reverted together, so you can think about the Batch as a single undo step. If you want to extend one
+	 * undo step you can call another method on the same Batch object. If you want to create a separate undo step
+	 * you can create a new Batch.
+	 *
+	 * For example to create two separate undo steps you can call:
+	 *
+	 *		doc.batch().insert( firstPosition, 'foo' );
+	 *		doc.batch().insert( secondPosition, 'bar' );
+	 *
+	 * To create a single undo step:
+	 *
+	 *		const batch = doc.batch();
+	 *		batch.insert( firstPosition, 'foo' );
+	 *		batch.insert( secondPosition, 'bar' );
+	 *
+	 * Note that all document modification methods (insert, remove, split, etc.) are chainable so you can shorten code to:
+	 *
+	 *		doc.batch().insert( firstPosition, 'foo' ).insert( secondPosition, 'bar' );
+	 *
+	 * @class treeModel.Batch
+	 */
+	class Batch {
+		/**
+		 * Creates Batch instance. Not recommended to use directly, use {@link treeModel.Document#batch} instead.
+		 *
+		 * @constructor
+		 * @param {treeModel.Document} doc Document which this Batch changes.
+		 */
+		constructor( doc ) {
+			/**
+			 * Document which this Batch changes.
+			 *
+			 * @readonly
+			 * @type {treeModel.Document}
+			 */
+			this.doc = doc;
+
+			/**
+			 * Array of deltas which compose Batch.
+			 *
+			 * @readonly
+			 * @type {Array.<treeModel.delta.Delta>}
+			 */
+			this.deltas = [];
+		}
+
+		/**
+		 * Adds delta to the Batch instance. All modification methods (insert, remove, split, etc.) use this method
+		 * to add created deltas.
+		 *
+		 * @param {treeModel.delta.Delta} delta Delta to add.
+		 * @return {treeModel.delta.Delta} Added delta.
+		 */
+		addDelta( delta ) {
+			delta.batch = this;
+			this.deltas.push( delta );
+
+			return delta;
+		}
+
+		/**
+		 * Static method to register Batch methods. To make code scalable Batch do not have modification
+		 * methods built in. They can be registered using this method.
+		 *
+		 * This method checks if there is no naming collision and throws `batch-register-taken` if the method name
+		 * is already taken.
+		 *
+		 * Besides that no magic happens here, the method is added to the `Batch` class prototype.
+		 *
+		 * For example:
+		 *
+		 *		Batch.register( 'insert', function( position, nodes ) {
+		 *			// You can use a class inherit from Delta if that class should handle OT in the special way.
+		 *			const delta = new Delta();
+		 *
+		 * 			// Create operations which should be components of this delta.
+		 *			const operation = new InsertOperation( position, nodes, this.doc.version );
+		 *
+		 *			// Remember to apply every operation, no magic, you need to do it manually.
+		 *			this.doc.applyOperation( operation );
+		 *
+		 *			// Add operation to the delta.
+		 *			delta.addOperation( operation );
+		 *
+		 *			// Add delta to the Batch instance.
+		 *			this.addDelta( delta );
+		 *
+		 * 			// Make this method chainable.
+		 * 			return this;
+		 *		} );
+		 *
+		 * @param {String} name Method name.
+		 * @param {Function} creator Method body.
+		 */
+		static register( name, creator ) {
+			if ( Batch.prototype[ name ] ) {
+				/**
+				 * This batch method name is already taken.
+				 *
+				 * @error batch-register-taken
+				 * @param {String} name
+				 */
+				throw new CKEditorError(
+					'batch-register-taken: This batch method name is already taken.',
+					{ name: name } );
+			}
+
+			Batch.prototype[ name ] = creator;
+		}
+	}
+
+	return Batch;
+} );

+ 9 - 9
packages/ckeditor5-engine/src/document/delta/delta.js → packages/ckeditor5-engine/src/treemodel/delta/delta.js

@@ -12,9 +12,9 @@ CKEDITOR.define( [], () => {
 	 * Delta is a single, from the user action point of view, change in the editable document, like insert, split or
 	 * rename element. Delta is composed of operations, which are unit changes needed to be done to execute user action.
 	 *
-	 * Multiple deltas are grouped into a single {@link document.Transaction}.
+	 * Multiple deltas are grouped into a single {@link treeModel.Batch}.
 	 *
-	 * @class document.delta.Delta
+	 * @class treeModel.delta.Delta
 	 */
 	class Delta {
 		/**
@@ -24,19 +24,19 @@ CKEDITOR.define( [], () => {
 		 */
 		constructor() {
 			/**
-			 * {@link document.Transaction} which delta is a part of. This property is null by default and set by the
-			 * {@link Document.Transaction#addDelta} method.
+			 * {@link treeModel.Batch} which delta is a part of. This property is null by default and set by the
+			 * {@link treeModel.Batch#addDelta} method.
 			 *
 			 * @readonly
-			 * @type {document.Transaction}
+			 * @type {treeModel.Batch}
 			 */
-			this.transaction = null;
+			this.batch = null;
 
 			/**
 			 * Array of operations which compose delta.
 			 *
 			 * @readonly
-			 * @type {document.operation.Operation[]}
+			 * @type {treeModel.operation.Operation[]}
 			 */
 			this.operations = [];
 		}
@@ -44,7 +44,7 @@ CKEDITOR.define( [], () => {
 		/**
 		 * Add operation to the delta.
 		 *
-		 * @param {document.operation.Operation} operation Operation instance.
+		 * @param {treeModel.operation.Operation} operation Operation instance.
 		 */
 		addOperation( operation ) {
 			operation.delta = this;
@@ -55,4 +55,4 @@ CKEDITOR.define( [], () => {
 	}
 
 	return Delta;
-} );
+} );

+ 10 - 10
packages/ckeditor5-engine/src/document/delta/insertdelta.js → packages/ckeditor5-engine/src/treemodel/delta/insertdelta.js

@@ -6,15 +6,15 @@
 'use strict';
 
 CKEDITOR.define( [
-	'document/delta/delta',
-	'document/delta/register',
-	'document/operation/insertoperation'
+	'treemodel/delta/delta',
+	'treemodel/delta/register',
+	'treemodel/operation/insertoperation'
 ], ( Delta, register, InsertOperation ) => {
 	/**
-	 * To provide specific OT behavior and better collisions solving, the {@link document.Transaction#insert} method
+	 * To provide specific OT behavior and better collisions solving, the {@link treeModel.Batch#insert} method
 	 * uses the `InsertDelta` class which inherits from the `Delta` class and may overwrite some methods.
 	 *
-	 * @class document.delta.InsertDelta
+	 * @class treeModel.delta.InsertDelta
 	 */
 	class InsertDelta extends Delta {}
 
@@ -22,11 +22,11 @@ CKEDITOR.define( [
 	 * Inserts a node or nodes at the given position.
 	 *
 	 * @chainable
-	 * @memberOf document.Transaction
+	 * @memberOf treeModel.Batch
 	 * @method insert
-	 * @param {document.Position} position Position of insertion.
-	 * @param {document.Node|document.Text|document.NodeList|String|Iterable} nodes The list of nodes to be inserted.
-	 * List of nodes can be of any type accepted by the {@link document.NodeList} constructor.
+	 * @param {treeModel.Position} position Position of insertion.
+	 * @param {treeModel.Node|treeModel.Text|treeModel.NodeList|String|Iterable} nodes The list of nodes to be inserted.
+	 * List of nodes can be of any type accepted by the {@link treeModel.NodeList} constructor.
 	 */
 	register( 'insert', function( position, nodes ) {
 		const delta = new InsertDelta();
@@ -41,4 +41,4 @@ CKEDITOR.define( [
 	} );
 
 	return InsertDelta;
-} );
+} );

+ 18 - 18
packages/ckeditor5-engine/src/document/delta/mergedelta.js → packages/ckeditor5-engine/src/treemodel/delta/mergedelta.js

@@ -6,32 +6,32 @@
 'use strict';
 
 CKEDITOR.define( [
-	'document/delta/delta',
-	'document/delta/register',
-	'document/position',
-	'document/element',
-	'document/operation/removeoperation',
-	'document/operation/moveoperation',
+	'treemodel/delta/delta',
+	'treemodel/delta/register',
+	'treemodel/position',
+	'treemodel/element',
+	'treemodel/operation/removeoperation',
+	'treemodel/operation/moveoperation',
 	'ckeditorerror'
 ], ( Delta, register, Position, Element, RemoveOperation, MoveOperation, CKEditorError ) => {
 	/**
-	 * To provide specific OT behavior and better collisions solving, {@link document.Transaction#merge} method
+	 * To provide specific OT behavior and better collisions solving, {@link treeModel.Batch#merge} method
 	 * uses the `MergeDelta` class which inherits from the `Delta` class and may overwrite some methods.
 	 *
-	 * @class document.delta.MergeDelta
+	 * @class treeModel.delta.MergeDelta
 	 */
 	class MergeDelta extends Delta {}
 
 	/**
 	 * Merges two siblings at the given position.
 	 *
-	 * Node before and after the position have to be an element. Otherwise `transaction-merge-no-element-before` or
-	 * `transaction-merge-no-element-after` error will be thrown.
+	 * Node before and after the position have to be an element. Otherwise `batch-merge-no-element-before` or
+	 * `batch-merge-no-element-after` error will be thrown.
 	 *
 	 * @chainable
 	 * @method merge
-	 * @memberOf document.Transaction
-	 * @param {document.Position} position Position of merge.
+	 * @memberOf treeModel.Batch
+	 * @param {treeModel.Position} position Position of merge.
 	 */
 	register( 'merge', function( position ) {
 		const delta = new MergeDelta();
@@ -42,26 +42,26 @@ CKEDITOR.define( [
 			/**
 			 * Node before merge position must be an element.
 			 *
-			 * @error transaction-merge-no-element-before
+			 * @error batch-merge-no-element-before
 			 */
 			throw new CKEditorError(
-				'transaction-merge-no-element-before: Node before merge position must be an element.' );
+				'batch-merge-no-element-before: Node before merge position must be an element.' );
 		}
 
 		if ( !( nodeAfter instanceof Element ) ) {
 			/**
 			 * Node after merge position must be an element.
 			 *
-			 * @error transaction-merge-no-element-after
+			 * @error batch-merge-no-element-after
 			 */
 			throw new CKEditorError(
-				'transaction-merge-no-element-after: Node after merge position must be an element.' );
+				'batch-merge-no-element-after: Node after merge position must be an element.' );
 		}
 
 		const positionAfter = Position.createFromParentAndOffset( nodeAfter, 0 );
 		const positionBefore = Position.createFromParentAndOffset( nodeBefore, nodeBefore.getChildCount() );
 
-		const move = new MoveOperation( positionAfter, positionBefore, nodeAfter.getChildCount(), this.doc.version );
+		const move = new MoveOperation( positionAfter, nodeAfter.getChildCount(), positionBefore, this.doc.version );
 		this.doc.applyOperation( move );
 		delta.addOperation( move );
 
@@ -75,4 +75,4 @@ CKEDITOR.define( [
 	} );
 
 	return MergeDelta;
-} );
+} );

+ 4 - 4
packages/ckeditor5-engine/src/document/delta/register.js → packages/ckeditor5-engine/src/treemodel/delta/register.js

@@ -8,7 +8,7 @@
 // Register method exposed for deltas, which needs only this method, to make code simpler, more beautiful and, first of
 // all, to solve circular dependencies.
 CKEDITOR.define( [
-	'document/delta/transaction-base'
-], ( Transaction ) => {
-	return Transaction.register;
-} );
+	'treemodel/delta/batch-base'
+], ( Batch ) => {
+	return Batch.register;
+} );

+ 8 - 8
packages/ckeditor5-engine/src/document/delta/removedelta.js → packages/ckeditor5-engine/src/treemodel/delta/removedelta.js

@@ -6,15 +6,15 @@
 'use strict';
 
 CKEDITOR.define( [
-	'document/delta/delta',
-	'document/delta/register',
-	'document/operation/removeoperation'
+	'treemodel/delta/delta',
+	'treemodel/delta/register',
+	'treemodel/operation/removeoperation'
 ], ( Delta, register, RemoveOperation ) => {
 	/**
-	 * To provide specific OT behavior and better collisions solving, {@link document.Transaction#remove} method
+	 * To provide specific OT behavior and better collisions solving, {@link treeModel.Batch#remove} method
 	 * uses the `RemoveDelta` class which inherits from the `Delta` class and may overwrite some methods.
 	 *
-	 * @class document.delta.RemoveDelta
+	 * @class treeModel.delta.RemoveDelta
 	 */
 	class RemoveDelta extends Delta {}
 
@@ -23,8 +23,8 @@ CKEDITOR.define( [
 	 *
 	 * @chainable
 	 * @method remove
-	 * @memberOf document.Transaction
-	 * @param {document.Position} position Position before the first node to remove.
+	 * @memberOf treeModel.Batch
+	 * @param {treeModel.Position} position Position before the first node to remove.
 	 * @param {Number} howMany How many nodes to remove.
 	 */
 	register( 'remove', function( position, howMany ) {
@@ -44,4 +44,4 @@ CKEDITOR.define( [
 	} );
 
 	return RemoveDelta;
-} );
+} );

+ 15 - 15
packages/ckeditor5-engine/src/document/delta/splitdelta.js → packages/ckeditor5-engine/src/treemodel/delta/splitdelta.js

@@ -6,32 +6,32 @@
 'use strict';
 
 CKEDITOR.define( [
-	'document/delta/delta',
-	'document/delta/register',
-	'document/position',
-	'document/element',
-	'document/operation/insertoperation',
-	'document/operation/moveoperation',
+	'treemodel/delta/delta',
+	'treemodel/delta/register',
+	'treemodel/position',
+	'treemodel/element',
+	'treemodel/operation/insertoperation',
+	'treemodel/operation/moveoperation',
 	'ckeditorerror'
 ], ( Delta, register, Position, Element, InsertOperation, MoveOperation, CKEditorError ) => {
 	/**
-	 * To provide specific OT behavior and better collisions solving, the {@link document.Transaction#split} method
+	 * To provide specific OT behavior and better collisions solving, the {@link treeModel.Batch#split} method
 	 * uses `SplitDelta` class which inherits from the `Delta` class and may overwrite some methods.
 	 *
-	 * @class document.delta.SplitDelta
+	 * @class treeModel.delta.SplitDelta
 	 */
 	class SplitDelta extends Delta {}
 
 	/**
 	 * Splits a node at the given position.
 	 *
-	 * This cannot be a position inside the root element. The `transaction-split-root` error will be thrown if
+	 * This cannot be a position inside the root element. The `batch-split-root` error will be thrown if
 	 * you try to split the root element.
 	 *
 	 * @chainable
 	 * @method split
-	 * @memberOf document.Transaction
-	 * @param {document.Position} position Position of split.
+	 * @memberOf treeModel.Batch
+	 * @param {treeModel.Position} position Position of split.
 	 */
 	register( 'split', function( position ) {
 		const delta = new SplitDelta();
@@ -41,9 +41,9 @@ CKEDITOR.define( [
 			/**
 			 * Root element can not be split.
 			 *
-			 * @error transaction-split-root
+			 * @error batch-split-root
 			 */
-			throw new CKEditorError( 'transaction-split-root: Root element can not be split.' );
+			throw new CKEditorError( 'batch-split-root: Root element can not be split.' );
 		}
 
 		const copy = new Element( splitElement.name, splitElement.getAttrs() );
@@ -54,8 +54,8 @@ CKEDITOR.define( [
 
 		const move = new MoveOperation(
 			position,
-			Position.createFromParentAndOffset( copy, 0 ),
 			splitElement.getChildCount() - position.offset,
+			Position.createFromParentAndOffset( copy, 0 ),
 			this.doc.version
 		);
 
@@ -68,4 +68,4 @@ CKEDITOR.define( [
 	} );
 
 	return SplitDelta;
-} );
+} );

+ 228 - 0
packages/ckeditor5-engine/src/treemodel/document.js

@@ -0,0 +1,228 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+'use strict';
+
+CKEDITOR.define( [
+	'treemodel/element',
+	'treemodel/rootelement',
+	'treemodel/batch',
+	'emittermixin',
+	'utils',
+	'ckeditorerror'
+], ( Element, RootElement, Batch, EmitterMixin, utils, CKEditorError ) => {
+	const graveyardSymbol = Symbol( 'graveyard' );
+
+	/**
+	 * Document tree model describes all editable data in the editor. It may contain multiple {@link #roots root elements},
+	 * for example if the editor have multiple editable areas, each area will be represented by the separate root.
+	 *
+	 * All changes in the document are done by {@link treeModel.operation.Operation operations}. To create operations in
+	 * the simple way use use the {@link treeModel.Batch} API, for example:
+	 *
+	 *		doc.batch().insert( position, nodes ).split( otherPosition );
+	 *
+	 * @see #batch
+	 *
+	 * @class treeModel.Document
+	 */
+	class Document {
+		/**
+		 * Creates an empty document instance with no {@link #roots}.
+		 *
+		 * @constructor
+		 */
+		constructor() {
+			/**
+			 * List of roots that are owned and managed by this document.
+			 *
+			 * @readonly
+			 * @property {Map} roots
+			 */
+			this.roots = new Map();
+
+			// Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
+			this.createRoot( graveyardSymbol );
+
+			/**
+			 * Document version. It starts from `0` and every operation increases the version number. It is used to ensure that
+			 * operations are applied on the proper document version. If the {@link treeModel.operation.Operation#baseVersion} will
+			 * not match document version the {@link document-applyOperation-wrong-version} error is thrown.
+			 *
+			 * @readonly
+			 * @property {Number} version
+			 */
+			this.version = 0;
+
+			/**
+			 * Array of pending changes. See: {@link #enqueueChanges}.
+			 *
+			 * @private
+			 * @property {Array.<Function>}
+			 */
+			this._pendingChanges = [];
+		}
+
+		/**
+		 * Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
+		 *
+		 * @readonly
+		 * @property {treeModel.RootElement} graveyard
+		 */
+		get graveyard() {
+			return this.getRoot( graveyardSymbol );
+		}
+
+		/**
+		 * This is the entry point for all document changes. All changes on the document are done using
+		 * {@link treeModel.operation.Operation operations}. To create operations in the simple way use the
+		 * {@link treeModel.Batch} API available via {@link #batch} method.
+		 *
+		 * This method calls {@link #change} event.
+		 *
+		 * @param {treeModel.operation.Operation} operation Operation to be applied.
+		 */
+		applyOperation( operation ) {
+			if ( operation.baseVersion !== this.version ) {
+				/**
+				 * Only operations with matching versions can be applied.
+				 *
+				 * @error document-applyOperation-wrong-version
+				 * @param {treeModel.operation.Operation} operation
+				 */
+				throw new CKEditorError(
+					'document-applyOperation-wrong-version: Only operations with matching versions can be applied.',
+					{ operation: operation } );
+			}
+
+			let changes = operation._execute();
+
+			this.version++;
+
+			const batch = operation.delta && operation.delta.batch;
+			this.fire( 'change', operation.type, changes, batch );
+		}
+
+		/**
+		 * Creates a {@link treeModel.Batch} instance which allows to change the document.
+		 *
+		 * @returns {treeModel.Batch} Batch instance.
+		 */
+		batch() {
+			return new Batch( this );
+		}
+
+		/**
+		 * Creates a new top-level root.
+		 *
+		 * @param {String|Symbol} name Unique root name.
+		 * @returns {treeModel.RootElement} Created root.
+		 */
+		createRoot( name ) {
+			if ( this.roots.has( name ) ) {
+				/**
+				 * Root with specified name already exists.
+				 *
+				 * @error document-createRoot-name-exists
+				 * @param {treeModel.Document} doc
+				 * @param {String} name
+				 */
+				throw new CKEditorError(
+					'document-createRoot-name-exists: Root with specified name already exists.',
+					{ name: name }
+				);
+			}
+
+			const root = new RootElement( this );
+			this.roots.set( name, root );
+
+			return root;
+		}
+
+		/**
+		 * Enqueue a callback with document changes. Any changes to be done on document (mostly using {@link #batch} should
+		 * be placed in the queued callback. If no other plugin is changing document at the moment, the callback will be
+		 * called immediately. Otherwise it will wait for all previously queued changes to finish happening. This way
+		 * queued callback will not interrupt other callbacks.
+		 *
+		 * When all queued changes are done {@link #changesDone} event is fired.
+		 *
+		 * @param {Function} callback Callback to enqueue.
+		 */
+		enqueueChanges( callback ) {
+			this._pendingChanges.push( callback );
+
+			if ( this._pendingChanges.length == 1 ) {
+				while ( this._pendingChanges.length ) {
+					this._pendingChanges[ 0 ]();
+					this._pendingChanges.shift();
+				}
+
+				this.fire( 'changesDone' );
+			}
+		}
+
+		/**
+		 * Returns top-level root by it's name.
+		 *
+		 * @param {String|Symbol} name Name of the root to get.
+		 * @returns {treeModel.RootElement} Root registered under given name.
+		 */
+		getRoot( name ) {
+			if ( !this.roots.has( name ) ) {
+				/**
+				 * Root with specified name does not exist.
+				 *
+				 * @error document-createRoot-root-not-exist
+				 * @param {String} name
+				 */
+				throw new CKEditorError(
+					'document-createRoot-root-not-exist: Root with specified name does not exist.',
+					{ name: name }
+				);
+			}
+
+			return this.roots.get( name );
+		}
+
+		/**
+		 * Fired when document changes by applying an operation.
+		 *
+		 * There are 5 types of change:
+		 *
+		 * * 'insert' when nodes are inserted,
+		 * * 'remove' when nodes are removed,
+		 * * 'reinsert' when remove is undone,
+		 * * 'move' when nodes are moved,
+		 * * 'attr' when attributes change.
+		 *
+		 * Change event is fired after the change is done. This means that any ranges or positions passed in
+		 * `changeInfo` are referencing nodes and paths in updated tree model.
+		 *
+		 * @event change
+		 * @param {String} type Change type, possible option: 'insert', 'remove', 'reinsert', 'move', 'attr'.
+		 * @param {Object} changeInfo Additional information about the change.
+		 * @param {treeModel.Range} changeInfo.range Range containing changed nodes. Note that for 'remove' the range will be in the
+		 * {@link #graveyard graveyard root}.
+		 * @param {treeModel.Position} [changeInfo.sourcePosition] Change source position. Exists for 'remove', 'reinsert' and 'move'.
+		 * Note that for 'reinsert' the source position will be in the {@link #graveyard graveyard root}.
+		 * @param {treeModel.Attribute} [changeInfo.oldAttr] Only for 'attr' type. If the type is 'attr' and `oldAttr`
+		 * is `undefined` it means that new attribute was inserted. Otherwise it contains changed or removed attribute.
+		 * @param {treeModel.Attribute} [changeInfo.newAttr] Only for 'attr' type. If the type is 'attr' and `newAttr`
+		 * is `undefined` it means that attribute was removed. Otherwise it contains changed or inserted attribute.
+		 * @param {treeModel.Batch} {@link treeModel.Batch} of changes which this change is a part of.
+		 */
+
+		/**
+		 * Fired when all queued document changes are done. See {@link #enqueueChanges}.
+		 *
+		 * @event changesDone
+		 */
+	}
+
+	utils.extend( Document.prototype, EmitterMixin );
+
+	return Document;
+} );

+ 41 - 43
packages/ckeditor5-engine/src/document/element.js → packages/ckeditor5-engine/src/treemodel/element.js

@@ -6,15 +6,13 @@
 'use strict';
 
 CKEDITOR.define( [
-	'document/node',
-	'document/nodelist',
-	'document/range',
-	'document/position'
+	'treemodel/node',
+	'treemodel/nodelist'
 ], ( Node, NodeList ) => {
 	/**
 	 * Tree data model element.
 	 *
-	 * @class document.Element
+	 * @class treeModel.Element
 	 */
 	class Element extends Node {
 		/**
@@ -23,9 +21,9 @@ CKEDITOR.define( [
 		 * This constructor should be used only internally by the document.
 		 *
 		 * @param {String} name Node name.
-		 * @param {Iterable} attrs Iterable collection of {@link document.Attribute attributes}.
-		 * @param {document.Node|document.Text|document.NodeList|String|Iterable} children List of nodes to be inserted
-		 * into created element. List of nodes can be of any type accepted by the {@link document.NodeList} constructor.
+		 * @param {Iterable} attrs Iterable collection of {@link treeModel.Attribute attributes}.
+		 * @param {treeModel.Node|treeModel.Text|treeModel.NodeList|String|Iterable} children List of nodes to be inserted
+		 * into created element. List of nodes can be of any type accepted by the {@link treeModel.NodeList} constructor.
 		 * @constructor
 		 */
 		constructor( name, attrs, children ) {
@@ -43,7 +41,7 @@ CKEDITOR.define( [
 			 * List of children nodes.
 			 *
 			 * @protected
-			 * @property {document.NodeList} _children
+			 * @property {treeModel.NodeList} _children
 			 */
 			this._children = new NodeList();
 
@@ -52,15 +50,44 @@ CKEDITOR.define( [
 			}
 		}
 
+		/**
+		 * Gets child at the given index.
+		 *
+		 * @param {Number} index Index of child.
+		 * @returns {treeModel.Node} Child node.
+		 */
+		getChild( index ) {
+			return this._children.get( index );
+		}
+
+		/**
+		 * Gets the number of element's children.
+		 *
+		 * @returns {Number} The number of element's children.
+		 */
+		getChildCount() {
+			return this._children.length;
+		}
+
+		/**
+		 * Gets index of the given child node.
+		 *
+		 * @param {treeModel.Node} node Child node.
+		 * @returns {Number} Index of the child node.
+		 */
+		getChildIndex( node ) {
+			return this._children.indexOf( node );
+		}
+
 		/**
 		 * Inserts a list of child nodes on the given index and sets the parent of these nodes to this element.
 		 *
 		 * Note that the list of children can be modified only in elements not yet attached to the document.
-		 * All attached nodes should be modified using the {@link document.operation.InsertOperation}.
+		 * All attached nodes should be modified using the {@link treeModel.operation.InsertOperation}.
 		 *
 		 * @param {Number} index Position where nodes should be inserted.
-		 * @param {document.Node|document.Text|document.NodeList|String|Iterable} nodes The list of nodes to be inserted.
-		 * The list of nodes can be of any type accepted by the {@link document.NodeList} constructor.
+		 * @param {treeModel.Node|treeModel.Text|treeModel.NodeList|String|Iterable} nodes The list of nodes to be inserted.
+		 * The list of nodes can be of any type accepted by the {@link treeModel.NodeList} constructor.
 		 */
 		insertChildren( index, nodes ) {
 			this._children.insert( index, new NodeList( nodes ) );
@@ -74,11 +101,11 @@ CKEDITOR.define( [
 		 * Removes number of child nodes starting at the given index and set the parent of these nodes to `null`.
 		 *
 		 * Note that the list of children can be modified only in elements not yet attached to the document.
-		 * All attached nodes should be modified using the {@link document.operation.RemoveOperation}.
+		 * All attached nodes should be modified using the {@link treeModel.operation.RemoveOperation}.
 		 *
 		 * @param {Number} index Position of the first node to remove.
 		 * @param {Number} number Number of nodes to remove.
-		 * @returns {document.NodeList} The list of removed nodes.
+		 * @returns {treeModel.NodeList} The list of removed nodes.
 		 */
 
 		removeChildren( index, number ) {
@@ -88,35 +115,6 @@ CKEDITOR.define( [
 
 			return this._children.remove( index, number );
 		}
-
-		/**
-		 * Gets child at the given index.
-		 *
-		 * @param {Number} index Index of child.
-		 * @returns {document.Node} Child node.
-		 */
-		getChild( index ) {
-			return this._children.get( index );
-		}
-
-		/**
-		 * Gets index of the given child node.
-		 *
-		 * @param {document.Node} node Child node.
-		 * @returns {Number} Index of the child node.
-		 */
-		getChildIndex( node ) {
-			return this._children.indexOf( node );
-		}
-
-		/**
-		 * Gets the number of element's children.
-		 *
-		 * @returns {Number} The number of element's children.
-		 */
-		getChildCount() {
-			return this._children.length;
-		}
 	}
 
 	return Element;

+ 92 - 92
packages/ckeditor5-engine/src/document/node.js → packages/ckeditor5-engine/src/treemodel/node.js

@@ -5,12 +5,12 @@
 
 'use strict';
 
-CKEDITOR.define( [ 'document/attribute', 'utils', 'ckeditorerror' ], ( Attribute, utils, CKEditorError ) => {
+CKEDITOR.define( [ 'treemodel/attribute', 'utils', 'ckeditorerror' ], ( Attribute, utils, CKEditorError ) => {
 	/**
 	 * Abstract document tree node class.
 	 *
 	 * @abstract
-	 * @class document.Node
+	 * @class treeModel.Node
 	 */
 	class Node {
 		/**
@@ -18,22 +18,22 @@ CKEDITOR.define( [ 'document/attribute', 'utils', 'ckeditorerror' ], ( Attribute
 		 *
 		 * This is an abstract class, so this constructor should not be used directly.
 		 *
-		 * @param {Iterable} attrs Iterable collection of {@link document.Attribute attributes}.
+		 * @param {Iterable} attrs Iterable collection of {@link treeModel.Attribute attributes}.
 		 * @constructor
 		 */
 		constructor( attrs ) {
 			/**
-			 * Parent element. Null by default. Set by {@link document.Element#insertChildren}.
+			 * Parent element. Null by default. Set by {@link treeModel.Element#insertChildren}.
 			 *
 			 * @readonly
-			 * @property {document.Element|null} parent
+			 * @property {treeModel.Element|null} parent
 			 */
 			this.parent = null;
 
 			/**
 			 * Attributes set.
 			 *
-			 * Attributes of nodes attached to the document can be changed only be the {@link document.operation.ChangeOperation}.
+			 * Attributes of nodes attached to the document can be changed only be the {@link treeModel.operation.AttributeOperation}.
 			 *
 			 * @private
 			 * @property {Set} _attrs
@@ -41,33 +41,6 @@ CKEDITOR.define( [ 'document/attribute', 'utils', 'ckeditorerror' ], ( Attribute
 			this._attrs = new Set( attrs );
 		}
 
-		/**
-		 * Index of the node in the parent element or null if the node has no parent.
-		 *
-		 * Throws error if the parent element does not contain this node.
-		 *
-		 * @returns {Number|Null} Index of the node in the parent element or null if the node has not parent.
-		 */
-		getIndex() {
-			let pos;
-
-			if ( !this.parent ) {
-				return null;
-			}
-
-			// No parent or child doesn't exist in parent's children.
-			if ( ( pos = this.parent.getChildIndex( this ) ) == -1 ) {
-				/**
-				 * The node's parent does not contain this node. It means that the document tree is corrupted.
-				 *
-				 * @error node-not-found-in-parent
-				 */
-				throw new CKEditorError( 'node-not-found-in-parent: The node\'s parent does not contain this node.' );
-			}
-
-			return pos;
-		}
-
 		/**
 		 * Depth of the node, which equals to total number of its parents.
 		 *
@@ -87,6 +60,30 @@ CKEDITOR.define( [ 'document/attribute', 'utils', 'ckeditorerror' ], ( Attribute
 			return depth;
 		}
 
+		/**
+		 * Nodes next sibling or `null` if it is the last child.
+		 *
+		 * @readonly
+		 * @property {treeModel.Node|null} nextSibling
+		 */
+		get nextSibling() {
+			const index = this.getIndex();
+
+			return ( index !== null && this.parent.getChild( index + 1 ) ) || null;
+		}
+
+		/**
+		 * Nodes previous sibling or null if it is the last child.
+		 *
+		 * @readonly
+		 * @property {treeModel.Node|null} previousSibling
+		 */
+		get previousSibling() {
+			const index = this.getIndex();
+
+			return ( index !== null && this.parent.getChild( index - 1 ) ) || null;
+		}
+
 		/**
 		 * The top parent for the node. If node has no parent it is the root itself.
 		 *
@@ -104,34 +101,82 @@ CKEDITOR.define( [ 'document/attribute', 'utils', 'ckeditorerror' ], ( Attribute
 		}
 
 		/**
-		 * Nodes next sibling or `null` if it is the last child.
+		 * Finds an attribute by a key.
 		 *
-		 * @readonly
-		 * @property {document.Node|null} nextSibling
+		 * @param {String} attr The attribute key.
+		 * @returns {treeModel.Attribute} The found attribute.
 		 */
-		get nextSibling() {
-			const index = this.getIndex();
+		getAttr( key ) {
+			for ( let attr of this._attrs ) {
+				if ( attr.key == key ) {
+					return attr.value;
+				}
+			}
 
-			return ( index !== null && this.parent.getChild( index + 1 ) ) || null;
+			return null;
 		}
 
 		/**
-		 * Nodes previous sibling or null if it is the last child.
+		 * Returns attribute iterator. It can be use to create a new element with the same attributes:
 		 *
-		 * @readonly
-		 * @property {document.Node|null} previousSibling
+		 *		const copy = new Element( element.name, element.getAttrs() );
+		 *
+		 * @returns {Iterable.<treeModel.Attribute>} Attribute iterator.
 		 */
-		get previousSibling() {
-			const index = this.getIndex();
+		getAttrs() {
+			return this._attrs[ Symbol.iterator ]();
+		}
 
-			return ( index !== null && this.parent.getChild( index - 1 ) ) || null;
+		/**
+		 * Index of the node in the parent element or null if the node has no parent.
+		 *
+		 * Throws error if the parent element does not contain this node.
+		 *
+		 * @returns {Number|Null} Index of the node in the parent element or null if the node has not parent.
+		 */
+		getIndex() {
+			let pos;
+
+			if ( !this.parent ) {
+				return null;
+			}
+
+			// No parent or child doesn't exist in parent's children.
+			if ( ( pos = this.parent.getChildIndex( this ) ) == -1 ) {
+				/**
+				 * The node's parent does not contain this node. It means that the document tree is corrupted.
+				 *
+				 * @error node-not-found-in-parent
+				 */
+				throw new CKEditorError( 'node-not-found-in-parent: The node\'s parent does not contain this node.' );
+			}
+
+			return pos;
+		}
+
+		/**
+		 * Gets path to the node. For example if the node is the second child of the first child of the root then the path
+		 * will be `[ 1, 2 ]`. This path can be used as a parameter of {@link treeModel.Position}.
+		 *
+		 * @returns {Number[]} The path.
+		 */
+		getPath() {
+			const path = [];
+			let node = this; // jscs:ignore safeContextKeyword
+
+			while ( node.parent ) {
+				path.unshift( node.getIndex() );
+				node = node.parent;
+			}
+
+			return path;
 		}
 
 		/**
 		 * Returns `true` if the node contains an attribute with the same key and value as given or the same key if the
 		 * given parameter is a string.
 		 *
-		 * @param {document.Attribute|String} attr An attribute or a key to compare.
+		 * @param {treeModel.Attribute|String} key An attribute or a key to compare.
 		 * @returns {Boolean} True if node contains given attribute or an attribute with the given key.
 		 */
 		hasAttr( key ) {
@@ -157,22 +202,6 @@ CKEDITOR.define( [ 'document/attribute', 'utils', 'ckeditorerror' ], ( Attribute
 			return false;
 		}
 
-		/**
-		 * Finds an attribute by a key.
-		 *
-		 * @param {String} attr The attribute key.
-		 * @returns {document.Attribute} The found attribute.
-		 */
-		getAttr( key ) {
-			for ( let attr of this._attrs ) {
-				if ( attr.key == key ) {
-					return attr.value;
-				}
-			}
-
-			return null;
-		}
-
 		/**
 		 * Removes attribute from the list of attributes.
 		 *
@@ -191,7 +220,7 @@ CKEDITOR.define( [ 'document/attribute', 'utils', 'ckeditorerror' ], ( Attribute
 		/**
 		 * Sets a given attribute. If the attribute with the same key already exists it will be removed.
 		 *
-		 * @param {document.Attribute} attr Attribute to set.
+		 * @param {treeModel.Attribute} attr Attribute to set.
 		 */
 		setAttr( attr ) {
 			this.removeAttr( attr.key );
@@ -199,24 +228,6 @@ CKEDITOR.define( [ 'document/attribute', 'utils', 'ckeditorerror' ], ( Attribute
 			this._attrs.add( attr );
 		}
 
-		/**
-		 * Gets path to the node. For example if the node is the second child of the first child of the root then the path
-		 * will be `[ 1, 2 ]`. This path can be used as a parameter of {@link document.Position}.
-		 *
-		 * @returns {Number[]} The path.
-		 */
-		getPath() {
-			const path = [];
-			let node = this; // jscs:ignore safeContextKeyword
-
-			while ( node.parent ) {
-				path.unshift( node.getIndex() );
-				node = node.parent;
-			}
-
-			return path;
-		}
-
 		/**
 		 * Custom toJSON method to solve child-parent circular dependencies.
 		 *
@@ -230,17 +241,6 @@ CKEDITOR.define( [ 'document/attribute', 'utils', 'ckeditorerror' ], ( Attribute
 
 			return json;
 		}
-
-		/**
-		 * Returns attribute iterator. It can be use to create a new element with the same attributes:
-		 *
-		 *		const copy = new Element( element.name, element.getAttrs() );
-		 *
-		 * @returns {Iterable.<document.Attribute>} Attribute iterator.
-		 */
-		getAttrs() {
-			return this._attrs[ Symbol.iterator ]();
-		}
 	}
 
 	return Node;

+ 32 - 32
packages/ckeditor5-engine/src/document/nodelist.js → packages/ckeditor5-engine/src/treemodel/nodelist.js

@@ -6,20 +6,20 @@
 'use strict';
 
 CKEDITOR.define( [
-	'document/character',
-	'document/text',
-	'document/node',
+	'treemodel/character',
+	'treemodel/text',
+	'treemodel/node',
 	'utils'
 ], ( Character, Text, Node, utils ) => {
 	/**
 	 * List of nodes. It is used to represent multiple nodes with a given order, for example children of
-	 * {@link document.Element} object or nodes inserted using {@link document.operation.InsertOperation}.
+	 * {@link treeModel.Element} object or nodes inserted using {@link treeModel.operation.InsertOperation}.
 	 *
 	 * Thanks to the constructor, which accepts various arguments, this class lets you easily create desired list of nodes.
 	 *
 	 * It also may internally compress nodes.
 	 *
-	 * @class document.NodeList
+	 * @class treeModel.NodeList
 	 */
 	class NodeList {
 		/**
@@ -48,7 +48,7 @@ CKEDITOR.define( [
 		 *		nodeListA === nodeListB // true
 		 *		nodeListB.length // 3
 		 *
-		 * @param {document.Node|document.Text|document.NodeList|String|Iterable} nodes List of nodes.
+		 * @param {treeModel.Node|treeModel.Text|treeModel.NodeList|String|Iterable} nodes List of nodes.
 		 * @constructor
 		 */
 		constructor( nodes ) {
@@ -94,40 +94,36 @@ CKEDITOR.define( [
 		}
 
 		/**
-		 * Returns node at the given index.
+		 * Number of nodes in the node list.
 		 *
-		 * @param {Number} index Node index.
-		 * @returns {document.Node} Node at given index.
+		 * @readonly
+		 * @property {Number} length
 		 */
-		get( index ) {
-			return this._nodes[ index ];
+		get length() {
+			return this._nodes.length;
 		}
 
 		/**
-		 * Inserts nodes from the given node list into this node list at the given index.
-		 *
-		 * @param {Number} index Position where nodes should be inserted.
-		 * @param {document.NodeList} nodeList List of nodes to insert.
+		 * Node list iterator.
 		 */
-		insert( index, nodeList ) {
-			this._nodes.splice.apply( this._nodes, [ index, 0 ].concat( nodeList._nodes ) );
+		[ Symbol.iterator ]() {
+			return this._nodes[ Symbol.iterator ]();
 		}
 
 		/**
-		 * Removes number of nodes starting at the given index.
+		 * Returns node at the given index.
 		 *
-		 * @param {Number} index Position of the first node to remove.
-		 * @param {Number} number Number of nodes to remove.
-		 * @returns {document.NodeList} List of removed nodes.
+		 * @param {Number} index Node index.
+		 * @returns {treeModel.Node} Node at given index.
 		 */
-		remove( index, number ) {
-			return new NodeList( this._nodes.splice( index, number ) );
+		get( index ) {
+			return this._nodes[ index ];
 		}
 
 		/**
 		 * Search for the node in the node list.
 		 *
-		 * @param {document.Node} node Node to find.
+		 * @param {treeModel.Node} node Node to find.
 		 * @returns {Number} Position of the node in the list.
 		 */
 		indexOf( node ) {
@@ -135,20 +131,24 @@ CKEDITOR.define( [
 		}
 
 		/**
-		 * Number of nodes in the node list.
+		 * Inserts nodes from the given node list into this node list at the given index.
 		 *
-		 * @readonly
-		 * @property {Number} length
+		 * @param {Number} index Position where nodes should be inserted.
+		 * @param {treeModel.NodeList} nodeList List of nodes to insert.
 		 */
-		get length() {
-			return this._nodes.length;
+		insert( index, nodeList ) {
+			this._nodes.splice.apply( this._nodes, [ index, 0 ].concat( nodeList._nodes ) );
 		}
 
 		/**
-		 * Node list iterator.
+		 * Removes number of nodes starting at the given index.
+		 *
+		 * @param {Number} index Position of the first node to remove.
+		 * @param {Number} number Number of nodes to remove.
+		 * @returns {treeModel.NodeList} List of removed nodes.
 		 */
-		[ Symbol.iterator ]() {
-			return this._nodes[ Symbol.iterator ]();
+		remove( index, number ) {
+			return new NodeList( this._nodes.splice( index, number ) );
 		}
 	}
 

+ 48 - 36
packages/ckeditor5-engine/src/document/operation/changeoperation.js → packages/ckeditor5-engine/src/treemodel/operation/attributeoperation.js

@@ -5,15 +5,18 @@
 
 'use strict';
 
-CKEDITOR.define( [ 'document/operation/operation', 'ckeditorerror' ], ( Operation, CKEditorError ) => {
+CKEDITOR.define( [
+	'treemodel/operation/operation',
+	'ckeditorerror'
+], ( Operation, CKEditorError ) => {
 	/**
 	 * Operation to change nodes' attribute. Using this class you can add, remove or change value of the attribute.
 	 *
-	 * @class document.operation.ChangeOperation
+	 * @class treeModel.operation.AttributeOperation
 	 */
-	class ChangeOperation extends Operation {
+	class AttributeOperation extends Operation {
 		/**
-		 * Creates a change operation.
+		 * Creates an operation that changes, removes or adds attributes.
 		 *
 		 * If only the new attribute is set, then it will be inserted. Note that in all nodes in ranges there must be
 		 * no attributes with the same key as the new attribute.
@@ -24,10 +27,10 @@ CKEDITOR.define( [ 'document/operation/operation', 'ckeditorerror' ], ( Operatio
 		 * If both new and old attributes are set, then the operation will change the attribute value. Note that both new and
 		 * old attributes have to have the same key and the old attribute must be present in all nodes in ranges.
 		 *
-		 * @param {document.Range} range Range on which the operation should be applied.
-		 * @param {document.Attribute|null} oldAttr Attribute to be removed. If `null`, then the operation just inserts a new attribute.
-		 * @param {document.Attribute|null} newAttr Attribute to be added. If `null`, then the operation just removes the attribute.
-		 * @param {Number} baseVersion {@link document.Document#version} on which the operation can be applied.
+		 * @param {treeModel.Range} range Range on which the operation should be applied.
+		 * @param {treeModel.Attribute|null} oldAttr Attribute to be removed. If `null`, then the operation just inserts a new attribute.
+		 * @param {treeModel.Attribute|null} newAttr Attribute to be added. If `null`, then the operation just removes the attribute.
+		 * @param {Number} baseVersion {@link treeModel.Document#version} on which the operation can be applied.
 		 * @constructor
 		 */
 		constructor( range, oldAttr, newAttr, baseVersion ) {
@@ -37,7 +40,7 @@ CKEDITOR.define( [ 'document/operation/operation', 'ckeditorerror' ], ( Operatio
 			 * Range on which operation should be applied.
 			 *
 			 * @readonly
-			 * @type {document.Range}
+			 * @type {treeModel.Range}
 			 */
 			this.range = range;
 
@@ -45,7 +48,7 @@ CKEDITOR.define( [ 'document/operation/operation', 'ckeditorerror' ], ( Operatio
 			 * Old attribute to change. Set to `null` if operation inserts a new attribute.
 			 *
 			 * @readonly
-			 * @type {document.Attribute|null}
+			 * @type {treeModel.Attribute|null}
 			 */
 			this.oldAttr = oldAttr;
 
@@ -53,78 +56,87 @@ CKEDITOR.define( [ 'document/operation/operation', 'ckeditorerror' ], ( Operatio
 			 * New attribute. Set to `null` if operation removes the attribute.
 			 *
 			 * @readonly
-			 * @type {document.Attribute|null}
+			 * @type {treeModel.Attribute|null}
 			 */
 			this.newAttr = newAttr;
 		}
 
+		get type() {
+			return 'attr';
+		}
+
+		clone() {
+			return new AttributeOperation( this.range.clone(), this.oldAttr, this.newAttr, this.baseVersion );
+		}
+
+		getReversed() {
+			return new AttributeOperation( this.range, this.newAttr, this.oldAttr, this.baseVersion + 1 );
+		}
+
 		_execute() {
 			const oldAttr = this.oldAttr;
 			const newAttr = this.newAttr;
-			let value;
 
 			if ( oldAttr !== null && newAttr !== null && oldAttr.key != newAttr.key ) {
 				/**
 				 * Old and new attributes should have the same keys.
 				 *
-				 * @error operation-change-different-keys
-				 * @param {document.Attribute} oldAttr
-				 * @param {document.Attribute} newAttr
+				 * @error operation-attribute-different-keys
+				 * @param {treeModel.Attribute} oldAttr
+				 * @param {treeModel.Attribute} newAttr
 				 */
 				throw new CKEditorError(
-					'operation-change-different-keys: Old and new attributes should have the same keys.',
+					'operation-attribute-different-keys: Old and new attributes should have the same keys.',
 					{ oldAttr: oldAttr, newAttr: newAttr } );
 			}
 
 			// Remove or change.
 			if ( oldAttr !== null ) {
-				for ( value of this.range ) {
-					if ( !value.node.hasAttr( oldAttr ) ) {
+				for ( let node of this.range.getNodes() ) {
+					if ( !node.hasAttr( oldAttr ) ) {
 						/**
 						 * The attribute which should be removed does not exists for the given node.
 						 *
-						 * @error operation-change-no-attr-to-remove
-						 * @param {document.Node} node
-						 * @param {document.Attribute} attr
+						 * @error operation-attribute-no-attr-to-remove
+						 * @param {treeModel.Node} node
+						 * @param {treeModel.Attribute} attr
 						 */
 						throw new CKEditorError(
-							'operation-change-no-attr-to-remove: The attribute which should be removed does not exists for given node.',
-							{ node: value.node, attr: oldAttr } );
+							'operation-attribute-no-attr-to-remove: The attribute which should be removed does not exists for given node.',
+							{ node: node, attr: oldAttr } );
 					}
 
 					// There is no use in removing attribute if we will overwrite it later.
 					// Still it is profitable to run through the loop to check if all nodes in the range has old attribute.
 					if ( newAttr === null ) {
-						value.node.removeAttr( oldAttr.key );
+						node.removeAttr( oldAttr.key );
 					}
 				}
 			}
 
 			// Insert or change.
 			if ( newAttr !== null ) {
-				for ( value of this.range ) {
-					if ( oldAttr === null && value.node.hasAttr( newAttr.key ) ) {
+				for ( let node of this.range.getNodes() ) {
+					if ( oldAttr === null && node.hasAttr( newAttr.key ) ) {
 						/**
 						 * The attribute with given key already exists for the given node.
 						 *
-						 * @error operation-change-attr-exists
-						 * @param {document.Node} node
-						 * @param {document.Attribute} attr
+						 * @error operation-attribute-attr-exists
+						 * @param {treeModel.Node} node
+						 * @param {treeModel.Attribute} attr
 						 */
 						throw new CKEditorError(
-							'operation-change-attr-exists: The attribute with given key already exists.',
-							{ node: value.node, attr: newAttr } );
+							'operation-attribute-attr-exists: The attribute with given key already exists.',
+							{ node: node, attr: newAttr } );
 					}
 
-					value.node.setAttr( newAttr );
+					node.setAttr( newAttr );
 				}
 			}
-		}
 
-		getReversed() {
-			return new ChangeOperation( this.range, this.newAttr, this.oldAttr, this.baseVersion + 1 );
+			return { range: this.range, oldAttr: oldAttr, newAttr: newAttr };
 		}
 	}
 
-	return ChangeOperation;
+	return AttributeOperation;
 } );

+ 27 - 14
packages/ckeditor5-engine/src/document/operation/insertoperation.js → packages/ckeditor5-engine/src/treemodel/operation/insertoperation.js

@@ -6,23 +6,24 @@
 'use strict';
 
 CKEDITOR.define( [
-	'document/operation/operation',
-	'document/nodelist',
-	'document/operation/removeoperation'
-], ( Operation, NodeList ) => {
+	'treemodel/operation/operation',
+	'treemodel/nodelist',
+	'treemodel/range',
+	'treemodel/operation/removeoperation'
+], ( Operation, NodeList, Range ) => {
 	/**
 	 * Operation to insert list of nodes on the given position in the tree data model.
 	 *
-	 * @class document.operation.InsertOperation
+	 * @class treeModel.operation.InsertOperation
 	 */
 	class InsertOperation extends Operation {
 		/**
 		 * Creates an insert operation.
 		 *
-		 * @param {document.Position} position Position of insertion.
-		 * @param {document.Node|document.Text|document.NodeList|String|Iterable} nodes The list of nodes to be inserted.
-		 * List of nodes can be any type accepted by the {@link document.NodeList} constructor.
-		 * @param {Number} baseVersion {@link document.Document#version} on which operation can be applied.
+		 * @param {treeModel.Position} position Position of insertion.
+		 * @param {treeModel.Node|treeModel.Text|treeModel.NodeList|String|Iterable} nodes The list of nodes to be inserted.
+		 * List of nodes can be any type accepted by the {@link treeModel.NodeList} constructor.
+		 * @param {Number} baseVersion {@link treeModel.Document#version} on which operation can be applied.
 		 * @constructor
 		 */
 		constructor( position, nodes, baseVersion ) {
@@ -32,7 +33,7 @@ CKEDITOR.define( [
 			 * Position of insertion.
 			 *
 			 * @readonly
-			 * @type {document.Position}
+			 * @type {treeModel.Position}
 			 */
 			this.position = position;
 
@@ -40,21 +41,33 @@ CKEDITOR.define( [
 			 * List of nodes to insert.
 			 *
 			 * @readonly
-			 * @type {document.NodeList}
+			 * @type {treeModel.NodeList}
 			 */
 			this.nodeList = new NodeList( nodes );
 		}
 
-		_execute() {
-			this.position.parent.insertChildren( this.position.offset, this.nodeList );
+		get type() {
+			return 'insert';
+		}
+
+		clone() {
+			return new InsertOperation( this.position, this.nodeList, this.baseVersion );
 		}
 
 		getReversed() {
 			// Because of circular dependencies we need to re-require remove operation here.
-			const RemoveOperation = CKEDITOR.require( 'document/operation/removeoperation' );
+			const RemoveOperation = CKEDITOR.require( 'treemodel/operation/removeoperation' );
 
 			return new RemoveOperation( this.position, this.nodeList.length, this.baseVersion + 1 );
 		}
+
+		_execute() {
+			this.position.parent.insertChildren( this.position.offset, this.nodeList );
+
+			return {
+				range: Range.createFromPositionAndShift( this.position, this.nodeList.length )
+			};
+		}
 	}
 
 	return InsertOperation;

+ 33 - 23
packages/ckeditor5-engine/src/document/operation/moveoperation.js → packages/ckeditor5-engine/src/treemodel/operation/moveoperation.js

@@ -6,49 +6,61 @@
 'use strict';
 
 CKEDITOR.define( [
-	'document/operation/operation',
-	'document/nodelist',
+	'treemodel/operation/operation',
+	'treemodel/range',
 	'ckeditorerror',
 	'utils'
-], ( Operation, NodeList, CKEditorError, utils ) => {
+], ( Operation, Range, CKEditorError, utils ) => {
 	/**
 	 * Operation to move list of subsequent nodes from one position in the document to another.
 	 *
-	 * @class document.operation.MoveOperation
+	 * @class treeModel.operation.MoveOperation
 	 */
 	class MoveOperation extends Operation {
 		/**
 		 * Creates a move operation.
 		 *
-		 * @param {document.Position} sourcePosition Position before the first element to move.
-		 * @param {document.Position} targetPosition Position where moved elements will be inserted.
+		 * @param {treeModel.Position} sourcePosition Position before the first element to move.
 		 * @param {Number} howMany How many consecutive nodes to move, starting from `sourcePosition`.
-		 * @param {Number} baseVersion {@link document.Document#version} on which operation can be applied.
+		 * @param {treeModel.Position} targetPosition Position where moved elements will be inserted.
+		 * @param {Number} baseVersion {@link treeModel.Document#version} on which operation can be applied.
 		 * @constructor
 		 */
-		constructor( sourcePosition, targetPosition, howMany, baseVersion ) {
+		constructor( sourcePosition, howMany, targetPosition, baseVersion ) {
 			super( baseVersion );
 
 			/**
 			 * Source move position.
 			 *
-			 * @type {document.Position}
+			 * @type {treeModel.Position}
 			 */
 			this.sourcePosition = sourcePosition;
 
 			/**
-			 * Target move position.
+			 * How many nodes to move.
 			 *
-			 * @type {document.Position}
+			 * @type {Number}
 			 */
-			this.targetPosition = targetPosition;
+			this.howMany = howMany;
 
 			/**
-			 * How many nodes to move.
+			 * Target move position.
 			 *
-			 * @type {Number}
+			 * @type {treeModel.Position}
 			 */
-			this.howMany = howMany;
+			this.targetPosition = targetPosition;
+		}
+
+		get type() {
+			return 'move';
+		}
+
+		clone() {
+			return new MoveOperation( this.sourcePosition.clone(), this.howMany, this.targetPosition.clone(), this.baseVersion );
+		}
+
+		getReversed() {
+			return new MoveOperation( this.targetPosition.clone(), this.howMany, this.sourcePosition.clone(), this.baseVersion + 1 );
 		}
 
 		_execute() {
@@ -88,11 +100,8 @@ CKEDITOR.define( [
 					'operation-move-range-into-itself: Trying to move a range of nodes to the inside of that range.'
 				);
 			} else {
-				const sourcePath = this.sourcePosition.getParentPath();
-				const targetPath = this.targetPosition.getParentPath();
-
-				if ( utils.compareArrays( sourcePath, targetPath ) == utils.compareArrays.PREFIX ) {
-					let i = sourcePath.length;
+				if ( utils.compareArrays( this.sourcePosition.getParentPath(), this.targetPosition.getParentPath() ) == utils.compareArrays.PREFIX ) {
+					let i = this.sourcePosition.path.length - 1;
 
 					if ( this.targetPosition.path[ i ] >= sourceOffset && this.targetPosition.path[ i ] < sourceOffset + this.howMany ) {
 						/**
@@ -117,10 +126,11 @@ CKEDITOR.define( [
 			const removedNodes = sourceElement.removeChildren( sourceOffset, this.howMany );
 
 			targetElement.insertChildren( targetOffset, removedNodes );
-		}
 
-		getReversed() {
-			return new MoveOperation( this.targetPosition, this.sourcePosition, this.howMany, this.baseVersion + 1 );
+			return {
+				sourcePosition: this.sourcePosition,
+				range: Range.createFromPositionAndShift( this.targetPosition, this.howMany )
+			};
 		}
 	}
 

+ 37 - 0
packages/ckeditor5-engine/src/treemodel/operation/nooperation.js

@@ -0,0 +1,37 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+'use strict';
+
+CKEDITOR.define( [
+	'treemodel/operation/operation'
+], ( Operation ) => {
+	/**
+	 * Operation which is doing nothing ("empty operation", "do-nothing operation", "noop").
+	 * This is an operation, which when executed does not change the tree model.
+	 * It still has some parameters defined for transformation purposes.
+	 *
+	 * In most cases this operation is a result of transforming operations. When transformation returns
+	 * {@link treeModel.operation.NoOperation} it means that changes done by the transformed operation
+	 * have already been applied.
+	 *
+	 * @class treeModel.operation.NoOperation
+	 */
+	class NoOperation extends Operation {
+		clone() {
+			return new NoOperation( this.baseVersion );
+		}
+
+		getReversed() {
+			return new NoOperation( this.baseVersion + 1 );
+		}
+
+		_execute() {
+			// Do nothing.
+		}
+	}
+
+	return NoOperation;
+} );

+ 80 - 0
packages/ckeditor5-engine/src/treemodel/operation/operation.js

@@ -0,0 +1,80 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+'use strict';
+
+CKEDITOR.define( [], () => {
+	/**
+	 * Abstract base operation class.
+	 *
+	 * @abstract
+	 * @class treeModel.operation.Operation
+	 */
+	class Operation {
+		/**
+		 * Base operation constructor.
+		 *
+		 * @param {Number} baseVersion {@link treeModel.Document#version} on which the operation can be applied.
+		 * @constructor
+		 */
+		constructor( baseVersion ) {
+			/**
+			 * {@link treeModel.Document#version} on which operation can be applied. If you try to
+			 * {@link treeModel.Document#applyOperation apply} operation with different base version than the
+			 * {@link treeModel.Document#version document version} the {@link document-applyOperation-wrong-version}
+			 * error is thrown.
+			 *
+			 * @property {Number}
+			 */
+			this.baseVersion = baseVersion;
+
+			/**
+			 * Operation type.
+			 *
+			 * @property {String} type
+			 */
+
+			/**
+			 * {@link treeModel.Delta Delta} which the operation is a part of. This property is set by the
+			 * {@link treeModel.Delta delta} when the operations is added to it by the
+			 * {@link treeModel.Delta#addOperation} method.
+			 *
+			 * @property {treeModel.Delta} delta
+			 */
+
+			/**
+			 * Creates and returns an operation that has the same parameters as this operation.
+			 *
+			 * @method clone
+			 * @returns {treeModel.operation.Operation} Clone of this operation.
+			 */
+
+			/**
+			 * Creates and returns a reverse operation. Reverse operation when executed right after
+			 * the original operation will bring back tree model state to the point before the original
+			 * operation execution. In other words, it reverses changes done by the original operation.
+			 *
+			 * Keep in mind that tree model state may change since executing the original operation,
+			 * so reverse operation will be "outdated". In that case you will need to
+			 * {@link treeModel.operation.transform} it by all operations that were executed after the original operation.
+			 *
+			 * @method getReversed
+			 * @returns {treeModel.operation.Operation} Reversed operation.
+			 */
+
+			/**
+			 * Executes the operation - modifications described by the operation attributes
+			 * will be applied to the tree model.
+			 *
+			 * @protected
+			 * @method _execute
+			 * @returns {Object} Object with additional information about the applied changes. Always has `range`
+			 * property containing changed nodes. May have additional properties depending on the operation type.
+			 */
+		}
+	}
+
+	return Operation;
+} );

+ 10 - 6
packages/ckeditor5-engine/src/document/operation/reinsertoperation.js → packages/ckeditor5-engine/src/treemodel/operation/reinsertoperation.js

@@ -6,27 +6,31 @@
 'use strict';
 
 CKEDITOR.define( [
-	'document/operation/moveoperation',
-	'document/operation/removeoperation'
+	'treemodel/operation/moveoperation',
+	'treemodel/operation/removeoperation'
 ], ( MoveOperation ) => {
 	/**
 	 * Operation to reinsert previously removed nodes back to the non-graveyard root.
-	 * This is basically {@link document.operation.MoveOperation} but it returns
-	 * {@link document.operation.RemoveOperation} when reversed.
+	 * This is basically {@link treeModel.operation.MoveOperation} but it returns
+	 * {@link treeModel.operation.RemoveOperation} when reversed.
 	 *
 	 * With this class, we achieve two goals: by having separate classes it's easier to distinguish whether move
 	 * operation is actually a remove/reinsert operation and fire proper events. Also it
 	 * will be easier to expand if we need to change operation's behavior if it is remove/reinsert.
 	 *
-	 * @class document.operation.ReinsertOperation
+	 * @class treeModel.operation.ReinsertOperation
 	 */
 	class ReinsertOperation extends MoveOperation {
 		getReversed() {
 			// Because of circular dependencies we need to re-require reinsert operation here.
-			const RemoveOperation = CKEDITOR.require( 'document/operation/removeoperation' );
+			const RemoveOperation = CKEDITOR.require( 'treemodel/operation/removeoperation' );
 
 			return new RemoveOperation( this.targetPosition, this.howMany, this.baseVersion + 1 );
 		}
+
+		get type() {
+			return 'reinsert';
+		}
 	}
 
 	return ReinsertOperation;

+ 14 - 12
packages/ckeditor5-engine/src/document/operation/removeoperation.js → packages/ckeditor5-engine/src/treemodel/operation/removeoperation.js

@@ -6,38 +6,40 @@
 'use strict';
 
 CKEDITOR.define( [
-	'document/operation/moveoperation',
-	'document/position',
-	'document/operation/reinsertoperation'
+	'treemodel/operation/moveoperation',
+	'treemodel/position',
+	'treemodel/operation/reinsertoperation'
 ], ( MoveOperation, Position ) => {
 	/**
 	 * Operation to remove a range of nodes.
 	 *
-	 * @class document.operation.RemoveOperation
+	 * @class treeModel.operation.RemoveOperation
 	 */
 	class RemoveOperation extends MoveOperation {
 		/**
 		 * Creates a remove operation.
 		 *
-		 * @param {document.Position} position Position before the first node to remove.
+		 * @param {treeModel.Position} position Position before the first node to remove.
 		 * @param {Number} howMany How many nodes to remove.
-		 * @param {Number} baseVersion {@link document.Document#version} on which operation can be applied.
+		 * @param {Number} baseVersion {@link treeModel.Document#version} on which operation can be applied.
 		 * @constructor
 		 */
 		constructor( position, howMany, baseVersion ) {
-			const graveyard = position.root.document._graveyard;
-
 			// Position in a graveyard where nodes were moved.
-			const graveyardPosition = Position.createFromParentAndOffset( graveyard, 0 );
+			const graveyardPosition = Position.createFromParentAndOffset( position.root.document.graveyard, 0 );
+
+			super( position, howMany, graveyardPosition, baseVersion );
+		}
 
-			super( position, graveyardPosition, howMany, baseVersion );
+		get type() {
+			return 'remove';
 		}
 
 		getReversed() {
 			// Because of circular dependencies we need to re-require reinsert operation here.
-			const ReinsertOperation = CKEDITOR.require( 'document/operation/reinsertoperation' );
+			const ReinsertOperation = CKEDITOR.require( 'treemodel/operation/reinsertoperation' );
 
-			return new ReinsertOperation( this.targetPosition, this.sourcePosition, this.howMany, this.baseVersion + 1 );
+			return new ReinsertOperation( this.targetPosition, this.howMany, this.sourcePosition, this.baseVersion + 1 );
 		}
 	}
 

+ 422 - 0
packages/ckeditor5-engine/src/treemodel/operation/transform.js

@@ -0,0 +1,422 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+'use strict';
+
+/**
+ * Transforms given {treeModel.operation.Operation} by another {treeModel.operation.Operation} and returns the result of
+ * that transformation as an array containing one or more {treeModel.operation.Operation} elements.
+ *
+ * Operations work on specified positions, passed to them when they are created. Whenever {@link treeModel.Document document}
+ * changes, we have to reflect those modifications by updating or "transforming" operations which are not yet applied.
+ * When an operation is transformed, its parameters may change based on the operation by which it is transformed.
+ * If the transform-by operation applied any modifications to the Tree Data Model which affect positions or nodes
+ * connected with transformed operation, those changes will be reflected in the parameters of the returned operation(s).
+ *
+ * Whenever the {@link treeModel.Document document} has different {@link treeModel.Document#baseVersion}
+ * than the operation you want to {@link treeModel.Document#applyOperation apply}, you need to transform that
+ * operation by all operations which were already applied to the {@link treeModel.Document document} and have greater
+ * {@link treeModel.Document#baseVersion} than the operation being applied. Transform them in the same order as those
+ * operations which were applied. This way all modifications done to the Tree Data Model will be reflected
+ * in the operation parameters and the operation will "operate" on "up-to-date" version of the Tree Data Model.
+ * This is mostly the case with Operational Transformations but it might be needed in particular features as well.
+ *
+ * In some cases, when given operation apply changes to the same nodes as this operation, two or more operations need
+ * to be created as one would not be able to reflect the combination of these operations.
+ * This is why an array is returned instead of a single object. All returned operations have to be applied
+ * (or further transformed) to get an effect which was intended in pre-transformed operation.
+ *
+ * Sometimes two operations are in conflict. This happens when they modify the same node in a different way, i.e.
+ * set different value for the same attribute or move the node into different positions. When this happens,
+ * we need to decide which operation is more important. We can't assume that operation `a` or operation `b` is always
+ * more important. In Operational Transformations algorithms we often need to get a result of transforming
+ * `a` by `b` and also `b` by `a`. In both transformations the same operation has to be the important one. If we assume
+ * that first or the second passed operation is always more important we won't be able to solve this case.
+ *
+ * @function treeModel.operation.transform
+ * @param {treeModel.operation.Operation} a Operation that will be transformed.
+ * @param {treeModel.operation.Operation} b Operation to transform by.
+ * @param {Boolean} isAMoreImportantThanB Flag indicating whether the operation which will be transformed (`a`) should be treated
+ * as more important when resolving conflicts.
+ * @returns {Array.<treeModel.operation.Operation>} Result of the transformation.
+ */
+
+CKEDITOR.define( [
+	'treemodel/operation/insertoperation',
+	'treemodel/operation/attributeoperation',
+	'treemodel/operation/moveoperation',
+	'treemodel/operation/nooperation',
+	'treemodel/range',
+	'utils'
+], ( InsertOperation, AttributeOperation, MoveOperation, NoOperation, Range, utils ) => {
+	const ot = {
+		InsertOperation: {
+			// Transforms InsertOperation `a` by InsertOperation `b`. Accepts a flag stating whether `a` is more important
+			// than `b` when it comes to resolving conflicts. Returns results as an array of operations.
+			InsertOperation( a, b, isStrong ) {
+				// Transformed operations are always new instances, not references to the original operations.
+				const transformed = a.clone();
+
+				// Transform insert position by the other operation position.
+				transformed.position = transformed.position.getTransformedByInsertion( b.position, b.nodeList.length, !isStrong );
+
+				return [ transformed ];
+			},
+
+			AttributeOperation: doNotUpdate,
+
+			// Transforms InsertOperation `a` by MoveOperation `b`. Accepts a flag stating whether `a` is more important
+			// than `b` when it comes to resolving conflicts. Returns results as an array of operations.
+			MoveOperation( a, b, isStrong ) {
+				const transformed = a.clone();
+
+				// Transform insert position by the other operation parameters.
+				transformed.position = a.position.getTransformedByMove( b.sourcePosition, b.targetPosition, b.howMany, !isStrong );
+
+				return [ transformed ];
+			}
+		},
+
+		AttributeOperation: {
+			// Transforms AttributeOperation `a` by InsertOperation `b`. Returns results as an array of operations.
+			InsertOperation( a, b ) {
+				// Transform this operation's range.
+				const ranges = a.range.getTransformedByInsertion( b.position, b.nodeList.length );
+
+				// Map transformed range(s) to operations and return them.
+				return ranges.reverse().map( ( range ) => {
+					return new AttributeOperation(
+						range,
+						a.oldAttr,
+						a.newAttr,
+						a.baseVersion
+					);
+				} );
+			},
+
+			// Transforms AttributeOperation `a` by AttributeOperation `b`. Accepts a flag stating whether `a` is more important
+			// than `b` when it comes to resolving conflicts. Returns results as an array of operations.
+			AttributeOperation( a, b, isStrong ) {
+				if ( haveConflictingAttributes( a, b ) ) {
+					// If operations attributes are in conflict, check if their ranges intersect and manage them properly.
+					let operations = [];
+
+					// First, we want to apply change to the part of a range that has not been changed by the other operation.
+					operations = operations.concat(
+						a.range.getDifference( b.range ).map( ( range ) => {
+							return new AttributeOperation( range, a.oldAttr, a.newAttr, a.baseVersion );
+						} )
+					);
+
+					if ( isStrong ) {
+						// If this operation is more important, we want also want to apply change to the part of the
+						// original range that has already been changed by the other operation. Since that range
+						// got changed we have to update oldAttr.
+						const common = a.range.getIntersection( b.range );
+
+						if ( common !== null ) {
+							operations.push( new AttributeOperation( common, b.oldAttr, a.newAttr, a.baseVersion ) );
+						}
+					}
+
+					// If no operations has been added nothing should get updated, but since we need to return
+					// an instance of Operation we add NoOperation to the array.
+					if ( operations.length === 0 ) {
+						operations.push( new NoOperation( a.baseVersion ) );
+					}
+
+					return operations;
+				} else {
+					// If operations don't conflict simply, return an array containing just a clone of this operation.
+					return [ a.clone() ];
+				}
+			},
+
+			// Transforms AttributeOperation `a` by MoveOperation `b`. Returns results as an array of operations.
+			MoveOperation( a, b ) {
+				// Convert MoveOperation properties into a range.
+				const rangeB = Range.createFromPositionAndShift( b.sourcePosition, b.howMany );
+
+				// Get target position from the state "after" nodes specified by MoveOperation are "detached".
+				const newTargetPosition = b.targetPosition.getTransformedByDeletion( b.sourcePosition, b.howMany );
+
+				// This will aggregate transformed ranges.
+				let ranges = [];
+
+				// Difference is a part of changed range that is modified by AttributeOperation but are not affected
+				// by MoveOperation. This can be zero, one or two ranges (if moved range is inside changed range).
+				// If two ranges were returned it means that rangeB was inside rangeA. We will cover rangeB later.
+				// Right now we will make a simplification and join difference ranges and transform them as one.
+				const difference = joinRanges( a.range.getDifference( rangeB ) );
+
+				// Common is a range of nodes that is affected by MoveOperation. So it got moved to other place.
+				const common = a.range.getIntersection( rangeB );
+
+				if ( difference !== null ) {
+					// MoveOperation removes nodes from their original position. We acknowledge this by proper transformation.
+					// Take the start and the end of the range and transform them by deletion of moved nodes.
+					// Note that if rangeB was inside AttributeOperation range, only difference.end will be transformed.
+					// This nicely covers the joining simplification we did in the previous step.
+					difference.start = difference.start.getTransformedByDeletion( b.sourcePosition, b.howMany );
+					difference.end = difference.end.getTransformedByDeletion( b.sourcePosition, b.howMany );
+
+					// MoveOperation pastes nodes into target position. We acknowledge this by proper transformation.
+					// Note that since we operate on transformed difference range, we should transform by
+					// previously transformed target position.
+					// Note that we do not use Position.getTransformedByMove on range boundaries because we need to
+					// transform by insertion a range as a whole, since newTargetPosition might be inside that range.
+					ranges = difference.getTransformedByInsertion( newTargetPosition, b.howMany, false ).reverse();
+				}
+
+				if ( common !== null ) {
+					// Here we do not need to worry that newTargetPosition is inside moved range, because that
+					// would mean that the MoveOperation targets into itself, and that is incorrect operation.
+					// Instead, we calculate the new position of that part of original range.
+					common.start = common.start._getCombined( b.sourcePosition, newTargetPosition );
+					common.end = common.end._getCombined( b.sourcePosition, newTargetPosition );
+
+					ranges.push( common );
+				}
+
+				// Map transformed range(s) to operations and return them.
+				return ranges.map( ( range ) => {
+					return new AttributeOperation(
+						range,
+						a.oldAttr,
+						a.newAttr,
+						a.baseVersion
+					);
+				} );
+			}
+		},
+
+		MoveOperation: {
+			// Transforms MoveOperation `a` by InsertOperation `b`. Accepts a flag stating whether `a` is more important
+			// than `b` when it comes to resolving conflicts. Returns results as an array of operations.
+			InsertOperation( a, b, isStrong ) {
+				// Get target position from the state "after" nodes are inserted by InsertOperation.
+				const newTargetPosition = a.targetPosition.getTransformedByInsertion( b.position, b.nodeList.length, !isStrong );
+
+				// Create range from MoveOperation properties and transform it by insertion as well.
+				const rangeB = Range.createFromPositionAndShift( a.sourcePosition, a.howMany );
+				const ranges = rangeB.getTransformedByInsertion( b.position, b.nodeList.length, true );
+
+				// Map transformed range(s) to operations and return them.
+				return ranges.reverse().map( ( range ) => {
+					return new MoveOperation(
+						range.start,
+						range.end.offset - range.start.offset,
+						newTargetPosition.clone(),
+						a.baseVersion
+					);
+				} );
+			},
+
+			AttributeOperation: doNotUpdate,
+
+			// Transforms MoveOperation `a` by MoveOperation `b`. Accepts a flag stating whether `a` is more important
+			// than `b` when it comes to resolving conflicts. Returns results as an array of operations.
+			MoveOperation( a, b, isStrong ) {
+				// Special case when both move operations' target positions are inside nodes that are
+				// being moved by the other move operation. So in other words, we move ranges into inside of each other.
+				// This case can't be solved reasonably (on the other hand, it should not happen often).
+				if ( moveTargetIntoMovedRange( a, b ) && moveTargetIntoMovedRange( b, a ) ) {
+					// Instead of transforming operation, we return a reverse of the operation that we transform by.
+					// So when the results of this "transformation" will be applied, `b` MoveOperation will get reversed.
+					return [ b.getReversed() ];
+				}
+
+				// Create ranges from MoveOperations properties.
+				const rangeA = Range.createFromPositionAndShift( a.sourcePosition, a.howMany );
+				const rangeB = Range.createFromPositionAndShift( b.sourcePosition, b.howMany );
+
+				// Special case when transformed range contains both the other operation's whole range and target.
+				// In such case, operations are not really conflicting and we should leave transformed operation as it is.
+				// Without this we would have 3 or 4 operations and the transformation result would probably be not intuitive.
+				if ( rangeA.containsRange( rangeB ) && rangeA.containsPosition( b.targetPosition ) ) {
+					return [ a.clone() ];
+				}
+				// Mirror situation for the case above - now transformed range is wholly contained in the other
+				// operation's range and also targets to that range. Without this special treatment we would
+				// transform this operation into NoOperation, but this would not be compatible with the result
+				// generated by the special case above.
+				else if ( rangeB.containsRange( rangeA ) && rangeB.containsPosition( a.targetPosition ) ) {
+					return [
+						new MoveOperation(
+							a.sourcePosition._getCombined( b.sourcePosition, b.targetPosition ),
+							a.howMany,
+							a.targetPosition._getCombined( b.sourcePosition, b.targetPosition ),
+							a.baseVersion
+						)
+					];
+				}
+
+				// All the other non-special cases are treated by generic algorithm below.
+
+				const differenceSet = rangeA.getDifference( rangeB );
+				const common = rangeA.getIntersection( rangeB );
+
+				// This will aggregate transformed ranges.
+				let ranges = [];
+
+				// Get target position from the state "after" nodes specified by other MoveOperation are "detached".
+				const moveTargetPosition = b.targetPosition.getTransformedByDeletion( b.sourcePosition, b.howMany );
+
+				// First, we take care of that part of the range that is only modified by transformed operation.
+				for ( let i = 0; i < differenceSet.length; i++ ) {
+					// MoveOperation removes nodes from their original position. We acknowledge this by proper transformation.
+					// Take the start and the end of the range and transform them by deletion of moved nodes.
+					differenceSet[ i ].start = differenceSet[ i ].start.getTransformedByDeletion( b.sourcePosition, b.howMany );
+					differenceSet[ i ].end = differenceSet[ i ].end.getTransformedByDeletion( b.sourcePosition, b.howMany );
+
+					// MoveOperation pastes nodes into target position. We acknowledge this by proper transformation.
+					// Note that since we operate on transformed difference range, we should transform by
+					// previously transformed target position.
+					// Note that we do not use Position.getTransformedByMove on range boundaries because we need to
+					// transform by insertion a range as a whole, since newTargetPosition might be inside that range.
+					ranges = ranges.concat( differenceSet[ i ].getTransformedByInsertion( moveTargetPosition, b.howMany, true ) );
+				}
+
+				// Then, we have to manage the common part of both move ranges.
+				// If MoveOperations has common range it can be one of two:
+				// * on the same tree level - it means that we move the same nodes into different places
+				// * on deeper tree level - it means that we move nodes that are inside moved nodes
+				// The operations are conflicting only if they try to move exactly same nodes, so only in the first case.
+				// So, we will handle common range if it is "deeper" or if transformed operation is more important.
+				let isDeeper = utils.compareArrays( b.sourcePosition.getParentPath(), a.sourcePosition.getParentPath() ) == utils.compareArrays.PREFIX;
+
+				if ( common !== null && ( isDeeper || isStrong ) ) {
+					// Here we do not need to worry that newTargetPosition is inside moved range, because that
+					// would mean that the MoveOperation targets into itself, and that is incorrect operation.
+					// Instead, we calculate the new position of that part of original range.
+					common.start = common.start._getCombined( b.sourcePosition, moveTargetPosition );
+					common.end = common.end._getCombined( b.sourcePosition, moveTargetPosition );
+
+					// We have to take care of proper range order.
+					// Note that both push, splice and unshift do the same if there are no ranges in the array.
+					if ( rangeB.end.isAfter( rangeA.end ) ) {
+						ranges.push( common );
+					} else if ( rangeB.start.isBefore( rangeA.start ) ) {
+						ranges.unshift( common );
+					} else {
+						ranges.splice( 1, 0, common );
+					}
+				}
+
+				// At this point we transformed this operation's source ranges it means that nothing should be changed.
+				// But since we need to return an instance of Operation we return an array with NoOperation.
+				if ( ranges.length === 0 ) {
+					return [ new NoOperation( a.baseVersion ) ];
+				}
+
+				// Target position also could be affected by the other MoveOperation. We will transform it.
+				let newTargetPosition = a.targetPosition.getTransformedByMove( b.sourcePosition, moveTargetPosition, b.howMany, !isStrong );
+
+				// Map transformed range(s) to operations and return them.
+				return ranges.reverse().map( ( range ) => {
+					return new MoveOperation(
+						range.start,
+						range.end.offset - range.start.offset,
+						newTargetPosition,
+						a.baseVersion
+					);
+				} );
+			}
+		}
+	};
+
+	return ( a, b, isStrong ) => {
+		let group;
+		let algorithm;
+
+		if ( a instanceof InsertOperation ) {
+			group = ot.InsertOperation;
+		} else if ( a instanceof AttributeOperation ) {
+			group = ot.AttributeOperation;
+		} else if ( a instanceof MoveOperation ) {
+			group = ot.MoveOperation;
+		} else {
+			algorithm = doNotUpdate;
+		}
+
+		if ( group ) {
+			if ( b instanceof InsertOperation ) {
+				algorithm = group.InsertOperation;
+			} else if ( b instanceof AttributeOperation ) {
+				algorithm = group.AttributeOperation;
+			} else if ( b instanceof MoveOperation ) {
+				algorithm = group.MoveOperation;
+			} else {
+				algorithm = doNotUpdate;
+			}
+		}
+
+		let transformed = algorithm( a, b, isStrong );
+
+		return updateBaseVersions( a.baseVersion, transformed );
+	};
+
+	// When we don't want to update an operation, we create and return a clone of it.
+	// Returns the operation in "unified format" - wrapped in an Array.
+	function doNotUpdate( operation ) {
+		return [ operation.clone() ];
+	}
+
+	// Takes an Array of operations and sets consecutive base versions for them, starting from given base version.
+	// Returns the passed array.
+	function updateBaseVersions( baseVersion, operations ) {
+		for ( let i = 0; i < operations.length; i++ ) {
+			operations[ i ].baseVersion = baseVersion + i + 1;
+		}
+
+		return operations;
+	}
+
+	// Checks whether MoveOperation targetPosition is inside a node from the moved range of the other MoveOperation.
+	function moveTargetIntoMovedRange( a, b ) {
+		return a.targetPosition.getTransformedByDeletion( b.sourcePosition, b.howMany ) === null;
+	}
+
+	// Takes two AttributeOperations and checks whether their attributes are in conflict.
+	// This happens when both operations changes an attribute with the same key and they either set different
+	// values for this attribute or one of them removes it while the other one sets it.
+	// Returns true if attributes are in conflict.
+	function haveConflictingAttributes( a, b ) {
+		// Keeping in mind that newAttr or oldAttr might be null.
+		// We will retrieve the key from whichever parameter is set.
+		const keyA = ( a.newAttr || a.oldAttr ).key;
+		const keyB = ( b.newAttr || b.oldAttr ).key;
+
+		if ( keyA != keyB ) {
+			// Different keys - not conflicting.
+			return false;
+		}
+
+		if ( a.newAttr === null && b.newAttr === null ) {
+			// Both remove the attribute - not conflicting.
+			return false;
+		}
+
+		// Check if they set different value or one of them removes the attribute.
+		return ( a.newAttr === null && b.newAttr !== null ) ||
+			( a.newAttr !== null && b.newAttr === null ) ||
+			( !a.newAttr.isEqual( b.newAttr ) );
+	}
+
+	// Gets an array of Ranges and produces one Range out of it. The root of a new range will be same as
+	// the root of the first range in the array. If any of given ranges has different root than the first range,
+	// it will be discarded.
+	function joinRanges( ranges ) {
+		if ( ranges.length === 0 ) {
+			return null;
+		} else if ( ranges.length == 1 ) {
+			return ranges[ 0 ];
+		} else {
+			ranges[ 0 ].end = ranges[ ranges.length - 1 ].end;
+
+			return ranges[ 0 ];
+		}
+	}
+} );

+ 490 - 0
packages/ckeditor5-engine/src/treemodel/position.js

@@ -0,0 +1,490 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+'use strict';
+
+CKEDITOR.define( [ 'treemodel/rootelement', 'utils', 'ckeditorerror' ], ( RootElement, utils, CKEditorError ) => {
+	const SAME = 0;
+	const AFTER = 1;
+	const BEFORE = 2;
+	const DIFFERENT = 3;
+
+	/**
+	 * Position in the tree. Position is always located before or after a node.
+	 * See {@link #path} property for more information.
+	 *
+	 * @class treeModel.Position
+	 */
+	class Position {
+		/**
+		 * Creates a position.
+		 *
+		 * @param {treeModel.RootElement} root Root element for the path. Note that this element can not have a parent.
+		 * @param {Array.<Number>} path Position path. Must contain at least one item. See {@link #path} property for more information.
+		 * @constructor
+		 */
+		constructor( root, path ) {
+			if ( !( root instanceof RootElement ) ) {
+				/**
+				 * Position root has to be an instance of RootElement.
+				 *
+				 * @error position-root-not-rootelement
+				 * @param root
+				 */
+				throw new CKEditorError( 'position-root-not-rootelement: Position root has to be an instance of RootElement.', { root: root } );
+			}
+
+			/**
+			 * Root element for the path. Note that this element can not have a parent.
+			 *
+			 * @type {treeModel.RootElement}
+			 */
+			this.root = root;
+
+			if ( !( path instanceof Array ) || path.length === 0 ) {
+				/**
+				 * Position path must be an Array with at least one item.
+				 *
+				 * @error position-path-incorrect
+				 * @param path
+				 */
+				throw new CKEditorError( 'position-path-incorrect: Position path must be an Array with at least one item.', { path: path } );
+			}
+
+			/**
+			 * Position of the node it the tree. For example:
+			 *
+			 * root
+			 *  |- p         Before: [ 0 ]       After: [ 1 ]
+			 *  |- ul        Before: [ 1 ]       After: [ 2 ]
+			 *     |- li     Before: [ 1, 0 ]    After: [ 1, 1 ]
+			 *     |  |- f   Before: [ 1, 0, 0 ] After: [ 1, 0, 1 ]
+			 *     |  |- o   Before: [ 1, 0, 1 ] After: [ 1, 0, 2 ]
+			 *     |  |- o   Before: [ 1, 0, 2 ] After: [ 1, 0, 3 ]
+			 *     |- li     Before: [ 1, 1 ]    After: [ 1, 2 ]
+			 *        |- b   Before: [ 1, 1, 0 ] After: [ 1, 1, 1 ]
+			 *        |- a   Before: [ 1, 1, 1 ] After: [ 1, 1, 2 ]
+			 *        |- r   Before: [ 1, 1, 2 ] After: [ 1, 1, 3 ]
+			 *
+			 * @type {Number[]}
+			 */
+			this.path = path;
+		}
+
+		/**
+		 * Node directly after the position.
+		 *
+		 * @readonly
+		 * @property {treeModel.Node}
+		 */
+		get nodeAfter() {
+			return this.parent.getChild( this.offset ) || null;
+		}
+
+		/**
+		 * Node directly before the position.
+		 *
+		 * @readonly
+		 * @type {treeModel.Node}
+		 */
+		get nodeBefore() {
+			return this.parent.getChild( this.offset - 1 ) || null;
+		}
+
+		/**
+		 * Offset at which the position is located in the {@link #parent}.
+		 *
+		 * @readonly
+		 * @property {Number} offset
+		 */
+		get offset() {
+			return utils.last( this.path );
+		}
+
+		/**
+		 * Sets offset in the parent, which is the last element of the path.
+		 */
+		set offset( newOffset ) {
+			this.path[ this.path.length - 1 ] = newOffset;
+		}
+
+		/**
+		 * Parent element of the position. The position is located at {@link #offset} in this element.
+		 *
+		 * @readonly
+		 * @property {treeModel.Element} parent
+		 */
+		get parent() {
+			let parent = this.root;
+
+			let i, len;
+
+			for ( i = 0, len = this.path.length - 1; i < len; i++ ) {
+				parent = parent.getChild( this.path[ i ] );
+			}
+
+			return parent;
+		}
+
+		/**
+		 * Creates and returns a new instance of {@link treeModel.Position}
+		 * which is equal to this {@link treeModel.Position position}.
+		 *
+		 * @returns {treeModel.Position} Cloned {@link treeModel.Position position}.
+		 */
+		clone() {
+			return new Position( this.root, this.path.slice() );
+		}
+
+		/**
+		 * Checks whether this position is before or after given position.
+		 *
+		 * @param {treeModel.Position} otherPosition Position to compare with.
+		 * @returns {Number} A flag indicating whether this position is {@link #BEFORE} or
+		 * {@link #AFTER} or {@link #SAME} as given position. If positions are in different roots,
+		 * {@link #DIFFERENT} flag is returned.
+		 */
+		compareWith( otherPosition ) {
+			if ( this.root != otherPosition.root ) {
+				return DIFFERENT;
+			}
+
+			const result = utils.compareArrays( this.path, otherPosition.path );
+
+			switch ( result ) {
+				case utils.compareArrays.SAME:
+					return SAME;
+
+				case utils.compareArrays.PREFIX:
+					return BEFORE;
+
+				case utils.compareArrays.EXTENSION:
+					return AFTER;
+
+				default:
+					if ( this.path[ result ] < otherPosition.path[ result ] ) {
+						return BEFORE;
+					} else {
+						return AFTER;
+					}
+			}
+		}
+
+		/**
+		 * Returns the path to the parent, which is the {@link treeModel.Position#path} without the last element.
+		 *
+		 * This method returns the parent path even if the parent does not exists.
+		 *
+		 * @returns {Number[]} Path to the parent.
+		 */
+		getParentPath() {
+			return this.path.slice( 0, -1 );
+		}
+
+		/**
+		 * Returns this position after being updated by removing `howMany` nodes starting from `deletePosition`.
+		 * It may happen that this position is in a removed node. If that is the case, `null` is returned instead.
+		 *
+		 * @param {treeModel.Position} deletePosition Position before the first removed node.
+		 * @param {Number} howMany How many nodes are removed.
+		 * @returns {treeModel.Position|null} Transformed position or `null`.
+		 */
+		getTransformedByDeletion( deletePosition, howMany ) {
+			let transformed = this.clone();
+
+			// This position can't be affected if deletion was in a different root.
+			if ( this.root != deletePosition.root ) {
+				return transformed;
+			}
+
+			if ( utils.compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == utils.compareArrays.SAME ) {
+				// If nodes are removed from the node that is pointed by this position...
+				if ( deletePosition.offset < this.offset ) {
+					// And are removed from before an offset of that position...
+					// Decrement the offset accordingly.
+					if ( deletePosition.offset + howMany > this.offset ) {
+						transformed.offset = deletePosition.offset;
+					} else {
+						transformed.offset -= howMany;
+					}
+				}
+			} else if ( utils.compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == utils.compareArrays.PREFIX ) {
+				// If nodes are removed from a node that is on a path to this position...
+				const i = deletePosition.path.length - 1;
+
+				if ( deletePosition.offset < this.path[ i ] ) {
+					// And are removed from before next node of that path...
+					if ( deletePosition.offset + howMany > this.path[ i ] ) {
+						// If the next node of that path is removed return null
+						// because the node containing this position got removed.
+						return null;
+					} else {
+						// Otherwise, decrement index on that path.
+						transformed.path[ i ] -= howMany;
+					}
+				}
+			}
+
+			return transformed;
+		}
+
+		/**
+		 * Returns this position after being updated by inserting `howMany` nodes at `insertPosition`.
+		 *
+		 * @param {treeModel.Position} insertPosition Position where nodes are inserted.
+		 * @param {Number} howMany How many nodes are inserted.
+		 * @param {Boolean} insertBefore Flag indicating whether nodes are inserted before or after `insertPosition`.
+		 * This is important only when `insertPosition` and this position are same. If that is the case and the flag is
+		 * set to `true`, this position will get transformed. If the flag is set to `false`, it won't.
+		 * @returns {treeModel.Position} Transformed position.
+		 */
+		getTransformedByInsertion( insertPosition, howMany, insertBefore ) {
+			let transformed = this.clone();
+
+			// This position can't be affected if insertion was in a different root.
+			if ( this.root != insertPosition.root ) {
+				return transformed;
+			}
+
+			if ( utils.compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == utils.compareArrays.SAME ) {
+				// If nodes are inserted in the node that is pointed by this position...
+				if ( insertPosition.offset < this.offset || ( insertPosition.offset == this.offset && insertBefore ) ) {
+					// And are inserted before an offset of that position...
+					// "Push" this positions offset.
+					transformed.offset += howMany;
+				}
+			} else if ( utils.compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == utils.compareArrays.PREFIX ) {
+				// If nodes are inserted in a node that is on a path to this position...
+				const i = insertPosition.path.length - 1;
+
+				if ( insertPosition.offset <= this.path[ i ] ) {
+					// And are inserted before next node of that path...
+					// "Push" the index on that path.
+					transformed.path[ i ] += howMany;
+				}
+			}
+
+			return transformed;
+		}
+
+		/**
+		 * Returns this position after being updated by moving `howMany` attributes from `sourcePosition` to `targetPosition`.
+		 *
+		 * @param {treeModel.Position} sourcePosition Position before the first element to move.
+		 * @param {treeModel.Position} targetPosition Position where moved elements will be inserted.
+		 * @param {Number} howMany How many consecutive nodes to move, starting from `sourcePosition`.
+		 * @param {Boolean} insertBefore Flag indicating whether moved nodes are pasted before or after `insertPosition`.
+		 * This is important only when `targetPosition` and this position are same. If that is the case and the flag is
+		 * set to `true`, this position will get transformed by range insertion. If the flag is set to `false`, it won't.
+		 * @returns {treeModel.Position} Transformed position.
+		 */
+		getTransformedByMove( sourcePosition, targetPosition, howMany, insertBefore ) {
+			// Moving a range removes nodes from their original position. We acknowledge this by proper transformation.
+			let transformed = this.getTransformedByDeletion( sourcePosition, howMany );
+
+			if ( transformed !== null ) {
+				// This position is not inside a removed node.
+				// Next step is to reflect pasting nodes, which might further affect the position.
+				transformed = transformed.getTransformedByInsertion( targetPosition, howMany, insertBefore );
+			} else {
+				// This position is inside a removed node. In this case, we are unable to simply transform it by range insertion.
+				// Instead, we calculate a combination of this position, move source position and target position.
+				transformed = this._getCombined( sourcePosition, targetPosition );
+			}
+
+			return transformed;
+		}
+
+		/**
+		 * Checks whether this position is after given position.
+		 *
+		 * **Note:** see {treeModel.Position#isBefore}.
+		 *
+		 * @param {treeModel.Position} otherPosition Position to compare with.
+		 * @returns {Boolean} True if this position is after given position.
+		 */
+		isAfter( otherPosition ) {
+			return this.compareWith( otherPosition ) == AFTER;
+		}
+
+		/**
+		 * Checks whether this position is before given position.
+		 *
+		 * **Note:** watch out when using negation of the value returned by this method, because the negation will also
+		 * be `true` if positions are in different roots and you might not expect this. You should probably use
+		 * `a.isAfter( b ) || a.isEqual( b )` or `!a.isBefore( p ) && a.root == b.root` in most scenarios. If your
+		 * condition uses multiple `isAfter` and `isBefore` checks, build them so they do not use negated values, i.e.:
+		 *
+		 *  if ( a.isBefore( b ) && c.isAfter( d ) ) {
+		 *    // do A.
+		 *  } else {
+		 *    // do B.
+		 *  }
+		 *
+		 * or, if you have only one if-branch:
+		 *
+		 *  if ( !( a.isBefore( b ) && c.isAfter( d ) ) {
+		 *    // do B.
+		 *  }
+		 *
+		 * rather than:
+		 *
+		 *  if ( !a.isBefore( b ) || && !c.isAfter( d ) ) {
+		 *    // do B.
+		 *  } else {
+		 *    // do A.
+		 *  }
+		 *
+		 * @param {treeModel.Position} otherPosition Position to compare with.
+		 * @returns {Boolean} True if this position is before given position.
+		 */
+		isBefore( otherPosition ) {
+			return this.compareWith( otherPosition ) == BEFORE;
+		}
+
+		/**
+		 * Checks whether this position equals given position.
+		 *
+		 * @param {treeModel.Position} otherPosition Position to compare with.
+		 * @returns {Boolean} True if positions are same.
+		 */
+		isEqual( otherPosition ) {
+			return this.compareWith( otherPosition ) == SAME;
+		}
+
+		/**
+		 * Creates a new position after given node.
+		 *
+		 * @param {treeModel.Node} node Node the position should be directly after.
+		 * @returns {treeModel.Position}
+		 */
+		static createAfter( node ) {
+			if ( !node.parent ) {
+				/**
+				 * You can not make position after root.
+				 *
+				 * @error position-after-root
+				 * @param {treeModel.Node} root
+				 */
+				throw new CKEditorError( 'position-after-root: You can not make position after root.', { root: node } );
+			}
+
+			return Position.createFromParentAndOffset( node.parent, node.getIndex() + 1 );
+		}
+
+		/**
+		 * Creates a new position before the given node.
+		 *
+		 * @param {treeModel.node} node Node the position should be directly before.
+		 * @returns {treeModel.Position}
+		 */
+		static createBefore( node ) {
+			if ( !node.parent ) {
+				/**
+				 * You can not make position before root.
+				 *
+				 * @error position-before-root
+				 * @param {treeModel.Node} root
+				 */
+				throw new CKEditorError( 'position-before-root: You can not make position before root.', { root: node } );
+			}
+
+			return Position.createFromParentAndOffset( node.parent, node.getIndex() );
+		}
+
+		/**
+		 * Creates a new position from the parent element and the offset in that element.
+		 *
+		 * @param {treeModel.Element} parent Position parent element.
+		 * @param {Number} offset Position offset.
+		 * @returns {treeModel.Position}
+		 */
+		static createFromParentAndOffset( parent, offset ) {
+			const path = parent.getPath();
+
+			path.push( offset );
+
+			return new Position( parent.root, path );
+		}
+
+		/**
+		 * Returns a new position that is a combination of this position and given positions. The combined
+		 * position is this position transformed by moving a range starting at `from` to `to` position.
+		 * It is expected that this position is inside the moved range.
+		 *
+		 * In other words, this method in a smart way "cuts out" `source` path from this position and
+		 * injects `target` path in it's place, while doing necessary fixes in order to get a correct path.
+		 *
+		 * Example:
+		 *
+		 * 	let original = new Position( root, [ 2, 3, 1 ] );
+		 * 	let source = new Position( root, [ 2, 2 ] );
+		 * 	let target = new Position( otherRoot, [ 1, 1, 3 ] );
+		 * 	let combined = original.getCombined( source, target );
+		 * 	// combined.path is [ 1, 1, 4, 1 ], combined.root is otherRoot
+		 *
+		 * Explanation:
+		 *
+		 * We have a position `[ 2, 3, 1 ]` and move some nodes from `[ 2, 2 ]` to `[ 1, 1, 3 ]`. The original position
+		 * was inside moved nodes and now should point to the new place. The moved nodes will be after
+		 * positions `[ 1, 1, 3 ]`, `[ 1, 1, 4 ]`, `[ 1, 1, 5 ]`. Since our position was in the second moved node,
+		 * the transformed position will be in a sub-tree of a node at `[ 1, 1, 4 ]`. Looking at original path, we
+		 * took care of `[ 2, 3 ]` part of it. Now we have to add the rest of the original path to the transformed path.
+		 * Finally, the transformed position will point to `[ 1, 1, 4, 1 ]`.
+		 *
+		 * @protected
+		 * @param {treeModel.Position} source Beginning of the moved range.
+		 * @param {treeModel.Position} target Position where the range is moved.
+		 * @returns {treeModel.Position} Combined position.
+		 */
+		_getCombined( source, target ) {
+			const i = source.path.length - 1;
+
+			// The first part of a path to combined position is a path to the place where nodes were moved.
+			let combined = target.clone();
+
+			// Then we have to update the rest of the path.
+
+			// Fix the offset because this position might be after `from` position and we have to reflect that.
+			combined.offset = combined.offset + this.path[ i ] - source.offset;
+
+			// Then, add the rest of the path.
+			// If this position is at the same level as `from` position nothing will get added.
+			combined.path = combined.path.concat( this.path.slice( i + 1 ) );
+
+			return combined;
+		}
+	}
+
+	/**
+	 * Flag for "is after" relation between Positions.
+	 *
+	 * @type {Number}
+	 */
+	Position.AFTER = AFTER;
+
+	/**
+	 * Flag for "is before" relation between Positions.
+	 *
+	 * @type {Number}
+	 */
+	Position.BEFORE = BEFORE;
+
+	/**
+	 * Flag for "are in different roots" relation between Positions.
+	 *
+	 * @type {Number}
+	 */
+	Position.DIFFERENT = DIFFERENT;
+
+	/**
+	 * Flag for "are same" relation between Positions.
+	 *
+	 * @type {Number}
+	 */
+	Position.SAME = SAME;
+
+	return Position;
+} );

+ 17 - 17
packages/ckeditor5-engine/src/document/positioniterator.js → packages/ckeditor5-engine/src/treemodel/positioniterator.js

@@ -6,9 +6,9 @@
 'use strict';
 
 CKEDITOR.define( [
-	'document/character',
-	'document/element',
-	'document/position'
+	'treemodel/character',
+	'treemodel/element',
+	'treemodel/position'
 ], ( Character, Element, Position ) => {
 	const ELEMENT_ENTER = 0;
 	const ELEMENT_LEAVE = 1;
@@ -17,14 +17,14 @@ CKEDITOR.define( [
 	/**
 	 * Position iterator class. It allows to iterate forward and backward over the tree document.
 	 *
-	 * @class document.PositionIterator
+	 * @class treeModel.PositionIterator
 	 */
 	class PositionIterator {
 		/**
 		 * Creates a range iterator.
 		 *
-		 * @param {document.Range} [boundaries] Range to define boundaries of the iterator.
-		 * @param {document.Position} [iteratorPosition] Starting position.
+		 * @param {treeModel.Range} [boundaries] Range to define boundaries of the iterator.
+		 * @param {treeModel.Position} [iteratorPosition] Starting position.
 		 * @constructor
 		 */
 		constructor( boundaries, iteratorPosition ) {
@@ -38,7 +38,7 @@ CKEDITOR.define( [
 			/**
 			 * Iterator position.
 			 *
-			 * @property {document.Position} position
+			 * @property {treeModel.Position} position
 			 */
 
 			/**
@@ -49,7 +49,7 @@ CKEDITOR.define( [
 			 *
 			 * If boundaries are not defined they are set before first and after last child of the root node.
 			 *
-			 * @property {document.Range} boundaries
+			 * @property {treeModel.Range} boundaries
 			 */
 		}
 
@@ -61,14 +61,14 @@ CKEDITOR.define( [
 		 * @returns {Object} return.value
 		 * @returns {Number} return.value.type Encountered value type, possible options: {@link PositionIterator#ELEMENT_ENTER},
 		 * {@link PositionIterator#ELEMENT_LEAVE} or {@link PositionIterator#CHARACTER}.
-		 * @returns {document.Node} return.value.node Encountered node.
+		 * @returns {treeModel.Node} return.value.node Encountered node.
 		 */
 		next() {
 			const position = this.position;
 			const parent = position.parent;
 
 			// Ugh... added here because of circular deps in AMD ;<.
-			Element = CKEDITOR.require( 'document/element' );
+			Element = CKEDITOR.require( 'treemodel/element' );
 
 			// We are at the end of the root.
 			if ( parent.parent === null && position.offset === parent.getChildCount() ) {
@@ -104,7 +104,7 @@ CKEDITOR.define( [
 		 * @returns {Object} return.value
 		 * @returns {Number} return.value.type Encountered value type, possible options: {@link PositionIterator#ELEMENT_ENTER},
 		 * {@link PositionIterator#ELEMENT_LEAVE} or {@link PositionIterator#CHARACTER}.
-		 * @returns {document.Node} return.value.node Scanned node.
+		 * @returns {treeModel.Node} return.value.node Scanned node.
 		 */
 		previous() {
 			const position = this.position;
@@ -148,31 +148,31 @@ CKEDITOR.define( [
 	}
 
 	/**
-	 * Flag for entering element.
+	 * Flag for character.
 	 *
 	 * @static
 	 * @readonly
 	 * @property {Number}
 	 */
-	PositionIterator.ELEMENT_ENTER = ELEMENT_ENTER;
+	PositionIterator.CHARACTER = CHARACTER;
 
 	/**
-	 * Flag for leaving element.
+	 * Flag for entering element.
 	 *
 	 * @static
 	 * @readonly
 	 * @property {Number}
 	 */
-	PositionIterator.ELEMENT_LEAVE = ELEMENT_LEAVE;
+	PositionIterator.ELEMENT_ENTER = ELEMENT_ENTER;
 
 	/**
-	 * Flag for character.
+	 * Flag for leaving element.
 	 *
 	 * @static
 	 * @readonly
 	 * @property {Number}
 	 */
-	PositionIterator.CHARACTER = CHARACTER;
+	PositionIterator.ELEMENT_LEAVE = ELEMENT_LEAVE;
 
 	return PositionIterator;
 } );

+ 306 - 0
packages/ckeditor5-engine/src/treemodel/range.js

@@ -0,0 +1,306 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+'use strict';
+
+CKEDITOR.define( [ 'treemodel/position', 'treemodel/positioniterator', 'utils' ], ( Position, PositionIterator, utils ) => {
+	/**
+	 * Range class. Range is iterable.
+	 *
+	 * @class treeModel.Range
+	 */
+	class Range {
+		/**
+		 * Creates a range.
+		 *
+		 * @param {treeModel.Position} start Start position.
+		 * @param {treeModel.Position} end End position.
+		 * @constructor
+		 */
+		constructor( start, end ) {
+			/**
+			 * Start position.
+			 *
+			 * @property {treeModel.Position}
+			 */
+			this.start = start;
+
+			/**
+			 * End position.
+			 *
+			 * @property {treeModel.Position}
+			 */
+			this.end = end;
+		}
+
+		/**
+		 * Range iterator.
+		 *
+		 * @see treeModel.PositionIterator
+		 */
+		[ Symbol.iterator ]() {
+			return new PositionIterator( this );
+		}
+
+		/**
+		 * Creates and returns a new instance of {@link treeModel.Range}
+		 * which is equal to this {@link treeModel.Range range}.
+		 *
+		 * @returns {treeModel.Position} Cloned {@link treeModel.Range range}.
+		 */
+		clone() {
+			return new Range( this.start.clone(), this.end.clone() );
+		}
+
+		/**
+		 * Checks whether this contains given {@link treeModel.Position position}.
+		 *
+		 * @param {treeModel.Position} position Position to check.
+		 * @returns {Boolean} True if given {@link treeModel.Position position} is contained.
+		 */
+		containsPosition( position ) {
+			return position.isAfter( this.start ) && position.isBefore( this.end );
+		}
+
+		/**
+		 * Checks whether this range contains given {@link treeModel.Range range}.
+		 *
+		 * @param {treeModel.Range} otherRange Range to check.
+		 * @returns {Boolean} True if given {@link treeModel.Range range} boundaries are contained by this range.
+		 */
+		containsRange( otherRange ) {
+			return this.containsPosition( otherRange.start ) && this.containsPosition( otherRange.end );
+		}
+
+		/**
+		 * Gets a part of this {@link treeModel.Range range} which is not a part of given {@link treeModel.Range range}. Returned
+		 * array contains zero, one or two {@link treeModel.Range ranges}.
+		 *
+		 * Examples:
+		 *
+		 *		let range = new Range( new Position( root, [ 2, 7 ] ), new Position( root, [ 4, 0, 1 ] ) );
+		 *		let otherRange = new Range( new Position( root, [ 1 ] ), new Position( root, [ 5 ] ) );
+		 *		let transformed = range.getDifference( otherRange );
+		 *		// transformed array has no ranges because `otherRange` contains `range`
+		 *
+		 *		otherRange = new Range( new Position( root, [ 1 ] ), new Position( root, [ 3 ] ) );
+		 *		transformed = range.getDifference( otherRange );
+		 *		// transformed array has one range: from [ 3 ] to [ 4, 0, 1 ]
+		 *
+		 *		otherRange = new Range( new Position( root, [ 3 ] ), new Position( root, [ 4 ] ) );
+		 *		transformed = range.getDifference( otherRange );
+		 *		// transformed array has two ranges: from [ 2, 7 ] to [ 3 ] and from [ 4 ] to [ 4, 0, 1 ]
+		 *
+		 * @param {treeModel.Range} otherRange Range to differentiate against.
+		 * @returns {Array.<treeModel.Range>} The difference between ranges.
+		 */
+		getDifference( otherRange ) {
+			const ranges = [];
+
+			if ( this.start.isBefore( otherRange.end ) && this.end.isAfter( otherRange.start ) ) {
+				// Ranges intersect.
+
+				if ( this.containsPosition( otherRange.start ) ) {
+					// Given range start is inside this range. This means that we have to
+					// add shrunken range - from the start to the middle of this range.
+					ranges.push(
+						new Range(
+							this.start.clone(),
+							otherRange.start.clone()
+						)
+					);
+				}
+
+				if ( this.containsPosition( otherRange.end ) ) {
+					// Given range end is inside this range. This means that we have to
+					// add shrunken range - from the middle of this range to the end.
+					ranges.push(
+						new Range(
+							otherRange.end.clone(),
+							this.end.clone()
+						)
+					);
+				}
+			} else {
+				// Ranges do not intersect, return the original range.
+				ranges.push( this.clone() );
+			}
+
+			return ranges;
+		}
+
+		/**
+		 * Returns an intersection of this {@link treeModel.Range range} and given {@link treeModel.Range range}. Intersection
+		 * is a common part of both of those ranges. If ranges has no common part, returns `null`.
+		 *
+		 * Examples:
+		 *
+		 *		let range = new Range( new Position( root, [ 2, 7 ] ), new Position( root, [ 4, 0, 1 ] ) );
+		 *		let otherRange = new Range( new Position( root, [ 1 ] ), new Position( root, [ 2 ] ) );
+		 *		let transformed = range.getIntersection( otherRange ); // null - ranges have no common part
+		 *
+		 *		otherRange = new Range( new Position( root, [ 3 ] ), new Position( root, [ 5 ] ) );
+		 *		transformed = range.getIntersection( otherRange ); // range from [ 3 ] to [ 4, 0, 1 ]
+		 *
+		 * @param {treeModel.Range} otherRange Range to check for intersection.
+		 * @returns {treeModel.Range|null} A common part of given ranges or null if ranges have no common part.
+		 */
+		getIntersection( otherRange ) {
+			if ( this.start.isBefore( otherRange.end ) && this.end.isAfter( otherRange.start ) ) {
+				// Ranges intersect, so a common range will be returned.
+				// At most, it will be same as this range.
+				let commonRangeStart = this.start;
+				let commonRangeEnd = this.end;
+
+				if ( this.containsPosition( otherRange.start ) ) {
+					// Given range start is inside this range. This means thaNt we have to
+					// shrink common range to the given range start.
+					commonRangeStart = otherRange.start;
+				}
+
+				if ( this.containsPosition( otherRange.end ) ) {
+					// Given range end is inside this range. This means that we have to
+					// shrink common range to the given range end.
+					commonRangeEnd = otherRange.end;
+				}
+
+				return new Range( commonRangeStart.clone(), commonRangeEnd.clone() );
+			}
+
+			// Ranges do not intersect, so they do not have common part.
+			return null;
+		}
+
+		/**
+		 * Returns an iterator that iterates over all {@link treeModel.Node nodes} that are in this range and returns them.
+		 * A node is in the range when it is after a {@link treeModel.Position position} contained in this range.
+		 * In other words, this iterates over all {@link treeModel.Character}s that are inside the range and
+		 * all the {@link treeModel.Element}s we enter into when iterating over this range.
+		 *
+		 * Note, that this method will not return a parent node of start position. This is in contrary to {@link treeModel.PositionIterator}
+		 * which will return that node with {@link treeModel.PositionIterator#ELEMENT_LEAVE} type. This method, also, returns each
+		 * {@link treeModel.Element} once, while iterator return it twice: for {@link treeModel.PositionIterator#ELEMENT_ENTER} and
+		 * {@link treeModel.PositionIterator#ELEMENT_LEAVE}.
+		 *
+		 * @see {treeModel.PositionIterator}
+		 * @returns {treeModel.Node}
+		 */
+		*getNodes() {
+			for ( let value of this ) {
+				if ( value.type != PositionIterator.ELEMENT_LEAVE ) {
+					yield value.node;
+				}
+			}
+		}
+
+		/**
+		 * Returns an array containing one or two {treeModel.Range ranges} that are a result of transforming this
+		 * {@link treeModel.Range range} by inserting `howMany` nodes at `insertPosition`. Two {@link treeModel.Range ranges} are
+		 * returned if the insertion was inside this {@link treeModel.Range range}.
+		 *
+		 * Examples:
+		 *
+		 *		let range = new Range( new Position( root, [ 2, 7 ] ), new Position( root, [ 4, 0, 1 ] ) );
+		 *		let transformed = range.getTransformedByInsertion( new Position( root, [ 1 ] ), 2 );
+		 *		// transformed array has one range from [ 4, 7 ] to [ 6, 0, 1 ]
+		 *
+		 *		transformed = range.getTransformedByInsertion( new Position( root, [ 3, 2 ] ), 4 );
+		 *		// transformed array has two ranges: from [ 2, 7 ] to [ 3, 2 ] and from [ 3, 6 ] to [ 4, 0, 1 ]
+		 *
+		 *		transformed = range.getTransformedByInsertion( new Position( root, [ 3, 2 ] ), 4, true );
+		 *		// transformed array has one range which is equal to `range`. This is because of spreadOnlyOnSameLevel flag.
+		 *
+		 * @param {treeModel.Position} insertPosition Position where nodes are inserted.
+		 * @param {Number} howMany How many nodes are inserted.
+		 * @param {Boolean} spreadOnlyOnSameLevel Flag indicating whether this {treeModel.Range range} should be spread
+		 * if insertion was inside a node from this {treeModel.Range range} but not in the range itself.
+		 * @returns {Array.<treeModel.Range>} Result of the transformation.
+		 */
+		getTransformedByInsertion( insertPosition, howMany, spreadOnlyOnSameLevel ) {
+			// Flag indicating whether this whole range and given insertPosition is on the same tree level.
+			const areOnSameLevel = utils.compareArrays( this.start.getParentPath(), this.end.getParentPath() ) == utils.compareArrays.SAME &&
+				utils.compareArrays( this.start.getParentPath(), insertPosition.getParentPath() ) == utils.compareArrays.SAME;
+
+			if ( this.containsPosition( insertPosition ) && ( !spreadOnlyOnSameLevel || areOnSameLevel ) ) {
+				// Range has to be spread. The first part is from original start to the spread point.
+				// The other part is from spread point to the original end, but transformed by
+				// insertion to reflect insertion changes.
+
+				return [
+					new Range(
+						this.start.clone(),
+						insertPosition.clone()
+					),
+					new Range(
+						insertPosition.getTransformedByInsertion( insertPosition, howMany, true ),
+						this.end.getTransformedByInsertion( insertPosition, howMany, true )
+					)
+				];
+			} else {
+				// If insertion is not inside the range, simply transform range boundaries (positions) by the insertion.
+				// Both, one or none of them might be affected by the insertion.
+
+				const range = this.clone();
+
+				range.start = range.start.getTransformedByInsertion( insertPosition, howMany, true );
+				range.end = range.end.getTransformedByInsertion( insertPosition, howMany, false );
+
+				return [ range ];
+			}
+		}
+
+		/**
+		 * Two ranges equal if their start and end positions equal.
+		 *
+		 * @param {treeModel.Range} otherRange Range to compare with.
+		 * @returns {Boolean} True if ranges equal.
+		 */
+		isEqual( otherRange ) {
+			return this.start.isEqual( otherRange.start ) && this.end.isEqual( otherRange.end );
+		}
+
+		/**
+		 * Creates a range inside an element which starts before the first child and ends after the last child.
+		 *
+		 * @param {treeModel.Element} element Element which is a parent for the range.
+		 * @returns {treeModel.Range} Created range.
+		 */
+		static createFromElement( element ) {
+			return Range.createFromParentsAndOffsets( element, 0, element, element.getChildCount() );
+		}
+
+		/**
+		 * Creates a new range spreading from specified position to the same position moved by given shift.
+		 *
+		 * @param {treeModel.Position} position Beginning of the range.
+		 * @param {Number} shift How long the range should be.
+		 * @returns {treeModel.Range}
+		 */
+		static createFromPositionAndShift( position, shift ) {
+			let endPosition = position.clone();
+			endPosition.offset += shift;
+
+			return new Range( position, endPosition );
+		}
+
+		/**
+		 * Creates a range from given parents and offsets.
+		 *
+		 * @param {treeModel.Element} startElement Start position parent element.
+		 * @param {Number} startOffset Start position offset.
+		 * @param {treeModel.Element} endElement End position parent element.
+		 * @param {Number} endOffset End position offset.
+		 * @returns {treeModel.Range} Created range.
+		 */
+		static createFromParentsAndOffsets( startElement, startOffset, endElement, endOffset ) {
+			return new Range(
+				Position.createFromParentAndOffset( startElement, startOffset ),
+				Position.createFromParentAndOffset( endElement, endOffset )
+			);
+		}
+	}
+
+	return Range;
+} );

+ 5 - 5
packages/ckeditor5-engine/src/document/rootelement.js → packages/ckeditor5-engine/src/treemodel/rootelement.js

@@ -5,27 +5,27 @@
 
 'use strict';
 
-CKEDITOR.define( [ 'document/element' ], ( Element ) => {
+CKEDITOR.define( [ 'treemodel/element' ], ( Element ) => {
 	/**
 	 * Class for nodes that are roots of trees in tree data model.
 	 *
-	 * @class document.RootElement
+	 * @class treeModel.RootElement
 	 */
 	class RootElement extends Element {
 		/**
 		 * Creates tree root node.
 		 *
-		 * @param {document.Document} doc {@link document.Document} that is an owner of the root.
+		 * @param {treeModel.Document} doc {@link treeModel.Document} that is an owner of the root.
 		 * @constructor
 		 */
 		constructor( doc ) {
 			super( 'root' );
 
 			/**
-			 * {@link document.Document} that is an owner of this root.
+			 * {@link treeModel.Document} that is an owner of this root.
 			 *
 			 * @readonly
-			 * @property {document.Document}
+			 * @property {treeModel.Document}
 			 */
 			this.document = doc;
 		}

+ 82 - 0
packages/ckeditor5-engine/src/treemodel/smartrange.js

@@ -0,0 +1,82 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+'use strict';
+
+CKEDITOR.define( [ 'treemodel/range', 'emittermixin', 'utils' ], ( Range, EmitterMixin, utils ) => {
+	/**
+	 * SmartRange is a Range in the Tree Model that updates itself as the tree changes. It may be used as a bookmark.
+	 * SmartRange object may fire 'update' event whenever it gets changed by internal mechanisms.
+	 *
+	 * @class treeModel.SmartRange
+	 */
+	class SmartRange extends Range {
+		/**
+		 * Creates a smart range.
+		 *
+		 * @see {treeModel.Range}
+		 * @constructor
+		 */
+		constructor( start, end ) {
+			super( start, end );
+
+			this.listenTo( this.root.document, 'update', transform, this );
+		}
+	}
+
+	/**
+	 * Updates this position accordingly to the updates applied to the Tree Model. Bases on change events.
+	 *
+	 * @method transform
+	 * @param {String} type Type of changes applied to the Tree Model.
+	 * @param {treeModel.Range} range Range containing the result of applied change.
+	 * @param {treeModel.Position} [position] Additional position parameter provided by some change events.
+	 * @private
+	 */
+	function transform( type, range, position ) {
+		/*jshint validthis: true */
+
+		let howMany = range.end.offset - range.start.offset;
+		let newStart, newEnd;
+
+		switch ( type ) {
+			case 'insert':
+				newStart = this.start.getTransformedByInsertion( range.start, howMany, true );
+				newEnd = this.end.getTransformedByInsertion( range.start, howMany, false );
+				break;
+
+			case 'move':
+			case 'remove':
+			case 'reinsert':
+				let differenceSet = this.getDifference( Range.createFromPositionAndShift( position, howMany ) );
+
+				if ( differenceSet.length > 0 ) {
+					let diff = differenceSet[ 0 ];
+
+					if ( differenceSet.length > 1 ) {
+						diff.end = differenceSet[ 1 ].end.clone();
+					}
+
+					newStart = diff.start.getTransformedByDeletion( position, howMany ).getTransformedByInsertion( range.start, howMany );
+					newEnd = diff.end.getTransformedByDeletion( position, howMany ).getTransformedByInsertion( range.start, howMany );
+				} else {
+					newStart = this.start._getCombined( position, range.start );
+					newEnd = this.end._getCombined( position, range.start );
+				}
+
+				break;
+		}
+
+		if ( !newStart.isEqual( this.start ) || !newEnd.isEqual( this.end ) ) {
+			this.start = newStart;
+			this.end = newEnd;
+			this.fire( 'update' );
+		}
+	}
+
+	utils.extend( SmartRange.prototype, EmitterMixin );
+
+	return SmartRange;
+} );

+ 6 - 6
packages/ckeditor5-engine/src/document/text.js → packages/ckeditor5-engine/src/treemodel/text.js

@@ -7,17 +7,17 @@
 
 CKEDITOR.define( [], () => {
 	/**
-	 * Data structure for text with attributes. Note that the `Text` is not a {@link document.Node},
-	 * because it will never be part of the document tree. {@link document.Character is a node}.
+	 * Data structure for text with attributes. Note that the `Text` is not a {@link treeModel.Node},
+	 * because it will never be part of the document tree. {@link treeModel.Character is a node}.
 	 *
-	 * @class document.Text
+	 * @class treeModel.Text
 	 */
 	class Text {
 		/**
 		 * Creates a text with attributes.
 		 *
 		 * @param {String} text Described text.
-		 * @param {Iterable} attrs Iterable collection of {@link document.Attribute attributes}.
+		 * @param {Iterable} attrs Iterable collection of {@link treeModel.Attribute attributes}.
 		 * @constructor
 		 */
 		constructor( text, attrs ) {
@@ -30,7 +30,7 @@ CKEDITOR.define( [], () => {
 			this.text = text;
 
 			/**
-			 * Iterable collection of {@link document.Attribute attributes}.
+			 * Iterable collection of {@link treeModel.Attribute attributes}.
 			 *
 			 * @property {Iterable}
 			 */
@@ -39,4 +39,4 @@ CKEDITOR.define( [], () => {
 	}
 
 	return Text;
-} );
+} );

+ 13 - 17
packages/ckeditor5-engine/src/utils.js

@@ -55,18 +55,21 @@ CKEDITOR.define( [ 'utils-lodash', 'lib/lodash/lodash-ckeditor' ], ( lodashInclu
 
 		/**
 		 * Compares how given arrays relate to each other. One array can be: same as another array, prefix of another array
-		 * or completely different.
+		 * or completely different. If arrays are different, first index at which they differ is returned. Otherwise,
+		 * a flag specifying the relation is returned. Flags are negative numbers, so whenever a number >= 0 is returned
+		 * it means that arrays differ.
 		 *
 		 *   compareArrays( [ 0, 2 ], [ 0, 2 ] ); // SAME
 		 *   compareArrays( [ 0, 2 ], [ 0, 2, 1 ] ); // PREFIX
 		 *   compareArrays( [ 0, 2 ], [ 0 ] ); // EXTENSION
-		 *   compareArrays( [ 0, 2 ], [ 1, 2 ] ); // DIFFERENT
+		 *   compareArrays( [ 0, 2 ], [ 1, 2 ] ); // 0
+		 *   compareArrays( [ 0, 2 ], [ 0, 1 ] ); // 1
 		 *
 		 * @param {Array} a Array that is compared.
 		 * @param {Array} b Array to compare with.
-		 * @returns {Number} How array `a` is related to array `b`. Represented by one of flags:
-		 * `a` is {@link utils.compareArrays#SAME same}, `a` is a {@link utils.compareArrays#PREFIX prefix),
-		 * `a` is a {@link utils.compareArrays#EXTENSION extension}, or `a` is {@link utils.compareArrays#DIFFERENT different}.
+		 * @returns {Number} An index at which arrays differ, or if they do not differ, how array `a` is related to array `b`.
+		 * This is represented by one of flags: `a` is {@link utils.compareArrays#SAME same}, `a` is
+		 * a {@link utils.compareArrays#PREFIX prefix) or `a` is an {@link utils.compareArrays#EXTENSION extension}.
 		 */
 		compareArrays( a, b ) {
 			const minLen = Math.min( a.length, b.length );
@@ -74,7 +77,7 @@ CKEDITOR.define( [ 'utils-lodash', 'lib/lodash/lodash-ckeditor' ], ( lodashInclu
 			for ( let i = 0; i < minLen; i++ ) {
 				if ( a[ i ] != b[ i ] ) {
 					// The arrays are different.
-					return utils.compareArrays.DIFFERENT;
+					return i;
 				}
 			}
 
@@ -86,7 +89,7 @@ CKEDITOR.define( [ 'utils-lodash', 'lib/lodash/lodash-ckeditor' ], ( lodashInclu
 				// Compared array is shorter so it is a prefix of the other array.
 				return utils.compareArrays.PREFIX;
 			} else {
-				// Compared array is longer so it is a suffix of the other array.
+				// Compared array is longer so it is an extension of the other array.
 				return utils.compareArrays.EXTENSION;
 			}
 		},
@@ -115,28 +118,21 @@ CKEDITOR.define( [ 'utils-lodash', 'lib/lodash/lodash-ckeditor' ], ( lodashInclu
 	 *
 	 * @type {Number}
 	 */
-	utils.compareArrays.SAME = 0;
+	utils.compareArrays.SAME = -1;
 
 	/**
 	 * Flag for "is a prefix of" relation between arrays.
 	 *
 	 * @type {Number}
 	 */
-	utils.compareArrays.PREFIX = 1;
+	utils.compareArrays.PREFIX = -2;
 
 	/**
 	 * Flag for "is a suffix of" relation between arrays.
 	 *
 	 * @type {number}
 	 */
-	utils.compareArrays.EXTENSION = 2;
-
-	/**
-	 * Flag for "is different than" relation between arrays.
-	 *
-	 * @type {Number}
-	 */
-	utils.compareArrays.DIFFERENT = 3;
+	utils.compareArrays.EXTENSION = -3;
 
 	// Extend "utils" with Lo-Dash methods.
 	for ( let i = 0; i < lodashIncludes.length; i++ ) {

+ 0 - 120
packages/ckeditor5-engine/tests/document/document.js

@@ -1,120 +0,0 @@
-/**
- * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md.
- */
-
-/* bender-tags: document */
-
-'use strict';
-
-const modules = bender.amd.require(
-	'document/document',
-	'document/rootelement',
-	'document/transaction',
-	'ckeditorerror'
-);
-
-describe( 'Document', () => {
-	let Document, RootElement, Transaction, CKEditorError;
-
-	before( () => {
-		Document = modules[ 'document/document' ];
-		RootElement = modules[ 'document/rootelement' ];
-		Transaction = modules[ 'document/transaction' ];
-		CKEditorError = modules.ckeditorerror;
-	} );
-
-	let document;
-
-	beforeEach( () => {
-		document = new Document();
-	} );
-
-	describe( 'constructor', () => {
-		it( 'should create Document with no data', () => {
-			expect( document ).to.have.property( 'roots' ).that.is.instanceof( Map );
-			expect( document.roots.size ).to.equal( 1 );
-			expect( document._graveyard ).to.be.instanceof( RootElement );
-			expect( document._graveyard.getChildCount() ).to.equal( 0 );
-		} );
-	} );
-
-	describe( 'createRoot', () => {
-		it( 'should create a new RootElement, add it to roots map and return it', () => {
-			let root = document.createRoot( 'root' );
-
-			expect( document.roots.size ).to.equal( 2 );
-			expect( root ).to.be.instanceof( RootElement );
-			expect( root.getChildCount() ).to.equal( 0 );
-		} );
-
-		it( 'should throw an error when trying to create a second root with the same name', () => {
-			document.createRoot( 'root' );
-
-			expect(
-				() => {
-					document.createRoot( 'root' );
-				}
-			).to.throw( CKEditorError, /document-createRoot-name-exists/ );
-		} );
-	} );
-
-	describe( 'getRoot', () => {
-		it( 'should return a RootElement previously created with given name', () => {
-			let newRoot = document.createRoot( 'root' );
-			let getRoot = document.getRoot( 'root' );
-
-			expect( getRoot ).to.equal( newRoot );
-		} );
-
-		it( 'should throw an error when trying to get non-existent root', () => {
-			expect(
-				() => {
-					document.getRoot( 'root' );
-				}
-			).to.throw( CKEditorError, /document-createRoot-root-not-exist/ );
-		} );
-	} );
-
-	describe( 'applyOperation', () => {
-		it( 'should increase document version, execute operation and fire operationApplied', () => {
-			let operationApplied = sinon.spy();
-			let operation = {
-				baseVersion: 0,
-				_execute: sinon.spy()
-			};
-
-			document.on( 'operationApplied', operationApplied );
-
-			document.applyOperation( operation );
-
-			expect( document.version ).to.equal( 1 );
-			sinon.assert.calledOnce( operationApplied );
-			sinon.assert.calledOnce( operation._execute );
-		} );
-
-		it( 'should throw an error on the operation base version and the document version is different', () => {
-			let operationApplied = sinon.spy();
-			let operation = {
-				baseVersion: 1
-			};
-
-			document.on( 'operationApplied', operationApplied );
-
-			expect(
-				() => {
-					document.applyOperation( operation );
-				}
-			).to.throw( CKEditorError, /document-applyOperation-wrong-version/ );
-		} );
-	} );
-
-	describe( 'createTransaction', () => {
-		it( 'should create a new transaction with the document property', () => {
-			const transaction = document.createTransaction();
-
-			expect( transaction ).to.be.instanceof( Transaction );
-			expect( transaction ).to.have.property( 'doc' ).that.equals( document );
-		} );
-	} );
-} );

+ 0 - 229
packages/ckeditor5-engine/tests/document/position.js

@@ -1,229 +0,0 @@
-/**
- * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md.
- */
-
-/* bender-tags: document */
-
-'use strict';
-
-const modules = bender.amd.require(
-	'document/element',
-	'document/character',
-	'document/position',
-	'document/document',
-	'ckeditorerror',
-	'document/nodelist'
-);
-
-describe( 'position', () => {
-	let Element, Character, Document, NodeList, Position, CKEditorError;
-
-	let doc, root, p, ul, li1, li2, f, o, z, b, a, r;
-
-	// root
-	//  |- p         Before: [ 0 ]       After: [ 1 ]
-	//  |- ul        Before: [ 1 ]       After: [ 2 ]
-	//     |- li     Before: [ 1, 0 ]    After: [ 1, 1 ]
-	//     |  |- f   Before: [ 1, 0, 0 ] After: [ 1, 0, 1 ]
-	//     |  |- o   Before: [ 1, 0, 1 ] After: [ 1, 0, 2 ]
-	//     |  |- z   Before: [ 1, 0, 2 ] After: [ 1, 0, 3 ]
-	//     |- li     Before: [ 1, 1 ]    After: [ 1, 2 ]
-	//        |- b   Before: [ 1, 1, 0 ] After: [ 1, 1, 1 ]
-	//        |- a   Before: [ 1, 1, 1 ] After: [ 1, 1, 2 ]
-	//        |- r   Before: [ 1, 1, 2 ] After: [ 1, 1, 3 ]
-	before( () => {
-		Element = modules[ 'document/element' ];
-		Character = modules[ 'document/character' ];
-		Document = modules[ 'document/document' ];
-		NodeList = modules[ 'document/nodelist' ];
-		Position = modules[ 'document/position' ];
-		CKEditorError = modules.ckeditorerror;
-
-		doc = new Document();
-
-		root = doc.createRoot( 'root' );
-
-		f = new Character( 'f' );
-		o = new Character( 'o' );
-		z = new Character( 'z' );
-
-		li1 = new Element( 'li', [], [ f, o, z ] );
-
-		b = new Character( 'b' );
-		a = new Character( 'a' );
-		r = new Character( 'r' );
-
-		li2 = new Element( 'li', [], [ b, a, r ] );
-
-		ul = new Element( 'ul', [], [ li1, li2 ] );
-
-		p = new Element( 'p' );
-
-		root.insertChildren( 0, [ p, ul ] );
-	} );
-
-	it( 'should create a position with path and document', () => {
-		let position = new Position( [ 0 ], root );
-
-		expect( position ).to.have.property( 'path' ).that.deep.equals( [ 0 ] );
-		expect( position ).to.have.property( 'root' ).that.equals( root );
-	} );
-
-	it( 'should make positions form node and offset', () => {
-		expect( Position.createFromParentAndOffset( root, 0 ) ).to.have.property( 'path' ).that.deep.equals( [ 0 ] );
-		expect( Position.createFromParentAndOffset( root, 1 ) ).to.have.property( 'path' ).that.deep.equals( [ 1 ] );
-		expect( Position.createFromParentAndOffset( root, 2 ) ).to.have.property( 'path' ).that.deep.equals( [ 2 ] );
-
-		expect( Position.createFromParentAndOffset( p, 0 ) ).to.have.property( 'path' ).that.deep.equals( [ 0, 0 ] );
-
-		expect( Position.createFromParentAndOffset( ul, 0 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0 ] );
-		expect( Position.createFromParentAndOffset( ul, 1 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1 ] );
-		expect( Position.createFromParentAndOffset( ul, 2 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 2 ] );
-
-		expect( Position.createFromParentAndOffset( li1, 0 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 0 ] );
-		expect( Position.createFromParentAndOffset( li1, 1 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 1 ] );
-		expect( Position.createFromParentAndOffset( li1, 2 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 2 ] );
-		expect( Position.createFromParentAndOffset( li1, 3 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 3 ] );
-	} );
-
-	it( 'should make positions before elements', () => {
-		expect( Position.createBefore( p ) ).to.have.property( 'path' ).that.deep.equals( [ 0 ] );
-
-		expect( Position.createBefore( ul ) ).to.have.property( 'path' ).that.deep.equals( [ 1 ] );
-
-		expect( Position.createBefore( li1 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0 ] );
-
-		expect( Position.createBefore( f ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 0 ] );
-		expect( Position.createBefore( o ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 1 ] );
-		expect( Position.createBefore( z ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 2 ] );
-
-		expect( Position.createBefore( li2 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1 ] );
-
-		expect( Position.createBefore( b ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1, 0 ] );
-		expect( Position.createBefore( a ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1, 1 ] );
-		expect( Position.createBefore( r ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1, 2 ] );
-	} );
-
-	it( 'should throw error if one try to make positions before root', () => {
-		expect(
-			() => {
-				Position.createBefore( root );
-			}
-		).to.throw( CKEditorError, /position-before-root/ );
-	} );
-
-	it( 'should make positions after elements', () => {
-		expect( Position.createAfter( p ) ).to.have.property( 'path' ).that.deep.equals( [ 1 ] );
-
-		expect( Position.createAfter( ul ) ).to.have.property( 'path' ).that.deep.equals( [ 2 ] );
-
-		expect( Position.createAfter( li1 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1 ] );
-
-		expect( Position.createAfter( f ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 1 ] );
-		expect( Position.createAfter( o ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 2 ] );
-		expect( Position.createAfter( z ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 3 ] );
-
-		expect( Position.createAfter( li2 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 2 ] );
-
-		expect( Position.createAfter( b ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1, 1 ] );
-		expect( Position.createAfter( a ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1, 2 ] );
-		expect( Position.createAfter( r ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1, 3 ] );
-	} );
-
-	it( 'should throw error if one try to make positions after root', () => {
-		expect(
-			() => {
-				Position.createAfter( root );
-			}
-		).to.throw( CKEditorError, /position-after-root/ );
-	} );
-
-	it( 'should have parent', () => {
-		expect( new Position( [ 0 ], root ) ).to.have.property( 'parent' ).that.equals( root );
-		expect( new Position( [ 1 ], root ) ).to.have.property( 'parent' ).that.equals( root );
-		expect( new Position( [ 2 ], root ) ).to.have.property( 'parent' ).that.equals( root );
-
-		expect( new Position( [ 0, 0 ], root ) ).to.have.property( 'parent' ).that.equals( p );
-
-		expect( new Position( [ 1, 0 ], root ) ).to.have.property( 'parent' ).that.equals( ul );
-		expect( new Position( [ 1, 1 ], root ) ).to.have.property( 'parent' ).that.equals( ul );
-		expect( new Position( [ 1, 2 ], root ) ).to.have.property( 'parent' ).that.equals( ul );
-
-		expect( new Position( [ 1, 0, 0 ], root ) ).to.have.property( 'parent' ).that.equals( li1 );
-		expect( new Position( [ 1, 0, 1 ], root ) ).to.have.property( 'parent' ).that.equals( li1 );
-		expect( new Position( [ 1, 0, 2 ], root ) ).to.have.property( 'parent' ).that.equals( li1 );
-		expect( new Position( [ 1, 0, 3 ], root ) ).to.have.property( 'parent' ).that.equals( li1 );
-	} );
-
-	it( 'should have offset', () => {
-		expect( new Position( [ 0 ], root ) ).to.have.property( 'offset' ).that.equals( 0 );
-		expect( new Position( [ 1 ], root ) ).to.have.property( 'offset' ).that.equals( 1 );
-		expect( new Position( [ 2 ], root ) ).to.have.property( 'offset' ).that.equals( 2 );
-
-		expect( new Position( [ 0, 0 ], root ) ).to.have.property( 'offset' ).that.equals( 0 );
-
-		expect( new Position( [ 1, 0 ], root ) ).to.have.property( 'offset' ).that.equals( 0 );
-		expect( new Position( [ 1, 1 ], root ) ).to.have.property( 'offset' ).that.equals( 1 );
-		expect( new Position( [ 1, 2 ], root ) ).to.have.property( 'offset' ).that.equals( 2 );
-
-		expect( new Position( [ 1, 0, 0 ], root ) ).to.have.property( 'offset' ).that.equals( 0 );
-		expect( new Position( [ 1, 0, 1 ], root ) ).to.have.property( 'offset' ).that.equals( 1 );
-		expect( new Position( [ 1, 0, 2 ], root ) ).to.have.property( 'offset' ).that.equals( 2 );
-		expect( new Position( [ 1, 0, 3 ], root ) ).to.have.property( 'offset' ).that.equals( 3 );
-	} );
-
-	it( 'should have nodeBefore', () => {
-		expect( new Position( [ 0 ], root ) ).to.have.property( 'nodeBefore' ).that.is.null;
-		expect( new Position( [ 1 ], root ) ).to.have.property( 'nodeBefore' ).that.equals( p );
-		expect( new Position( [ 2 ], root ) ).to.have.property( 'nodeBefore' ).that.equals( ul );
-
-		expect( new Position( [ 0, 0 ], root ) ).to.have.property( 'nodeBefore' ).that.is.null;
-
-		expect( new Position( [ 1, 0 ], root ) ).to.have.property( 'nodeBefore' ).that.is.null;
-		expect( new Position( [ 1, 1 ], root ) ).to.have.property( 'nodeBefore' ).that.equals( li1 );
-		expect( new Position( [ 1, 2 ], root ) ).to.have.property( 'nodeBefore' ).that.equals( li2 );
-
-		expect( new Position( [ 1, 0, 0 ], root ) ).to.have.property( 'nodeBefore' ).that.is.null;
-		expect( new Position( [ 1, 0, 1 ], root ) ).to.have.property( 'nodeBefore' ).that.equals( f );
-		expect( new Position( [ 1, 0, 2 ], root ) ).to.have.property( 'nodeBefore' ).that.equals( o );
-		expect( new Position( [ 1, 0, 3 ], root ) ).to.have.property( 'nodeBefore' ).that.equals( z );
-	} );
-
-	it( 'should have nodeAfter', () => {
-		expect( new Position( [ 0 ], root ) ).to.have.property( 'nodeAfter' ).that.equals( p );
-		expect( new Position( [ 1 ], root ) ).to.have.property( 'nodeAfter' ).that.equals( ul );
-		expect( new Position( [ 2 ], root ) ).to.have.property( 'nodeAfter' ).that.is.null;
-
-		expect( new Position( [ 0, 0 ], root ) ).to.have.property( 'nodeAfter' ).that.is.null;
-
-		expect( new Position( [ 1, 0 ], root ) ).to.have.property( 'nodeAfter' ).that.equals( li1 );
-		expect( new Position( [ 1, 1 ], root ) ).to.have.property( 'nodeAfter' ).that.equals( li2 );
-		expect( new Position( [ 1, 2 ], root ) ).to.have.property( 'nodeAfter' ).that.is.null;
-
-		expect( new Position( [ 1, 0, 0 ], root ) ).to.have.property( 'nodeAfter' ).that.equals( f );
-		expect( new Position( [ 1, 0, 1 ], root ) ).to.have.property( 'nodeAfter' ).that.equals( o );
-		expect( new Position( [ 1, 0, 2 ], root ) ).to.have.property( 'nodeAfter' ).that.equals( z );
-		expect( new Position( [ 1, 0, 3 ], root ) ).to.have.property( 'nodeAfter' ).that.is.null;
-	} );
-
-	it( 'should equals another position with the same path', () => {
-		let position = new Position( [ 1, 1, 2 ], root );
-		let samePosition = new Position( [ 1, 1, 2 ], root );
-
-		expect( position.isEqual( samePosition ) ).to.be.true;
-	} );
-
-	it( 'should not equals another position with the different path', () => {
-		let position = new Position( [ 1, 1, 1 ], root );
-		let differentNode = new Position( [ 1, 2, 2 ], root );
-
-		expect( position.isEqual( differentNode ) ).to.be.false;
-	} );
-
-	it( 'should have proper parent path', () => {
-		let position = new Position( [ 1, 2, 3 ], root );
-
-		expect( position.getParentPath() ).to.deep.equal( [ 1, 2 ] );
-	} );
-} );

+ 0 - 118
packages/ckeditor5-engine/tests/document/range.js

@@ -1,118 +0,0 @@
-/**
- * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md.
- */
-
-/* bender-tags: document */
-
-'use strict';
-
-const modules = bender.amd.require(
-	'document/range',
-	'document/position',
-	'document/element',
-	'document/character',
-	'document/document'
-);
-
-describe( 'Range', () => {
-	let Range, Position, Element, Character, Document;
-
-	let start, end;
-
-	before( () => {
-		Position = modules[ 'document/position' ];
-		Range = modules[ 'document/range' ];
-		Element = modules[ 'document/element' ];
-		Character = modules[ 'document/character' ];
-		Document = modules[ 'document/document' ];
-
-		start = new Position( [ 0 ] );
-		end = new Position( [ 1 ] );
-	} );
-
-	let range;
-
-	beforeEach( () => {
-		range = new Range( start, end );
-	} );
-
-	describe( 'constructor', () => {
-		it( 'should create a range with given positions', () => {
-			expect( range ).to.have.property( 'start' ).that.equal( start );
-			expect( range ).to.have.property( 'end' ).that.equal( end );
-		} );
-	} );
-
-	describe( 'isEqual', () => {
-		it( 'should return true if the ranges are the same', () => {
-			let sameStart = new Position( [ 0 ] );
-			let sameEnd = new Position( [ 1 ] );
-
-			let sameRange = new Range( sameStart, sameEnd );
-
-			expect( range.isEqual( sameRange ) ).to.be.true;
-		} );
-
-		it( 'should return false if the start position is different', () => {
-			let range = new Range( start, end );
-
-			let diffStart = new Position( [ 1 ] );
-			let sameEnd = new Position( [ 1 ] );
-
-			let diffRange = new Range( diffStart, sameEnd );
-
-			expect( range.isEqual( diffRange ) ).to.not.be.true;
-		} );
-
-		it( 'should return false if the end position is different', () => {
-			let sameStart = new Position( [ 0 ] );
-			let diffEnd = new Position( [ 0 ] );
-
-			let diffRange = new Range( sameStart, diffEnd );
-
-			expect( range.isEqual( diffRange ) ).to.not.be.true;
-		} );
-	} );
-
-	describe( 'static constructors', () => {
-		let doc, root, p, f, o, z;
-
-		// root
-		//  |- p
-		//     |- f
-		//     |- o
-		//     |- z
-		before( () => {
-			doc = new Document();
-
-			root = doc.createRoot( 'root' );
-
-			f = new Character( 'f' );
-			o = new Character( 'o' );
-			z = new Character( 'z' );
-
-			p = new Element( 'p', [], [ f, o, z ] );
-
-			root.insertChildren( 0, [ p ] );
-		} );
-
-		describe( 'createFromElement', () => {
-			it( 'should return range', () => {
-				const range = Range.createFromElement( p );
-
-				expect( range.start.path ).to.deep.equal( [ 0, 0 ] );
-				expect( range.end.path ).to.deep.equal( [ 0, 3 ] );
-			} );
-		} );
-
-		describe( 'createFromParentsAndOffsets', () => {
-			it( 'should return range', () => {
-				const range = Range.createFromParentsAndOffsets( root, 0, p, 2 );
-
-				expect( range.start.path ).to.deep.equal( [ 0 ] );
-				expect( range.end.path ).to.deep.equal( [ 0, 2 ] );
-			} );
-		} );
-	} );
-} );

+ 0 - 82
packages/ckeditor5-engine/tests/document/transaction.js

@@ -1,82 +0,0 @@
-/**
- * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md.
- */
-
-/* bender-tags: document, delta */
-
-'use strict';
-
-const modules = bender.amd.require(
-	'document/transaction',
-	'document/delta/delta',
-	'ckeditorerror' );
-
-describe( 'Transaction', () => {
-	let Transaction, Delta, CKEditorError;
-
-	before( () => {
-		Transaction = modules[ 'document/transaction' ];
-		Delta = modules[ 'document/delta/delta' ];
-		CKEditorError = modules.ckeditorerror;
-	} );
-
-	it( 'should have registered basic methods', () => {
-		const transaction = new Transaction();
-
-		expect( transaction.setAttr ).to.be.a( 'function' );
-		expect( transaction.removeAttr ).to.be.a( 'function' );
-	} );
-
-	describe( 'Transaction.register', () => {
-		let TestDelta;
-
-		before( () => {
-			TestDelta = class extends Delta {
-				constructor( transaction ) {
-					super( transaction, [] );
-				}
-			};
-		} );
-
-		afterEach( () => {
-			delete Transaction.prototype.foo;
-		} );
-
-		it( 'should register function which return an delta', () => {
-			Transaction.register( 'foo', function() {
-				this.addDelta( new TestDelta() );
-			} );
-
-			const transaction = new Transaction();
-
-			transaction.foo();
-
-			expect( transaction.deltas.length ).to.equal( 1 );
-			expect( transaction.deltas[ 0 ] ).to.be.instanceof( TestDelta );
-		} );
-
-		it( 'should register function which return an multiple deltas', () => {
-			Transaction.register( 'foo', function() {
-				this.addDelta( new TestDelta() );
-				this.addDelta( new TestDelta() );
-			} );
-
-			const transaction = new Transaction();
-
-			transaction.foo();
-
-			expect( transaction.deltas.length ).to.equal( 2 );
-			expect( transaction.deltas[ 0 ] ).to.be.instanceof( TestDelta );
-			expect( transaction.deltas[ 1 ] ).to.be.instanceof( TestDelta );
-		} );
-
-		it( 'should throw if one try to register the same transaction twice', () => {
-			Transaction.register( 'foo', () => {} );
-
-			expect( () => {
-				Transaction.register( 'foo', () => {} );
-			} ).to.throw( CKEditorError, /^transaction-register-taken/ );
-		} );
-	} );
-} );

+ 3 - 3
packages/ckeditor5-engine/tests/document/attribute.js → packages/ckeditor5-engine/tests/treemodel/attribute.js

@@ -3,17 +3,17 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document */
+/* bender-tags: treemodel */
 
 'use strict';
 
-const modules = bender.amd.require( 'document/attribute' );
+const modules = bender.amd.require( 'treemodel/attribute' );
 
 describe( 'Attribute', () => {
 	let Attribute;
 
 	before( () => {
-		Attribute = modules[ 'document/attribute' ];
+		Attribute = modules[ 'treemodel/attribute' ];
 	} );
 
 	beforeEach( () => {

+ 83 - 0
packages/ckeditor5-engine/tests/treemodel/batch.js

@@ -0,0 +1,83 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/* bender-tags: treemodel, delta */
+
+'use strict';
+
+const modules = bender.amd.require(
+	'treemodel/batch',
+	'treemodel/delta/delta',
+	'ckeditorerror'
+);
+
+describe( 'Batch', () => {
+	let Batch, Delta, CKEditorError;
+
+	before( () => {
+		Batch = modules[ 'treemodel/batch' ];
+		Delta = modules[ 'treemodel/delta/delta' ];
+		CKEditorError = modules.ckeditorerror;
+	} );
+
+	it( 'should have registered basic methods', () => {
+		const batch = new Batch();
+
+		expect( batch.setAttr ).to.be.a( 'function' );
+		expect( batch.removeAttr ).to.be.a( 'function' );
+	} );
+
+	describe( 'Batch.register', () => {
+		let TestDelta;
+
+		before( () => {
+			TestDelta = class extends Delta {
+				constructor( batch ) {
+					super( batch, [] );
+				}
+			};
+		} );
+
+		afterEach( () => {
+			delete Batch.prototype.foo;
+		} );
+
+		it( 'should register function which return an delta', () => {
+			Batch.register( 'foo', function() {
+				this.addDelta( new TestDelta() );
+			} );
+
+			const batch = new Batch();
+
+			batch.foo();
+
+			expect( batch.deltas.length ).to.equal( 1 );
+			expect( batch.deltas[ 0 ] ).to.be.instanceof( TestDelta );
+		} );
+
+		it( 'should register function which return an multiple deltas', () => {
+			Batch.register( 'foo', function() {
+				this.addDelta( new TestDelta() );
+				this.addDelta( new TestDelta() );
+			} );
+
+			const batch = new Batch();
+
+			batch.foo();
+
+			expect( batch.deltas.length ).to.equal( 2 );
+			expect( batch.deltas[ 0 ] ).to.be.instanceof( TestDelta );
+			expect( batch.deltas[ 1 ] ).to.be.instanceof( TestDelta );
+		} );
+
+		it( 'should throw if one try to register the same batch twice', () => {
+			Batch.register( 'foo', () => {} );
+
+			expect( () => {
+				Batch.register( 'foo', () => {} );
+			} ).to.throw( CKEditorError, /^batch-register-taken/ );
+		} );
+	} );
+} );

+ 9 - 9
packages/ckeditor5-engine/tests/document/character.js → packages/ckeditor5-engine/tests/treemodel/character.js

@@ -5,7 +5,7 @@
 
 /* jshint expr: true */
 
-/* bender-tags: document */
+/* bender-tags: treemodel */
 
 /* bender-include: ../_tools/tools.js */
 
@@ -14,20 +14,20 @@
 const getIteratorCount = bender.tools.core.getIteratorCount;
 
 const modules = bender.amd.require(
-	'document/character',
-	'document/node',
-	'document/element',
-	'document/attribute'
+	'treemodel/character',
+	'treemodel/node',
+	'treemodel/element',
+	'treemodel/attribute'
 );
 
 describe( 'Character', () => {
 	let Element, Character, Node, Attribute;
 
 	before( () => {
-		Element = modules[ 'document/element' ];
-		Character = modules[ 'document/character' ];
-		Node = modules[ 'document/node' ];
-		Attribute = modules[ 'document/attribute' ];
+		Element = modules[ 'treemodel/element' ];
+		Character = modules[ 'treemodel/character' ];
+		Node = modules[ 'treemodel/node' ];
+		Attribute = modules[ 'treemodel/attribute' ];
 	} );
 
 	describe( 'constructor', () => {

+ 145 - 77
packages/ckeditor5-engine/tests/document/deltas/changedelta.js → packages/ckeditor5-engine/tests/treemodel/delta/attributedelta.js

@@ -3,7 +3,7 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document, delta */
+/* bender-tags: treemodel, delta */
 
 /* bender-include: ../../_tools/tools.js */
 
@@ -12,41 +12,41 @@
 const getIteratorCount = bender.tools.core.getIteratorCount;
 
 const modules = bender.amd.require(
-	'document/transaction',
-	'document/document',
-	'document/text',
-	'document/attribute',
-	'document/range',
-	'document/position',
-	'document/element',
-	'document/character' );
+	'treemodel/batch',
+	'treemodel/document',
+	'treemodel/text',
+	'treemodel/attribute',
+	'treemodel/range',
+	'treemodel/position',
+	'treemodel/element',
+	'treemodel/character' );
 
-describe( 'Transaction', () => {
-	let Transaction, Document, Text, Attribute, Range, Position, Element, Character;
+describe( 'Batch', () => {
+	let Batch, Document, Text, Attribute, Range, Position, Element, Character;
 
-	let doc, root, transaction;
+	let doc, root, batch;
 
 	before( () => {
-		Transaction = modules[ 'document/transaction' ];
-		Document = modules[ 'document/document' ];
-		Text = modules[ 'document/text' ];
-		Attribute = modules[ 'document/attribute' ];
-		Range = modules[ 'document/range' ];
-		Position = modules[ 'document/position' ];
-		Element = modules[ 'document/element' ];
-		Character = modules[ 'document/character' ];
+		Batch = modules[ 'treemodel/batch' ];
+		Document = modules[ 'treemodel/document' ];
+		Text = modules[ 'treemodel/text' ];
+		Attribute = modules[ 'treemodel/attribute' ];
+		Range = modules[ 'treemodel/range' ];
+		Position = modules[ 'treemodel/position' ];
+		Element = modules[ 'treemodel/element' ];
+		Character = modules[ 'treemodel/character' ];
 	} );
 
 	beforeEach( () => {
 		doc = new Document();
 		root = doc.createRoot( 'root' );
-		transaction = doc.createTransaction();
+		batch = doc.batch();
 	} );
 
 	function getOperationsCount() {
 		let count = 0;
 
-		for ( let delta of transaction.deltas ) {
+		for ( let delta of batch.deltas ) {
 			count += getIteratorCount( delta.operations );
 		}
 
@@ -64,62 +64,62 @@ describe( 'Transaction', () => {
 
 		describe( 'setAttr', () => {
 			it( 'should create the attribute on element', () => {
-				transaction.setAttr( 'b', 2, node );
+				batch.setAttr( 'b', 2, node );
 				expect( getOperationsCount() ).to.equal( 1 );
 				expect( node.getAttr( 'b' ) ).to.equal( 2 );
 			} );
 
 			it( 'should change the attribute of element', () => {
-				transaction.setAttr( 'a', 2, node );
+				batch.setAttr( 'a', 2, node );
 				expect( getOperationsCount() ).to.equal( 1 );
 				expect( node.getAttr( 'a' ) ).to.equal( 2 );
 			} );
 
 			it( 'should create the attribute on character', () => {
-				transaction.setAttr( 'b', 2, character );
+				batch.setAttr( 'b', 2, character );
 				expect( getOperationsCount() ).to.equal( 1 );
 				expect( character.getAttr( 'b' ) ).to.equal( 2 );
 			} );
 
 			it( 'should change the attribute of character', () => {
-				transaction.setAttr( 'a', 2, character );
+				batch.setAttr( 'a', 2, character );
 				expect( getOperationsCount() ).to.equal( 1 );
 				expect( character.getAttr( 'a' ) ).to.equal( 2 );
 			} );
 
 			it( 'should do nothing if the attribute value is the same', () => {
-				transaction.setAttr( 'a', 1, node );
+				batch.setAttr( 'a', 1, node );
 				expect( getOperationsCount() ).to.equal( 0 );
 				expect( node.getAttr( 'a' ) ).to.equal( 1 );
 			} );
 
 			it( 'should be chainable', () => {
-				const chain = transaction.setAttr( 'b', 2, node );
-				expect( chain ).to.equal( transaction );
+				const chain = batch.setAttr( 'b', 2, node );
+				expect( chain ).to.equal( batch );
 			} );
 		} );
 
 		describe( 'removeAttr', () => {
 			it( 'should remove the attribute from element', () => {
-				transaction.removeAttr( 'a', node );
+				batch.removeAttr( 'a', node );
 				expect( getOperationsCount() ).to.equal( 1 );
 				expect( node.getAttr( 'a' ) ).to.be.null;
 			} );
 
 			it( 'should remove the attribute from character', () => {
-				transaction.removeAttr( 'a', character );
+				batch.removeAttr( 'a', character );
 				expect( getOperationsCount() ).to.equal( 1 );
 				expect( character.getAttr( 'a' ) ).to.be.null;
 			} );
 
 			it( 'should do nothing if the attribute is not set', () => {
-				transaction.removeAttr( 'b', node );
+				batch.removeAttr( 'b', node );
 				expect( getOperationsCount() ).to.equal( 0 );
 			} );
 
 			it( 'should be chainable', () => {
-				const chain = transaction.removeAttr( 'a', node );
-				expect( chain ).to.equal( transaction );
+				const chain = batch.removeAttr( 'a', node );
+				expect( chain ).to.equal( batch );
 			} );
 		} );
 	} );
@@ -132,23 +132,25 @@ describe( 'Transaction', () => {
 				new Text( 'xxx', [ new Attribute( 'a', 1 ) ] ),
 				new Text( 'xxx', [ new Attribute( 'a', 2 ) ] ),
 				'xxx',
-				new Text( 'xxx', [ new Attribute( 'a', 1 ) ] )
+				new Text( 'xxx', [ new Attribute( 'a', 1 ) ] ),
+				new Element( 'e', [ new Attribute( 'a', 2 ) ], 'xxx' ),
+				'xxx'
 			] );
 		} );
 
 		function getRange( startIndex, endIndex ) {
 			return new Range(
-					Position.createFromParentAndOffset( root, startIndex ),
-					Position.createFromParentAndOffset( root, endIndex )
-				);
+				Position.createFromParentAndOffset( root, startIndex ),
+				Position.createFromParentAndOffset( root, endIndex )
+			);
 		}
 
 		function getChangesAttrsCount() {
 			let count = 0;
 
-			for ( let delta of transaction.deltas ) {
+			for ( let delta of batch.deltas ) {
 				for ( let operation of delta.operations ) {
-					count += getIteratorCount( operation.range );
+					count += getIteratorCount( operation.range.getNodes() );
 				}
 			}
 
@@ -156,120 +158,186 @@ describe( 'Transaction', () => {
 		}
 
 		function getCompressedAttrs() {
-			// default: 111---111222---111
+			// default: 111---111222---1112------
 			const range = Range.createFromElement( root );
 
-			return Array.from( range ).map( value => value.node.getAttr( 'a' ) || '-' ).join( '' );
+			return Array.from( range.getNodes() ).map( node => node.getAttr( 'a' ) || '-' ).join( '' );
 		}
 
 		describe( 'setAttr', () => {
 			it( 'should set the attribute on the range', () => {
-				transaction.setAttr( 'a', 3, getRange( 3, 6 ) );
+				batch.setAttr( 'a', 3, getRange( 3, 6 ) );
 				expect( getOperationsCount() ).to.equal( 1 );
 				expect( getChangesAttrsCount() ).to.equal( 3 );
-				expect( getCompressedAttrs() ).to.equal( '111333111222---111' );
+				expect( getCompressedAttrs() ).to.equal( '111333111222---1112------' );
 			} );
 
 			it( 'should split the operations if parts of the range have different attributes', () => {
-				transaction.setAttr( 'a', 3, getRange( 4, 14 ) );
+				batch.setAttr( 'a', 3, getRange( 4, 14 ) );
 				expect( getOperationsCount() ).to.equal( 4 );
 				expect( getChangesAttrsCount() ).to.equal( 10 );
-				expect( getCompressedAttrs() ).to.equal( '111-3333333333-111' );
+				expect( getCompressedAttrs() ).to.equal( '111-3333333333-1112------' );
 			} );
 
 			it( 'should split the operations if parts of the part of the range have the attribute', () => {
-				transaction.setAttr( 'a', 2, getRange( 4, 14 ) );
+				batch.setAttr( 'a', 2, getRange( 4, 14 ) );
 				expect( getOperationsCount() ).to.equal( 3 );
 				expect( getChangesAttrsCount() ).to.equal( 7 );
-				expect( getCompressedAttrs() ).to.equal( '111-2222222222-111' );
+				expect( getCompressedAttrs() ).to.equal( '111-2222222222-1112------' );
 			} );
 
 			it( 'should strip the range if the beginning have the attribute', () => {
-				transaction.setAttr( 'a', 1, getRange( 1, 5 ) );
+				batch.setAttr( 'a', 1, getRange( 1, 5 ) );
 				expect( getOperationsCount() ).to.equal( 1 );
 				expect( getChangesAttrsCount() ).to.equal( 2 );
-				expect( getCompressedAttrs() ).to.equal( '11111-111222---111' );
+				expect( getCompressedAttrs() ).to.equal( '11111-111222---1112------' );
 			} );
 
 			it( 'should strip the range if the ending have the attribute', () => {
-				transaction.setAttr( 'a', 1, getRange( 13, 17 ) );
+				batch.setAttr( 'a', 1, getRange( 13, 17 ) );
 				expect( getOperationsCount() ).to.equal( 1 );
 				expect( getChangesAttrsCount() ).to.equal( 2 );
-				expect( getCompressedAttrs() ).to.equal( '111---111222-11111' );
+				expect( getCompressedAttrs() ).to.equal( '111---111222-111112------' );
 			} );
 
 			it( 'should do nothing if the range has attribute', () => {
-				transaction.setAttr( 'a', 1, getRange( 0, 3 ) );
+				batch.setAttr( 'a', 1, getRange( 0, 3 ) );
+				expect( getOperationsCount() ).to.equal( 0 );
+				expect( getCompressedAttrs() ).to.equal( '111---111222---1112------' );
+			} );
+
+			it( 'should not check range\'s start position node when creating operations', () => {
+				let range = new Range(
+					new Position( root, [ 18, 1 ] ),
+					new Position( root, [ 19 ] )
+				);
+
+				batch.setAttr( 'a', 1, range );
+				expect( getOperationsCount() ).to.equal( 1 );
+				expect( getChangesAttrsCount() ).to.equal( 2 );
+				expect( getCompressedAttrs() ).to.equal( '111---111222---1112-11---' );
+			} );
+
+			it( 'should not change elements attribute if range contains closing tag', () => {
+				let range = new Range(
+					new Position( root, [ 18, 1 ] ),
+					new Position( root, [ 21 ] )
+				);
+
+				batch.setAttr( 'a', 1, range );
+				expect( getOperationsCount() ).to.equal( 1 );
+				expect( getChangesAttrsCount() ).to.equal( 4 );
+				expect( getCompressedAttrs() ).to.equal( '111---111222---1112-1111-' );
+			} );
+
+			it( 'should not create an operation if the range contains only closing tag', () => {
+				let range = new Range(
+					new Position( root, [ 18, 3 ] ),
+					new Position( root, [ 19 ] )
+				);
+
+				batch.setAttr( 'a', 3, range );
+				expect( getOperationsCount() ).to.equal( 0 );
+				expect( getCompressedAttrs() ).to.equal( '111---111222---1112------' );
+			} );
+
+			it( 'should not create an operation if is collapsed', () => {
+				batch.setAttr( 'a', 1, getRange( 3, 3 ) );
 				expect( getOperationsCount() ).to.equal( 0 );
-				expect( getCompressedAttrs() ).to.equal( '111---111222---111' );
+				expect( getCompressedAttrs() ).to.equal( '111---111222---1112------' );
 			} );
 
 			it( 'should create a proper operations for the mixed range', () => {
-				transaction.setAttr( 'a', 1, getRange( 0, 18 ) );
-				expect( getOperationsCount() ).to.equal( 3 );
-				expect( getChangesAttrsCount() ).to.equal( 9 );
-				expect( getCompressedAttrs() ).to.equal( '111111111111111111' );
+				batch.setAttr( 'a', 1, getRange( 0, 20 ) );
+				expect( getOperationsCount() ).to.equal( 5 );
+				expect( getChangesAttrsCount() ).to.equal( 14 );
+				expect( getCompressedAttrs() ).to.equal( '11111111111111111111111--' );
 			} );
 
 			it( 'should be chainable', () => {
-				const chain = transaction.setAttr( 'a', 3, getRange( 3, 6 ) );
-				expect( chain ).to.equal( transaction );
+				const chain = batch.setAttr( 'a', 3, getRange( 3, 6 ) );
+				expect( chain ).to.equal( batch );
 			} );
 		} );
 
 		describe( 'removeAttr', () => {
 			it( 'should remove the attribute on the range', () => {
-				transaction.removeAttr( 'a', getRange( 0, 2 ) );
+				batch.removeAttr( 'a', getRange( 0, 2 ) );
 				expect( getOperationsCount() ).to.equal( 1 );
 				expect( getChangesAttrsCount() ).to.equal( 2 );
-				expect( getCompressedAttrs() ).to.equal( '--1---111222---111' );
+				expect( getCompressedAttrs() ).to.equal( '--1---111222---1112------' );
 			} );
 
 			it( 'should split the operations if parts of the range have different attributes', () => {
-				transaction.removeAttr( 'a', getRange( 7, 11 ) );
+				batch.removeAttr( 'a', getRange( 7, 11 ) );
 				expect( getOperationsCount() ).to.equal( 2 );
 				expect( getChangesAttrsCount() ).to.equal( 4 );
-				expect( getCompressedAttrs() ).to.equal( '111---1----2---111' );
+				expect( getCompressedAttrs() ).to.equal( '111---1----2---1112------' );
 			} );
 
 			it( 'should split the operations if parts of the part of the range have no attribute', () => {
-				transaction.removeAttr( 'a', getRange( 1, 7 ) );
+				batch.removeAttr( 'a', getRange( 1, 7 ) );
 				expect( getOperationsCount() ).to.equal( 2 );
 				expect( getChangesAttrsCount() ).to.equal( 3 );
-				expect( getCompressedAttrs() ).to.equal( '1------11222---111' );
+				expect( getCompressedAttrs() ).to.equal( '1------11222---1112------' );
 			} );
 
 			it( 'should strip the range if the beginning have no attribute', () => {
-				transaction.removeAttr( 'a', getRange( 4, 12 ) );
+				batch.removeAttr( 'a', getRange( 4, 12 ) );
 				expect( getOperationsCount() ).to.equal( 2 );
 				expect( getChangesAttrsCount() ).to.equal( 6 );
-				expect( getCompressedAttrs() ).to.equal( '111------------111' );
+				expect( getCompressedAttrs() ).to.equal( '111------------1112------' );
 			} );
 
 			it( 'should strip the range if the ending have no attribute', () => {
-				transaction.removeAttr( 'a', getRange( 7, 15 ) );
+				batch.removeAttr( 'a', getRange( 7, 15 ) );
 				expect( getOperationsCount() ).to.equal( 2 );
 				expect( getChangesAttrsCount() ).to.equal( 5 );
-				expect( getCompressedAttrs() ).to.equal( '111---1--------111' );
+				expect( getCompressedAttrs() ).to.equal( '111---1--------1112------' );
 			} );
 
 			it( 'should do nothing if the range has no attribute', () => {
-				transaction.removeAttr( 'a', getRange( 4, 5 ) );
+				batch.removeAttr( 'a', getRange( 4, 5 ) );
+				expect( getOperationsCount() ).to.equal( 0 );
+				expect( getCompressedAttrs() ).to.equal( '111---111222---1112------' );
+			} );
+
+			it( 'should not check range\'s start position node when creating operations', () => {
+				let range = new Range(
+					new Position( root, [ 18, 3 ] ),
+					new Position( root, [ 19 ] )
+				);
+
+				batch.removeAttr( 'a', range );
+				expect( getOperationsCount() ).to.equal( 0 );
+				expect( getChangesAttrsCount() ).to.equal( 0 );
+				expect( getCompressedAttrs() ).to.equal( '111---111222---1112------' );
+			} );
+
+			it( 'should not apply operation twice in the range contains opening and closing tags', () => {
+				batch.removeAttr( 'a', getRange( 18, 22 ) );
+				expect( getOperationsCount() ).to.equal( 1 );
+				expect( getChangesAttrsCount() ).to.equal( 1 );
+				expect( getCompressedAttrs() ).to.equal( '111---111222---111-------' );
+			} );
+
+			it( 'should not create an operation if range is collapsed', () => {
+				batch.removeAttr( 'a', getRange( 3, 3 ) );
 				expect( getOperationsCount() ).to.equal( 0 );
-				expect( getCompressedAttrs() ).to.equal( '111---111222---111' );
+				expect( getCompressedAttrs() ).to.equal( '111---111222---1112------' );
 			} );
 
 			it( 'should create a proper operations for the mixed range', () => {
-				transaction.removeAttr( 'a', getRange( 3, 15 ) );
+				batch.removeAttr( 'a', getRange( 3, 15 ) );
 				expect( getOperationsCount() ).to.equal( 2 );
 				expect( getChangesAttrsCount() ).to.equal( 6 );
-				expect( getCompressedAttrs() ).to.equal( '111------------111' );
+				expect( getCompressedAttrs() ).to.equal( '111------------1112------' );
 			} );
 
 			it( 'should be chainable', () => {
-				const chain = transaction.removeAttr( 'a', getRange( 0, 2 ) );
-				expect( chain ).to.equal( transaction );
+				const chain = batch.removeAttr( 'a', getRange( 0, 2 ) );
+				expect( chain ).to.equal( batch );
 			} );
 		} );
 	} );
-} );
+} );

+ 5 - 5
packages/ckeditor5-engine/tests/document/deltas/delta.js → packages/ckeditor5-engine/tests/treemodel/delta/delta.js

@@ -3,7 +3,7 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document, delta */
+/* bender-tags: treemodel, delta */
 
 /* bender-include: ../../_tools/tools.js */
 
@@ -12,20 +12,20 @@
 const getIteratorCount = bender.tools.core.getIteratorCount;
 
 const modules = bender.amd.require(
-	'document/delta/delta' );
+	'treemodel/delta/delta' );
 
 describe( 'Delta', () => {
 	let Delta;
 
 	before( () => {
-		Delta = modules[ 'document/delta/delta' ];
+		Delta = modules[ 'treemodel/delta/delta' ];
 	} );
 
 	describe( 'constructor', () => {
 		it( 'should create an delta with empty properties', () => {
 			const delta = new Delta();
 
-			expect( delta ).to.have.property( 'transaction' ).that.is.null;
+			expect( delta ).to.have.property( 'batch' ).that.is.null;
 			expect( delta ).to.have.property( 'operations' ).that.a( 'array' ).and.have.length( 0 );
 		} );
 	} );
@@ -64,4 +64,4 @@ describe( 'Delta', () => {
 			expect( count ).to.equal( 3 );
 		} );
 	} );
-} );
+} );

+ 13 - 13
packages/ckeditor5-engine/tests/document/deltas/insertdelta.js → packages/ckeditor5-engine/tests/treemodel/delta/insertdelta.js

@@ -3,22 +3,22 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document, delta */
+/* bender-tags: treemodel, delta */
 
 'use strict';
 
 const modules = bender.amd.require(
-	'document/document',
-	'document/position' );
+	'treemodel/document',
+	'treemodel/position' );
 
-describe( 'Transaction', () => {
+describe( 'Batch', () => {
 	let Document, Position;
 
 	let doc, root;
 
 	before( () => {
-		Document = modules[ 'document/document' ];
-		Position = modules[ 'document/position' ];
+		Document = modules[ 'treemodel/document' ];
+		Position = modules[ 'treemodel/position' ];
 	} );
 
 	beforeEach( () => {
@@ -27,8 +27,8 @@ describe( 'Transaction', () => {
 	} );
 
 	it( 'should insert text', () => {
-		const position = new Position( [ 0 ], root );
-		doc.createTransaction().insert( position, 'foo' );
+		const position = new Position( root, [ 0 ] );
+		doc.batch().insert( position, 'foo' );
 
 		expect( root.getChildCount() ).to.equal( 3 );
 		expect( root.getChild( 0 ).character ).to.equal( 'f' );
@@ -37,10 +37,10 @@ describe( 'Transaction', () => {
 	} );
 
 	it( 'should be chainable', () => {
-		const position = new Position( [ 0 ], root );
-		const transaction = doc.createTransaction();
+		const position = new Position( root, [ 0 ] );
+		const batch = doc.batch();
 
-		const chain = transaction.insert( position, 'foo' );
-		expect( chain ).to.equal( transaction );
+		const chain = batch.insert( position, 'foo' );
+		expect( chain ).to.equal( batch );
 	} );
-} );
+} );

+ 19 - 19
packages/ckeditor5-engine/tests/document/deltas/mergedelta.js → packages/ckeditor5-engine/tests/treemodel/delta/mergedelta.js

@@ -3,7 +3,7 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document, delta */
+/* bender-tags: treemodel, delta */
 
 /* bender-include: ../../_tools/tools.js */
 
@@ -12,22 +12,22 @@
 const getIteratorCount = bender.tools.core.getIteratorCount;
 
 const modules = bender.amd.require(
-	'document/document',
-	'document/position',
-	'document/element',
-	'document/attribute',
+	'treemodel/document',
+	'treemodel/position',
+	'treemodel/element',
+	'treemodel/attribute',
 	'ckeditorerror' );
 
-describe( 'Transaction', () => {
+describe( 'Batch', () => {
 	let Document, Position, Element, Attribute, CKEditorError;
 
 	let doc, root, p1, p2;
 
 	before( () => {
-		Document = modules[ 'document/document' ];
-		Position = modules[ 'document/position' ];
-		Element = modules[ 'document/element' ];
-		Attribute = modules[ 'document/attribute' ];
+		Document = modules[ 'treemodel/document' ];
+		Position = modules[ 'treemodel/position' ];
+		Element = modules[ 'treemodel/element' ];
+		Attribute = modules[ 'treemodel/attribute' ];
 		CKEditorError = modules.ckeditorerror;
 	} );
 
@@ -43,7 +43,7 @@ describe( 'Transaction', () => {
 
 	describe( 'merge', () => {
 		it( 'should merge foo and bar into foobar', () => {
-			doc.createTransaction().merge( new Position( [ 1 ], root ) );
+			doc.batch().merge( new Position( root, [ 1 ] ) );
 
 			expect( root.getChildCount() ).to.equal( 1 );
 			expect( root.getChild( 0 ).name ).to.equal( 'p' );
@@ -60,21 +60,21 @@ describe( 'Transaction', () => {
 
 		it( 'should throw if there is no element after', () => {
 			expect( () => {
-				doc.createTransaction().merge( new Position( [ 2 ], root ) );
-			} ).to.throw( CKEditorError, /^transaction-merge-no-element-after/ );
+				doc.batch().merge( new Position( root, [ 2 ] ) );
+			} ).to.throw( CKEditorError, /^batch-merge-no-element-after/ );
 		} );
 
 		it( 'should throw if there is no element before', () => {
 			expect( () => {
-				doc.createTransaction().merge( new Position( [ 0, 2 ], root ) );
-			} ).to.throw( CKEditorError, /^transaction-merge-no-element-before/ );
+				doc.batch().merge( new Position( root, [ 0, 2 ] ) );
+			} ).to.throw( CKEditorError, /^batch-merge-no-element-before/ );
 		} );
 
 		it( 'should be chainable', () => {
-			const transaction = doc.createTransaction();
+			const batch = doc.batch();
 
-			const chain = transaction.merge( new Position( [ 1 ], root ) );
-			expect( chain ).to.equal( transaction );
+			const chain = batch.merge( new Position( root, [ 1 ] ) );
+			expect( chain ).to.equal( batch );
 		} );
 	} );
-} );
+} );

+ 15 - 15
packages/ckeditor5-engine/tests/document/deltas/removedelta.js → packages/ckeditor5-engine/tests/treemodel/delta/removedelta.js

@@ -3,22 +3,22 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document, delta */
+/* bender-tags: treemodel, delta */
 
 'use strict';
 
 const modules = bender.amd.require(
-	'document/document',
-	'document/position' );
+	'treemodel/document',
+	'treemodel/position' );
 
-describe( 'Transaction', () => {
+describe( 'Batch', () => {
 	let Document, Position;
 
 	let doc, root;
 
 	before( () => {
-		Document = modules[ 'document/document' ];
-		Position = modules[ 'document/position' ];
+		Document = modules[ 'treemodel/document' ];
+		Position = modules[ 'treemodel/position' ];
 	} );
 
 	beforeEach( () => {
@@ -29,8 +29,8 @@ describe( 'Transaction', () => {
 
 	describe( 'remove', () => {
 		it( 'should remove one element', () => {
-			const position = new Position( [ 1 ], root );
-			doc.createTransaction().remove( position );
+			const position = new Position( root, [ 1 ] );
+			doc.batch().remove( position );
 
 			expect( root.getChildCount() ).to.equal( 5 );
 			expect( root.getChild( 0 ).character ).to.equal( 'f' );
@@ -41,8 +41,8 @@ describe( 'Transaction', () => {
 		} );
 
 		it( 'should remove 3 elements', () => {
-			const position = new Position( [ 1 ], root );
-			doc.createTransaction().remove( position, 3 );
+			const position = new Position( root, [ 1 ] );
+			doc.batch().remove( position, 3 );
 
 			expect( root.getChildCount() ).to.equal( 3 );
 			expect( root.getChild( 0 ).character ).to.equal( 'f' );
@@ -51,11 +51,11 @@ describe( 'Transaction', () => {
 		} );
 
 		it( 'should be chainable', () => {
-			const position = new Position( [ 1 ], root );
-			const transaction = doc.createTransaction();
+			const position = new Position( root, [ 1 ] );
+			const batch = doc.batch();
 
-			const chain = transaction.remove( position );
-			expect( chain ).to.equal( transaction );
+			const chain = batch.remove( position );
+			expect( chain ).to.equal( batch );
 		} );
 	} );
-} );
+} );

+ 18 - 18
packages/ckeditor5-engine/tests/document/deltas/splitdelta.js → packages/ckeditor5-engine/tests/treemodel/delta/splitdelta.js

@@ -3,7 +3,7 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document, delta */
+/* bender-tags: treemodel, delta */
 
 /* bender-include: ../../_tools/tools.js */
 
@@ -12,22 +12,22 @@
 const getIteratorCount = bender.tools.core.getIteratorCount;
 
 const modules = bender.amd.require(
-	'document/document',
-	'document/position',
-	'document/element',
-	'document/attribute',
+	'treemodel/document',
+	'treemodel/position',
+	'treemodel/element',
+	'treemodel/attribute',
 	'ckeditorerror' );
 
-describe( 'Transaction', () => {
+describe( 'Batch', () => {
 	let Document, Position, Element, Attribute, CKEditorError;
 
 	let doc, root, p;
 
 	before( () => {
-		Document = modules[ 'document/document' ];
-		Position = modules[ 'document/position' ];
-		Element = modules[ 'document/element' ];
-		Attribute = modules[ 'document/attribute' ];
+		Document = modules[ 'treemodel/document' ];
+		Position = modules[ 'treemodel/position' ];
+		Element = modules[ 'treemodel/element' ];
+		Attribute = modules[ 'treemodel/attribute' ];
 		CKEditorError = modules.ckeditorerror;
 	} );
 
@@ -42,7 +42,7 @@ describe( 'Transaction', () => {
 
 	describe( 'split', () => {
 		it( 'should split foobar to foo and bar', () => {
-			doc.createTransaction().split( new Position( [ 0, 3 ], root ) );
+			doc.batch().split( new Position( root, [ 0, 3 ] ) );
 
 			expect( root.getChildCount() ).to.equal( 2 );
 
@@ -64,7 +64,7 @@ describe( 'Transaction', () => {
 		} );
 
 		it( 'should create an empty paragraph if we split at the end', () => {
-			doc.createTransaction().split( new Position( [ 0, 6 ], root ) );
+			doc.batch().split( new Position( root, [ 0, 6 ] ) );
 
 			expect( root.getChildCount() ).to.equal( 2 );
 
@@ -87,15 +87,15 @@ describe( 'Transaction', () => {
 
 		it( 'should throw if we try to split a root', () => {
 			expect( () => {
-				doc.createTransaction().split( new Position( [ 0 ], root ) );
-			} ).to.throw( CKEditorError, /^transaction-split-root/ );
+				doc.batch().split( new Position( root, [ 0 ] ) );
+			} ).to.throw( CKEditorError, /^batch-split-root/ );
 		} );
 
 		it( 'should be chainable', () => {
-			const transaction = doc.createTransaction();
+			const batch = doc.batch();
 
-			const chain = transaction.split( new Position( [ 0, 3 ], root ) );
-			expect( chain ).to.equal( transaction );
+			const chain = batch.split( new Position( root, [ 0, 3 ] ) );
+			expect( chain ).to.equal( batch );
 		} );
 	} );
-} );
+} );

+ 186 - 0
packages/ckeditor5-engine/tests/treemodel/document/change-event.js

@@ -0,0 +1,186 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/* bender-tags: treemodel */
+
+'use strict';
+
+const modules = bender.amd.require(
+	'treemodel/document',
+	'treemodel/element',
+	'treemodel/rootelement',
+	'treemodel/attribute',
+	'treemodel/position',
+	'treemodel/range',
+	'treemodel/operation/attributeoperation',
+	'treemodel/operation/insertoperation',
+	'treemodel/operation/moveoperation',
+	'treemodel/operation/reinsertoperation',
+	'treemodel/operation/removeoperation'
+);
+
+describe( 'Document change event', () => {
+	let Document, RootElement, Element, Range, Position;
+	let AttributeOperation, InsertOperation, MoveOperation, ReinsertOperation, RemoveOperation, Attribute;
+
+	before( () => {
+		Document = modules[ 'treemodel/document' ];
+		Element = modules[ 'treemodel/element' ];
+		RootElement = modules[ 'treemodel/rootelement' ];
+		Attribute = modules[ 'treemodel/attribute' ];
+		Position = modules[ 'treemodel/position' ];
+		Range = modules[ 'treemodel/range' ];
+
+		InsertOperation = modules[ 'treemodel/operation/insertoperation' ];
+		AttributeOperation = modules[ 'treemodel/operation/attributeoperation' ];
+		MoveOperation = modules[ 'treemodel/operation/moveoperation' ];
+		ReinsertOperation = modules[ 'treemodel/operation/reinsertoperation' ];
+		RemoveOperation = modules[ 'treemodel/operation/removeoperation' ];
+	} );
+
+	let doc, root, graveyard, types, changes;
+
+	beforeEach( () => {
+		doc = new Document();
+		root = doc.createRoot( 'root' );
+		graveyard = doc.graveyard;
+
+		types = [];
+		changes = [];
+
+		doc.on( 'change', ( evt, type, change ) => {
+			types.push( type );
+			changes.push( change );
+		} );
+	} );
+
+	it( 'should be fired when text is inserted', () => {
+		doc.applyOperation( new InsertOperation( new Position( root, [ 0 ] ), 'foo', doc.version ) );
+
+		expect( changes ).to.have.length( 1 );
+		expect( types[ 0 ] ).to.equal( 'insert' );
+		expect( changes[ 0 ].range ).to.deep.equal( Range.createFromParentsAndOffsets( root, 0, root, 3 ) );
+	} );
+
+	it( 'should be fired when element is inserted', () => {
+		const element = new Element( 'p' );
+		doc.applyOperation( new InsertOperation( new Position( root, [ 0 ] ), element, doc.version ) );
+
+		expect( changes ).to.have.length( 1 );
+		expect( types[ 0 ] ).to.equal( 'insert' );
+		expect( changes[ 0 ].range ).to.deep.equal( Range.createFromParentsAndOffsets( root, 0, root, 1 ) );
+	} );
+
+	it( 'should be fired when nodes are inserted', () => {
+		const element = new Element( 'p' );
+		doc.applyOperation( new InsertOperation( new Position( root, [ 0 ] ), [ element, 'foo' ], doc.version ) );
+
+		expect( changes ).to.have.length( 1 );
+		expect( types[ 0 ] ).to.equal( 'insert' );
+		expect( changes[ 0 ].range ).to.deep.equal( Range.createFromParentsAndOffsets( root, 0, root, 4 ) );
+	} );
+
+	it( 'should be fired when nodes are moved', () => {
+		const p1 = new Element( 'p' );
+		p1.insertChildren( 0, [ new Element( 'p' ), 'foo' ] );
+
+		const p2 = new Element( 'p' );
+
+		root.insertChildren( 0, [ p1, p2 ] );
+
+		doc.applyOperation(
+			new MoveOperation(
+				new Position( root, [ 0, 0 ] ),
+				3,
+				new Position( root, [ 1, 0 ] ),
+				doc.version
+			)
+		);
+
+		expect( changes ).to.have.length( 1 );
+		expect( types[ 0 ] ).to.equal( 'move' );
+		expect( changes[ 0 ].range ).to.deep.equal( Range.createFromParentsAndOffsets( p2, 0, p2, 3 ) );
+		expect( changes[ 0 ].sourcePosition ).to.deep.equal( Position.createFromParentAndOffset( p1, 0 ) );
+	} );
+
+	it( 'should be fired when multiple nodes are removed and reinserted', () => {
+		root.insertChildren( 0, 'foo' );
+
+		const removeOperation = new RemoveOperation( new Position( root, [ 0 ] ), 3, doc.version );
+		doc.applyOperation( removeOperation );
+
+		const reinsertOperation = removeOperation.getReversed();
+		doc.applyOperation( reinsertOperation );
+
+		expect( changes ).to.have.length( 2 );
+
+		expect( types[ 0 ] ).to.equal( 'remove' );
+		expect( changes[ 0 ].range ).to.deep.equal( Range.createFromParentsAndOffsets( graveyard, 0, graveyard, 3 ) );
+		expect( changes[ 0 ].sourcePosition ).to.deep.equal( Position.createFromParentAndOffset( root, 0 ) );
+
+		expect( types[ 1 ] ).to.equal( 'reinsert' );
+		expect( changes[ 1 ].range ).to.deep.equal( Range.createFromParentsAndOffsets( root, 0, root, 3 ) );
+		expect( changes[ 1 ].sourcePosition ).to.deep.equal( Position.createFromParentAndOffset( graveyard, 0 ) );
+	} );
+
+	it( 'should be fired when attribute is inserted', () => {
+		root.insertChildren( 0, 'foo' );
+
+		doc.applyOperation(
+			new AttributeOperation(
+				Range.createFromParentsAndOffsets( root, 0, root, 3 ),
+				null,
+				new Attribute( 'key', 'new' ),
+				doc.version
+			)
+		);
+
+		expect( changes ).to.have.length( 1 );
+		expect( types[ 0 ] ).to.equal( 'attr' );
+		expect( changes[ 0 ].range ).to.deep.equal( Range.createFromParentsAndOffsets( root, 0, root, 3 ) );
+		expect( changes[ 0 ].oldAttr ).to.be.null;
+		expect( changes[ 0 ].newAttr ).to.deep.equal( new Attribute( 'key', 'new' ) );
+	} );
+
+	it( 'should be fired when attribute is removed', () => {
+		const elem = new Element( 'p', [ new Attribute( 'key', 'old' ) ] );
+		root.insertChildren( 0, elem );
+
+		doc.applyOperation(
+			new AttributeOperation(
+				Range.createFromParentsAndOffsets( root, 0, elem, 0 ),
+				new Attribute( 'key', 'old' ),
+				null,
+				doc.version
+			)
+		);
+
+		expect( changes ).to.have.length( 1 );
+		expect( types[ 0 ] ).to.equal( 'attr' );
+		expect( changes[ 0 ].range ).to.deep.equal( Range.createFromParentsAndOffsets( root, 0, elem, 0 ) );
+		expect( changes[ 0 ].oldAttr ).to.deep.equal( new Attribute( 'key', 'old' ) );
+		expect( changes[ 0 ].newAttr ).to.be.null;
+	}  );
+
+	it( 'should be fired when attribute changes', () => {
+		const elem = new Element( 'p', [ new Attribute( 'key', 'old' ) ] );
+		root.insertChildren( 0, elem );
+
+		doc.applyOperation(
+			new AttributeOperation(
+				Range.createFromParentsAndOffsets( root, 0, elem, 0 ),
+				new Attribute( 'key', 'old' ),
+				new Attribute( 'key', 'new' ),
+				doc.version
+			)
+		);
+
+		expect( changes ).to.have.length( 1 );
+		expect( types[ 0 ] ).to.equal( 'attr' );
+		expect( changes[ 0 ].range ).to.deep.equal( Range.createFromParentsAndOffsets( root, 0, elem, 0 ) );
+		expect( changes[ 0 ].oldAttr ).to.deep.equal( new Attribute( 'key', 'old' ) );
+		expect( changes[ 0 ].newAttr ).to.deep.equal( new Attribute( 'key', 'new' ) );
+	}  );
+} );

+ 183 - 0
packages/ckeditor5-engine/tests/treemodel/document/document.js

@@ -0,0 +1,183 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/* bender-tags: treemodel */
+
+'use strict';
+
+const modules = bender.amd.require(
+	'treemodel/document',
+	'treemodel/rootelement',
+	'treemodel/batch',
+	'ckeditorerror'
+);
+
+describe( 'Document', () => {
+	let Document, RootElement, Batch, CKEditorError;
+
+	before( () => {
+		Document = modules[ 'treemodel/document' ];
+		RootElement = modules[ 'treemodel/rootelement' ];
+		Batch = modules[ 'treemodel/batch' ];
+		CKEditorError = modules.ckeditorerror;
+	} );
+
+	let doc;
+
+	beforeEach( () => {
+		doc = new Document();
+	} );
+
+	describe( 'constructor', () => {
+		it( 'should create Document with no data and empty graveyard', () => {
+			expect( doc ).to.have.property( 'roots' ).that.is.instanceof( Map );
+			expect( doc.roots.size ).to.equal( 1 );
+			expect( doc.graveyard ).to.be.instanceof( RootElement );
+			expect( doc.graveyard.getChildCount() ).to.equal( 0 );
+		} );
+	} );
+
+	describe( 'createRoot', () => {
+		it( 'should create a new RootElement, add it to roots map and return it', () => {
+			let root = doc.createRoot( 'root' );
+
+			expect( doc.roots.size ).to.equal( 2 );
+			expect( root ).to.be.instanceof( RootElement );
+			expect( root.getChildCount() ).to.equal( 0 );
+		} );
+
+		it( 'should throw an error when trying to create a second root with the same name', () => {
+			doc.createRoot( 'root' );
+
+			expect(
+				() => {
+					doc.createRoot( 'root' );
+				}
+			).to.throw( CKEditorError, /document-createRoot-name-exists/ );
+		} );
+	} );
+
+	describe( 'getRoot', () => {
+		it( 'should return a RootElement previously created with given name', () => {
+			let newRoot = doc.createRoot( 'root' );
+			let getRoot = doc.getRoot( 'root' );
+
+			expect( getRoot ).to.equal( newRoot );
+		} );
+
+		it( 'should throw an error when trying to get non-existent root', () => {
+			expect(
+				() => {
+					doc.getRoot( 'root' );
+				}
+			).to.throw( CKEditorError, /document-createRoot-root-not-exist/ );
+		} );
+	} );
+
+	describe( 'applyOperation', () => {
+		it( 'should increase document version, execute operation and fire event with proper data', () => {
+			const changeCallback = sinon.spy();
+			const type = 't';
+			const data = { data: 'x' };
+			const batch = 'batch';
+
+			let operation = {
+				type: type,
+				delta: { batch: batch },
+				baseVersion: 0,
+				_execute: sinon.stub().returns( data )
+			};
+
+			doc.on( 'change', changeCallback );
+			doc.applyOperation( operation );
+
+			expect( doc.version ).to.equal( 1 );
+			sinon.assert.calledOnce( operation._execute );
+
+			sinon.assert.calledOnce( changeCallback );
+			expect( changeCallback.args[ 0 ][ 1 ] ).to.equal( type );
+			expect( changeCallback.args[ 0 ][ 2 ] ).to.equal( data );
+			expect( changeCallback.args[ 0 ][ 3 ] ).to.equal( batch );
+		} );
+
+		it( 'should throw an error on the operation base version and the document version is different', () => {
+			let operation = {
+				baseVersion: 1
+			};
+
+			expect(
+				() => {
+					doc.applyOperation( operation );
+				}
+			).to.throw( CKEditorError, /document-applyOperation-wrong-version/ );
+		} );
+	} );
+
+	describe( 'batch', () => {
+		it( 'should create a new batch with the document property', () => {
+			const batch = doc.batch();
+
+			expect( batch ).to.be.instanceof( Batch );
+			expect( batch ).to.have.property( 'doc' ).that.equals( doc );
+		} );
+	} );
+
+	describe( 'enqueue', () => {
+		it( 'should be executed immediately and fire changesDone event', () => {
+			let order = [];
+
+			doc.on( 'changesDone', () => order.push( 'done' ) );
+
+			doc.enqueueChanges( () => order.push( 'enqueue1' ) );
+
+			expect( order ).to.have.length( 2 );
+			expect( order[ 0 ] ).to.equal( 'enqueue1' );
+			expect( order[ 1 ] ).to.equal( 'done' );
+		} );
+
+		it( 'should fire done every time queue is empty', () => {
+			let order = [];
+
+			doc.on( 'changesDone', () => order.push( 'done' ) );
+
+			doc.enqueueChanges( () => order.push( 'enqueue1' ) );
+			doc.enqueueChanges( () => order.push( 'enqueue2' ) );
+
+			expect( order ).to.have.length( 4 );
+			expect( order[ 0 ] ).to.equal( 'enqueue1' );
+			expect( order[ 1 ] ).to.equal( 'done' );
+			expect( order[ 2 ] ).to.equal( 'enqueue2' );
+			expect( order[ 3 ] ).to.equal( 'done' );
+		} );
+
+		it( 'should put callbacks in the proper order', () => {
+			let order = [];
+
+			doc.on( 'changesDone', () => order.push( 'done' ) );
+
+			doc.enqueueChanges( () => {
+				order.push( 'enqueue1 start' );
+				doc.enqueueChanges( () => {
+					order.push( 'enqueue2 start' );
+					doc.enqueueChanges( () => order.push( 'enqueue4' ) );
+					order.push( 'enqueue2 end' );
+				} );
+
+				doc.enqueueChanges( () => order.push( 'enqueue3' ) );
+
+				order.push( 'enqueue1 end' );
+			} );
+
+			expect( order ).to.have.length( 7 );
+			expect( order[ 0 ] ).to.equal( 'enqueue1 start' );
+			expect( order[ 1 ] ).to.equal( 'enqueue1 end' );
+			expect( order[ 2 ] ).to.equal( 'enqueue2 start' );
+			expect( order[ 3 ] ).to.equal( 'enqueue2 end' );
+			expect( order[ 4 ] ).to.equal( 'enqueue3' );
+			expect( order[ 5 ] ).to.equal( 'enqueue4' );
+			expect( order[ 6 ] ).to.equal( 'done' );
+		} );
+	} );
+} );

+ 9 - 9
packages/ckeditor5-engine/tests/document/element.js → packages/ckeditor5-engine/tests/treemodel/element.js

@@ -5,7 +5,7 @@
 
 /* jshint expr: true */
 
-/* bender-tags: document */
+/* bender-tags: treemodel */
 
 /* bender-include: ../_tools/tools.js */
 
@@ -14,20 +14,20 @@
 const getIteratorCount = bender.tools.core.getIteratorCount;
 
 const modules = bender.amd.require(
-	'document/node',
-	'document/nodelist',
-	'document/element',
-	'document/attribute'
+	'treemodel/node',
+	'treemodel/nodelist',
+	'treemodel/element',
+	'treemodel/attribute'
 );
 
 describe( 'Element', () => {
 	let Element, Node, NodeList, Attribute;
 
 	before( () => {
-		Element = modules[ 'document/element' ];
-		Node = modules[ 'document/node' ];
-		NodeList = modules[ 'document/nodelist' ];
-		Attribute = modules[ 'document/attribute' ];
+		Element = modules[ 'treemodel/element' ];
+		Node = modules[ 'treemodel/node' ];
+		NodeList = modules[ 'treemodel/nodelist' ];
+		Attribute = modules[ 'treemodel/attribute' ];
 	} );
 
 	describe( 'constructor', () => {

+ 9 - 9
packages/ckeditor5-engine/tests/document/node.js → packages/ckeditor5-engine/tests/treemodel/node.js

@@ -3,7 +3,7 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document */
+/* bender-tags: treemodel */
 
 /* bender-include: ../_tools/tools.js */
 
@@ -12,10 +12,10 @@
 const getIteratorCount = bender.tools.core.getIteratorCount;
 
 const modules = bender.amd.require(
-	'document/element',
-	'document/character',
-	'document/attribute',
-	'document/nodelist',
+	'treemodel/element',
+	'treemodel/character',
+	'treemodel/attribute',
+	'treemodel/nodelist',
 	'ckeditorerror'
 );
 
@@ -27,10 +27,10 @@ describe( 'Node', () => {
 	let charB, charA, charR, img;
 
 	before( () => {
-		Element = modules[ 'document/element' ];
-		Character = modules[ 'document/character' ];
-		Attribute = modules[ 'document/attribute' ];
-		NodeList = modules[ 'document/nodelist' ];
+		Element = modules[ 'treemodel/element' ];
+		Character = modules[ 'treemodel/character' ];
+		Attribute = modules[ 'treemodel/attribute' ];
+		NodeList = modules[ 'treemodel/nodelist' ];
 		CKEditorError = modules.ckeditorerror;
 
 		charB = new Character( 'b' );

+ 9 - 9
packages/ckeditor5-engine/tests/document/nodelist.js → packages/ckeditor5-engine/tests/treemodel/nodelist.js

@@ -3,25 +3,25 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document */
+/* bender-tags: treemodel */
 
 'use strict';
 
 const modules = bender.amd.require(
-	'document/nodelist',
-	'document/character',
-	'document/text',
-	'document/attribute'
+	'treemodel/nodelist',
+	'treemodel/character',
+	'treemodel/text',
+	'treemodel/attribute'
 );
 
 describe( 'NodeList', () => {
 	let NodeList, Character, Text, Attribute;
 
 	before( () => {
-		NodeList = modules[ 'document/nodelist' ];
-		Character = modules[ 'document/character' ];
-		Text = modules[ 'document/text' ];
-		Attribute = modules[ 'document/attribute' ];
+		NodeList = modules[ 'treemodel/nodelist' ];
+		Character = modules[ 'treemodel/character' ];
+		Text = modules[ 'treemodel/text' ];
+		Attribute = modules[ 'treemodel/attribute' ];
 	} );
 
 	describe( 'constructor', () => {

+ 141 - 75
packages/ckeditor5-engine/tests/document/operation/changeoperation.js → packages/ckeditor5-engine/tests/treemodel/operation/attributeoperation.js

@@ -3,7 +3,8 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document */
+/* bender-tags: treemodel, operation */
+/* global describe, before, beforeEach, it, expect */
 
 /* bender-include: ../../_tools/tools.js */
 
@@ -12,29 +13,29 @@
 const getIteratorCount = bender.tools.core.getIteratorCount;
 
 const modules = bender.amd.require(
-	'document/document',
-	'document/operation/changeoperation',
-	'document/position',
-	'document/range',
-	'document/character',
-	'document/attribute',
-	'document/nodelist',
-	'document/text',
+	'treemodel/document',
+	'treemodel/element',
+	'treemodel/operation/attributeoperation',
+	'treemodel/position',
+	'treemodel/range',
+	'treemodel/character',
+	'treemodel/attribute',
+	'treemodel/text',
 	'ckeditorerror'
 );
 
-describe( 'ChangeOperation', () => {
-	let Document, ChangeOperation, Position, Range, Character, Attribute, NodeList, Text, CKEditorError;
+describe( 'AttributeOperation', () => {
+	let Document, Element, AttributeOperation, Position, Range, Character, Attribute, Text, CKEditorError;
 
 	before( () => {
-		Document = modules[ 'document/document' ];
-		ChangeOperation = modules[ 'document/operation/changeoperation' ];
-		Position = modules[ 'document/position' ];
-		Range = modules[ 'document/range' ];
-		Character = modules[ 'document/character' ];
-		Attribute = modules[ 'document/attribute' ];
-		NodeList = modules[ 'document/nodelist' ];
-		Text = modules[ 'document/text' ];
+		Document = modules[ 'treemodel/document' ];
+		Element = modules[ 'treemodel/element' ];
+		AttributeOperation = modules[ 'treemodel/operation/attributeoperation' ];
+		Position = modules[ 'treemodel/position' ];
+		Range = modules[ 'treemodel/range' ];
+		Character = modules[ 'treemodel/character' ];
+		Attribute = modules[ 'treemodel/attribute' ];
+		Text = modules[ 'treemodel/text' ];
 		CKEditorError = modules.ckeditorerror;
 	} );
 
@@ -45,14 +46,25 @@ describe( 'ChangeOperation', () => {
 		root = doc.createRoot( 'root' );
 	} );
 
+	it( 'should have proper type', () => {
+		const op = new AttributeOperation(
+			new Range( new Position( root, [ 0 ] ), new Position( root, [ 2 ] ) ),
+			null,
+			new Attribute( 'isNew', true ),
+			doc.version
+		);
+
+		expect( op.type ).to.equal( 'attr' );
+	} );
+
 	it( 'should insert attribute to the set of nodes', () => {
 		let newAttr = new Attribute( 'isNew', true );
 
 		root.insertChildren( 0, 'bar' );
 
 		doc.applyOperation(
-			new ChangeOperation(
-				new Range( new Position( [ 0 ], root ), new Position( [ 2 ], root ) ),
+			new AttributeOperation(
+				new Range( new Position( root, [ 0 ] ), new Position( root, [ 2 ] ) ),
 				null,
 				newAttr,
 				doc.version
@@ -74,8 +86,8 @@ describe( 'ChangeOperation', () => {
 		root.insertChildren( 0, new Character( 'x', [ fooAttr, barAttr ] ) );
 
 		doc.applyOperation(
-			new ChangeOperation(
-				new Range( new Position( [ 0 ], root ), new Position( [ 1 ], root ) ),
+			new AttributeOperation(
+				new Range( new Position( root, [ 0 ] ), new Position( root, [ 1 ] ) ),
 				null,
 				newAttr,
 				doc.version
@@ -97,8 +109,8 @@ describe( 'ChangeOperation', () => {
 		root.insertChildren( 0, new Text( 'bar', [ oldAttr ] ) );
 
 		doc.applyOperation(
-			new ChangeOperation(
-				new Range( new Position( [ 0 ], root ), new Position( [ 2 ], root ) ),
+			new AttributeOperation(
+				new Range( new Position( root, [ 0 ] ), new Position( root, [ 2 ] ) ),
 				oldAttr,
 				newAttr,
 				doc.version
@@ -124,8 +136,8 @@ describe( 'ChangeOperation', () => {
 		root.insertChildren( 0, new Character( 'x', [ fooAttr, x1Attr, barAttr ] ) );
 
 		doc.applyOperation(
-			new ChangeOperation(
-				new Range( new Position( [ 0 ], root ), new Position( [ 1 ], root ) ),
+			new AttributeOperation(
+				new Range( new Position( root, [ 0 ] ), new Position( root, [ 1 ] ) ),
 				x1Attr,
 				x2Attr,
 				doc.version
@@ -148,8 +160,8 @@ describe( 'ChangeOperation', () => {
 		root.insertChildren( 0, new Character( 'x', [ fooAttr, xAttr, barAttr ] ) );
 
 		doc.applyOperation(
-			new ChangeOperation(
-				new Range( new Position( [ 0 ], root ), new Position( [ 1 ], root ) ),
+			new AttributeOperation(
+				new Range( new Position( root, [ 0 ] ), new Position( root, [ 1 ] ) ),
 				xAttr,
 				null,
 				doc.version
@@ -163,14 +175,14 @@ describe( 'ChangeOperation', () => {
 		expect( root.getChild( 0 ).hasAttr( barAttr ) ).to.be.true;
 	} );
 
-	it( 'should create a change operation as a reverse', () => {
+	it( 'should create an AttributeOperation as a reverse', () => {
 		let oldAttr = new Attribute( 'x', 'old' );
 		let newAttr = new Attribute( 'x', 'new' );
-		let range = new Range( new Position( [ 0 ], root ), new Position( [ 3 ], root ) );
-		let operation = new ChangeOperation( range, oldAttr, newAttr, doc.version );
+		let range = new Range( new Position( root, [ 0 ] ), new Position( root, [ 3 ] ) );
+		let operation = new AttributeOperation( range, oldAttr, newAttr, doc.version );
 		let reverse = operation.getReversed();
 
-		expect( reverse ).to.be.an.instanceof( ChangeOperation );
+		expect( reverse ).to.be.an.instanceof( AttributeOperation );
 		expect( reverse.baseVersion ).to.equal( 1 );
 		expect( reverse.range ).to.equal( range );
 		expect( reverse.oldAttr ).to.equal( newAttr );
@@ -182,8 +194,8 @@ describe( 'ChangeOperation', () => {
 
 		root.insertChildren( 0, 'bar' );
 
-		let operation = new ChangeOperation(
-			new Range( new Position( [ 0 ], root ), new Position( [ 3 ], root ) ),
+		let operation = new AttributeOperation(
+			new Range( new Position( root, [ 0 ] ), new Position( root, [ 3 ] ) ),
 			null,
 			newAttr,
 			doc.version
@@ -201,14 +213,54 @@ describe( 'ChangeOperation', () => {
 		expect( getIteratorCount( root.getChild( 2 ).getAttrs() ) ).to.equal( 0 );
 	} );
 
+	it( 'should not set attribute of element if change range starts in the middle of that element', () => {
+		let fooAttr = new Attribute( 'foo', true );
+
+		let eleA = new Element( 'a', [], 'abc' );
+		let eleB = new Element( 'b', [], 'xyz' );
+
+		root.insertChildren( 0, [ eleA, eleB ] );
+
+		doc.applyOperation(
+			new AttributeOperation(
+				new Range( new Position( root, [ 0, 2 ] ), new Position( root, [ 1, 2 ] ) ),
+				null,
+				fooAttr,
+				doc.version
+			)
+		);
+
+		expect( root.getChild( 0 ).hasAttr( fooAttr ) ).to.be.false;
+	} );
+
+	it( 'should not remove attribute of element if change range starts in the middle of that element', () => {
+		let fooAttr = new Attribute( 'foo', true );
+
+		let eleA = new Element( 'a', [ fooAttr ], 'abc' );
+		let eleB = new Element( 'b', [ fooAttr ], 'xyz' );
+
+		root.insertChildren( 0, [ eleA, eleB ] );
+
+		doc.applyOperation(
+			new AttributeOperation(
+				new Range( new Position( root, [ 0, 3 ] ), new Position( root, [ 1, 0 ] ) ),
+				fooAttr,
+				null,
+				doc.version
+			)
+		);
+
+		expect( root.getChild( 0 ).hasAttr( fooAttr ) ).to.be.true;
+	} );
+
 	it( 'should undo changing attribute by applying reverse operation', () => {
 		let oldAttr = new Attribute( 'isNew', false );
 		let newAttr = new Attribute( 'isNew', true );
 
 		root.insertChildren( 0, new Text( 'bar', [ oldAttr ] ) );
 
-		let operation = new ChangeOperation(
-			new Range( new Position( [ 0 ], root ), new Position( [ 3 ], root ) ),
+		let operation = new AttributeOperation(
+			new Range( new Position( root, [ 0 ] ), new Position( root, [ 3 ] ) ),
 			oldAttr,
 			newAttr,
 			doc.version
@@ -235,8 +287,8 @@ describe( 'ChangeOperation', () => {
 
 		root.insertChildren( 0, new Text( 'bar', [ fooAttr ] ) );
 
-		let operation = new ChangeOperation(
-			new Range( new Position( [ 0 ], root ), new Position( [ 3 ], root ) ),
+		let operation = new AttributeOperation(
+			new Range( new Position( root, [ 0 ] ), new Position( root, [ 3 ] ) ),
 			fooAttr,
 			null,
 			doc.version
@@ -263,18 +315,16 @@ describe( 'ChangeOperation', () => {
 
 		root.insertChildren( 0, 'x' );
 
-		expect(
-			() => {
-				doc.applyOperation(
-					new ChangeOperation(
-						new Range( new Position( [ 0 ], root ), new Position( [ 1 ], root ) ),
-						fooAttr,
-						null,
-						doc.version
-					)
-				);
-			}
-		).to.throw( CKEditorError, /operation-change-no-attr-to-remove/ );
+		expect( () => {
+			doc.applyOperation(
+				new AttributeOperation(
+					new Range( new Position( root, [ 0 ] ), new Position( root, [ 1 ] ) ),
+					fooAttr,
+					null,
+					doc.version
+				)
+			);
+		} ).to.throw( CKEditorError, /operation-attribute-no-attr-to-remove/ );
 	} );
 
 	it( 'should throw an error when one try to insert and the attribute already exists', () => {
@@ -283,18 +333,16 @@ describe( 'ChangeOperation', () => {
 
 		root.insertChildren( 0, new Character( 'x', [ x1Attr ] ) );
 
-		expect(
-			() => {
-				doc.applyOperation(
-					new ChangeOperation(
-						new Range( new Position( [ 0 ], root ), new Position( [ 1 ], root ) ),
-						null,
-						x2Attr,
-						doc.version
-					)
-				);
-			}
-		).to.throw( CKEditorError, /operation-change-attr-exists/ );
+		expect( () => {
+			doc.applyOperation(
+				new AttributeOperation(
+					new Range( new Position( root, [ 0 ] ), new Position( root, [ 1 ] ) ),
+					null,
+					x2Attr,
+					doc.version
+				)
+			);
+		} ).to.throw( CKEditorError, /operation-attribute-attr-exists/ );
 	} );
 
 	it( 'should throw an error when one try to change and the new and old attributes have different keys', () => {
@@ -303,17 +351,35 @@ describe( 'ChangeOperation', () => {
 
 		root.insertChildren( 0, 'x' );
 
-		expect(
-			() => {
-				doc.applyOperation(
-					new ChangeOperation(
-						new Range( new Position( [ 0 ], root ), new Position( [ 1 ], root ) ),
-						fooAttr,
-						barAttr,
-						doc.version
-					)
-				);
-			}
-		).to.throw( CKEditorError, /operation-change-different-keys/ );
+		expect( () => {
+			doc.applyOperation(
+				new AttributeOperation(
+					new Range( new Position( root, [ 0 ] ), new Position( root, [ 1 ] ) ),
+					fooAttr,
+					barAttr,
+					doc.version
+				)
+			);
+		} ).to.throw( CKEditorError, /operation-attribute-different-keys/ );
+	} );
+
+	it( 'should create an AttributeOperation with the same parameters when cloned', () => {
+		let range = new Range( new Position( root, [ 0 ] ), new Position( root, [ 1 ] ) );
+		let oldAttr = new Attribute( 'foo', 'old' );
+		let newAttr = new Attribute( 'foo', 'bar' );
+		let baseVersion = doc.version;
+
+		let op = new AttributeOperation( range, oldAttr, newAttr, baseVersion );
+
+		let clone = op.clone();
+
+		// New instance rather than a pointer to the old instance.
+		expect( clone ).not.to.be.equal( op );
+
+		expect( clone ).to.be.instanceof( AttributeOperation );
+		expect( clone.range.isEqual( range ) ).to.be.true;
+		expect( clone.oldAttr.isEqual( oldAttr ) ).to.be.true;
+		expect( clone.newAttr.isEqual( newAttr ) ).to.be.true;
+		expect( clone.baseVersion ).to.equal( baseVersion );
 	} );
 } );

+ 57 - 20
packages/ckeditor5-engine/tests/document/operation/insertoperation.js → packages/ckeditor5-engine/tests/treemodel/operation/insertoperation.js

@@ -3,28 +3,33 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document */
+/* bender-tags: treemodel, operation */
+/* global describe, before, beforeEach, it, expect */
 
 'use strict';
 
 const modules = bender.amd.require(
-	'document/document',
-	'document/operation/insertoperation',
-	'document/operation/removeoperation',
-	'document/position',
-	'document/character',
-	'document/nodelist'
+	'treemodel/document',
+	'treemodel/node',
+	'treemodel/nodelist',
+	'treemodel/operation/insertoperation',
+	'treemodel/operation/removeoperation',
+	'treemodel/position',
+	'treemodel/character',
+	'treemodel/nodelist'
 );
 
 describe( 'InsertOperation', () => {
-	let Document, InsertOperation, RemoveOperation, Position, Character;
+	let Document, Node, NodeList, InsertOperation, RemoveOperation, Position, Character;
 
 	before( () => {
-		Document = modules[ 'document/document' ];
-		InsertOperation = modules[ 'document/operation/insertoperation' ];
-		RemoveOperation = modules[ 'document/operation/removeoperation' ];
-		Position = modules[ 'document/position' ];
-		Character = modules[ 'document/character' ];
+		Document = modules[ 'treemodel/document' ];
+		Node = modules[ 'treemodel/node' ];
+		NodeList = modules[ 'treemodel/nodelist' ];
+		InsertOperation = modules[ 'treemodel/operation/insertoperation' ];
+		RemoveOperation = modules[ 'treemodel/operation/removeoperation' ];
+		Position = modules[ 'treemodel/position' ];
+		Character = modules[ 'treemodel/character' ];
 	} );
 
 	let doc, root;
@@ -34,10 +39,20 @@ describe( 'InsertOperation', () => {
 		root = doc.createRoot( 'root' );
 	} );
 
+	it( 'should have proper type', () => {
+		const opp = new InsertOperation(
+			new Position( root, [ 0 ] ),
+			new Character( 'x' ),
+			doc.version
+		);
+
+		expect( opp.type ).to.equal( 'insert' );
+	} );
+
 	it( 'should insert node', () => {
 		doc.applyOperation(
 			new InsertOperation(
-				new Position( [ 0 ], root ),
+				new Position( root, [ 0 ] ),
 				new Character( 'x' ),
 				doc.version
 			)
@@ -51,7 +66,7 @@ describe( 'InsertOperation', () => {
 	it( 'should insert set of nodes', () => {
 		doc.applyOperation(
 			new InsertOperation(
-				new Position( [ 0 ], root ),
+				new Position( root, [ 0 ] ),
 				'bar',
 				doc.version
 			)
@@ -69,7 +84,7 @@ describe( 'InsertOperation', () => {
 
 		doc.applyOperation(
 			new InsertOperation(
-				new Position( [ 1 ], root ),
+				new Position( root, [ 1 ] ),
 				'bar',
 				doc.version
 			)
@@ -87,7 +102,7 @@ describe( 'InsertOperation', () => {
 	it( 'should insert text', () => {
 		doc.applyOperation(
 			new InsertOperation(
-				new Position( [ 0 ], root ),
+				new Position( root, [ 0 ] ),
 				[ 'foo', new Character( 'x' ), 'bar' ],
 				doc.version
 			)
@@ -105,7 +120,7 @@ describe( 'InsertOperation', () => {
 	} );
 
 	it( 'should create a remove operation as a reverse', () => {
-		let position = new Position( [ 0 ], root );
+		let position = new Position( root, [ 0 ] );
 		let operation = new InsertOperation(
 			position,
 			[ 'foo', new Character( 'x' ), 'bar' ],
@@ -122,7 +137,7 @@ describe( 'InsertOperation', () => {
 
 	it( 'should undo insert node by applying reverse operation', () => {
 		let operation = new InsertOperation(
-			new Position( [ 0 ], root ),
+			new Position( root, [ 0 ] ),
 			new Character( 'x' ),
 			doc.version
 		);
@@ -141,7 +156,7 @@ describe( 'InsertOperation', () => {
 
 	it( 'should undo insert set of nodes by applying reverse operation', () => {
 		let operation = new InsertOperation(
-			new Position( [ 0 ], root ),
+			new Position( root, [ 0 ] ),
 			'bar',
 			doc.version
 		);
@@ -157,4 +172,26 @@ describe( 'InsertOperation', () => {
 		expect( doc.version ).to.equal( 2 );
 		expect( root.getChildCount() ).to.equal( 0 );
 	} );
+
+	it( 'should create operation with the same parameters when cloned', () => {
+		let position = new Position( root, [ 0 ] );
+		let nodeA = new Node();
+		let nodeB = new Node();
+		let nodes = new NodeList( [ nodeA, nodeB ] );
+		let baseVersion = doc.version;
+
+		let op = new InsertOperation( position, nodes, baseVersion );
+
+		let clone = op.clone();
+
+		// New instance rather than a pointer to the old instance.
+		expect( clone ).not.to.be.equal( op );
+
+		expect( clone ).to.be.instanceof( InsertOperation );
+		expect( clone.position.isEqual( position ) ).to.be.true;
+		expect( clone.nodeList.get( 0 ) ).to.equal( nodeA );
+		expect( clone.nodeList.get( 1 ) ).to.equal( nodeB );
+		expect( clone.nodeList.length ).to.equal( 2 );
+		expect( clone.baseVersion ).to.equal( baseVersion );
+	} );
 } );

+ 75 - 59
packages/ckeditor5-engine/tests/document/operation/moveoperation.js → packages/ckeditor5-engine/tests/treemodel/operation/moveoperation.js

@@ -3,16 +3,17 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document */
+/* bender-tags: treemodel, operation */
+/* global describe, before, beforeEach, it, expect */
 
 'use strict';
 
 const modules = bender.amd.require(
-	'document/document',
-	'document/operation/moveoperation',
-	'document/position',
-	'document/element',
-	'document/nodelist',
+	'treemodel/document',
+	'treemodel/operation/moveoperation',
+	'treemodel/position',
+	'treemodel/element',
+	'treemodel/nodelist',
 	'ckeditorerror'
 );
 
@@ -20,11 +21,11 @@ describe( 'MoveOperation', () => {
 	let Document, MoveOperation, Position, Element, NodeList, CKEditorError;
 
 	before( () => {
-		Document = modules[ 'document/document' ];
-		MoveOperation = modules[ 'document/operation/moveoperation' ];
-		Position = modules[ 'document/position' ];
-		Element = modules[ 'document/element' ];
-		NodeList = modules[ 'document/nodelist' ];
+		Document = modules[ 'treemodel/document' ];
+		MoveOperation = modules[ 'treemodel/operation/moveoperation' ];
+		Position = modules[ 'treemodel/position' ];
+		Element = modules[ 'treemodel/element' ];
+		NodeList = modules[ 'treemodel/nodelist' ];
 		CKEditorError = modules.ckeditorerror;
 	} );
 
@@ -35,6 +36,17 @@ describe( 'MoveOperation', () => {
 		root = doc.createRoot( 'root' );
 	} );
 
+	it( 'should have proper type', () => {
+		const opp = new MoveOperation(
+			new Position( root, [ 0, 0 ] ),
+			new Position( root, [ 1, 0 ] ),
+			1,
+			doc.version
+		);
+
+		expect( opp.type ).to.equal( 'move' );
+	} );
+
 	it( 'should move from one node to another', () => {
 		let p1 = new Element( 'p1', [], new Element( 'x' ) );
 		let p2 = new Element( 'p2' );
@@ -43,9 +55,9 @@ describe( 'MoveOperation', () => {
 
 		doc.applyOperation(
 			new MoveOperation(
-				new Position( [ 0, 0 ], root ),
-				new Position( [ 1, 0 ], root ),
+				new Position( root, [ 0, 0 ] ),
 				1,
+				new Position( root, [ 1, 0 ] ),
 				doc.version
 			)
 		);
@@ -64,9 +76,9 @@ describe( 'MoveOperation', () => {
 
 		doc.applyOperation(
 			new MoveOperation(
-				new Position( [ 2 ], root ),
-				new Position( [ 1 ], root ),
+				new Position( root, [ 2 ] ),
 				2,
+				new Position( root, [ 1 ] ),
 				doc.version
 			)
 		);
@@ -85,9 +97,9 @@ describe( 'MoveOperation', () => {
 
 		doc.applyOperation(
 			new MoveOperation(
-				new Position( [ 1 ], root ),
-				new Position( [ 4 ], root ),
+				new Position( root, [ 1 ] ),
 				2,
+				new Position( root, [ 4 ] ),
 				doc.version
 			)
 		);
@@ -104,18 +116,18 @@ describe( 'MoveOperation', () => {
 	it( 'should create a move operation as a reverse', () => {
 		let nodeList = new NodeList( 'bar' );
 
-		let sourcePosition = new Position( [ 0 ], root );
-		let targetPosition = new Position( [ 4 ], root );
+		let sourcePosition = new Position( root, [ 0 ] );
+		let targetPosition = new Position( root, [ 4 ] );
 
-		let operation = new MoveOperation( sourcePosition, targetPosition, nodeList.length, doc.version );
+		let operation = new MoveOperation( sourcePosition, nodeList.length, targetPosition, doc.version );
 
 		let reverse = operation.getReversed();
 
 		expect( reverse ).to.be.an.instanceof( MoveOperation );
 		expect( reverse.baseVersion ).to.equal( 1 );
 		expect( reverse.howMany ).to.equal( nodeList.length );
-		expect( reverse.sourcePosition ).to.equal( targetPosition );
-		expect( reverse.targetPosition ).to.equal( sourcePosition );
+		expect( reverse.sourcePosition.isEqual( targetPosition ) ).to.be.true;
+		expect( reverse.targetPosition.isEqual( sourcePosition ) ).to.be.true;
 	} );
 
 	it( 'should undo move node by applying reverse operation', () => {
@@ -125,9 +137,9 @@ describe( 'MoveOperation', () => {
 		root.insertChildren( 0, [ p1, p2 ] );
 
 		let operation = new MoveOperation(
-			new Position( [ 0, 0 ], root ),
-			new Position( [ 1, 0 ], root ),
+			new Position( root, [ 0, 0 ] ),
 			1,
+			new Position( root, [ 1, 0 ] ),
 			doc.version
 		);
 
@@ -151,18 +163,14 @@ describe( 'MoveOperation', () => {
 	it( 'should throw an error if number of nodes to move exceeds the number of existing nodes in given element', () => {
 		root.insertChildren( 0, 'xbarx' );
 
-		expect(
-			() => {
-				doc.applyOperation(
-					new MoveOperation(
-						new Position( [ 3 ], root ),
-						new Position( [ 1 ], root ),
-						3,
-						doc.version
-					)
-				);
-			}
-		).to.throw( CKEditorError, /operation-move-nodes-do-not-exist/ );
+		let operation = new MoveOperation(
+			new Position( root, [ 3 ] ),
+			3,
+			new Position( root, [ 1 ] ),
+			doc.version
+		);
+
+		expect( () => doc.applyOperation( operation ) ).to.throw( CKEditorError, /operation-move-nodes-do-not-exist/ );
 	} );
 
 	it( 'should throw an error if target or source parent-element specified by position does not exist', () => {
@@ -171,36 +179,28 @@ describe( 'MoveOperation', () => {
 		root.insertChildren( 0, [ 'ab', p ] );
 
 		let operation = new MoveOperation(
-			new Position( [ 2, 0 ], root ),
-			new Position( [ 1 ], root ),
+			new Position( root, [ 2, 0 ] ),
 			3,
+			new Position( root, [ 1 ] ),
 			doc.version
 		);
 
 		root.removeChildren( 2, 1 );
 
-		expect(
-			() => {
-				doc.applyOperation( operation );
-			}
-		).to.throw( CKEditorError, /operation-move-position-invalid/ );
+		expect( () => doc.applyOperation( operation ) ).to.throw( CKEditorError, /operation-move-position-invalid/ );
 	} );
 
 	it( 'should throw an error if operation tries to move a range between the beginning and the end of that range', () => {
 		root.insertChildren( 0, 'xbarx' );
 
 		let operation = new MoveOperation(
-			new Position( [ 1 ], root ),
-			new Position( [ 2 ], root ),
+			new Position( root, [ 1 ] ),
 			3,
+			new Position( root, [ 2 ] ),
 			doc.version
 		);
 
-		expect(
-			() => {
-				doc.applyOperation( operation );
-			}
-		).to.throw( CKEditorError, /operation-move-range-into-itself/ );
+		expect( () => doc.applyOperation( operation ) ).to.throw( CKEditorError, /operation-move-range-into-itself/ );
 	} );
 
 	it( 'should throw an error if operation tries to move a range into a sub-tree of a node that is in that range', () => {
@@ -208,17 +208,13 @@ describe( 'MoveOperation', () => {
 		root.insertChildren( 0, [ 'ab', p, 'xy' ] );
 
 		let operation = new MoveOperation(
-			new Position( [ 1 ], root ),
-			new Position( [ 2, 0, 0 ], root ),
+			new Position( root, [ 1 ] ),
 			3,
+			new Position( root, [ 2, 0, 0 ] ),
 			doc.version
 		);
 
-		expect(
-			() => {
-				doc.applyOperation( operation );
-			}
-		).to.throw( CKEditorError, /operation-move-node-into-itself/ );
+		expect( () => doc.applyOperation( operation ) ).to.throw( CKEditorError, /operation-move-node-into-itself/ );
 	} );
 
 	it( 'should not throw an error if operation move a range into a sibling', () => {
@@ -226,9 +222,9 @@ describe( 'MoveOperation', () => {
 		root.insertChildren( 0, [ 'ab', p, 'xy' ] );
 
 		let operation = new MoveOperation(
-			new Position( [ 1 ], root ),
-			new Position( [ 2, 0 ], root ),
+			new Position( root, [ 1 ] ),
 			1,
+			new Position( root, [ 2, 0 ] ),
 			doc.version
 		);
 
@@ -242,4 +238,24 @@ describe( 'MoveOperation', () => {
 		expect( p.getChildCount() ).to.equal( 1 );
 		expect( p.getChild( 0 ).character ).to.equal( 'b' );
 	} );
+
+	it( 'should create operation with the same parameters when cloned', () => {
+		let sourcePosition = new Position( root, [ 0 ] );
+		let targetPosition = new Position( root, [ 1 ] );
+		let howMany = 4;
+		let baseVersion = doc.version;
+
+		let op = new MoveOperation( sourcePosition, howMany, targetPosition, baseVersion );
+
+		let clone = op.clone();
+
+		// New instance rather than a pointer to the old instance.
+		expect( clone ).not.to.be.equal( op );
+
+		expect( clone ).to.be.instanceof( MoveOperation );
+		expect( clone.sourcePosition.isEqual( sourcePosition ) ).to.be.true;
+		expect( clone.targetPosition.isEqual( targetPosition ) ).to.be.true;
+		expect( clone.howMany ).to.equal( howMany );
+		expect( clone.baseVersion ).to.equal( baseVersion );
+	} );
 } );

+ 48 - 0
packages/ckeditor5-engine/tests/treemodel/operation/nooperation.js

@@ -0,0 +1,48 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/* bender-tags: treemodel, operation */
+
+'use strict';
+
+const modules = bender.amd.require(
+	'treemodel/document',
+	'treemodel/operation/nooperation'
+);
+
+describe( 'NoOperation', () => {
+	let Document, NoOperation;
+
+	before( function() {
+		Document = modules[ 'treemodel/document' ];
+		NoOperation = modules[ 'treemodel/operation/nooperation' ];
+	} );
+
+	let noop, doc, root;
+
+	beforeEach( () => {
+		noop = new NoOperation( 0 );
+		doc = new Document();
+		root = doc.createRoot( 'root' );
+	} );
+
+	it( 'should not throw an error when applied', () => {
+		expect( () => doc.applyOperation( noop ) ).to.not.throw( Error );
+	} );
+
+	it( 'should create a do-nothing operation as a reverse', () => {
+		const reverse = noop.getReversed();
+
+		expect( reverse ).to.be.an.instanceof( NoOperation );
+		expect( reverse.baseVersion ).to.equal( 1 );
+	} );
+
+	it( 'should create a do-nothing operation having same parameters when cloned', () => {
+		const clone = noop.clone();
+
+		expect( clone ).to.be.an.instanceof( NoOperation );
+		expect( clone.baseVersion ).to.equal( 0 );
+	} );
+} );

+ 19 - 15
packages/ckeditor5-engine/tests/document/operation/reinsertoperation.js → packages/ckeditor5-engine/tests/treemodel/operation/reinsertoperation.js

@@ -3,27 +3,27 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document */
+/* bender-tags: treemodel, operation */
 
 'use strict';
 
 const modules = bender.amd.require(
-	'document/document',
-	'document/operation/reinsertoperation',
-	'document/operation/removeoperation',
-	'document/operation/moveoperation',
-	'document/position'
+	'treemodel/document',
+	'treemodel/operation/reinsertoperation',
+	'treemodel/operation/removeoperation',
+	'treemodel/operation/moveoperation',
+	'treemodel/position'
 );
 
 describe( 'ReinsertOperation', () => {
 	let Document, ReinsertOperation, RemoveOperation, MoveOperation, Position;
 
 	before( () => {
-		Document = modules[ 'document/document' ];
-		ReinsertOperation = modules[ 'document/operation/reinsertoperation' ];
-		RemoveOperation = modules[ 'document/operation/removeoperation' ];
-		MoveOperation = modules[ 'document/operation/moveoperation' ];
-		Position = modules[ 'document/position' ];
+		Document = modules[ 'treemodel/document' ];
+		ReinsertOperation = modules[ 'treemodel/operation/reinsertoperation' ];
+		RemoveOperation = modules[ 'treemodel/operation/removeoperation' ];
+		MoveOperation = modules[ 'treemodel/operation/moveoperation' ];
+		Position = modules[ 'treemodel/position' ];
 	} );
 
 	let doc, root, graveyard, operation, graveyardPosition, rootPosition;
@@ -31,19 +31,23 @@ describe( 'ReinsertOperation', () => {
 	beforeEach( () => {
 		doc = new Document();
 		root = doc.createRoot( 'root' );
-		graveyard = doc._graveyard;
+		graveyard = doc.graveyard;
 
-		graveyardPosition = new Position( [ 0 ], graveyard );
-		rootPosition = new Position( [ 0 ], root );
+		graveyardPosition = new Position( graveyard, [ 0 ] );
+		rootPosition = new Position( root, [ 0 ] );
 
 		operation = new ReinsertOperation(
 			graveyardPosition,
-			rootPosition,
 			2,
+			rootPosition,
 			doc.version
 		);
 	} );
 
+	it( 'should have proper type', () => {
+		expect( operation.type ).to.equal( 'reinsert' );
+	} );
+
 	it( 'should extend MoveOperation class', () => {
 		expect( operation ).to.be.instanceof( MoveOperation );
 	} );

+ 26 - 16
packages/ckeditor5-engine/tests/document/operation/removeoperation.js → packages/ckeditor5-engine/tests/treemodel/operation/removeoperation.js

@@ -3,27 +3,27 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document */
+/* bender-tags: treemodel, operation */
 
 'use strict';
 
 const modules = bender.amd.require(
-	'document/document',
-	'document/operation/reinsertoperation',
-	'document/operation/removeoperation',
-	'document/operation/moveoperation',
-	'document/position'
+	'treemodel/document',
+	'treemodel/operation/reinsertoperation',
+	'treemodel/operation/removeoperation',
+	'treemodel/operation/moveoperation',
+	'treemodel/position'
 );
 
 describe( 'RemoveOperation', () => {
 	let Document, ReinsertOperation, RemoveOperation, MoveOperation, Position;
 
 	before( () => {
-		Document = modules[ 'document/document' ];
-		ReinsertOperation = modules[ 'document/operation/reinsertoperation' ];
-		RemoveOperation = modules[ 'document/operation/removeoperation' ];
-		MoveOperation = modules[ 'document/operation/removeoperation' ];
-		Position = modules[ 'document/position' ];
+		Document = modules[ 'treemodel/document' ];
+		ReinsertOperation = modules[ 'treemodel/operation/reinsertoperation' ];
+		RemoveOperation = modules[ 'treemodel/operation/removeoperation' ];
+		MoveOperation = modules[ 'treemodel/operation/removeoperation' ];
+		Position = modules[ 'treemodel/position' ];
 	} );
 
 	let doc, root, graveyard;
@@ -31,12 +31,22 @@ describe( 'RemoveOperation', () => {
 	beforeEach( () => {
 		doc = new Document();
 		root = doc.createRoot( 'root' );
-		graveyard = doc._graveyard;
+		graveyard = doc.graveyard;
+	} );
+
+	it( 'should have proper type', () => {
+		const opp = new RemoveOperation(
+			new Position( root, [ 2 ] ),
+			2,
+			doc.version
+		);
+
+		expect( opp.type ).to.equal( 'remove' );
 	} );
 
 	it( 'should extend MoveOperation class', () => {
 		let operation = new RemoveOperation(
-			new Position( [ 2 ], root ),
+			new Position( root, [ 2 ] ),
 			2,
 			doc.version
 		);
@@ -53,7 +63,7 @@ describe( 'RemoveOperation', () => {
 
 		doc.applyOperation(
 			new RemoveOperation(
-				new Position( [ 2 ], root ),
+				new Position( root, [ 2 ] ),
 				2,
 				doc.version
 			)
@@ -69,7 +79,7 @@ describe( 'RemoveOperation', () => {
 	} );
 
 	it( 'should create a reinsert operation as a reverse', () => {
-		let position = new Position( [ 0 ], root );
+		let position = new Position( root, [ 0 ] );
 		let operation = new RemoveOperation( position, 2, 0 );
 		let reverse = operation.getReversed();
 
@@ -81,7 +91,7 @@ describe( 'RemoveOperation', () => {
 	} );
 
 	it( 'should undo remove set of nodes by applying reverse operation', () => {
-		let position = new Position( [ 0 ], root );
+		let position = new Position( root, [ 0 ] );
 		let operation = new RemoveOperation( position, 3, 0 );
 		let reverse = operation.getReversed();
 

+ 2382 - 0
packages/ckeditor5-engine/tests/treemodel/operation/transform.js

@@ -0,0 +1,2382 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/* jshint expr: true */
+
+/* bender-tags: treemodel, operation */
+/* global describe, before, beforeEach, it, expect */
+
+'use strict';
+
+const modules = bender.amd.require(
+	'treemodel/rootelement',
+	'treemodel/node',
+	'treemodel/position',
+	'treemodel/range',
+	'treemodel/attribute',
+	'treemodel/operation/transform',
+	'treemodel/operation/insertoperation',
+	'treemodel/operation/attributeoperation',
+	'treemodel/operation/moveoperation',
+	'treemodel/operation/nooperation'
+);
+
+describe( 'transform', () => {
+	let RootElement, Node, Position, Range, Attribute, InsertOperation, AttributeOperation, MoveOperation, NoOperation;
+	let transform;
+
+	before( () => {
+		RootElement = modules[ 'treemodel/rootelement' ];
+		Node = modules[ 'treemodel/node' ];
+		Position = modules[ 'treemodel/position' ];
+		Range = modules[ 'treemodel/range' ];
+		Attribute = modules[ 'treemodel/attribute' ];
+		InsertOperation = modules[ 'treemodel/operation/insertoperation' ];
+		AttributeOperation = modules[ 'treemodel/operation/attributeoperation' ];
+		MoveOperation = modules[ 'treemodel/operation/moveoperation' ];
+		NoOperation = modules[ 'treemodel/operation/nooperation' ];
+
+		transform = modules[ 'treemodel/operation/transform' ];
+	} );
+
+	let root, op, nodeA, nodeB, expected, baseVersion;
+
+	beforeEach( () => {
+		root = new RootElement( null );
+
+		nodeA = new Node();
+		nodeB = new Node();
+
+		baseVersion = 0;
+	} );
+
+	function expectOperation( op, params ) {
+		for ( let i in params ) {
+			if ( params.hasOwnProperty( i ) ) {
+				if ( i == 'type' ) {
+					expect( op ).to.be.instanceof( params[ i ] );
+				}
+				else if ( params[ i ] instanceof Array ) {
+					expect( op[ i ].length ).to.equal( params[ i ].length );
+
+					for ( let j = 0; j < params[ i ].length; j++ ) {
+						expect( op[ i ][ j ] ).to.equal( params[ i ][ j ] );
+					}
+				} else if ( params[ i ] instanceof Position || params[ i ] instanceof Range ) {
+					expect( op[ i ].isEqual( params[ i ] ) ).to.be.true;
+				} else {
+					expect( op[ i ] ).to.equal( params[ i ] );
+				}
+			}
+		}
+	}
+
+	describe( 'InsertOperation', () => {
+		let nodeC, nodeD, position;
+
+		beforeEach( () => {
+			nodeC = new Node();
+			nodeD = new Node();
+
+			position = new Position( root, [ 0, 2, 1 ] );
+
+			op = new InsertOperation( position, [ nodeA, nodeB ], baseVersion );
+
+			expected = {
+				type: InsertOperation,
+				position: position.clone(),
+				baseVersion: baseVersion + 1
+			};
+		} );
+
+		describe( 'by InsertOperation', () => {
+			it( 'target at different position: no position update', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 1, 3, 2 ] ),
+					[ nodeC, nodeD ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target at offset before: increment offset', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 0, 2, 0 ] ),
+					[ nodeC, nodeD ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+				expected.position.offset += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target at same offset and is important: increment offset', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 0, 2, 1 ] ),
+					[ nodeC, nodeD ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+				expected.position.offset += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target at same offset and is less important: no position update', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 0, 2, 1 ] ),
+					[ nodeC, nodeD ],
+					baseVersion
+				);
+
+				let transOp = transform( transformBy, true );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target at offset after: no position update', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 0, 2, 2 ] ),
+					[ nodeC, nodeD ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target before node from path: increment index on path', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 0, 1 ] ),
+					[ nodeC, nodeD ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+				expected.position.path[ 1 ] += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target after node from path: no position update', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 0, 6 ] ),
+					[ nodeC, nodeD ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+		} );
+
+		describe( 'by AttributeOperation', () => {
+			it( 'no position update', () => {
+				let rangeStart = position.clone();
+				let rangeEnd = position.clone();
+				rangeEnd.offset += 2;
+
+				let transformBy = new AttributeOperation(
+					new Range( rangeStart, rangeEnd ),
+					null,
+					new Attribute( 'foo', 'bar' ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+		} );
+
+		describe( 'by MoveOperation', () => {
+			it( 'range and target are different than insert position: no position update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 1, 3, 2 ] ),
+					2,
+					new Position( root, [ 2, 1 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range offset is before insert position offset: decrement offset', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 0, 2, 0 ] ),
+					1,
+					new Position( root, [ 1, 1 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+				expected.position.offset--;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range offset is after insert position offset: no position update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 0, 2, 4 ] ),
+					1,
+					new Position( root, [ 1, 1 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target offset before insert position offset: increment offset', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 1, 1 ] ),
+					2,
+					new Position( root, [ 0, 2, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+				expected.position.offset += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target offset after insert position offset: no position update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 1, 1 ] ),
+					2,
+					new Position( root, [ 0, 2, 4 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target offset same as insert position offset and is important: increment offset', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 1, 1 ] ),
+					2,
+					new Position( root, [ 0, 2, 1 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+				expected.position.offset += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target offset same as insert position offset and is less important: no position update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 1, 1 ] ),
+					2,
+					new Position( root, [ 0, 2, 1 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy, true );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range is before node from insert position path: decrement index on path', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 0, 0 ] ),
+					2,
+					new Position( root, [ 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+				expected.position.path[ 1 ] -= 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range is after node from insert position path: no position update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 0, 4 ] ),
+					2,
+					new Position( root, [ 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target before node from insert position path: increment index on path', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 1, 0 ] ),
+					2,
+					new Position( root, [ 0, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+				expected.position.path[ 1 ] += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target after node from insert position path: no position update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 1, 0 ] ),
+					2,
+					new Position( root, [ 0, 4 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range has node that contains insert position: update position', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 0, 1 ] ),
+					2,
+					new Position( root, [ 1, 1 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+				expected.position.path = [ 1, 2, 1 ];
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range contains insert position (on same level): set position offset to range start', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 0, 2, 0 ] ),
+					3,
+					new Position( root, [ 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+				expected.position.offset = 0;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+		} );
+
+		describe( 'by NoOperation', () => {
+			it( 'no operation update', () => {
+				let transformBy = new NoOperation( baseVersion );
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+		} );
+	} );
+
+	describe( 'AttributeOperation', () => {
+		let start, end, range, oldAttr, newAttr, anotherOldAttr, anotherNewAttr;
+
+		beforeEach( () => {
+			oldAttr = new Attribute( 'foo', 'abc' );
+			newAttr = new Attribute( 'foo', 'bar' );
+
+			anotherOldAttr = new Attribute( oldAttr.key, 'another' );
+			anotherNewAttr = new Attribute( oldAttr.key, 'anothernew' );
+
+			expected = {
+				type: AttributeOperation,
+				oldAttr: oldAttr,
+				newAttr: newAttr,
+				baseVersion: baseVersion + 1
+			};
+		} );
+
+		describe( 'with multi-level range', () => {
+			beforeEach( () => {
+				start = new Position( root, [ 1, 2 ] );
+				end = new Position( root, [ 2, 2, 4 ] );
+
+				range = new Range( start, end );
+
+				op = new AttributeOperation( range, oldAttr, newAttr, baseVersion );
+
+				expected.range = new Range( start.clone(), end.clone() );
+			} );
+
+			describe( 'by InsertOperation', () => {
+				it( 'target at different position: no operation update', () => {
+					let transformBy = new InsertOperation(
+						new Position( root, [ 3, 3, 2 ] ),
+						[ nodeA, nodeB ],
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'target at offset before: increment offset', () => {
+					let transformBy = new InsertOperation(
+						new Position( root, [ 1, 1 ] ),
+						[ nodeA, nodeB ],
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expected.range.start.offset += 2;
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'target at same offset: increment offset', () => {
+					let transformBy = new InsertOperation(
+						new Position( root, [ 1, 2 ] ),
+						[ nodeA, nodeB ],
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expected.range.start.offset += 2;
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'target at offset after: no operation update', () => {
+					let transformBy = new InsertOperation(
+						new Position( root, [ 3, 2 ] ),
+						[ nodeA, nodeB ],
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'target before node from path: increment index on path', () => {
+					let transformBy = new InsertOperation(
+						new Position( root, [ 0 ] ),
+						[ nodeA, nodeB ],
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expected.range.start.path[ 0 ] += 2;
+					expected.range.end.path[ 0 ] += 2;
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'target after node from path: no position change', () => {
+					let transformBy = new InsertOperation(
+						new Position( root, [ 2, 6 ] ),
+						[ nodeA, nodeB ],
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'target inside change range: split into two operations', () => {
+					let transformBy = new InsertOperation(
+						new Position( root, [ 1, 3, 1 ] ),
+						[ nodeA, nodeB ],
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 2 );
+
+					expected.range.start.path = [ 1, 3, 3 ];
+
+					expectOperation( transOp[ 0 ], expected );
+
+					expected.range.start = op.range.start;
+					expected.range.end.path = [ 1, 3, 1 ];
+					expected.baseVersion++;
+
+					expectOperation( transOp[ 1 ], expected );
+				} );
+			} );
+
+			describe( 'by AttributeOperation', () => {
+				it( 'attributes have different key: no operation update', () => {
+					let transformBy = new AttributeOperation(
+						range.clone(),
+						new Attribute( 'abc', true ),
+						new Attribute( 'abc', false ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'attributes set same value: no operation update', () => {
+					let transformBy = new AttributeOperation(
+						range.clone(),
+						oldAttr,
+						newAttr,
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'both operations removes attribute: no operation update', () => {
+					op.newAttr = null;
+
+					let transformBy = new AttributeOperation(
+						new Range( new Position( root, [ 1, 1, 4 ] ), new Position( root, [ 3 ] ) ),
+						anotherOldAttr,
+						null,
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy, true );
+
+					expected.newAttr = null;
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				describe( 'that is less important and', () => {
+					it( 'range does not intersect original range: no operation update', () => {
+						let transformBy = new AttributeOperation(
+							new Range( new Position( root, [ 3, 0 ] ), new Position( root, [ 4 ] ) ),
+							anotherOldAttr,
+							null,
+							baseVersion
+						);
+
+						let transOp = transform( op, transformBy, true );
+
+						expect( transOp.length ).to.equal( 1 );
+						expectOperation( transOp[ 0 ], expected );
+					} );
+
+					it( 'range contains original range: update oldAttr', () => {
+						let transformBy = new AttributeOperation(
+							new Range( new Position( root, [ 1, 1, 4 ] ), new Position( root, [ 3 ] ) ),
+							anotherOldAttr,
+							null,
+							baseVersion
+						);
+
+						let transOp = transform( op, transformBy, true );
+
+						expected.oldAttr = anotherOldAttr;
+
+						expect( transOp.length ).to.equal( 1 );
+						expectOperation( transOp[ 0 ], expected );
+					} );
+
+					// [ original range   <   ]   range transformed by >
+					it( 'range intersects on left: split into two operations, update oldAttr', () => {
+						// Get more test cases and better code coverage
+						op.newAttr = null;
+
+						let transformBy = new AttributeOperation(
+							new Range( new Position( root, [ 1, 4, 2 ] ), new Position( root, [ 3 ] ) ),
+							anotherOldAttr,
+							// Get more test cases and better code coverage
+							anotherNewAttr,
+							baseVersion
+						);
+
+						let transOp = transform( op, transformBy, true );
+
+						expect( transOp.length ).to.equal( 2 );
+
+						expected.newAttr = null;
+
+						expected.range.end.path = [ 1, 4, 2 ];
+
+						expectOperation( transOp[ 0 ], expected );
+
+						expected.range.start.path = [ 1, 4, 2 ];
+						expected.range.end = op.range.end;
+						expected.oldAttr = anotherOldAttr;
+						expected.baseVersion++;
+
+						expectOperation( transOp[ 1 ], expected );
+					} );
+
+					// [  range transformed by  <   ]  original range  >
+					it( 'range intersects on right: split into two operations, update oldAttr', () => {
+						let transformBy = new AttributeOperation(
+							new Range( new Position( root, [ 1 ] ), new Position( root, [ 2, 1 ] ) ),
+							anotherOldAttr,
+							null,
+							baseVersion
+						);
+
+						let transOp = transform( op, transformBy, true );
+
+						expect( transOp.length ).to.equal( 2 );
+
+						expected.range.start.path = [ 2, 1 ];
+
+						expectOperation( transOp[ 0 ], expected );
+
+						expected.range.start = op.range.start;
+						expected.range.end.path = [ 2, 1 ];
+						expected.oldAttr = anotherOldAttr;
+						expected.baseVersion++;
+
+						expectOperation( transOp[ 1 ], expected );
+					} );
+
+					it( 'range is inside original range: split into three operations, update oldAttr', () => {
+						let transformBy = new AttributeOperation(
+							new Range( new Position( root, [ 1, 4, 1 ] ), new Position( root, [ 2, 1 ] ) ),
+							anotherOldAttr,
+							null,
+							baseVersion
+						);
+
+						let transOp = transform( op, transformBy, true );
+
+						expect( transOp.length ).to.equal( 3 );
+
+						expected.range.end.path = [ 1, 4, 1 ];
+
+						expectOperation( transOp[ 0 ], expected );
+
+						expected.range.start.path = [ 2, 1 ];
+						expected.range.end = op.range.end;
+						expected.baseVersion++;
+
+						expectOperation( transOp[ 1 ], expected );
+
+						expected.range.start.path = [ 1, 4, 1 ];
+						expected.range.end.path = [ 2, 1 ];
+						expected.oldAttr = anotherOldAttr;
+						expected.baseVersion++;
+
+						expectOperation( transOp[ 2 ], expected );
+					} );
+				} );
+
+				describe( 'that is more important and', () => {
+					it( 'range does not intersect original range: no operation update', () => {
+						let transformBy = new AttributeOperation(
+							new Range( new Position( root, [ 3, 0 ] ), new Position( root, [ 4 ] ) ),
+							oldAttr,
+							null,
+							baseVersion
+						);
+
+						let transOp = transform( op, transformBy );
+
+						expect( transOp.length ).to.equal( 1 );
+						expectOperation( transOp[ 0 ], expected );
+					} );
+
+					it( 'range contains original range: convert to NoOperation', () => {
+						let transformBy = new AttributeOperation(
+							new Range( new Position( root, [ 1, 1, 4 ] ), new Position( root, [ 3 ] ) ),
+							oldAttr,
+							null,
+							baseVersion
+						);
+
+						let transOp = transform( op, transformBy );
+
+						expect( transOp.length ).to.equal( 1 );
+						expectOperation( transOp[ 0 ], {
+							type: NoOperation,
+							baseVersion: baseVersion + 1
+						} );
+					} );
+
+					// [ original range   <   ]   range transformed by >
+					it( 'range intersects on left: shrink original range', () => {
+						let transformBy = new AttributeOperation(
+							new Range( new Position( root, [ 1, 4, 2 ] ), new Position( root, [ 3 ] ) ),
+							oldAttr,
+							null,
+							baseVersion
+						);
+
+						let transOp = transform( op, transformBy );
+
+						expected.range.end.path = [ 1, 4, 2 ];
+
+						expect( transOp.length ).to.equal( 1 );
+						expectOperation( transOp[ 0 ], expected );
+					} );
+
+					// [  range transformed by  <   ]  original range  >
+					it( 'range intersects on right: shrink original range', () => {
+						let transformBy = new AttributeOperation(
+							new Range( new Position( root, [ 1 ] ), new Position( root, [ 2, 1 ] ) ),
+							oldAttr,
+							null,
+							baseVersion
+						);
+
+						let transOp = transform( op, transformBy );
+
+						expected.range.start.path = [ 2, 1 ];
+
+						expect( transOp.length ).to.equal( 1 );
+						expectOperation( transOp[ 0 ], expected );
+					} );
+
+					it( 'range is inside original range: split into two operations', () => {
+						let transformBy = new AttributeOperation(
+							new Range( new Position( root, [ 1, 4, 1 ] ), new Position( root, [ 2, 1 ] ) ),
+							oldAttr,
+							null,
+							baseVersion
+						);
+
+						let transOp = transform( op, transformBy );
+
+						expect( transOp.length ).to.equal( 2 );
+
+						expected.range.end.path = [ 1, 4, 1 ];
+
+						expectOperation( transOp[ 0 ], expected );
+
+						expected.range.start.path = [ 2, 1 ];
+						expected.range.end = op.range.end;
+						expected.baseVersion++;
+
+						expectOperation( transOp[ 1 ], expected );
+					} );
+				} );
+			} );
+
+			describe( 'by MoveOperation', () => {
+				it( 'range and target are different than change range: no operation update', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 1, 1, 2 ] ),
+						2,
+						new Position( root, [ 3, 4 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'range offset is before change range start offset: decrement offset', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 1, 0 ] ),
+						2,
+						new Position( root, [ 3, 4, 1 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expected.range.start.offset -= 2;
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'target offset is before change range start offset: increment offset', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 3, 4, 1 ] ),
+						2,
+						new Position( root, [ 1, 0 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expected.range.start.offset += 2;
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'range is before node from path to change range: decrement index on path', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 0 ] ),
+						1,
+						new Position( root, [ 2, 4, 1 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expected.range.start.path[ 0 ]--;
+					expected.range.end.path[ 0 ]--;
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'range is after node from path to change range: no position change', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 3 ] ),
+						2,
+						new Position( root, [ 0, 1 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'target before node from path to change range: increment index on path', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 3, 4, 1 ] ),
+						2,
+						new Position( root, [ 1, 0 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expected.range.start.path[ 1 ] += 2;
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'target after node from path to change range: no position change', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 3, 4, 1 ] ),
+						2,
+						new Position( root, [ 3 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'range intersects on left with change range: split into two operations', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 2, 1 ] ),
+						3,
+						new Position( root, [ 4 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 2 );
+
+					expected.range.end.path = [ 2, 1 ];
+
+					expectOperation( transOp[ 0 ], expected );
+
+					expected.range.start.path = [ 4 ];
+					expected.range.end.path = [ 5, 4 ];
+					expected.baseVersion++;
+
+					expectOperation( transOp[ 1 ], expected );
+				} );
+
+				it( 'range intersects on right with change range: split into two operation', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 1, 1 ] ),
+						3,
+						new Position( root, [ 0, 0 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 2 );
+
+					expected.range.start.path = [ 1, 1 ];
+
+					expectOperation( transOp[ 0 ], expected );
+
+					expected.range.start.path = [ 0, 1 ];
+					expected.range.end.path = [ 0, 3 ];
+					expected.baseVersion++;
+
+					expectOperation( transOp[ 1 ], expected );
+				} );
+
+				it( 'range contains change range: update change range', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 1 ] ),
+						2,
+						new Position( root, [ 3, 4, 1 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expected.range.start.path = [ 1, 4, 1, 2 ];
+					expected.range.end.path = [ 1, 4, 2, 2, 4 ];
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'range is inside change range: split into two operations', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 1, 4 ] ),
+						2,
+						new Position( root, [ 3, 2 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 2 );
+
+					expectOperation( transOp[ 0 ], expected );
+
+					expected.range.start.path = [ 3, 2 ];
+					expected.range.end.path = [ 3, 4 ];
+					expected.baseVersion++;
+
+					expectOperation( transOp[ 1 ], expected );
+				} );
+
+				it( 'target inside change range: split into two operations', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 3, 4, 1 ] ),
+						2,
+						new Position( root, [ 1, 4 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 2 );
+
+					expected.range.start.path = [ 1, 6 ];
+
+					expectOperation( transOp[ 0 ], expected );
+
+					expected.range.start = op.range.start;
+					expected.range.end.path = [ 1, 4 ];
+					expected.baseVersion++;
+
+					expectOperation( transOp[ 1 ], expected );
+				} );
+
+				it( 'range intersects change range and target inside change range: split into three operations', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 1, 1 ] ),
+						3,
+						new Position( root, [ 2 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 3 );
+
+					expected.range.start.path = [ 5 ];
+					expected.range.end.path = [ 5, 2, 4 ];
+
+					expectOperation( transOp[ 0 ], expected );
+
+					expected.range.start.path = [ 1, 1 ];
+					expected.range.end.path = [ 2 ];
+					expected.baseVersion++;
+
+					expectOperation( transOp[ 1 ], expected );
+
+					expected.range.start.path = [ 3 ];
+					expected.range.end.path = [ 5 ];
+					expected.baseVersion++;
+
+					expectOperation( transOp[ 2 ], expected );
+				} );
+			} );
+
+			describe( 'by NoOperation', () => {
+				it( 'no operation update', () => {
+					let transformBy = new NoOperation( baseVersion );
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+			} );
+		} );
+
+		// Some extra cases for a AttributeOperation that operates on single tree level range.
+		// This means that the change range start and end differs only on offset value.
+		// This test suite also have some modifications to the original operation
+		// to get more test cases covered and better code coverage.
+		describe( 'with single-level range', () => {
+			beforeEach( () => {
+				start = new Position( root, [ 0, 2, 1 ] );
+				end = new Position( root, [ 0, 2, 4 ] );
+
+				range = new Range( start, end );
+
+				op = new AttributeOperation( range, oldAttr, newAttr, baseVersion );
+
+				expected.range = new Range( start.clone(), end.clone() );
+			} );
+
+			describe( 'by InsertOperation', () => {
+				it( 'target at offset before: increment offset', () => {
+					let transformBy = new InsertOperation(
+						new Position( root, [ 0, 2, 0 ] ),
+						[ nodeA, nodeB ],
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expected.range.start.offset += 2;
+					expected.range.end.offset += 2;
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'target at same offset: increment offset', () => {
+					let transformBy = new InsertOperation(
+						new Position( root, [ 0, 2, 1 ] ),
+						[ nodeA, nodeB ],
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expected.range.start.offset += 2;
+					expected.range.end.offset += 2;
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+			} );
+
+			describe( 'by MoveOperation', () => {
+				it( 'range offset is before change range start offset: decrement offset', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 0, 2, 0 ] ),
+						1,
+						new Position( root, [ 2, 4, 1 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expected.range.start.offset--;
+					expected.range.end.offset--;
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'target offset is before change range start offset: increment offset', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 2, 4, 1 ] ),
+						2,
+						new Position( root, [ 0, 2, 0 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expected.range.start.offset += 2;
+					expected.range.end.offset += 2;
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'range intersects on left with change range: split into two operations', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 0, 2, 2 ] ),
+						4,
+						new Position( root, [ 2, 4, 1 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 2 );
+
+					expected.range.end.offset -= 2;
+
+					expectOperation( transOp[ 0 ], expected );
+
+					expected.range.start.path = [ 2, 4, 1 ];
+					expected.range.end.path = [ 2, 4, 3 ];
+					expected.baseVersion++;
+
+					expectOperation( transOp[ 1 ], expected );
+				} );
+
+				it( 'range intersects on right with change range: split into two operation', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 0, 2, 0 ] ),
+						2,
+						new Position( root, [ 2, 4, 1 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 2 );
+
+					expected.range.start.offset -= 1;
+					expected.range.end.offset -= 2;
+
+					expectOperation( transOp[ 0 ], expected );
+
+					expected.range.start.path = [ 2, 4, 2 ];
+					expected.range.end.path = [ 2, 4, 3 ];
+					expected.baseVersion++;
+
+					expectOperation( transOp[ 1 ], expected );
+				} );
+
+				it( 'range contains change range: update change range', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 0, 1 ] ),
+						3,
+						new Position( root, [ 2, 4, 1 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expected.range.start.path = [ 2, 4, 2, 1 ];
+					expected.range.end.path = [ 2, 4, 2, 4 ];
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'range is inside change range: split into two operations', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 0, 2, 2 ] ),
+						1,
+						new Position( root, [ 2, 4, 1 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 2 );
+
+					expected.range.end.offset--;
+
+					expectOperation( transOp[ 0 ], expected );
+
+					expected.range.start.path = [ 2, 4, 1 ];
+					expected.range.end.path = [ 2, 4, 2 ];
+					expected.baseVersion++;
+
+					expectOperation( transOp[ 1 ], expected );
+				} );
+
+				it( 'range is same as change range: update change range', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 0, 2, 1 ] ),
+						3,
+						new Position( root, [ 2, 4, 1 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expected.range.start.path = [ 2, 4, 1 ];
+					expected.range.end.path = [ 2, 4, 4 ];
+
+					expect( transOp.length ).to.equal( 1 );
+					expectOperation( transOp[ 0 ], expected );
+				} );
+
+				it( 'target inside change range: split into two operations', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 2, 4, 1 ] ),
+						2,
+						new Position( root, [ 0, 2, 2 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 2 );
+
+					expected.range.start.offset = 4;
+					expected.range.end.offset = 6;
+
+					expectOperation( transOp[ 0 ], expected );
+
+					expected.range.start.offset = op.range.start.offset;
+					expected.range.end.offset = 2;
+					expected.baseVersion++;
+
+					expectOperation( transOp[ 1 ], expected );
+				} );
+
+				it( 'range intersects change range and target inside change range: split into three operations', () => {
+					let transformBy = new MoveOperation(
+						new Position( root, [ 0, 2, 0 ] ),
+						2,
+						new Position( root, [ 0, 2, 3 ] ),
+						baseVersion
+					);
+
+					let transOp = transform( op, transformBy );
+
+					expect( transOp.length ).to.equal( 3 );
+
+					expected.range.start.offset = 3;
+					expected.range.end.offset = 4;
+
+					expectOperation( transOp[ 0 ], expected );
+
+					expected.range.start.offset = 0;
+					expected.range.end.offset = 1;
+					expected.baseVersion++;
+
+					expectOperation( transOp[ 1 ], expected );
+
+					expected.range.start.offset = 2;
+					expected.range.end.offset = 3;
+					expected.baseVersion++;
+
+					expectOperation( transOp[ 2 ], expected );
+				} );
+			} );
+		} );
+	} );
+
+	describe( 'MoveOperation', () => {
+		let sourcePosition, targetPosition, rangeEnd, howMany;
+
+		beforeEach( () => {
+			sourcePosition = new Position( root, [ 2, 2, 4 ] );
+			targetPosition = new Position( root, [ 3, 3, 3 ] );
+			howMany = 2;
+
+			rangeEnd = sourcePosition.clone();
+			rangeEnd.offset += howMany;
+
+			op = new MoveOperation( sourcePosition, howMany, targetPosition, baseVersion );
+
+			expected = {
+				type: MoveOperation,
+				sourcePosition: sourcePosition.clone(),
+				targetPosition: targetPosition.clone(),
+				howMany: howMany,
+				baseVersion: baseVersion + 1
+			};
+		} );
+
+		describe( 'by InsertOperation', () => {
+			it( 'target at different position than move range and target: no operation update', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 1, 3, 2 ] ),
+					[ nodeA, nodeB ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target inside node from move range: no operation update', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 2, 2, 3, 1 ] ),
+					[ nodeA, nodeB ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target at offset before range offset: increment range offset', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 2, 2, 0 ] ),
+					[ nodeA, nodeB ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.sourcePosition.offset += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target at offset after range offset: no operation update', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 2, 2, 6 ] ),
+					[ nodeA, nodeB ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target before node from range start path: increment index on range start path', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 2, 0 ] ),
+					[ nodeA, nodeB ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.sourcePosition.path[ 1 ] += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target after node from range start path: no operation update', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 2, 3 ] ),
+					[ nodeA, nodeB ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target offset before move target offset: increment target offset', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 3, 3, 2 ] ),
+					[ nodeA, nodeB ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.targetPosition.offset += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target offset after move target offset: no operation update', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 3, 3, 4 ] ),
+					[ nodeA, nodeB ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target before node from move target position path: increment index on move target position path', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 3, 0 ] ),
+					[ nodeA, nodeB ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.targetPosition.path[ 1 ] += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target after node from move target position path: no operation update', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 3, 6 ] ),
+					[ nodeA, nodeB ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target offset same as move target offset and is important: increment target offset', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 3, 3, 3 ] ),
+					[ nodeA, nodeB ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.targetPosition.offset += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target offset same as move target offset and is less important: no operation update', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 3, 3, 3 ] ),
+					[ nodeA, nodeB ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy, true );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target offset same as move target offset and is important: increment target offset', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 3, 3 ] ),
+					[ nodeA, nodeB ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.targetPosition.path[ 1 ] += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target inside move range: split into two operations', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 2, 2, 5 ] ),
+					[ nodeA, nodeB ],
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 2 );
+
+				expected.sourcePosition.path = [ 2, 2, 7 ];
+				expected.howMany = 1;
+
+				expectOperation( transOp[ 0 ], expected );
+
+				expected.sourcePosition.path = [ 2, 2, 4 ];
+				expected.howMany = 1;
+				expected.baseVersion++;
+
+				expectOperation( transOp[ 1 ], expected );
+			} );
+		} );
+
+		describe( 'by AttributeOperation', () => {
+			it( 'no operation update', () => {
+				let transformBy = new AttributeOperation(
+					new Range( sourcePosition, rangeEnd ),
+					new Attribute( 'abc', true ),
+					new Attribute( 'abc', false ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+		} );
+
+		describe( 'by MoveOperation', () => {
+			it( 'range and target different than transforming range and target: no operation update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 1, 2 ] ),
+					3,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target offset before transforming range start offset: increment range offset', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 4, 1, 0 ] ),
+					2,
+					new Position( root, [ 2, 2, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.sourcePosition.offset += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target offset after transforming range start offset: no operation update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 4, 1, 0 ] ),
+					2,
+					new Position( root, [ 2, 2, 7 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range start offset before transforming range start offset: decrement range offset', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 0 ] ),
+					2,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.sourcePosition.offset -= 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range start offset after transforming range start offset: no operation update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 9 ] ),
+					2,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy, true );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target before node from transforming range start path: increment index on range start path', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 4, 1, 0 ] ),
+					2,
+					new Position( root, [ 2, 1 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.sourcePosition.path[ 1 ] += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target after node from transforming range start path: no operation update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 4, 1, 0 ] ),
+					2,
+					new Position( root, [ 2, 5 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range before node from transforming range start path: decrement index on range start path', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 0 ] ),
+					2,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.sourcePosition.path[ 1 ] -= 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range after node from transforming range start path: no operation update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 3 ] ),
+					2,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target offset before transforming target offset: increment target offset', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 4, 1, 0 ] ),
+					2,
+					new Position( root, [ 3, 3, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.targetPosition.offset += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target offset after transforming target offset: no operation update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 4, 1, 0 ] ),
+					2,
+					new Position( root, [ 3, 3, 5 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range offset before transforming target offset: decrement target offset', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 3, 3, 0 ] ),
+					2,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.targetPosition.offset -= 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range offset after transforming target offset: no operation update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 3, 3, 5 ] ),
+					2,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target before node from transforming target path: increment index on target path', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 4, 1, 0 ] ),
+					2,
+					new Position( root, [ 3, 1 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.targetPosition.path[ 1 ] += 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target after node from transforming target path: no operation update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 4, 1, 0 ] ),
+					2,
+					new Position( root, [ 3, 5 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range before node from transforming target path: decrement index on target path', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 3, 0 ] ),
+					2,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.targetPosition.path[ 1 ] -= 2;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range after node from transforming target path: no operation update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 3, 5 ] ),
+					2,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target inside transforming move range: split into two operations', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 4, 1, 0 ] ),
+					2,
+					new Position( root, [ 2, 2, 5 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 2 );
+
+				expected.howMany = 1;
+				expected.sourcePosition.offset = 7;
+
+				expectOperation( transOp[ 0 ], expected );
+
+				expected.sourcePosition.offset = 4;
+				expected.baseVersion++;
+
+				expectOperation( transOp[ 1 ], expected );
+			} );
+
+			it( 'target inside a node from transforming range: no operation update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 4, 1, 0 ] ),
+					2,
+					new Position( root, [ 2, 2, 5, 1 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range has node that contains transforming range: update range path', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 1 ] ),
+					3,
+					new Position( root, [ 4, 2 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.sourcePosition.path = [ 4, 3, 4 ];
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range has node that contains transforming target: update target path', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 3, 2 ] ),
+					3,
+					new Position( root, [ 0, 1 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.targetPosition.path = [ 0, 2, 3 ];
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'target inside a node from transforming range and vice versa: reverse transform-by operation', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 3, 2 ] ),
+					3,
+					new Position( root, [ 2, 2, 5, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+				let reversed = transformBy.getReversed();
+
+				expected.sourcePosition = reversed.sourcePosition;
+				expected.targetPosition = reversed.targetPosition;
+				expected.howMany = reversed.howMany;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range is same as transforming range and is important: convert to NoOperation', () => {
+				let transformBy = new MoveOperation(
+					op.sourcePosition.clone(),
+					op.howMany,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], {
+					type: NoOperation,
+					baseVersion: baseVersion + 1
+				} );
+			} );
+
+			it( 'range is same as transforming range and is less important: update range path', () => {
+				let transformBy = new MoveOperation(
+					op.sourcePosition.clone(),
+					op.howMany,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy, true );
+
+				expected.sourcePosition.path = [ 4, 1, 0 ];
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range contains transforming range and is important: convert to NoOperation', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 3 ] ),
+					4,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], {
+					type: NoOperation,
+					baseVersion: baseVersion + 1
+				} );
+			} );
+
+			it( 'range contains transforming range and is less important: update range path', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 3 ] ),
+					4,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy, true );
+
+				expected.sourcePosition.path = [ 4, 1, 1 ];
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range contains transforming range and target and is important: update range path and target', () => {
+				op.targetPosition.path = [ 2, 2, 7 ];
+
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 3 ] ),
+					5,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+
+				expected.sourcePosition.path = [ 4, 1, 1 ];
+				expected.targetPosition.path = [ 4, 1, 4 ];
+
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range contains transforming range and target and is less important: update range path and target', () => {
+				op.targetPosition.path = [ 2, 2, 7 ];
+
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 3 ] ),
+					5,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy, true );
+
+				expect( transOp.length ).to.equal( 1 );
+
+				expected.sourcePosition.path = [ 4, 1, 1 ];
+				expected.targetPosition.path = [ 4, 1, 4 ];
+
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range intersects on left side of transforming range and is important: shrink range', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 3 ] ),
+					2,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.sourcePosition.path = [ 2, 2, 3 ];
+				expected.howMany = 1;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range intersects on left side of transforming range and is less important: split into two operations', () => {
+				// Get more test cases and better code coverage
+				let otherRoot = new RootElement( null );
+
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 3 ] ),
+					2,
+					new Position( otherRoot, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy, true );
+
+				expect( transOp.length ).to.equal( 2 );
+
+				expected.sourcePosition.path = [ 2, 2, 3 ];
+				expected.howMany = 1;
+
+				expectOperation( transOp[ 0 ], expected );
+
+				expected.sourcePosition = new Position( otherRoot, [ 4, 1, 1 ] );
+				expected.baseVersion++;
+
+				expectOperation( transOp[ 1 ], expected );
+			} );
+
+			it( 'range intersects on right side of transforming range and is important: shrink range', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 5 ] ),
+					2,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expected.howMany = 1;
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range intersects on right side of transforming range and is less important: split into two operations', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 5 ] ),
+					2,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy, true );
+
+				expect( transOp.length ).to.equal( 2 );
+
+				expected.sourcePosition.path = [ 4, 1, 0 ];
+				expected.howMany = 1;
+
+				expectOperation( transOp[ 0 ], expected );
+
+				expected.sourcePosition.path = op.sourcePosition.path;
+				expected.baseVersion++;
+
+				expectOperation( transOp[ 1 ], expected );
+			} );
+
+			it( 'range intersects on left side, target inside transforming range and is important: split into two operations', () => {
+				op.howMany = 4;
+
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 3 ] ),
+					2,
+					new Position( root, [ 2, 2, 6 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 2 );
+
+				expected.sourcePosition.path = [ 2, 2, 6 ];
+				expected.howMany = 2;
+
+				expectOperation( transOp[ 0 ], expected );
+
+				expected.sourcePosition.path = [ 2, 2, 3 ];
+				expected.howMany = 1;
+				expected.baseVersion++;
+
+				expectOperation( transOp[ 1 ], expected );
+			} );
+
+			it( 'range intersects on left side, target inside transforming range and is less important: split into three operations', () => {
+				op.howMany = 4;
+
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 3 ] ),
+					2,
+					new Position( root, [ 2, 2, 6 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy, true );
+
+				expect( transOp.length ).to.equal( 3 );
+
+				expected.sourcePosition.path = [ 2, 2, 6 ];
+				expected.howMany = 2;
+
+				expectOperation( transOp[ 0 ], expected );
+
+				expected.sourcePosition.path = [ 2, 2, 3 ];
+				expected.howMany = 1;
+				expected.baseVersion++;
+
+				expectOperation( transOp[ 1 ], expected );
+
+				expected.sourcePosition.path = [ 2, 2, 5 ];
+				expected.howMany = 1;
+				expected.baseVersion++;
+
+				expectOperation( transOp[ 2 ], expected );
+			} );
+
+			it( 'range intersects on right side, target inside transforming range and is important: split into two operations', () => {
+				op.howMany = 4;
+
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 7 ] ),
+					2,
+					new Position( root, [ 2, 2, 5 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 2 );
+
+				expected.sourcePosition.path = [ 2, 2, 7 ];
+				expected.howMany = 2;
+
+				expectOperation( transOp[ 0 ], expected );
+
+				expected.sourcePosition.path = [ 2, 2, 4 ];
+				expected.howMany = 1;
+				expected.baseVersion++;
+
+				expectOperation( transOp[ 1 ], expected );
+			} );
+
+			it( 'range intersects on right side, target inside transforming range and is less important: split into three operations', () => {
+				op.howMany = 4;
+
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 7 ] ),
+					2,
+					new Position( root, [ 2, 2, 5 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy, true );
+
+				expect( transOp.length ).to.equal( 3 );
+
+				expected.sourcePosition.path = [ 2, 2, 5 ];
+				expected.howMany = 1;
+
+				expectOperation( transOp[ 0 ], expected );
+
+				expected.sourcePosition.path = [ 2, 2, 7 ];
+				expected.howMany = 2;
+				expected.baseVersion++;
+
+				expectOperation( transOp[ 1 ], expected );
+
+				expected.sourcePosition.path = [ 2, 2, 4 ];
+				expected.howMany = 1;
+				expected.baseVersion++;
+
+				expectOperation( transOp[ 2 ], expected );
+			} );
+
+			it( 'range inside transforming range and is important: split into two operations', () => {
+				op.howMany = 4;
+
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 5 ] ),
+					2,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 2 );
+
+				expected.sourcePosition.path = [ 2, 2, 5 ];
+				expected.howMany = 1;
+
+				expectOperation( transOp[ 0 ], expected );
+
+				expected.sourcePosition.path = [ 2, 2, 4 ];
+				expected.baseVersion++;
+
+				expectOperation( transOp[ 1 ], expected );
+			} );
+
+			it( 'range inside transforming range and is less important: split into three operations', () => {
+				op.howMany = 4;
+
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 5 ] ),
+					2,
+					new Position( root, [ 4, 1, 0 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy, true );
+
+				expect( transOp.length ).to.equal( 3 );
+
+				expected.sourcePosition.path = [ 2, 2, 5 ];
+				expected.howMany = 1;
+
+				expectOperation( transOp[ 0 ], expected );
+
+				expected.sourcePosition.path = [ 4, 1, 0 ];
+				expected.howMany = 2;
+				expected.baseVersion++;
+
+				expectOperation( transOp[ 1 ], expected );
+
+				expected.sourcePosition.path = [ 2, 2, 4 ];
+				expected.howMany = 1;
+				expected.baseVersion++;
+
+				expectOperation( transOp[ 2 ], expected );
+			} );
+
+			it( 'range and target inside transforming range and is important: no operation update', () => {
+				op.howMany = 6;
+
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 5 ] ),
+					2,
+					new Position( root, [ 2, 2, 9 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+
+				expected.howMany = 6;
+
+				expectOperation( transOp[ 0 ], expected );
+			} );
+
+			it( 'range and target inside transforming range and is less important: no operation update', () => {
+				op.howMany = 6;
+
+				let transformBy = new MoveOperation(
+					new Position( root, [ 2, 2, 5 ] ),
+					2,
+					new Position( root, [ 2, 2, 9 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy, true );
+
+				expect( transOp.length ).to.equal( 1 );
+
+				expected.howMany = 6;
+
+				expectOperation( transOp[ 0 ], expected );
+			} );
+		} );
+
+		describe( 'by NoOperation', () => {
+			it( 'no operation update', () => {
+				let transformBy = new NoOperation( baseVersion );
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+		} );
+	} );
+
+	describe( 'NoOperation', () => {
+		beforeEach( () => {
+			op = new NoOperation( baseVersion );
+
+			expected = {
+				type: NoOperation,
+				baseVersion: baseVersion + 1
+			};
+		} );
+
+		describe( 'by InsertOperation', () => {
+			it( 'no operation update', () => {
+				let transformBy = new InsertOperation(
+					new Position( root, [ 0 ] ),
+					'a',
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+		} );
+
+		describe( 'by AttributeOperation', () => {
+			it( 'no operation update', () => {
+				let transformBy = new AttributeOperation(
+					new Range(
+						new Position( root, [ 0 ] ),
+						new Position( root, [ 1 ] )
+					),
+					new Attribute( 'foo', 'bar' ),
+					new Attribute( 'foo', 'xyz' ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+		} );
+
+		describe( 'by MoveOperation', () => {
+			it( 'no operation update', () => {
+				let transformBy = new MoveOperation(
+					new Position( root, [ 0 ] ),
+					2,
+					new Position( root, [ 1 ] ),
+					baseVersion
+				);
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+		} );
+
+		describe( 'by NoOperation', () => {
+			it( 'no operation update', () => {
+				let transformBy = new NoOperation( baseVersion );
+
+				let transOp = transform( op, transformBy );
+
+				expect( transOp.length ).to.equal( 1 );
+				expectOperation( transOp[ 0 ], expected );
+			} );
+		} );
+	} );
+} );

+ 501 - 0
packages/ckeditor5-engine/tests/treemodel/position.js

@@ -0,0 +1,501 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/* bender-tags: treemodel */
+
+'use strict';
+
+const modules = bender.amd.require(
+	'treemodel/element',
+	'treemodel/character',
+	'treemodel/position',
+	'treemodel/document',
+	'ckeditorerror',
+	'treemodel/nodelist'
+);
+
+describe( 'position', () => {
+	let Element, Character, Document, NodeList, Position, CKEditorError;
+
+	let doc, root, otherRoot, p, ul, li1, li2, f, o, z, b, a, r;
+
+	// root
+	//  |- p         Before: [ 0 ]       After: [ 1 ]
+	//  |- ul        Before: [ 1 ]       After: [ 2 ]
+	//     |- li     Before: [ 1, 0 ]    After: [ 1, 1 ]
+	//     |  |- f   Before: [ 1, 0, 0 ] After: [ 1, 0, 1 ]
+	//     |  |- o   Before: [ 1, 0, 1 ] After: [ 1, 0, 2 ]
+	//     |  |- z   Before: [ 1, 0, 2 ] After: [ 1, 0, 3 ]
+	//     |- li     Before: [ 1, 1 ]    After: [ 1, 2 ]
+	//        |- b   Before: [ 1, 1, 0 ] After: [ 1, 1, 1 ]
+	//        |- a   Before: [ 1, 1, 1 ] After: [ 1, 1, 2 ]
+	//        |- r   Before: [ 1, 1, 2 ] After: [ 1, 1, 3 ]
+	before( () => {
+		Element = modules[ 'treemodel/element' ];
+		Character = modules[ 'treemodel/character' ];
+		Document = modules[ 'treemodel/document' ];
+		NodeList = modules[ 'treemodel/nodelist' ];
+		Position = modules[ 'treemodel/position' ];
+		CKEditorError = modules.ckeditorerror;
+
+		doc = new Document();
+
+		root = doc.createRoot( 'root' );
+		otherRoot = doc.createRoot( 'otherRoot' );
+
+		f = new Character( 'f' );
+		o = new Character( 'o' );
+		z = new Character( 'z' );
+
+		li1 = new Element( 'li', [], [ f, o, z ] );
+
+		b = new Character( 'b' );
+		a = new Character( 'a' );
+		r = new Character( 'r' );
+
+		li2 = new Element( 'li', [], [ b, a, r ] );
+
+		ul = new Element( 'ul', [], [ li1, li2 ] );
+
+		p = new Element( 'p' );
+
+		root.insertChildren( 0, [ p, ul ] );
+	} );
+
+	it( 'should create a position with path and document', () => {
+		let position = new Position( root, [ 0 ] );
+
+		expect( position ).to.have.property( 'path' ).that.deep.equals( [ 0 ] );
+		expect( position ).to.have.property( 'root' ).that.equals( root );
+	} );
+
+	it( 'should throw error if given path is incorrect', () => {
+		expect( () => {
+			new Position( root, {} );
+		} ).to.throw( CKEditorError, /position-path-incorrect/ );
+
+		expect( () => {
+			new Position( root, [] );
+		} ).to.throw( CKEditorError, /position-path-incorrect/ );
+	} );
+
+	it( 'should throw error if given root is not a RootElement instance', () => {
+		expect( () => {
+			new Position();
+		} ).to.throw( CKEditorError, /position-root-not-rootelement/ );
+
+		expect( () => {
+			new Position( new Element( 'p' ), [ 0 ] );
+		} ).to.throw( CKEditorError, /position-root-not-rootelement/ );
+	} );
+
+	it( 'should create positions form node and offset', () => {
+		expect( Position.createFromParentAndOffset( root, 0 ) ).to.have.property( 'path' ).that.deep.equals( [ 0 ] );
+		expect( Position.createFromParentAndOffset( root, 1 ) ).to.have.property( 'path' ).that.deep.equals( [ 1 ] );
+		expect( Position.createFromParentAndOffset( root, 2 ) ).to.have.property( 'path' ).that.deep.equals( [ 2 ] );
+
+		expect( Position.createFromParentAndOffset( p, 0 ) ).to.have.property( 'path' ).that.deep.equals( [ 0, 0 ] );
+
+		expect( Position.createFromParentAndOffset( ul, 0 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0 ] );
+		expect( Position.createFromParentAndOffset( ul, 1 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1 ] );
+		expect( Position.createFromParentAndOffset( ul, 2 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 2 ] );
+
+		expect( Position.createFromParentAndOffset( li1, 0 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 0 ] );
+		expect( Position.createFromParentAndOffset( li1, 1 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 1 ] );
+		expect( Position.createFromParentAndOffset( li1, 2 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 2 ] );
+		expect( Position.createFromParentAndOffset( li1, 3 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 3 ] );
+	} );
+
+	it( 'should create positions before elements', () => {
+		expect( Position.createBefore( p ) ).to.have.property( 'path' ).that.deep.equals( [ 0 ] );
+
+		expect( Position.createBefore( ul ) ).to.have.property( 'path' ).that.deep.equals( [ 1 ] );
+
+		expect( Position.createBefore( li1 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0 ] );
+
+		expect( Position.createBefore( f ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 0 ] );
+		expect( Position.createBefore( o ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 1 ] );
+		expect( Position.createBefore( z ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 2 ] );
+
+		expect( Position.createBefore( li2 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1 ] );
+
+		expect( Position.createBefore( b ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1, 0 ] );
+		expect( Position.createBefore( a ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1, 1 ] );
+		expect( Position.createBefore( r ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1, 2 ] );
+	} );
+
+	it( 'should throw error if one try to create positions before root', () => {
+		expect( () => {
+			Position.createBefore( root );
+		} ).to.throw( CKEditorError, /position-before-root/ );
+	} );
+
+	it( 'should create positions after elements', () => {
+		expect( Position.createAfter( p ) ).to.have.property( 'path' ).that.deep.equals( [ 1 ] );
+
+		expect( Position.createAfter( ul ) ).to.have.property( 'path' ).that.deep.equals( [ 2 ] );
+
+		expect( Position.createAfter( li1 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1 ] );
+
+		expect( Position.createAfter( f ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 1 ] );
+		expect( Position.createAfter( o ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 2 ] );
+		expect( Position.createAfter( z ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 0, 3 ] );
+
+		expect( Position.createAfter( li2 ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 2 ] );
+
+		expect( Position.createAfter( b ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1, 1 ] );
+		expect( Position.createAfter( a ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1, 2 ] );
+		expect( Position.createAfter( r ) ).to.have.property( 'path' ).that.deep.equals( [ 1, 1, 3 ] );
+	} );
+
+	it( 'should throw error if one try to make positions after root', () => {
+		expect( () => {
+			Position.createAfter( root );
+		} ).to.throw( CKEditorError, /position-after-root/ );
+	} );
+
+	it( 'should have parent', () => {
+		expect( new Position( root, [ 0 ] ) ).to.have.property( 'parent' ).that.equals( root );
+		expect( new Position( root, [ 1 ] ) ).to.have.property( 'parent' ).that.equals( root );
+		expect( new Position( root, [ 2 ] ) ).to.have.property( 'parent' ).that.equals( root );
+
+		expect( new Position( root, [ 0, 0 ] ) ).to.have.property( 'parent' ).that.equals( p );
+
+		expect( new Position( root, [ 1, 0 ] ) ).to.have.property( 'parent' ).that.equals( ul );
+		expect( new Position( root, [ 1, 1 ] ) ).to.have.property( 'parent' ).that.equals( ul );
+		expect( new Position( root, [ 1, 2 ] ) ).to.have.property( 'parent' ).that.equals( ul );
+
+		expect( new Position( root, [ 1, 0, 0 ] ) ).to.have.property( 'parent' ).that.equals( li1 );
+		expect( new Position( root, [ 1, 0, 1 ] ) ).to.have.property( 'parent' ).that.equals( li1 );
+		expect( new Position( root, [ 1, 0, 2 ] ) ).to.have.property( 'parent' ).that.equals( li1 );
+		expect( new Position( root, [ 1, 0, 3 ] ) ).to.have.property( 'parent' ).that.equals( li1 );
+	} );
+
+	it( 'should have offset', () => {
+		expect( new Position( root, [ 0 ] ) ).to.have.property( 'offset' ).that.equals( 0 );
+		expect( new Position( root, [ 1 ] ) ).to.have.property( 'offset' ).that.equals( 1 );
+		expect( new Position( root, [ 2 ] ) ).to.have.property( 'offset' ).that.equals( 2 );
+
+		expect( new Position( root, [ 0, 0 ] ) ).to.have.property( 'offset' ).that.equals( 0 );
+
+		expect( new Position( root, [ 1, 0 ] ) ).to.have.property( 'offset' ).that.equals( 0 );
+		expect( new Position( root, [ 1, 1 ] ) ).to.have.property( 'offset' ).that.equals( 1 );
+		expect( new Position( root, [ 1, 2 ] ) ).to.have.property( 'offset' ).that.equals( 2 );
+
+		expect( new Position( root, [ 1, 0, 0 ] ) ).to.have.property( 'offset' ).that.equals( 0 );
+		expect( new Position( root, [ 1, 0, 1 ] ) ).to.have.property( 'offset' ).that.equals( 1 );
+		expect( new Position( root, [ 1, 0, 2 ] ) ).to.have.property( 'offset' ).that.equals( 2 );
+		expect( new Position( root, [ 1, 0, 3 ] ) ).to.have.property( 'offset' ).that.equals( 3 );
+	} );
+
+	it( 'should be able to set offset', () => {
+		let position = new Position( root, [ 1, 0, 2 ] );
+		position.offset = 4;
+
+		expect( position.offset ).to.equal( 4 );
+		expect( position.path ).to.deep.equal( [ 1, 0, 4 ] );
+	} );
+
+	it( 'should have nodeBefore', () => {
+		expect( new Position( root, [ 0 ] ) ).to.have.property( 'nodeBefore' ).that.is.null;
+		expect( new Position( root, [ 1 ] ) ).to.have.property( 'nodeBefore' ).that.equals( p );
+		expect( new Position( root, [ 2 ] ) ).to.have.property( 'nodeBefore' ).that.equals( ul );
+
+		expect( new Position( root, [ 0, 0 ] ) ).to.have.property( 'nodeBefore' ).that.is.null;
+
+		expect( new Position( root, [ 1, 0 ] ) ).to.have.property( 'nodeBefore' ).that.is.null;
+		expect( new Position( root, [ 1, 1 ] ) ).to.have.property( 'nodeBefore' ).that.equals( li1 );
+		expect( new Position( root, [ 1, 2 ] ) ).to.have.property( 'nodeBefore' ).that.equals( li2 );
+
+		expect( new Position( root, [ 1, 0, 0 ] ) ).to.have.property( 'nodeBefore' ).that.is.null;
+		expect( new Position( root, [ 1, 0, 1 ] ) ).to.have.property( 'nodeBefore' ).that.equals( f );
+		expect( new Position( root, [ 1, 0, 2 ] ) ).to.have.property( 'nodeBefore' ).that.equals( o );
+		expect( new Position( root, [ 1, 0, 3 ] ) ).to.have.property( 'nodeBefore' ).that.equals( z );
+	} );
+
+	it( 'should have nodeAfter', () => {
+		expect( new Position( root, [ 0 ] ) ).to.have.property( 'nodeAfter' ).that.equals( p );
+		expect( new Position( root, [ 1 ] ) ).to.have.property( 'nodeAfter' ).that.equals( ul );
+		expect( new Position( root, [ 2 ] ) ).to.have.property( 'nodeAfter' ).that.is.null;
+
+		expect( new Position( root, [ 0, 0 ] ) ).to.have.property( 'nodeAfter' ).that.is.null;
+
+		expect( new Position( root, [ 1, 0 ] ) ).to.have.property( 'nodeAfter' ).that.equals( li1 );
+		expect( new Position( root, [ 1, 1 ] ) ).to.have.property( 'nodeAfter' ).that.equals( li2 );
+		expect( new Position( root, [ 1, 2 ] ) ).to.have.property( 'nodeAfter' ).that.is.null;
+
+		expect( new Position( root, [ 1, 0, 0 ] ) ).to.have.property( 'nodeAfter' ).that.equals( f );
+		expect( new Position( root, [ 1, 0, 1 ] ) ).to.have.property( 'nodeAfter' ).that.equals( o );
+		expect( new Position( root, [ 1, 0, 2 ] ) ).to.have.property( 'nodeAfter' ).that.equals( z );
+		expect( new Position( root, [ 1, 0, 3 ] ) ).to.have.property( 'nodeAfter' ).that.is.null;
+	} );
+
+	it( 'should have proper parent path', () => {
+		let position = new Position( root, [ 1, 2, 3 ] );
+
+		expect( position.getParentPath() ).to.deep.equal( [ 1, 2 ] );
+	} );
+
+	it( 'should return a new, equal position when cloned', () => {
+		const position = new Position( root, [ 1, 2, 3 ] );
+		const clone = position.clone();
+
+		expect( clone ).not.to.be.equal( position ); // clone is not pointing to the same object as position
+		expect( clone.isEqual( position ) ).to.be.true; // but they are equal in the position-sense
+		expect( clone.path ).not.to.be.equal( position.path ); // make sure the paths are not the same array
+	} );
+
+	describe( 'isBefore', () => {
+		it( 'should return true if given position has same root and is before this position', () => {
+			let position = new Position( root, [ 1, 1, 2 ] );
+			let beforePosition = new Position( root, [ 1, 0 ] );
+
+			expect( position.isAfter( beforePosition ) ).to.be.true;
+		} );
+
+		it( 'should return false if given position has same root and is not before this position', () => {
+			let position = new Position( root, [ 1, 1, 2 ] );
+			let afterPosition = new Position( root, [ 1, 2 ] );
+
+			expect( position.isAfter( afterPosition ) ).to.be.false;
+		} );
+
+		it( 'should return false if given position has different root', () => {
+			let position = new Position( root, [ 1, 1, 2 ] );
+			let differentPosition = new Position( otherRoot, [ 1, 0 ] );
+
+			expect( position.isAfter( differentPosition ) ).to.be.false;
+		} );
+	} );
+
+	describe( 'isEqual', () => {
+		it( 'should return true if given position has same path and root', () => {
+			let position = new Position( root, [ 1, 1, 2 ] );
+			let samePosition = new Position( root, [ 1, 1, 2 ] );
+
+			expect( position.isEqual( samePosition ) ).to.be.true;
+		} );
+
+		it( 'should return false if given position has different path', () => {
+			let position = new Position( root, [ 1, 1, 1 ] );
+			let differentPosition = new Position( root, [ 1, 2, 2 ] );
+
+			expect( position.isEqual( differentPosition ) ).to.be.false;
+		} );
+
+		it( 'should return false if given position has different root', () => {
+			let position = new Position( root, [ 1, 1, 1 ] );
+			let differentPosition = new Position( otherRoot, [ 1, 1, 1 ] );
+
+			expect( position.isEqual( differentPosition ) ).to.be.false;
+		} );
+	} );
+
+	describe( 'isAfter', () => {
+		it( 'should return true if given position has same root and is after this position', () => {
+			let position = new Position( root, [ 1, 1, 2 ] );
+			let afterPosition = new Position( root, [ 1, 2 ] );
+
+			expect( position.isBefore( afterPosition ) ).to.be.true;
+		} );
+
+		it( 'should return false if given position has same root and is not after this position', () => {
+			let position = new Position( root, [ 1, 1, 2 ] );
+			let beforePosition = new Position( root, [ 1, 0 ] );
+
+			expect( position.isBefore( beforePosition ) ).to.be.false;
+		} );
+
+		it( 'should return false if given position has different root', () => {
+			let position = new Position( root, [ 1, 1, 2 ] );
+			let differentPosition = new Position( otherRoot, [ 1, 2 ] );
+
+			expect( position.isBefore( differentPosition ) ).to.be.false;
+		} );
+	} );
+
+	describe( 'compareWith', () => {
+		it( 'should return Position.SAME if positions are same', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const compared = new Position( root, [ 1, 2, 3 ] );
+
+			expect( position.compareWith( compared ) ).to.equal( Position.SAME );
+		} );
+
+		it( 'should return Position.BEFORE if the position is before compared one', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const compared = new Position( root, [ 1, 3 ] );
+
+			expect( position.compareWith( compared ) ).to.equal( Position.BEFORE );
+		} );
+
+		it( 'should return Position.AFTER if the position is after compared one', () => {
+			const position = new Position( root, [ 1, 2, 3, 4 ] );
+			const compared = new Position( root, [ 1, 2, 3 ] );
+
+			expect( position.compareWith( compared ) ).to.equal( Position.AFTER );
+		} );
+
+		it( 'should return Position.DIFFERENT if positions are in different roots', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const compared = new Position( otherRoot, [ 1, 2, 3 ] );
+
+			expect( position.compareWith( compared ) ).to.equal( Position.DIFFERENT );
+		} );
+	} );
+
+	describe( 'getTransformedByInsertion', () => {
+		it( 'should return a new Position instance', () => {
+			const position = new Position( root, [ 0 ] );
+			const transformed = position.getTransformedByInsertion( new Position( root, [ 2 ] ), 4, false );
+
+			expect( transformed ).not.to.equal( position );
+			expect( transformed ).to.be.instanceof( Position );
+		} );
+
+		it( 'should increment offset if insertion is in the same parent and closer offset', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const transformed = position.getTransformedByInsertion( new Position( root, [ 1, 2, 2 ] ), 2, false );
+
+			expect( transformed.offset ).to.equal( 5 );
+		} );
+
+		it( 'should not increment offset if insertion position is in different root', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const transformed = position.getTransformedByInsertion( new Position( otherRoot, [ 1, 2, 2 ] ), 2, false );
+
+			expect( transformed.offset ).to.equal( 3 );
+		} );
+
+		it( 'should not increment offset if insertion is in the same parent and the same offset', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const transformed = position.getTransformedByInsertion( new Position( root, [ 1, 2, 3 ] ), 2, false );
+
+			expect( transformed.offset ).to.equal( 3 );
+		} );
+
+		it( 'should increment offset if insertion is in the same parent and the same offset and it is inserted before', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const transformed = position.getTransformedByInsertion( new Position( root, [ 1, 2, 3 ] ), 2, true );
+
+			expect( transformed.offset ).to.equal( 5 );
+		} );
+
+		it( 'should not increment offset if insertion is in the same parent and further offset', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const transformed = position.getTransformedByInsertion( new Position( root, [ 1, 2, 4 ] ), 2, false );
+
+			expect( transformed.offset ).to.equal( 3 );
+		} );
+
+		it( 'should update path if insertion position parent is a node from that path and offset is before next node on that path', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const transformed = position.getTransformedByInsertion( new Position( root, [ 1, 2 ] ), 2, false );
+
+			expect( transformed.path ).to.deep.equal( [ 1, 4, 3 ] );
+		} );
+
+		it( 'should not update path if insertion position parent is a node from that path and offset is after next node on that path', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const transformed = position.getTransformedByInsertion( new Position( root, [ 1, 3 ] ), 2, false );
+
+			expect( transformed.path ).to.deep.equal( [ 1, 2, 3 ] );
+		} );
+	} );
+
+	describe( 'getTransformedByDeletion', () => {
+		it( 'should return a new Position instance', () => {
+			const position = new Position( root, [ 0 ] );
+			const transformed = position.getTransformedByDeletion( new Position( root, [ 2 ] ), 4 );
+
+			expect( transformed ).not.to.equal( position );
+			expect( transformed ).to.be.instanceof( Position );
+		} );
+
+		it( 'should return null if original position is inside one of removed nodes', () => {
+			const position = new Position( root, [ 1, 2 ] );
+			const transformed = position.getTransformedByDeletion( new Position( root, [ 0 ] ), 2 );
+
+			expect( transformed ).to.be.null;
+		} );
+
+		it( 'should decrement offset if deletion is in the same parent and closer offset', () => {
+			const position = new Position( root, [ 1, 2, 7 ] );
+			const transformed = position.getTransformedByDeletion( new Position( root, [ 1, 2, 2 ] ), 2 );
+
+			expect( transformed.offset ).to.equal( 5 );
+		} );
+
+		it( 'should set position offset to deletion offset if position is between removed nodes', () => {
+			const position = new Position( root, [ 1, 2, 4 ] );
+			const transformed = position.getTransformedByDeletion( new Position( root, [ 1, 2, 3 ] ), 5 );
+
+			expect( transformed.offset ).to.equal( 3 );
+		} );
+
+		it( 'should not decrement offset if deletion position is in different root', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const transformed = position.getTransformedByDeletion( new Position( otherRoot, [ 1, 2, 1 ] ), 2 );
+
+			expect( transformed.offset ).to.equal( 3 );
+		} );
+
+		it( 'should not decrement offset if deletion is in the same parent and further offset', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const transformed = position.getTransformedByDeletion( new Position( root, [ 1, 2, 4 ] ), 2 );
+
+			expect( transformed.offset ).to.equal( 3 );
+		} );
+
+		it( 'should update path if deletion position parent is a node from that path and offset is before next node on that path', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const transformed = position.getTransformedByDeletion( new Position( root, [ 1, 0 ] ), 2 );
+
+			expect( transformed.path ).to.deep.equal( [ 1, 0, 3 ] );
+		} );
+
+		it( 'should not update path if deletion position parent is a node from that path and offset is after next node on that path', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const transformed = position.getTransformedByDeletion( new Position( root, [ 1, 3 ] ), 2 );
+
+			expect( transformed.path ).to.deep.equal( [ 1, 2, 3 ] );
+		} );
+	} );
+
+	describe( 'getTransformedByMove', () => {
+		it( 'should increment offset if a range was moved to the same parent and closer offset', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const transformed = position.getTransformedByMove( new Position( root, [ 2 ] ), new Position( root, [ 1, 2, 0 ] ), 3, false );
+
+			expect( transformed.path ).to.deep.equal( [ 1, 2, 6 ] );
+		} );
+
+		it( 'should decrement offset if a range was moved from the same parent and closer offset', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const transformed = position.getTransformedByMove( new Position( root, [ 1, 2, 0 ] ), new Position( root, [ 2 ] ), 3, false );
+
+			expect( transformed.path ).to.deep.equal( [ 1, 2, 0 ] );
+		} );
+
+		it( 'should update path if a range contained this position', () => {
+			const position = new Position( root, [ 1, 2, 3 ] );
+			const transformed = position.getTransformedByMove( new Position( root, [ 1, 1 ] ), new Position( root, [ 2, 1 ] ), 3, false );
+
+			expect( transformed.path ).to.deep.equal( [ 2, 2, 3 ] );
+		} );
+	} );
+
+	describe( '_getCombined', () => {
+		it( 'should return correct combination of this and given positions', () => {
+			const position = new Position( root, [ 1, 3, 4, 2 ] );
+			const sourcePosition = new Position( root, [ 1, 1 ] );
+			const targetPosition = new Position( root, [ 2, 5 ] );
+
+			const combined = position._getCombined( sourcePosition, targetPosition );
+
+			expect( combined.path ).to.deep.equal( [ 2, 7, 4, 2 ] );
+		} );
+	} );
+} );

+ 21 - 21
packages/ckeditor5-engine/tests/document/positioniterator.js → packages/ckeditor5-engine/tests/treemodel/positioniterator.js

@@ -3,17 +3,17 @@
  * For licensing, see LICENSE.md.
  */
 
-/* bender-tags: document */
+/* bender-tags: treemodel */
 
 'use strict';
 
 const modules = bender.amd.require(
-	'document/document',
-	'document/element',
-	'document/character',
-	'document/positioniterator',
-	'document/position',
-	'document/range'
+	'treemodel/document',
+	'treemodel/element',
+	'treemodel/character',
+	'treemodel/positioniterator',
+	'treemodel/position',
+	'treemodel/range'
 );
 
 describe( 'range iterator', () => {
@@ -23,12 +23,12 @@ describe( 'range iterator', () => {
 	let doc, expectedItems, root, img1, paragraph, b, a, r, img2, x;
 
 	before( () => {
-		Document = modules[ 'document/document' ];
-		Element = modules[ 'document/element' ];
-		Character = modules[ 'document/character' ];
-		PositionIterator = modules[ 'document/positioniterator' ];
-		Position = modules[ 'document/position' ];
-		Range = modules[ 'document/range' ];
+		Document = modules[ 'treemodel/document' ];
+		Element = modules[ 'treemodel/element' ];
+		Character = modules[ 'treemodel/character' ];
+		PositionIterator = modules[ 'treemodel/positioniterator' ];
+		Position = modules[ 'treemodel/position' ];
+		Range = modules[ 'treemodel/range' ];
 
 		ELEMENT_ENTER = PositionIterator.ELEMENT_ENTER;
 		ELEMENT_LEAVE = PositionIterator.ELEMENT_LEAVE;
@@ -74,7 +74,7 @@ describe( 'range iterator', () => {
 	} );
 
 	it( 'should return next position', () => {
-		let iterator = new PositionIterator( new Position( [ 0 ], root ) ); // beginning of root
+		let iterator = new PositionIterator( new Position( root, [ 0 ] ) ); // beginning of root
 		let i, len;
 
 		for ( i = 0, len = expectedItems.length; i < len; i++ ) {
@@ -84,7 +84,7 @@ describe( 'range iterator', () => {
 	} );
 
 	it( 'should return previous position', () => {
-		let iterator = new PositionIterator( new Position( [ 2 ], root ) ); // ending of root
+		let iterator = new PositionIterator( new Position( root, [ 2 ] ) ); // ending of root
 
 		for ( let i = expectedItems.length - 1; i >= 0; i-- ) {
 			expect( iterator.previous() ).to.deep.equal( { done: false, value: expectedItems[ i ] } );
@@ -93,8 +93,8 @@ describe( 'range iterator', () => {
 	} );
 
 	it( 'should return next position in the boundaries', () => {
-		let start = new Position( [ 1, 0 ], root ); // p, 0
-		let end = new Position( [ 1, 3, 0 ], root ); // img, 0
+		let start = new Position( root, [ 1, 0 ] ); // p, 0
+		let end = new Position( root, [ 1, 3, 0 ] ); // img, 0
 
 		let iterator = new PositionIterator( new Range( start, end ) );
 
@@ -107,8 +107,8 @@ describe( 'range iterator', () => {
 	} );
 
 	it( 'should return previous position in the boundaries', () => {
-		let start = new Position( [ 1, 0 ], root ); // p, 0
-		let end = new Position( [ 1, 3, 0 ], root ); // img, 0
+		let start = new Position( root, [ 1, 0 ] ); // p, 0
+		let end = new Position( root, [ 1, 3, 0 ] ); // img, 0
 
 		let iterator = new PositionIterator( new Range( start, end ), end );
 
@@ -121,8 +121,8 @@ describe( 'range iterator', () => {
 	} );
 
 	it( 'should return iterate over the range', () => {
-		let start = new Position( [ 0 ], root ); // begging of root
-		let end = new Position( [ 2 ], root ); // ending of root
+		let start = new Position( root, [ 0 ] ); // begging of root
+		let end = new Position( root, [ 2 ] ); // ending of root
 		let range = new Range( start, end );
 
 		let i = 0;

+ 325 - 0
packages/ckeditor5-engine/tests/treemodel/range.js

@@ -0,0 +1,325 @@
+/**
+ * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/* bender-tags: treemodel */
+
+'use strict';
+
+const modules = bender.amd.require(
+	'treemodel/range',
+	'treemodel/position',
+	'treemodel/element',
+	'treemodel/character',
+	'treemodel/document'
+);
+
+describe( 'Range', () => {
+	let Range, Position, Element, Character, Document;
+
+	before( () => {
+		Position = modules[ 'treemodel/position' ];
+		Range = modules[ 'treemodel/range' ];
+		Element = modules[ 'treemodel/element' ];
+		Character = modules[ 'treemodel/character' ];
+		Document = modules[ 'treemodel/document' ];
+	} );
+
+	let range, start, end, root;
+
+	beforeEach( () => {
+		let doc = new Document();
+		root = doc.createRoot( 'root' );
+
+		start = new Position( root, [ 0 ] );
+		end = new Position( root, [ 1 ] );
+
+		range = new Range( start, end );
+	} );
+
+	describe( 'constructor', () => {
+		it( 'should create a range with given positions', () => {
+			expect( range ).to.have.property( 'start' ).that.equal( start );
+			expect( range ).to.have.property( 'end' ).that.equal( end );
+		} );
+	} );
+
+	describe( 'isEqual', () => {
+		it( 'should return true if the ranges are the same', () => {
+			let sameStart = new Position( root, [ 0 ] );
+			let sameEnd = new Position( root, [ 1 ] );
+
+			let sameRange = new Range( sameStart, sameEnd );
+
+			expect( range.isEqual( sameRange ) ).to.be.true;
+		} );
+
+		it( 'should return false if the start position is different', () => {
+			let range = new Range( start, end );
+
+			let diffStart = new Position( root, [ 1 ] );
+			let sameEnd = new Position( root, [ 1 ] );
+
+			let diffRange = new Range( diffStart, sameEnd );
+
+			expect( range.isEqual( diffRange ) ).to.not.be.true;
+		} );
+
+		it( 'should return false if the end position is different', () => {
+			let sameStart = new Position( root, [ 0 ] );
+			let diffEnd = new Position( root, [ 0 ] );
+
+			let diffRange = new Range( sameStart, diffEnd );
+
+			expect( range.isEqual( diffRange ) ).to.not.be.true;
+		} );
+	} );
+
+	describe( 'static constructors', () => {
+		let p, f, o, z;
+
+		// root
+		//  |- p
+		//     |- f
+		//     |- o
+		//     |- z
+		before( () => {
+			f = new Character( 'f' );
+			o = new Character( 'o' );
+			z = new Character( 'z' );
+
+			p = new Element( 'p', [], [ f, o, z ] );
+
+			root.insertChildren( 0, [ p ] );
+		} );
+
+		describe( 'createFromElement', () => {
+			it( 'should return range', () => {
+				const range = Range.createFromElement( p );
+
+				expect( range.start.path ).to.deep.equal( [ 0, 0 ] );
+				expect( range.end.path ).to.deep.equal( [ 0, 3 ] );
+			} );
+		} );
+
+		describe( 'createFromParentsAndOffsets', () => {
+			it( 'should return range', () => {
+				const range = Range.createFromParentsAndOffsets( root, 0, p, 2 );
+
+				expect( range.start.path ).to.deep.equal( [ 0 ] );
+				expect( range.end.path ).to.deep.equal( [ 0, 2 ] );
+			} );
+		} );
+
+		describe( 'createFromPositionAndShift', () => {
+			it( 'should make range from start position and offset', () => {
+				const position = new Position( root, [ 1, 2, 3 ] );
+				const range = Range.createFromPositionAndShift( position, 4 );
+
+				expect( range ).to.be.instanceof( Range );
+				expect( range.start.isEqual( position ) ).to.be.true;
+				expect( range.end.root ).to.equal( range.start.root );
+				expect( range.end.path ).to.deep.equal( [ 1, 2, 7 ] );
+			} );
+		} );
+	} );
+
+	describe( 'getNodes', () => {
+		it( 'should iterate over all nodes which "starts" in the range', () => {
+			let nodes = [];
+
+			const a = new Character( 'a' );
+			const b = new Character( 'b' );
+			const x = new Character( 'x' );
+			const y = new Character( 'y' );
+
+			const e1 = new Element( 'e1' );
+			const e2 = new Element( 'e2' );
+
+			e1.insertChildren( 0, [ a, b ] );
+			e2.insertChildren( 0, [ x, y ] );
+			root.insertChildren( 0, [ e1, e2 ] );
+
+			let range = new Range(
+				new Position( root, [ 0, 1 ] ),
+				new Position( root, [ 1, 1 ] )
+			);
+
+			for ( let node of range.getNodes() ) {
+				nodes.push( node );
+			}
+
+			expect( nodes ).to.deep.equal( [ b, e2, x ] );
+		} );
+	} );
+
+	describe( 'clone', () => {
+		it( 'should return a new, equal position', () => {
+			const clone = range.clone();
+
+			expect( clone ).not.to.be.equal( range ); // clone is not pointing to the same object as position
+			expect( clone.isEqual( range ) ).to.be.true; // but they are equal in the position-sense
+		} );
+	} );
+
+	describe( 'containsPosition', () => {
+		beforeEach( () => {
+			range = new Range( new Position( root, [ 1 ] ), new Position( root, [ 3 ] ) );
+		} );
+
+		it( 'should return false if position is before range', () => {
+			const position = new Position( root, [ 0, 4 ] );
+
+			expect( range.containsPosition( position ) ).to.be.false;
+		} );
+
+		it( 'should return false if position is after range', () => {
+			const position = new Position( root, [ 3, 0 ] );
+
+			expect( range.containsPosition( position ) ).to.be.false;
+		} );
+
+		it( 'should return true if position is inside range', () => {
+			const position = new Position( root, [ 2, 2 ] );
+
+			expect( range.containsPosition( position ) ).to.be.true;
+		} );
+	} );
+
+	describe( 'getTransformedByInsertion', () => {
+		it( 'should return an array of Range objects', () => {
+			const range = new Range( new Position( root, [ 0 ] ), new Position( root, [ 1 ] ) );
+			const transformed = range.getTransformedByInsertion( new Position( root, [ 2 ] ), 2 );
+
+			expect( transformed ).to.be.instanceof( Array );
+			expect( transformed[ 0 ] ).to.be.instanceof( Range );
+		} );
+
+		it( 'should update it\'s positions offsets if insertion is before range and they are affected', () => {
+			const range = new Range( new Position( root, [ 3, 2 ] ), new Position( root, [ 3, 4 ] ) );
+			const transformed = range.getTransformedByInsertion( new Position( root, [ 3, 1 ] ), 2 );
+
+			expect( transformed[ 0 ].start.offset ).to.equal( 4 );
+			expect( transformed[ 0 ].end.offset ).to.equal( 6 );
+		} );
+
+		it( 'should update it\'s positions paths if insertion is before range and they are affected', () => {
+			const range = new Range( new Position( root, [ 3, 2 ] ), new Position( root, [ 4, 4 ] ) );
+			const transformed = range.getTransformedByInsertion( new Position( root, [ 0 ] ), 2 );
+
+			expect( transformed[ 0 ].start.path[ 0 ] ).to.equal( 5 );
+			expect( transformed[ 0 ].end.path[ 0 ] ).to.equal( 6 );
+		} );
+
+		it( 'should return array with two ranges and updated positions if insertion was in the middle of range', () => {
+			const range = new Range( new Position( root, [ 3, 2 ] ), new Position( root, [ 5, 4 ] ) );
+			const transformed = range.getTransformedByInsertion( new Position( root, [ 4, 1, 6 ] ), 4 );
+
+			expect( transformed.length ).to.equal( 2 );
+
+			expect( transformed[ 0 ].start.path ).to.deep.equal( [ 3, 2 ] );
+			expect( transformed[ 0 ].end.path ).to.deep.equal( [ 4, 1, 6 ] );
+
+			expect( transformed[ 1 ].start.path ).to.deep.equal( [ 4, 1, 10 ] );
+			expect( transformed[ 1 ].end.path ).to.deep.equal( [ 5, 4 ] );
+		} );
+
+		it( 'should not updated positions if insertion is after range', () => {
+			const range = new Range( new Position( root, [ 3, 2 ] ), new Position( root, [ 4, 4 ] ) );
+			const transformed = range.getTransformedByInsertion( new Position( root, [ 4, 4 ] ), 3 );
+
+			expect( transformed[ 0 ].start.path ).to.deep.equal( [ 3, 2 ] );
+			expect( transformed[ 0 ].end.path ).to.deep.equal( [ 4, 4 ] );
+		} );
+	} );
+
+	describe( 'getDifference', () => {
+		let range;
+
+		beforeEach( () => {
+			range = new Range( new Position( root, [ 3, 2 ] ), new Position( root, [ 5, 4 ] ) );
+		} );
+
+		it( 'should return an array of Range objects', () => {
+			const otherRange = new Range( new Position( root, [ 6 ] ), new Position( root, [ 7 ] ) );
+			const diff = range.getDifference( otherRange );
+
+			expect( diff ).to.be.instanceof( Array );
+			expect( diff[ 0 ] ).to.be.instanceof( Range );
+		} );
+
+		it( 'should return original range if other range does not intersect with it', () => {
+			const otherRange = new Range( new Position( root, [ 6 ] ), new Position( root, [ 7 ] ) );
+			const diff = range.getDifference( otherRange );
+
+			expect( diff[ 0 ].start.path ).to.deep.equal( [ 3, 2 ] );
+			expect( diff[ 0 ].end.path ).to.deep.equal( [ 5, 4 ] );
+		} );
+
+		it( 'should return shrunken range if other range intersects with it', () => {
+			const otherRange = new Range( new Position( root, [ 4, 1 ] ), new Position( root, [ 7 ] ) );
+			const diff = range.getDifference( otherRange );
+
+			expect( diff[ 0 ].start.path ).to.deep.equal( [ 3, 2 ] );
+			expect( diff[ 0 ].end.path ).to.deep.equal( [ 4, 1 ] );
+		} );
+
+		it( 'should return an empty array if other range contains or is same as the original range', () => {
+			const otherRange = new Range( new Position( root, [ 2 ] ), new Position( root, [ 6 ] ) );
+			const diff = range.getDifference( otherRange );
+
+			expect( diff.length ).to.equal( 0 );
+		} );
+
+		it( 'should two ranges if other range is contained by the original range', () => {
+			const otherRange = new Range( new Position( root, [ 3, 7 ] ), new Position( root, [ 4, 1 ] ) );
+			const diff = range.getDifference( otherRange );
+
+			expect( diff.length ).to.equal( 2 );
+
+			expect( diff[ 0 ].start.path ).to.deep.equal( [ 3, 2 ] );
+			expect( diff[ 0 ].end.path ).to.deep.equal( [ 3, 7 ] );
+
+			expect( diff[ 1 ].start.path ).to.deep.equal( [ 4, 1 ] );
+			expect( diff[ 1 ].end.path ).to.deep.equal( [ 5, 4 ] );
+		} );
+	} );
+
+	describe( 'getIntersection', () => {
+		let range;
+
+		beforeEach( () => {
+			range = new Range( new Position( root, [ 3, 2 ] ), new Position( root, [ 5, 4 ] ) );
+		} );
+
+		it( 'should return null if ranges do not intersect', () => {
+			const otherRange = new Range( new Position( root, [ 5, 4 ] ), new Position( root, [ 7 ] ) );
+			const common = range.getIntersection( otherRange );
+
+			expect( common ).to.be.null;
+		} );
+
+		it( 'should return a range equal to the common part of ranges - original range contains the other range', () => {
+			const otherRange = new Range( new Position( root, [ 4 ] ), new Position( root, [ 5 ] ) );
+			const common = range.getIntersection( otherRange );
+
+			expect( common.isEqual( otherRange ) ).to.be.true;
+		} );
+
+		it( 'should return a range equal to the common part of ranges - original range is contained by the other range', () => {
+			const otherRange = new Range( new Position( root, [ 3 ] ), new Position( root, [ 6 ] ) );
+			const common = range.getIntersection( otherRange );
+
+			expect( common.isEqual( range ) ).to.be.true;
+		} );
+
+		it( 'should return a range equal to the common part of ranges - original range intersects with the other range', () => {
+			const otherRange = new Range( new Position( root, [ 3 ] ), new Position( root, [ 4, 7 ] ) );
+			const common = range.getIntersection( otherRange );
+
+			expect( common.start.path ).to.deep.equal( [ 3, 2 ] );
+			expect( common.end.path ).to.deep.equal( [ 4, 7 ] );
+		} );
+	} );
+} );

+ 7 - 7
packages/ckeditor5-engine/tests/document/rootelement.js → packages/ckeditor5-engine/tests/treemodel/rootelement.js

@@ -5,7 +5,7 @@
 
 /* jshint expr: true */
 
-/* bender-tags: document */
+/* bender-tags: treemodel */
 
 /* bender-include: ../_tools/tools.js */
 
@@ -14,18 +14,18 @@
 const getIteratorCount = bender.tools.core.getIteratorCount;
 
 const modules = bender.amd.require(
-	'document/document',
-	'document/element',
-	'document/rootelement'
+	'treemodel/document',
+	'treemodel/element',
+	'treemodel/rootelement'
 );
 
 describe( 'Element', () => {
 	let Document, Element, RootElement;
 
 	before( () => {
-		Document = modules[ 'document/document' ];
-		Element = modules[ 'document/element' ];
-		RootElement = modules[ 'document/rootelement' ];
+		Document = modules[ 'treemodel/document' ];
+		Element = modules[ 'treemodel/element' ];
+		RootElement = modules[ 'treemodel/rootelement' ];
 	} );
 
 	describe( 'constructor', () => {

+ 5 - 5
packages/ckeditor5-engine/tests/document/text.js → packages/ckeditor5-engine/tests/treemodel/text.js

@@ -5,20 +5,20 @@
 
 /* jshint expr: true */
 
-/* bender-tags: document */
+/* bender-tags: treemodel */
 
 'use strict';
 
 const modules = bender.amd.require(
-	'document/text',
-	'document/attribute'
+	'treemodel/text',
+	'treemodel/attribute'
 );
 
 describe( 'Text', () => {
 	describe( 'constructor', () => {
 		it( 'should create character without attributes', () => {
-			const Text = modules[ 'document/text' ];
-			const Attribute = modules[ 'document/attribute' ];
+			const Text = modules[ 'treemodel/text' ];
+			const Attribute = modules[ 'treemodel/attribute' ];
 
 			let attrs = [ new Attribute( 'bold', true ) ];
 			let text = new Text( 'bar', attrs );

+ 2 - 2
packages/ckeditor5-engine/tests/utils/utils.js

@@ -140,13 +140,13 @@ describe( 'utils', () => {
 			expect( result ).to.equal( utils.compareArrays.EXTENSION );
 		} );
 
-		it( 'should return DIFFERENT flag, when arrays are not same', () => {
+		it( 'should return index on which arrays differ, when arrays are not the same', () => {
 			let a = [ 'abc', 0, 3 ];
 			let b = [ 'abc', 1, 3 ];
 
 			let result = utils.compareArrays( a, b );
 
-			expect( result ).to.equal( utils.compareArrays.DIFFERENT );
+			expect( result ).to.equal( 1 );
 		} );
 	} );