Thursday, May 11, 2006

Syntax highlighting using Javascript

I've been looking around for a web-based source code editor. My search was for an editor embedded in a web page which would allow the modification of code stored in a server. This does not mean an editor for editing web-technology related source files. Searching the web mostly resulted in editors for JavaScript, html etc.

Currently About:Edit is a very good source code editor. It is commercial product that provides a lot of features including syntax highlighting. Its impossible to hide the source code of JavaScript apps, so my inquisitiveness got the better of me. I had a look at their source code. The code is very complicated and they have tried very very hard to make it as obfuscated as possible.

I came across some guy who had a post on their blog (I can’t acknowledge the source as I've lost it), a nice proof-of-concept of using JavaScript for syntax highlighting a static page. His idea was simple; use regular expressions to search for keywords in a document and then replace them with formatted text. Here’s an example,

var keywordPattern = /\band|not|null|equalp|match\b/g;

var text = document.getElementById("constraints").innerHTML;
document.getElementById("constraints").innerHTML =
text.replace(keywordPattern, function(text) {
return "" + text + ""

The code looks for a set of keywords (and, not etc) and adds a span tag around it. It works like a charm.

This is no solution to my intial problem of an code editor. However, it does provide a nice way of displaying code.

No comments: