Make text editor with syntax Highlight

Asked

Viewed 360 times

4

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

I thought of using a tag <pre> with the contenteditable="true", then using Regex I would replace the syntax of contentText, and modify innerHTML...

It just doesn’t 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.

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>

1 answer

4


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

You will have to capture the keystroke and create a whole logic behind to simulate the editor, for example, keep a list of lines and each row a list of tokens, edit it according to the key pressing 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:

https://stackoverflow.com/questions/7377344/how-do-i-write-a-parser-in-c https://en.wikipedia.org/wiki/Lexical_analysis

  • I managed to do something using a textarea, and taking the value of it to be presented in the pre tag. With what I read about, I think I can "redirect" the typed in the pre to the textarea... I believe I know how to do this. But I have a question I would like to resolve before continuing.. I know it doesn’t have to do with the main one, but I didn’t want to do another topic... In CSS, you can "force" the color of the child tags? I would like inside the quotes (" "), not to change the color in the syntax.... Print: http://prntscr.com/86i0oo By the way, the links helped me a lot. :)

  • 1

    Yes, yes, the! Important overrides any other statement. http://www.electrictoolbox.com/using-important-css/

  • Oh yeah, I’d forgotten the Mportant rsrs. Thanks. :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.