Use Pygments in Middleman for Syntax Highlighting

Middleman switched from the Python-based Pygments to the pure-Ruby Rouge for syntax highlighting with version 1.2.0 of the middleman-syntax extension. You can switch back to Pygments by adding a few lines to your config.rb file.

Switching from Pygments to Rouge means no more spawning Python processes when building your site. But Rouge doesn’t do everything that Pygments does. Pygments has PowerShell and Windows batch file support, for example.

If you depend on Pygments features or simply prefer to use Pygments, add this to your config.rb file to switch back:

require 'pygments'

activate :syntax

module ::Middleman::Syntax::Highlighter
  def self.highlight(code, language=nil, opts={})
    Pygments.highlight(code, lexer: language)
  end
end

You will also need to add the pygments.rb gem to your Gemfile and run bundle install:

gem 'pygments.rb', '~> 0.6.3'

If you need to pass options to Pygments, pass them after lexer: language in the call to Pygments.highlight rather than on the activate :syntax line as you would for most Middleman extensions. A more elegant implementation would support the latter, but this quick-and-dirty solution works well enough for me.

Tags: Middleman, Pygments, Rouge, static site generator