'How to have syntax highlighting in a contenteditable div?

I have a contenteditable div:

<div class="one" contenteditable="true">A</div>

If the user enters HTML, CSS or Javascript tags into that contenteditable div, how would I make it syntax highlighted?

So as the user types in variables, tags, etc, they are colour coded



Solution 1:[1]

This is not as easy as it might seem at first.

You can create your own solution using some existing highlighting library like PrismJS or HighlightJS and then implement a custom re-render functionality which saves the current cursor position -> parses the content & updates the look (this would be the task of the syntax highlighting lib), and then sets the cursor to the previous position again.

There is one "tutorial" by bililite which can help you with this task. You can find it here.

TBH: I'm surprised that there (correct me if I'm wrong) seems to be no open source solution for this. Would there be a need for that?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Patrick Hübl-Neschkudla