tadhg.com
tadhg.com
 

star-light Syntax Highlighter

17:23 Tue 29 May 2007
[, ]

I’ve been using star-light by Dean Edwards for a while to do syntax highlighting in HTML, and it works extremely well.

Most syntax highlighters for HTML output require server-side processing, such as a PHP script that parses the source file and styles it appropriately. I don’t like that option because it puts more strain on the server (and my old server is creaking as it is… because I haven’t moved stuff to the new one yet). I also like offline solutions, or at the least solutions that degrade gracefully when offline.

I’ve seen some JavaScript attempts at it, but they haven’t been flexible enough for my purposes, and have tended to feel somewhat intrusive.

star-light, on the other hand, seems ideal. It uses DHTML Behaviors, and a wrapper to get Mozilla to support them. I don’t quite understand what he does to get Mozilla’s engine to do that, but it looks very interesting.

It’s not intrusive, requiring just a class parameter for the pre element. If it can’t reach the files required for the styling, it doesn’t do anything, thus failing gracefully. It doesn’t look that hard to extend it for other languages, although I’ve had no need to do so thus far (Niall’s comment on investing contains Python, but applying the PHP syntax highlighting works perfectly well there). I have encountered a couple of bugs, in that I’ve been able to cause Firefox to crash if the HTML or XML highlighting is used on long chunks of code—I got around that by using the HTC highlighting for those instead, which is similar enough and doesn’t have that bug.

All in all, it’s an excellent, unobtrusive piece of code with no real drawbacks.

As an example, here’s some JavaScript highlighted by star-light (the JavaScript shows a basic closure structure):

myFunction(parameters, someEvent) {
	someEvent.hook = handleEvent;
	
	function handleEvent() {
		doSomethingWithParameters(parameters);
		/*Ha! I have access to the parameters even though you can't pass them to event handlers!*/
	}
};

Incidentally, this is how to make text in pre elements wrap:

white-space: pre; /* CSS2 */
white-space: -moz-pre-wrap; /* Mozilla */
white-space: -hp-pre-wrap; /* HP printers */
white-space: -o-pre-wrap; /* Opera 7 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: pre-wrap; /* CSS 2.1 */
white-space: pre-line; /* CSS 3 (and 2.1 as well, actually) */
word-wrap: break-word; /* IE */
« (previous)

Leave a Reply