Search code examples
ruby-on-railssyntax-highlightingslim-lang

Generate syntax highlighting for markdown in slim


I'm using slim in my rails app to generate my views, and have enabled the markdown engine (with redcarpet) so I can write markdown in my slim files like so:

h2#usage Usage
markdown:
    ### Via JavaScript

    Call the dropdowns via JavaScript:

    ```js
    $('.dropdown-toggle').dropdown()
    ```

I've also enabled fenced code blocks in my config/initializers/slim.rb:

Slim::Embedded.default_options[:markdown] = {
  fenced_code_blocks: true
}

My question is, how how do I configure either redcarpet or another gem to generate syntax highlighting for the fenced code blocks in my markdown? I've looked into pygments and rouge, but I'm a bit lost.


Solution

  • Stitching together a few things here:

    You can use the rouge gem for highlighting source code. It's pretty easy and well documented how to use it with Redcarpet. Getting Slim to use your renderer is the tricky part, but the luckily others have already fought this battle: a pretty old github issue and a resulting blog post

    require 'rouge/plugins/redcarpet'
    
    class HTML < Redcarpet::Render::HTML
      include Rouge::Plugins::Redcarpet # yep, that's it.
    end
    
    Slim::Embedded.set_default_options markdown: {
      renderer: HTML.new,
      fenced_code_blocks: true
    }
    

    I haven't tested this, so the code might need some tweaking.