Jun 10 2010

Syntax Highlighting for Ruby

Ruby RDiscount Syntax | comments

There are more than couple of ways to do syntax highlighting for Ruby code. Your geek blog doesn't look nice if the code cannot be read properly or cannot be copied easily. Gists work well. Most blogs now would probably just use gist.github.com especially if it's lengthly file or there are way to many stuff on it that you don't want to scare your visitors. By naming the file "syntax.rb" on gist.github.com for instance, it would know what code you are using and syntax highlighting will be based on the filename. See syntax.rb .

The following code used to work well for me:

def to_html(markdown)
  out = []
  noncode = []
  code_block = nil
  markdown.split("\n").each do |line|
  if !code_block and line.strip.downcase == '
'
    out << Maruku.new(noncode.join("\n")).to_html
    noncode = []
    code_block = []
  elsif code_block and line.strip.downcase == '
' convertor = Syntax::Convertors::HTML.for_syntax "ruby" highlighted = convertor.convert(code_block.join("\n")) out << "
#{highlighted}
" code_block = nil elsif code_block code_block << line else noncode << line end end out << Maruku.new(noncode.join("\n")).to_html out.join("\n") end

There are at least two problems with this code:

  1. Maruku, a markdown interpreter is slow. At least slower than RDiscount, another Markdown interpreter.
  2. The output doesn't look good even with CSS work done. There's white-space before the code making it appear intended when it fact it is not.
  3. There are just too many lines of code. Period.

I had to convert everything to HAML recently. Starting to feel an aversion towards using and overusing ERB.

This code works for me:


def to_html(markdown)
  markdown = markdown.gsub("
", '
').gsub("
", "
") markdown = RDiscount.new(markdown) markdown = markdown.to_html end

Why the code above is better:

  1. Uses RDiscount gem which is faster than Maruku
  2. It is intended to work with Javascript Syntax Highlighter. Just make sure to include the brush for Ruby on head tag along with the core.
  3. It allows user to copy and print the code
  4. It's shorter

The following video shows the difference:

And the final result can be seen on my blog.

comments powered by Disqus