Gravatar

Geoff Evason

Posts Tagged ‘javascript’

How To Get Code Syntax Highlighting on Your Blog

Friday, May 2nd, 2008

So, I’ve just recently updated the look and feel of my blog. I previously had a few blogs that I managed and I wanted to consolidate things into one place.

I looked into using some Rails CMSs (radiant, mephisto) but ultimately decided on using wordpress. I really do think Wordpress is the best tool for the job, and it has a great community and lots of plugins!

Anyway, back to the topic at hand. I’ve seen a bunch of blog posts with cool syntax highlighting. I hadn’t been able to figure out how to do it (until I looked at the markup for Tim Lucas’s site).

There are a few Wordpress plugins that let you do this, but none of them really struck me as being what I wanted. After investigating further I found code_highlighter.js by Dan Webb.

Apparently some code highlighters do work on the server side, where as this javascript file moves the work to the client. The idea of this code highlighter is simple. Just include the main code_highlighter.js script and any of the other 4 supported languge packs that you want to use (html, css, js, ruby). I personally just merged the 4 language packs into the main file so I only had one include.

If you are using wordpress, you need to upload the js file somwhere. The nature place is to create a scripts folder in your wordpress root folder. Or, you can create a scripts folder in your theme folder and include it like this:


<script type=“text/javascript” src="wp-content/themes/geoff/js/code_highlighter.js"></script>

I did the latter so that it’s nice and packaged within my theme.

The next step is to style it (which is easy to do using css). Here’s the css I use:


/* Code highlighting (derived from) VibrantInk colours from Justin Palmer @ http://encytemedia.com
*/

 pre {
   padding: 10px;
   overflow: auto;
   width: 100%;
 }
 pre, code {   background-color: #111; }

 /** RUBY / JAVASCRIPT **/
 code span.comment { 	color: #609; }
 code span.string { 	color: #5c2; }
 code span.brackets { }
 code span.symbol { 	color: #777; }
 code span.keywords { 	color: #d72; }

 /** HTML **/
 code.html span.tag { 	color: #ddd; }
 code.html span.attribute { 	color: #d72; }
 code.html span.string { 	color: #5c2; }
 code.html span.comment {	color: #609; }
 code.html span.doctype { 	color: #D7FF80; }

/** CSS **/
code.css .selectors {  color: #d72;}
code.css .properties {  color: #5c2;}