Ruby, iOS, and Other Development

A place to share useful code snippets, ideas, and techniques

All code in posted articles shall be considered public domain unless otherwise noted.
Comments remain the property of their authors.

2006-07-06

Syntax coloring

Someone asked recently about syntax coloring for Ruby code, specifically in the context of a blog. I responded on the list, but I thought I'd share how I create my posts here. First off, I use Firefox when creating a post on Blogger. This is in part because it's a great browser in general, but more specifically so I can use the mozex extension to work on my post in Vim.

Nearly all of my posts include some Ruby code, and it's much nicer to display it with syntax coloring. I used to use Vim's own HTML conversion, but it's slow and it uses explicit styles with colors. Upon hearing about it, I started using the syntax gem in the following Ruby script:

#!/usr/bin/env ruby

unless [1,2].include? ARGV.size
  $stderr.puts "Usage: #{$PROGRAM_NAME} <syntax> [file]"
  exit 1
end

require 'rubygems'
require 'syntax/convertors/html'

convertor = Syntax::Convertors::HTML.for_syntax ARGV.shift

highlighted = convertor.convert(ARGF.read)
highlighted.sub!(/^<pre>/, "<pre class=\"code\">\n")
puts highlighted

To actually write the code I generally open another window in Vim so I can use non-HTML syntax coloring on it and so I can test and debug it in a separate file. When it's ready I paste it into the blog post and run it through the highlighting script above. The actual coloring comes from the page's CSS rules, which you can see by viewing source. If you have any questions on the process, please leave a comment. Enjoy!

Labels: ,

2 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home