Gaurav
Gaurav

Reputation: 28755

Is there any way to select all the content of CKEditor 5 by code?

I want to select all content of the editor and execute a command on it in CKEditor 5.

Is it possible?

Upvotes: 1

Views: 2336

Answers (1)

Reinmar
Reinmar

Reputation: 22013

The shortest code which will get you there is this:

const root = doc.getRoot();

editor.model.change( writer => {
    writer.setSelection( root, 'in' );

    // Execute command in the same change() block to have just one undo step.
    editor.execute( 'someCommand' );
} );

It uses the model writer's setSelection().

However, it's not entirely correct. The above code tries to make the following selection:

<$root>[<paragraph>X</paragraph><paragraph>Y</paragraph>]</$root>

While what you want to have is this:

<$root><paragraph>[X</paragraph><paragraph>Y]</paragraph></$root>

That's because the selection should always stick to a text (or object elements).

Fortunately, since version 11.0.0 CKEditor 5 validates the selection's position and so it will be automatically moved to the correct place.

Prior to v11.0.0 or if you want to be really correct, you need to implement a bit longer solution which finds the right selection positions at the beginning and at the end of the content:

import Range from '@ckeditor/ckeditor5-engine/src/model/range';

const doc = editor.model.document;
const root = doc.getRoot();

editor.model.change( writer => {
    const range = Range.createIn( root );

    const startRange = editor.model.schema.getNearestSelectionRange( range.start );
    const endRange = editor.model.schema.getNearestSelectionRange( range.end );

    writer.setSelection( new Range( startRange.start, endRange.end ) );

    // Execute command in the same change() block to have just one undo step.
    editor.execute( 'someCommand' );
} );

Upvotes: 1

Related Questions