CKEditor5 Insert Text without breaking current element

Viewed 1462

I have the following code to insert Text at current position:

editor.model.change( writer => {
                    editor.model.insertContent( writer.createText('[Insert]') );
                });

This works fine in most case like inserting inside a paragraph or headline. Example given:

Before:

<h2>Sample</h2>

After insertion:

<h2>Samp[Insert]le</h2>



But if the text is preformatted for example with a custom font size it breaks the html element:

Before:

<p><span class="text-huge">Sample formatted text</span></p>

After insertion:

<p><span class="text-huge">Sample fo</span>[Insert]<span class="text-huge">rmatted text</span></p>

Notice, that the Element is split up and the text is inserted without applying the custom styles. The [Insert] is set between two spans...

How can I Insert a text directly without modifying html structure?

1 Answers

This happens because created text node has no attributes set. To do this you need to get current selection's attributes and pass it to the writer.createText() method. Then the created text node will have those attributes:

const model = editor.model;

model.change( writer => {
    const currentAttributes = model.document.selection.getAttributes();

    model.insertContent( writer.createText( '[Foo]', currentAttributes ) );
} );

Alternatively you can use writer.insertText() method if you're inserting text:

editor.model.change( writer => {
    const selection = editor.model.document.selection;

    const currentAttributes = selection.getAttributes();
    const insertPosition = selection.focus;

    writer.insertText( '[Foo]', currentAttributes, insertPosition );
} );
Related