A complete solution would look like this:
const pos = editor.document.selection.getFirstPosition(); // If you want to get the text up to the root boundary: // const posStart = Position.createAt( pos.root ); // const posEnd = Position.createAt( pos.root, 'end' ); // If you want to get the text up to the current element boundary: const posStart = Position.createAt( pos.parent ); const posEnd = Position.createAt( pos.parent, 'end' ); const rangeBefore = new Range( posStart, pos ); const rangeAfter = new Range( pos, posEnd ); let textBefore = ''; let textAfter = ''; // Range is iterable and uses TreeWalker to return all items in the range. // value is of type TreeWalkerValue. for ( const value of rangeBefore ) { if ( value.item.is( 'textProxy' ) ) { textBefore += value.item.data; } } for ( const value of rangeAfter ) { if ( value.item.is( 'textProxy' ) ) { textAfter += value.item.data; } } console.log( textBefore ); console.log( textAfter );
Here you can use TreeWalker to get all the elements in the range and align the text proxies you find there.
Please note that you get TextProxy instead of regular Text , because the walker may need to return part of the node text (if the range ends in the middle of this node text).
EDIT: To reinforce content in a data format (so - including HTML markup, not just text), you need to use several different methods:
function doStuff( editor ) { const pos = editor.document.selection.getFirstPosition(); const posStart = Position.createAt( pos.root ); const posEnd = Position.createAt( pos.root, 'end' ); const rangeBefore = new Range( posStart, pos ); const rangeAfter = new Range( pos, posEnd ); const fragBefore = editor.data.getSelectedContent( new Selection( [ rangeBefore ] ) ); const fragAfter = editor.data.getSelectedContent( new Selection( [ rangeAfter ] ) ); console.log( editor.data.stringify( fragBefore ) ); console.log( editor.data.stringify( fragAfter ) ); }
source share