May 21, 2008

Humane Code Highlighting and js2-mode

One feature of many text editors that I’ve always been a little skeptical about from a user interface perspective has been syntax highlighting. It certainly looks pretty and serves to make the process of reading and writing code more satisfying, but I’ve had a hard time justifying to myself that it’s something that’s truly useful in a concrete way.

The few examples that always come to mind are when syntax highlighting alerts me to the fact that I’m using the wrong syntax. For instance, a few days ago I was writing CSS that looked like this:

It struck me as odd that the term font-decoration was black, unlike the green terms above it. Without having to read any instructions, it was easy to infer that perhaps I font-decoration wasn’t a valid CSS property. When I tried text-decoration, the term lit up green, indicating that I was on the right track. This was far more pleasant and less cognitively jarring than saving the file, switching to my browser, reloading the page, and discovering that my page didn’t look like what I wanted.

Steve Yegge’s Javascript editing mode for Emacs, js2-mode, really takes this kind of “ambient usefulness” to the next level. That’s because it doesn’t just use colors and styles to indicate syntax, but to indicate semantics as well.

For instance, take this example:

Here js2-mode has underlined the variable poke in orange, which is its indicator that what I’ve typed there, while it will certainly compile and run, may not be the best idea. Moving the cursor to the underline, the text Variable poke hides argument appears in the minibuffer, alerting me to the fact that I won’t be able to access the poke parameter to my function because I’m redefining it in the body of the function.

The editing mode does a lot of things like this. It actually looks at the entire body of code you’re writing, and highlights a variable in bright orange if it hasn’t been declared anywhere (which in Javascript means that it’s implicitly global—eek). It tells me when I’ve written code that may parse correctly in some interpreters but not others. And it does things like this without interrupting my train of thought, and without making me run a separate static code analysis tool between writing and running my code. I’m basically at the point where I consider this tool as indispensable as Firebug; despite the fact that it’s still in the early stages of development and permanently hangs Emacs whenever I type a # character outside of a quoted string, it’s still saved me a lot of time and frustration by politely telling me what I might be doing wrong, instead of getting in my face about it or letting me find out the hard way.

© Atul Varma 2021