Friday, September 18, 2009

Syntax Highlighting

A lot of code these days in a variety of languages is posted on the web. I myself like to post small snippets of code every now and then. The pre HTML element was intended for just such a purpose. The content of these elements looks like code. Or, something that is code-like. However, the pre element poses a simple drawback; the code is still difficult to read in most cases. That's not to say that placing programming language code in a pre as opposed to somewhere mangled within the plain text is a bad thing, it is simply a matter of interpreting the code faster. Trying to read code that has not been highlighted to reflect the language in which the code was written is a challenge to say the least. With every programming language, there are several key tokens that carry more meaning than others when read by a human. For instance, in most object-oriented languages, the class keyword is going to stand out. Except, with code that is displayed on the web, it doesn't. At least not at first if the code isn't syntax-highlighted.

Spoken languages such as English don't really need the assistance of a syntax highlighter to emphasize various token types because humans either understand it, or they don't. There is quite a difference between what a computer is able to interpret and what a human is able to interpret. Hence the rigiditety of programming languages in comparison to spoken languages.

With programming language code that is displayed on the web, there is a simple need for that code to be displayed as if it were being displayed in an editor that supports syntax-highlighting. Even though the code isn't editable, that isn't the reason syntax-highlighting is built into code editors. It exists for reading purposes. It would probably be more productive to copy the code from the web and paste it into an editor that will highlight the syntax than it would be to try to read the code that is not highlighted.

This is where the Pygments Python package comes into play. Pygments is a very feature-rich syntax-highlighting application and API. Trac, which depends heavily on the need to display code on the web, is a perfect use case for Pygments and its' API. The application part of Pygments is a simple command line utility which is perfect for highlighting smaller snippets of code.

No comments :

Post a Comment