ruby-on-railshamlmarkdownredcarpet

How to get rid of additional spaces using redcarpet gem (Ruby on Rails)


I'm trying to write blog using markdown, and decided to install redcarpet gem. Everything looks fine, pygments.rb are doing great job with syntax highlighting, BUT the problem is, whenever I try to put block of code using ``` I get all lines (except the first one) indented by 6 additional spaces. How to get rid of that?

application_helper.rb

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

  def markdown(content)
    renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: true)
    options = {
      autolink: true,
      no_intra_emphasis: true,
      disable_indented_code_blocks: true,
      fenced_code_blocks: true,
      lax_html_blocks: true,
      strikethrough: true,
      superscript: true
    }
    Redcarpet::Markdown.new(renderer, options).render(content).html_safe
  end
end

Post view - show.html.haml

.container
  .show.title
    = @post.title
  .show.header
    = @post.header
  .show.created_at
    = @post.created_at
  .show.content
    = markdown @post.content

This is how code looks like in sublime:

code in sublime

This is how rendered post looks like with copy-pasted the same code to post content:

code after copy-paste to a post content

I'm using SublimeText3 with 2 spaces indentation, views are in html.haml format.

This is the exact input of post content:

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

  def markdown(content)
    renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: true)
    options = {
      autolink: true,
      no_intra_emphasis: true,
      disable_indented_code_blocks: true,
      fenced_code_blocks: true,
      lax_html_blocks: true,
      strikethrough: true,
      superscript: true
    }
    Redcarpet::Markdown.new(renderer, options).render(content).html_safe
  end
end

Solution

  • This is caused by Haml indenting the block so that the output HTML is neatly formatted, which is often what people want but can cause issues with whitespace sensitive code like this.

    There are a couple of ways to fix it. Firstly if you run with the :ugly option set to true (which should be the case in production) then the extra whitespace won’t be added anywhere and you’ll get the desired result.

    Alternatively you can use the whitespace preservation operator ~ instead of =. This will convert all newlines in the block to the entity (&#x000A), and so no extra whitespace will be added (as there are no newlines to add it to). This will change the HTML produces, but will look as you want when viewed in the browser.