Syntax Highlighting Textarea, Reloaded

A couple of years ago I tried my hand at making a DHTML-based syntax highlighting editor, for use in web applications. The result has been posted in my portfolio for quite some time, but it never worked particularly well, and was quite feature-poor. It was also very heavy - it relied on javascript for even basic editing capability, and therefore did not degrade well.

I had an idea about a year ago to start the whole thing over again with a different way of handling input (which I thought was pretty clever): Instead of building the editor from the ground up using javascript, use a textarea for the editor. Better yet, take an existing textarea, apply a javascript constructor to it, and it gets converted into a syntax highlighting textarea. I planned to accomplish this by making the textarea mostly transparent (but still slightly there, for interaction purposes) and positioning the highlighted text behind it. The highlighted text - colored with CSS - would be updated whenever the textarea changed. Simple, right?

I whipped up a quick proof of concept and quickly forgot about the whole idea as my workload became too great. A couple of days ago I decided to start fresh on this thing and do it right. Here are the results so far. It seems to work in Firefox, Opera, and IE6 to a limited extent; Safari borks it up because their tab width is different in a textarea than it is in a block of preformatted text (Don’t ask me why; this probably comes from Konq, though, and suggests that Konq will also fail).

The beauty of this is that the code will get submitted to a form containing the textarea without any trickery or additional work. Also, if javascript is disabled, the user will just be presented with a plain old textarea - and at least the application will still be usable.

There is a lot of optimization to be done. You might notice that it quickly gets unusably slow as the document gets longer and longer. This is because it typically has to re-color most of the document on every keypress. I’ve added an optimization wherein the highlighting will start from the last initial state before the cursor position (if it can be found), so this helps as long as you restrict your editing to the end of the document :-D. There has got to be a way to do a similar optimization which somehow detects when the parser returns to an initial state that was already an initial state, but I haven’t thought of it yet. It will probably involve “spying” on the input to the textarea to get an idea of what’s going on, and making parsing decisions based on that.

Anyway, stay tuned for that stuff, and e-mail me if you have a suggestion! Remember, comments are disabled because of the dirty spammers (who should all be killed in gruesome ways) - my e-mail address is jeremy at [the domain you're looking at].

Leave a comment

You must be logged in to post a comment.