Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CKEditor 5 - insert text

Tags:

ckeditor5

Is it possible to insert text into the editor at current selection?

I have tried

import Text from '@ckeditor/ckeditor5-engine/src/model/text';

function insertText() {
  let text = new Text('test');
  ckEditor.model.insertContent(text, ckEditor.model.document.selection);
}

where ckEditor is the editor object returned from ClassicEditor.create

code runs without error, but nothing happens

I have managed to get similar code to work from within a plugin, but here I am trying to inject the text from the host app

like image 968
Steve Avatar asked Mar 06 '23 09:03

Steve


2 Answers

I have managed to get similar code to work from within a plugin, but here I am trying to inject the text from the host app

It worked when you implemented it as a plugin because then you used the Text class from the same package which the ClassicEditor depend on to.

When you tried to do the same when using a bundle with the editor, you unknowingly duplicated the whole @ckeditor/ckeditor5-engine package. One instance of this package was bundled into the editor, and the second one you just used later on (in the snippet which you showed), so webpack imported it again.

This is an environmental issue that we have at the moment – you can't add plugins to a CKEditor 5 build.

Fortunately, we noticed this problem a long time ago and much has been improved since then. Inserting a text does not require importing anything:

editor.model.change( writer => {
    const insertPosition = editor.model.document.selection.getFirstPosition();
    writer.insertText( 'foo', insertPosition );
} );

The writer.insertText() method can also insert a text with attributes, so e.g. you can insert bolded text like this:

editor.model.change( writer => {
    const insertPosition = editor.model.document.selection.getFirstPosition();
    writer.insertText( 'foo', { bold: true }, insertPosition );
} );

Or if you want to insert a link, then see How to programatically insert link at current position in CKEditor 5

like image 179
Reinmar Avatar answered May 25 '23 12:05

Reinmar


That worked for me, using the editor returned by (ready):

insertTag(tag: string) {
  const insertPosition = this.editor.model.document.selection.getFirstPosition();
  const viewFragment = this.editor.data.processor.toView(`<p>${tag}</p>`);
  const modelFragment = this.editor.data.toModel(viewFragment);
  this.mod.insertContent(modelFragment);
}

See also the the font.

like image 29
gleitonfranco Avatar answered May 25 '23 12:05

gleitonfranco