Vidar Hokstad V2.0

Home Blog

2008-03-18 20:55 UTC Syntax highlighting in Ruby

Posted in: , , ,
I love syntax highlighting - I have gotten so dependent on it I find it painful to use editors without it. So it's extremely annoying to post code snippets without it online too.

Thankfully it's trivially simple to do in Ruby. For this blog I really wanted a solution that lets me keep the text clean in the database, but marks up the posts when rendering, so after some searches I ended up doing this:

gem install hpricot
gem install syntax

Then I added this:

require 'hpricot'               
require 'syntax/convertors/html'

def filter_content(content) h = Hpricot(content) c = Syntax::Convertors::HTML.for_syntax "ruby" h.search('//pre[@class="ruby"]') do |e| e.inner_html = c.convert(e.inner_text,false) end h.to_s end

Then all I need to do is call filter_content() with the post content, and put any code in pre tags with class="ruby".

(Hpricot is a great tool btw - I use it all over the place for mangling HTML.)

The remaining piece is just some CSS. The CSS was adapted from CSS found here, but I ended up changing most of the colors to match my editor settings better:

pre { background: #111122; padding: 10px; color: #228822; }
.ruby .normal { color: #fff; }
.ruby .comment { color: #005; font-style: italic; }
.ruby .keyword { color: #A44; font-weight: bold; }
.ruby .method { color: #44f; }
.ruby .class { color: #0c4; }
.ruby .module { color: #050; }
.ruby .punct { color: #668; font-weight: bold; }
.ruby .symbol { color: #ff0; }
.ruby .string { color: #4f4; }
.ruby .char { color: #F07; }
.ruby .ident { color: #fff; }
.ruby .constant { color: #0c4; }
.ruby .regex { color: #B66; background: #FEF; }
.ruby .number { color: #F99; }
.ruby .attribute { color: #fc4; }
.ruby .global { color: #7FB; }
.ruby .expr { color: #227; }
.ruby .escape { color: #277; }


No comments yet - Be the first one!

Post a Comment

Basic HTML allowed. Javascript required for anti-spam check

About me

E-mail: vidar@hokstad.com
Skype: vhokstad
View my LinkedIn profile

I was born April 21st, 1975, in Oslo, Norway. Since 2000 I've been living in London, UK. I'm married.

I'm working for Aardvark Media as Director of Technology. I'm also currently on the board of SpatialQ, a startup in the GIS space, and an advisor to Skoach, a startup doing a time management app for people with ADD.

Recent posts to my blog

Categories

StumbleUpon My link page

(Links I have stumbled and like)