Apply heading to selection only
Is this a bug report or feature request?
Other = > question
💻 Version of CKEditor
Custom CK5 based on classic build
❓ Question
How can I change the default behavior of the heading plugin when applying it to a selection.
Example:
Before selecting the text "test" and applying a heading
<p> this is a test sentence</p>
After selecting the text "test" and applying a heading
<p> this is a</p>
<h2>test</h2>
<p>sentence</p>
Steps I've taken to achieve this feature
Replace the execute function in headingcommand.js with:
execute( options ) {
const model = this.editor.model;
const document = model.document;
const modelElement = options.value; // the heading name
model.change(writer => {
const heading = writer.createElement(modelElement);
//TODO: get selected text, and pass to insert text
writer.insertText('example text', heading);
model.insertContent(heading);
});
}
Sadly this only replaces the text and doesn't split the node
@jodator, can you take a look at it?
Is this doable in the current version of ckeditor5 or would this require a lot of workaround?
Hi @josueexhume there's no easy API way to do it. I've came with something like this but this is a bit hacky (uses "enter" command to split blocks - as block splitting isn't easiest thing to do).
const model = editor.model;
const doc = model.document;
model.change( writer => {
// Cache the selected text.
const frag = model.getSelectedContent( doc.selection );
// Remove current selection.
model.deleteContent( doc.selection );
// Split current block (selection after deleteContent is collapsed).
editor.execute( 'enter' );
// Create a heading element and insert a cached text from frag.
const heading = writer.createElement( 'heading2' );
writer.append( frag.getChild( 0 ), heading );
// Insert content before current selection focus.
model.insertContent( heading, writer.createPositionBefore( doc.selection.focus.parent ) );
} );
showcase:

uses "enter" command to split blocks - as block splitting isn't easiest thing to do
Until now we could just use model.insertContent(), because splitting always was connected with inserting a new object. Maybe we need a new utility method in the writer. AFAIR, in this case, splitting "with" a non-object element (heading) will not work as intended.
Thanks, @jodator for now this somewhat works. The other use case that it didn't work for, was if I used it on multiple text blocks.
There has been no activity on this issue for the past two years. We've marked it as stale and will close it in 30 days. We understand it may be relevant, so if you're interested in the solution, leave a comment or reaction under this issue.
We've closed your issue due to inactivity over the last year. We understand that the issue may still be relevant. If so, feel free to open a new one (and link this issue to it).