Syntax highlighting Ruby code
Since setting up this blog, I have been experimenting with various ways to display code on this blog. I started out trying some of the Wordpress plugins like SyntaxHighlighter that used the Google code javascript library, but I wasn’t very happy with the result.
Looking around, it seems like the Ruby community generally just handles code formatting using the Syntax module. Here’s the code that I have put together to handle formatting code for this blog:
#!/usr/bin/ruby require 'rubygems' require 'syntax/convertors/html' def convert(code) convertor = Syntax::Convertors::HTML.for_syntax "ruby" '<pre class="ruby">' + convertor.convert(code, false) + '</pre>' end if ARGV.size > 0 code = convert(ARGF.read) File.open(ARGF.path + ".html", "w").write(code) else # use clipboard if no file is specified code = convert(`pbpaste`) IO.popen("pbcopy", "w") { |clipboard| clipboard.print code } end
One thing that I found that I had to be careful with, however, when pasting code into the WordPress editor is that it has a tendency to remove all carriage returns from pasted markup. Obviously this isn’t a problem normally, but when dealing with preformatted <pre> tags, it tends to break the formatting. It looks like most WordPress users who are comfortable with HTML just disable the visual editor.