Highlight specific strings in TinyMCE editor without affecting underlying content

31 Views Asked by At

In a TinyMCE editor (currently stuck on v4.5.x), I would like to highlight strings that represent placeholders in a body of text - a very simple form of syntax highlighting.

enter image description here

I have reviewed a number of articles and SO posts on the topic, but have not yet found a clean solution to my particular use case. I have tried one approach of adding tags around matched placeholders within the 'change' event, but this has a few drawbacks such as lag due to continuous updates (could combat this with a debounce function of course) and losing cursor position (not sure how to deal with that yet). Naturally, I also don't want the tags to be saved along with the content.

I noticed that the TinyMCE API does include a mechanism for defining clean-up rules, but I have yet to find a clear explanation on these.

Example experimental code below:

        editor.on("change", function () {
            let content = editor.getContent();

            // Strip out and re-add <mark></mark> instances
            content = content.replace(/<\/?mark>/, '');
            content = content.replace(/(%[a-z_]+)/i, '<mark>$1</mark>');

            editor.setContent(content);
        });

Can anybody advise on the 'right' approach to solving this need? Perhaps there is a plugin that allows for flexible syntax rules to be specified? (My preference would be to avoid plugins if practical though.)

Bonus points if I can specify flexible highlighting CSS for the placeholders (eg. italics and a border)!

0

There are 0 best solutions below