From The Archives

Syntax Highlighting For Your Blog Using TextMate!

created February 26, 2009 at 1:37 am

I dare anyone to tell me a better way to spend the evening after an 11 hour workday staring at code than writing a blogpost about code. Haha, you'll have to forgive me if any of my writing seems scatterbrained that is most likely because my head is spinning like one of those amusement park rides that goes completely upside down and then stays there for 10 seconds before moving again.

Anyway I have only written a couple serious posts here and already I have had a few people ask me how I did my syntax highlighting. It is no secret online syntax highlighting solutions are not super amazing. They are pretty good, sure, but not awesome. That is where TextMate comes in. TextMate has a little known feature found in the Bundles menu under TextMate: Create HTML From Document.

That's it! Well not quite. The HTML TextMate generates is not perfect. For one it uses the <pre> tag which has been deprecated in XHTML 1.0 Strict. To fix that is easy just replace <pre> with <div> in the html as well as the styles. The next thing to do is move your styles out into their own stylesheet. One bizarre thing is that any user generated colours will appear in your stylesheet in the format color: rgba(255, 0, 9, 0.87); which will not work in Internet Explorer so you'll have to convert those to their hex values.

Also removing the <pre> tag will break the code in Internet Explorer:

pre.textmate-source { margin: 0px; padding: 0px 0px 0px 2px; font-family: Monaco, monospace; font-size: 12px; line-height: 1.3em; word-wrap: break-word; white-space: pre; white-space: pre-wrap; white-space: -moz-pre-wrap; white-space: -o-pre-wrap; }

The fix is super simple, however. This is the one I am using on this site:

.textmate-source { margin-top: 30px; margin-bottom: 30px; font-family: "Monaco", monospace; font-size: 11.5px; line-height: 1.3em; word-wrap: break-word; white-space: pre; } .limit-height { height: 400px; overflow: scroll; }

I added the extra margin in there just to give it some breathing room. Also if you want to make a scrollable box you can just add the "limit-height" class to the main div that holds your code. Another thing to note is that for some reason the "line-num" span class is in single quotes. It still validates, but you might as well make it double quotes for consistency. I am probably forgetting something, but I can barely keep my eyes open at the moment so I will add it if I think of it, but yeah very cool. Enjoy!