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

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)

10 Comments

Filed under ruby

10 responses to “Colorize code in your blog posts (with Ruby of course)

  1. Pingback: Code Syntax Highlighting for Blogs with VIM « Jonathan’s Techno-tales

  2. Talking about coloring the code, nice colors you are using. Do you have this theme available aynwhere?

  3. Hi Eduardo!

    I took the colors from the Railscast theme, http://railscasts.com/about

    I’ve used this one for quite some time, but recently switched back to the gorgeous Vibrant Ink.

    What theme do you use?

  4. Vibrant either, I think it’s unbeatable, but sometimes is good to change a little bit.

  5. I have used this example for colorize php code, thanx for example.

  6. What are the downsides of using hosted snippet services?

    There’s a Git one, and Snipt.net. Maybe SEO-related side-effects.

  7. You made some good points there. I did a search on the topic and found most people will agree with your blog.

    rH3uYcBX

  8. Опять нахлынуло маленькуюно от этого не менее интересную статейку :
    Там все фильмы сейчас снимаются(Консервы,Сафо,Дом солнца,Маша и море),правда это заповедник сейчас,но это вопрос решаемый.
    место куда вы хотите. Выезжать из Судака придется значительно раньше и тратить в жарком и душном летнем автобусе намного больше времени.

Leave a comment