# ModelDocument

class

Data model's document. It contains the model's structure, its selection and the history of changes.

Read more about working with the model in [introduction to the the editing engine's architecture](../framework/architecture/editing-engine.md#model).

Usually, the document contains just one [root element](#member-roots), so you can retrieve it by just calling [`getRoot`](#function-getRoot) without specifying its name:

```typescript
model.document.getRoot(); // -> returns the main root
```

However, the document may contain multiple roots – e.g. when the editor has multiple editable areas (e.g. a title and a body of a message).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L56)

<a id="properties">

## Properties

<a id="member-differ">

### `differ: Differ` _(readonly)_

The model differ object. Its role is to buffer changes done on the model document and then calculate a diff of those changes.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L81)

<a id="member-graveyard">

### `graveyard: ModelRootElement` _(readonly)_

The graveyard tree root. A document always has a graveyard root that stores removed nodes.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L223)

<a id="member-history">

### `history: History` _(readonly)_

The document's history.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L65)

<a id="member-isReadOnly">

### `isReadOnly: boolean` _(readonly)_

Defines whether the document is in a read-only mode.

The user should not be able to change the data of a document that is read-only.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L90)

<a id="member-model">

### `model: Model` _(readonly)_

The [model](module_engine_model_model-Model.md) that the document is a part of.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L60)

<a id="member-roots">

### `roots: Collection<ModelRootElement>` _(readonly)_

A list of roots that are owned and managed by this document. Use [`createRoot`](#function-createRoot), [`getRoot`](#function-getRoot) and [`getRootNames`](#function-getRootNames) to manipulate it.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L76)

<a id="member-selection">

### `selection: ModelDocumentSelection` _(readonly)_

The selection in this document.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L70)

<a id="member-version">

### `version: number`

The document version. Every applied operation increases the version number. It is used to ensure that operations are applied on a proper document version.

This property is equal to [`model.Document#history#version`](module_engine_model_history-History.md#member-version).

If the [base version](module_engine_model_operation_operation-Operation.md#member-baseVersion) does not match the document version, a [model-document-applyoperation-wrong-version](module_utils_ckeditorerror-CKEditorError.md) error is thrown.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L212)

#### Parameters

* `version: number`

<a id="member-_hasSelectionChangedFromTheLastChangeBlock">

### `_hasSelectionChangedFromTheLastChangeBlock: boolean` _(private)_

A flag that indicates whether the selection has changed since last change block.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L100)

<a id="member-_postFixers">

### `_postFixers: Set<ModelPostFixer>` _(private)_

Post-fixer callbacks registered to the model document.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L95)

<a id="methods">

## Methods

<a id="function-constructor">

### `constructor( model )`

Creates an empty document instance with no [`roots`](#member-roots) (other than the [graveyard root](#member-graveyard)).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L106)

#### Parameters

* `model: Model`

<a id="function-createRoot">

### `createRoot( elementName, rootName ) → ModelRootElement`

Creates a new root.

**Note:** do not use this method after the editor has been initialized! If you want to dynamically add a root, use [`model.Writer#addRoot`](module_engine_model_writer-ModelWriter.md#function-addRoot) instead.

**Note:** The default `elementName` value is `'$root'`. When the editor uses a custom root [`modelElement`](module_core_editor_editorconfig-RootConfig.md#member-modelElement), pass the configured model element name explicitly so the created root matches the schema the features expect. See the [Custom root elements](../framework/deep-dive/schema.md#custom-root-elements) section of the [Schema deep-dive](../framework/deep-dive/schema.md) guide for more details.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L244)

#### Parameters

* `elementName: string`

  The element name. Defaults to `'$root'` which also has some basic schema defined (e.g. `$block` elements are allowed inside the `$root`). Make sure to define a proper schema if you use a different name.

  Defaults to `'$root'`

* `rootName: string`

  A unique root name.

  Defaults to `'main'`

#### Returns

* `ModelRootElement`

  The created root.

<a id="function-delegate">

### `delegate( events ) → EmitterMixinDelegateChain` _(inherited)_

Delegates selected events to another [`Emitter`](module_utils_emittermixin-Emitter.md). For instance:

```typescript
emitterA.delegate( 'eventX' ).to( emitterB );
emitterA.delegate( 'eventX', 'eventY' ).to( emitterC );
```

then `eventX` is delegated (fired by) `emitterB` and `emitterC` along with `data`:

```typescript
emitterA.fire( 'eventX', data );
```

and `eventY` is delegated (fired by) `emitterC` along with `data`:

```typescript
emitterA.fire( 'eventY', data );
```

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L539)

#### Parameters

* `events: Array<string>`

  Event names that will be delegated to another emitter.

#### Returns

* `EmitterMixinDelegateChain`

<a id="function-destroy">

### `destroy() → void`

Removes all event listeners set by the document instance.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L263)

#### Returns

* `void`

<a id="function-fire">

### `fire( eventOrInfo, args ) → GetEventInfo<TEvent>[ 'return' ]` _(inherited)_

Fires an event, executing all callbacks registered for it.

The first parameter passed to callbacks is an [`EventInfo`](module_utils_eventinfo-EventInfo.md) object, followed by the optional `args` provided in the `fire()` method call.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L512)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type describing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `eventOrInfo: GetNameOrEventInfo<TEvent>`

  The name of the event or `EventInfo` object if event is delegated.

* `args: TEvent[ 'args' ]`

  Additional arguments to be passed to the callbacks.

#### Returns

* `GetEventInfo<TEvent>[ 'return' ]`

  By default the method returns `undefined`. However, the return value can be changed by listeners through modification of the [`evt.return`](module_utils_eventinfo-EventInfo.md#member-return)'s property (the event info is the first param of every callback).

<a id="function-getRoot">

### `getRoot( name ) → ModelRootElement | null`

Returns a root by its name.

Detached roots are returned by this method. This is to be able to operate on the detached root (for example, to be able to create a position inside such a root for undo feature purposes).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L277)

#### Parameters

* `name: string`

  The root name of the root to return.

  Defaults to `'main'`

#### Returns

* `ModelRootElement | null`

  The root registered under a given name or `null` when there is no root with the given name.

<a id="function-getRootNames">

### `getRootNames( includeDetached ) → Array<string>`

Returns an array with names of all roots added to the document (except the [graveyard root](#member-graveyard)).

Detached roots **are not** returned by this method by default. This is to make sure that all features or algorithms that operate on the document data know which roots are still a part of the document and should be processed.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L289)

#### Parameters

* `includeDetached: boolean`

  Specified whether detached roots should be returned as well.

  Defaults to `false`

#### Returns

* `Array<string>`

<a id="function-getRoots">

### `getRoots( includeDetached ) → Array<ModelRootElement>`

Returns an array with all roots added to the document (except the [graveyard root](#member-graveyard)).

Detached roots **are not** returned by this method by default. This is to make sure that all features or algorithms that operate on the document data know which roots are still a part of the document and should be processed.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L301)

#### Parameters

* `includeDetached: boolean`

  Specified whether detached roots should be returned as well.

  Defaults to `false`

#### Returns

* `Array<ModelRootElement>`

<a id="function-listenTo:BASE_EMITTER">

### `listenTo( emitter, event, callback, options? ) → void` _(inherited)_

Registers a callback function to be executed when an event is fired in a specific (emitter) object.

Events can be grouped in namespaces using `:`. When namespaced event is fired, it additionally fires all callbacks for that namespace.

```typescript
// myEmitter.on( ... ) is a shorthand for myEmitter.listenTo( myEmitter, ... ).
myEmitter.on( 'myGroup', genericCallback );
myEmitter.on( 'myGroup:myEvent', specificCallback );

// genericCallback is fired.
myEmitter.fire( 'myGroup' );
// both genericCallback and specificCallback are fired.
myEmitter.fire( 'myGroup:myEvent' );
// genericCallback is fired even though there are no callbacks for "foo".
myEmitter.fire( 'myGroup:foo' );
```

An event callback can [stop the event](module_utils_eventinfo-EventInfo.md#member-stop) and set the [return value](module_utils_eventinfo-EventInfo.md#member-return) of the [`fire`](#function-fire) method.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L475)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type describing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `emitter: Emitter`

  The object that fires the event.

* `event: TEvent[ 'name' ]`

  The name of the event.

* `callback: GetCallback<TEvent>`

  The function to be called on event.

* `options?: GetCallbackOptions<TEvent>`

  Additional options.

#### Returns

* `void`

<a id="function-off">

### `off( event, callback ) → void` _(inherited)_

Stops executing the callback on the given event. Shorthand for [`this.stopListening( this, event, callback )`](#function-stopListening:BASE_STOP).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L444)

#### Parameters

* `event: string`

  The name of the event.

* `callback: Function`

  The function to stop being called.

#### Returns

* `void`

<a id="function-on">

### `on( event, callback, options? ) → void` _(inherited)_

Registers a callback function to be executed when an event is fired.

Shorthand for [`this.listenTo( this, event, callback, options )`](#function-listenTo:BASE_EMITTER) (it makes the emitter listen on itself).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L416)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type descibing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `event: TEvent[ 'name' ]`

  The name of the event.

* `callback: GetCallback<TEvent>`

  The function to be called on event.

* `options?: GetCallbackOptions<TEvent>`

  Additional options.

#### Returns

* `void`

<a id="function-once">

### `once( event, callback, options? ) → void` _(inherited)_

Registers a callback function to be executed on the next time the event is fired only. This is similar to calling [`on`](#function-on) followed by [`off`](#function-off) in the callback.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L431)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type descibing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `event: TEvent[ 'name' ]`

  The name of the event.

* `callback: GetCallback<TEvent>`

  The function to be called on event.

* `options?: GetCallbackOptions<TEvent>`

  Additional options.

#### Returns

* `void`

<a id="function-registerPostFixer">

### `registerPostFixer( postFixer ) → void`

Used to register a post-fixer callback. A post-fixer mechanism guarantees that the features will operate on a correct model state.

An execution of a feature may lead to an incorrect document tree state. The callbacks are used to fix the document tree after it has changed. Post-fixers are fired just after all changes from the outermost change block were applied but before the [change event](#event-change) is fired. If a post-fixer callback made a change, it should return `true`. When this happens, all post-fixers are fired again to check if something else should not be fixed in the new document tree state.

As a parameter, a post-fixer callback receives a [writer](module_engine_model_writer-ModelWriter.md) instance connected with the executed changes block. Thanks to that, all changes done by the callback will be added to the same [batch](module_engine_model_batch-Batch.md) (and undo step) as the original changes. This makes post-fixer changes transparent for the user.

An example of a post-fixer is a callback that checks if all the data were removed from the editor. If so, the callback should add an empty paragraph so that the editor is never empty:

```typescript
document.registerPostFixer( writer => {
	const changes = document.differ.getChanges();

	// Check if the changes lead to an empty root in the editor.
	for ( const entry of changes ) {
		if ( entry.type == 'remove' && entry.position.root.isEmpty ) {
			writer.insertElement( 'paragraph', entry.position.root, 0 );

			// It is fine to return early, even if multiple roots would need to be fixed.
			// All post-fixers will be fired again, so if there are more empty roots, those will be fixed, too.
			return true;
		}
	}

	return false;
} );
```

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L342)

#### Parameters

* `postFixer: ModelPostFixer`

#### Returns

* `void`

<a id="function-stopDelegating">

### `stopDelegating( event?, emitter? ) → void` _(inherited)_

Stops delegating events. It can be used at different levels:

* To stop delegating all events.
* To stop delegating a specific event to all emitters.
* To stop delegating a specific event to a specific emitter.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L552)

#### Parameters

* `event?: string`

  The name of the event to stop delegating. If omitted, stops it all delegations.

* `emitter?: Emitter`

  (requires `event`) The object to stop delegating a particular event to. If omitted, stops delegation of `event` to all emitters.

#### Returns

* `void`

<a id="function-stopListening:BASE_STOP">

### `stopListening( emitter?, event?, callback? ) → void` _(inherited)_

Stops listening for events. It can be used at different levels:

* To stop listening to a specific callback.
* To stop listening to a specific event.
* To stop listening to all events fired by a specific object.
* To stop listening to all events fired by all objects.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L497)

#### Parameters

* `emitter?: Emitter`

  The object to stop listening to. If omitted, stops it for all objects.

* `event?: string`

  (Requires the `emitter`) The name of the event to stop listening to. If omitted, stops it for all events from `emitter`.

* `callback?: Function`

  (Requires the `event`) The function to be removed from the call list for the given `event`.

#### Returns

* `void`

<a id="function-toJSON">

### `toJSON() → unknown`

A custom `toJSON()` method to solve child-parent circular dependencies.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L351)

#### Returns

* `unknown`

  A clone of this object with the document property changed to a string.

<a id="function-_getDefaultRange">

### `_getDefaultRange() → ModelRange` _(internal)_

Returns the default range for this selection. The default range is a collapsed range that starts and ends at the beginning of this selection's document [default root](#function-_getDefaultRoot).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L423)

#### Returns

* `ModelRange`

<a id="function-_handleChangeBlock">

### `_handleChangeBlock( writer ) → void` _(internal)_

Check if there were any changes done on document, and if so, call post-fixers, fire `change` event for features and conversion and then reset the differ. Fire `change:data` event when at least one operation or buffered marker changes the data.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L371)

#### Parameters

* `writer: ModelWriter`

  The writer on which post-fixers will be called.

#### Returns

* `void`

#### Fires

* [change](#event-change)
* [change:data](#event-change:data)

<a id="function-_validateSelectionRange">

### `_validateSelectionRange( range ) → boolean` _(internal)_

Checks whether a given [range](module_engine_model_range-ModelRange.md) is a valid range for the [document's selection](#member-selection).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L444)

#### Parameters

* `range: ModelRange`

  A range to check.

#### Returns

* `boolean`

  `true` if `range` is valid, `false` otherwise.

<a id="function-_getDefaultRoot">

### `_getDefaultRoot() → ModelRootElement` _(protected)_

Returns the default root for this document which is either the first root that was added to the document using [`createRoot`](#function-createRoot) or the [graveyard root](#member-graveyard) if no other roots were created.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L411)

#### Returns

* `ModelRootElement`

  The default root for this document.

<a id="function-_hasDocumentChangedFromTheLastChangeBlock">

### `_hasDocumentChangedFromTheLastChangeBlock() → boolean` _(protected)_

Returns whether there is a buffered change or if the selection has changed from the last [`enqueueChange()` block](module_engine_model_model-Model.md#function-enqueueChange:DEFAULT_BATCH) or [`change()` block](module_engine_model_model-Model.md#function-change).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L401)

#### Returns

* `boolean`

  Returns `true` if document has changed from the last `change()` or `enqueueChange()` block.

<a id="function-_callPostFixers">

### `_callPostFixers( writer ) → void` _(private)_

Performs post-fixer loops. Executes post-fixer callbacks as long as none of them has done any changes to the model.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L454)

#### Parameters

* `writer: ModelWriter`

  The writer on which post-fixer callbacks will be called.

#### Returns

* `void`

<a id="events">

## Events

<a id="event-change">

### `change( eventInfo, batch )`

Fired after each [`enqueueChange()` block](module_engine_model_model-Model.md#function-enqueueChange:DEFAULT_BATCH) or the outermost [`change()` block](module_engine_model_model-Model.md#function-change) was executed and the document was changed during that block's execution.

The changes which this event will cover include:

* document structure changes,
* selection changes,
* marker changes.

If you want to be notified about all these changes, then simply listen to this event like this:

```typescript
model.document.on( 'change', () => {
	console.log( 'The document has changed!' );
} );
```

If, however, you only want to be notified about the data changes, then use `change:data` event, which is fired for document structure changes and marker changes (which affects the data).

```typescript
model.document.on( 'change:data', () => {
	console.log( 'The data has changed!' );
} );
```

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L514)

#### Parameters

* `eventInfo: EventInfo`

  An object containing information about the fired event.

* `batch: Batch`

  The batch that was used in the executed changes block.

<a id="event-change:data">

### `change:data( eventInfo, batch )`

Fired after each [`enqueueChange()` block](module_engine_model_model-Model.md#function-enqueueChange:DEFAULT_BATCH) or the outermost [`change()` block](module_engine_model_model-Model.md#function-change) was executed and the document was changed during that block's execution.

The changes which this event will cover include:

* document structure changes,
* selection changes,
* marker changes.

If you want to be notified about all these changes, then simply listen to this event like this:

```typescript
model.document.on( 'change', () => {
	console.log( 'The document has changed!' );
} );
```

If, however, you only want to be notified about the data changes, then use `change:data` event, which is fired for document structure changes and marker changes (which affects the data).

```typescript
model.document.on( 'change:data', () => {
	console.log( 'The data has changed!' );
} );
```

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-engine/src/model/document.ts#L514)

#### Parameters

* `eventInfo: EventInfo`

  An object containing information about the fired event.

* `batch: Batch`

  The batch that was used in the executed changes block.

---

Full index of the CKEditor 5 API reference: [llms.txt](llms.txt)
