Alpha Hydrae

Coding on the edge of the web...

Markdown Views With Syntax Highlighting in Rails

Today I had to add technical documentation pages to a Rails app. I chose to write those in Markdown as that’s what I’m used to and it’s a widely-used format. This post describes how to render Markdown views in a Rails application with Pygments for code syntax highlighting.

The markdown-rails gem enables .html.md views. Redcarpet is a better parser which you’ll want to use to have features like GitHub Flavored Markdown. Finally, pyments.rb will handle the syntax highlighting.

Add those gems to your Gemfile and run bundle install.

Gemfile
1
2
3
gem "markdown-rails"
gem "redcarpet"
gem "pygments.rb"

To configure the parser and enable syntax highlighting, you can add this initializer.

config/initializers/markdown.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Override the default renderer to add syntax highlighting with Pygments.
class PygmentsHTML < Redcarpet::Render::HTML

  def block_code code, language
    Pygments.highlight code, :lexer => language
  end
end

MarkdownRails.configure do |config|

  # See https://github.com/vmg/redcarpet for options.
  markdown = Redcarpet::Markdown.new(PygmentsHTML,
    :tables => true,
    :fenced_code_blocks => true,
    :autolink => true
  )

  config.render do |markdown_source|
    markdown.render markdown_source
  end
end

Note that you must have Pygments’ pygmentize command installed and in your path. You may install it on most platforms with easy_install:

1
easy_install Pygments

Well, that was pretty painless.

Comments