August 10, 2007...1:57 pm

Colorize code in your blog posts (with Ruby of course)

Jump to Comments

A couple of people asked me how I highlighted my code in a previous post.

Well, at first I though I’d tell the truth and say that I took the code and added colours manually in span and div. Then I though, hum, maybe I should print my code on a piece of paper and colorize with my girlfriend pen collection. Then I realize, it would look better if I just write the code directly in colours on a sheet of paper. Then I though, people think I know Ruby a lot so I better find some code on the internet and pretend I wrote it. Then, when I realize there was no solution for pasting code in a blog post on wordpress.com, the only solution left was really to write this code myself…

Using the simple syntax Ruby gem by Jamis Buck:


#!/usr/bin/env ruby
require 'rubygems'
require 'syntax/convertors/html'

BACKGROUND_COLOR = '#2B2B2B'
COLOR = '#E6E1DC'
COLORS = {
  :keyword => '#CC7833',
  :symbol => '#6E9CBE',
  :constant => '#DA4939',
  :attribute => '#D0D0FF',
  :string => '#A5C261'
}

html = Syntax::Convertors::HTML.for_syntax('ruby').convert(STDIN.read)

COLORS.each do |token, color|
  html.gsub!(%Q{class="#{token}"}, %Q{style="color:#{color}"})
end

puts %Q(<pre style="background-color:#{BACKGROUND_COLOR};color:#{COLOR};padding:6px;overflow:auto;line-height:12px;font-size:12px;padding:6px;"><code>#{html}</code></pre>)

Use it like this:
ruby2html < code.rb > code.html

Pretty cool but only for ruby…

Ends up I remember seeing a thing about a Ruby gem that could read TextMate magic and pops out the highlighted code. Switching gem…


#!/usr/bin/env ruby
require 'rubygems'
require 'uv'

BACKGROUND_COLOR = '#2B2B2B'
COLOR = '#E6E1DC'
COLORS = {
  :keyword => '#CC7833',
  :symbol => '#6E9CBE',
  :constant => '#DA4939',
  :attribute => '#D0D0FF',
  :string => '#A5C261',
  :comment => '#BC9458',
  :variable => '#D0D0FF'
}

html = Uv.parse(STDIN.read, 'xhtml', ARGV[0], false, 'sunburst')

COLORS.each do |token, color|
  html.gsub!(/class="#{token}"/i, %Q{style="color:#{color}"})
end

puts %Q(<pre style="background-color:#{BACKGROUND_COLOR};color:#{COLOR};padding:6px;overflow:auto;line-height:12px;font-size:12px;padding:6px;"><code>#{html}</code></pre>)

Use it like this:
code2html ruby < code.rb > code.html

You can use it with all languages supported by TextMate, just replace ruby with the desired syntax.

The catch is TextPow requires Oniguruma which I had to install from source. Or you could just wait for Ruby 2.0 as it will include Oniguruma…

Good luck with your highlighting!

Note: You don’t need to have TextMate to use this (I think, by looking at UV’s code)

8 Comments


Leave a Reply