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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With