I have user-entered markdown text stored in a database that I need to render with a custom Redcarpet renderer (for Prawn PDF generation). For single line breaks (i.e. "\r\n"
), the renderer correctly processes the break. However, when the text contains multiple line breaks in a row (i.e. "\r\n\r\n"
) the markdown renderer removes and ignores them.
Also, the linebreak
method is never called in my custom renderer while the paragraph
and emphasis
methods are.
Example ruby script:
require 'redcarpet'
class TestRenderer < Redcarpet::Render::Base
def paragraph(text)
text
end
def emphasis(text)
'<foo>' + text + '</foo>'
end
def linebreak
'<should this be called?>'
end
end
def markdown_this(content)
markdown = Redcarpet::Markdown.new(TestRenderer)
markdown.render(content.to_s)
end
s = '_testing_\r\nthat\r\nthis\r\n\r\nline\r\n\r\n\r\nbreaks'
s_rn = s.gsub '\r\n', "\r\n"
s_n = s.gsub '\r\n', "\n"
puts "\n\n"
puts 'raw string -----------------------'
puts s
puts 'gsub \r\n string -----------------'
puts s_rn
puts 'gsub \n string -------------------'
puts s_n
puts 'markdown \r\n string -------------'
puts markdown_this(s_rn)
puts 'markdown \n string ---------------'
puts markdown_this(s_n)
puts '----------------------------------'
puts "\n\n"
Any number of line breaks (more than one) is considered a paragraph in markdown, so parser just eats the extra line breaks and it has nothing to do with a renderer.
You can inherit from HTML renderer to better understand how it works.
class TestRenderer < Redcarpet::Render::HTML
Also see this answer which has info on how to add multiple line breaks (maybe you can get away with just replacing "\r\n"
with "\r\n "
before rendering markdown)