Make text editor with syntax highlight

4

How can I make a syntax highlighting HTML system for a text editor?

I thought of using a <pre> tag with contenteditable="true" , so using RegEx I would override the syntaxes of contentText, and would modify the innerHTML ...

But that does not work. Remembering that I want to make a system from scratch, and not use some script ready ... I just need a basic idea of how to do it.

Code:

<!DOCTYPE html>
<html>
<head>
    <script>
        function highlight(){
            txt = document.getElementsByTagName("pre")[0].textContent;
            txt = txt.replace(/ (abc|teste) /gi, "<span style='color:#F00'>teste</span>");
            document.getElementsByTagName("pre")[0].innerHTML = txt;
        }
    </script>
</head>

<body>
    <pre contenteditable="true" onkeyup="highlight();">
    </pre>
</body>
</html>
    
asked by anonymous 19.08.2015 / 03:15

1 answer

4

The implementation of this in itself is by no means a simple task, if it is just coloring the text but without allowing the user to edit, regular expressions serve the same you already did, now, for editing will have more headache.

You will have to capture the keystrokes and create a whole logic behind to simulate the editor, for example, keep a list of lines and each line a list of tokens, edit it according to the key press and position of the caret.

And then as the user edits the line, you would have to regenerate the graphical representation of it in the container.

Some things to read:

link link

    
19.08.2015 / 08:00