Markdown & Syntax Highlighting With Redcarpet & Pygments.rb

This tutorial will explain how to implement markdown with syntax highlighting into your Rails application.

Say for example you had a web application just like this one, or a blog, or comment section where you could post text. What if you wanted to be able to style that text, and if included, syntax highlight different programming languages.

Well you can, with two Ruby gems; redcarpet a markdown parser and pygments.rb a Ruby wrapper for a Python syntax highlighter.

To get started, simply add the following two lines into your Gemfile and run bundle install:

gem 'redcarpet'
gem 'pygments.rb'

Next we need to create a helper method, so that we can use a simple function in our views. Lets create this method inside the /helpers/application_helper.rb file.

module ApplicationHelper
    class HTMLwithPygments < Redcarpet::Render::HTML
        def block_code(code, language)
            Pygments.highlight(code, lexer: language)

    def markdown(text)
        renderer = true, filter_html: true)
        options = {
            autolink: true,
            no_intra_emphasis: true,
            fenced_code_blocks: true,
            lax_html_blocks: true,
            strikethrough: true,
            superscript: true,
        }, options).render(text).html_safe

For the markdown() function, we use a hash to add markdown extensions such as autolink etc. You can find more extensions here.

Next we need to create a file inside /assets/stylesheets/ called pygments.css.erb and paste just the following line into that file:

<%= Pygments.css(style: "monokai") %> 

This example uses the monokai syntax highlighting style, but there are many more options to choose from.

Finally, in our views file, such as show.html.erb, simply include the markdown() function before any database call that includes text. For example, if you're using a Post model and want to fetch the post body, use the following line:

<%= markdown(@post.body) %>

Make sure to restart your server as well.

Once this is all done, simply create a new post, and style it using markdown and include a programming language's syntax you like, the results speak for themselves.


Last post: March 16, 2017 :: © bytcode 2017 :: contact