Syntax highlighting in Ruby 2008-03-20

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"'//pre[@class="ruby"]') do |e|
        e.inner_html = c.convert(e.inner_text,false)

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; }

blog comments powered by Disqus