[Previous] The Prince and Me | Home | [Next] Restaurants Do Not Charge What You Write

Syntax Highlighting

I've used Enscript to syntax highlight ruby code in html, but it's not very good and causes html validation errors. So I found a better approach. I added some CSS and here's the ruby code:

#!/usr/bin/env ruby 

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

use_stdin = ARGV.empty?

if use_stdin
code = $stdin.read
else
code = File.read(ARGV[0])
end

convertor = Syntax::Convertors::HTML.for_syntax "ruby"
code_html = "<code class='ruby'> #{convertor.convert(code)} </code>"

if use_stdin
puts code_html
else
fn = "#{File.basename(ARGV[0], File.extname(ARGV[0]))}.html"
rio(fn) << code_html
end

Elliot Temple on December 28, 2007

Messages

Want to discuss this? Join my forum.

(Due to multi-year, sustained harassment from David Deutsch and his fans, commenting here requires an account. Accounts are not publicly available. Discussion info.)