I want to be able to highlight (i.e. wrap in a span with a color, or some other way) all text that matches a regex in CKEditor. I'd probably add a button to do this, and a button to remove highlighting. My specific use case is to highlight all mustache variables in my HTML templates (make it really easy to see where there are mustache variables).
I've implemented a version where I replace a regex matching mustaches with a span and then the capture group. This appears to break on some templates when I test.
To remove the highlighting, I use editor.removeStyle, which doesn't seem to work in all cases.
Here is an example of what I've implemented:
editor.addCommand( 'highlightMustache', {
exec: function( editor ) {
editor.focus();
editor.document.$.execCommand( 'SelectAll', false, null );
var mustacheRegex = /{{\s?([^}]*)\s?}}/g;
var data = editor.getData().replace(mustacheRegex, '<span style="background-color: #FFFF00">{{ $1 }}</span>');
editor.setData( data );
}
});
// command to unhighlight mustache parameters
editor.addCommand( 'unhighlightMustache', {
exec: function( editor ) {
editor.focus();
editor.document.$.execCommand( 'SelectAll', false, null );
var style = new CKEDITOR.style( { element:'span', styles: { 'background-color': '#FFFF00' },type:CKEDITOR.STYLE_INLINE,alwaysRemoveElement:1 } );
editor.removeStyle( style );
editor.getSelection().removeAllRanges();
}
});
Thanks!