class Rad::TextUtils::CustomMarkdown < Rad::TextUtils::Processor
def process markdown, env
markdown = github_flavoured_markdown markdown
markdown = image_box markdown
text = custom_markdown markdown
call_next text, env
end
protected
def custom_markdown markdown
# BlueCloth doesn't apply inside of HTML tags, so we temporarilly replacing it
markdown = markdown.gsub('<', 'HTML_BEGIN').gsub('>', 'HTML_END')
markdown = markdown.gsub(" \n", "
\n")
text = BlueCloth.new(markdown).to_html
text = text.gsub(/\A<.+?>/){"#{$&} "}.gsub(/<\/.+?>\Z/){" #{$&}"}
text = text.gsub('HTML_BEGIN', '<').gsub('HTML_END', '>')
text.gsub(/[\n]+/, "\n")
end
def github_flavoured_markdown markdown
# Extract pre blocks
extractions = {}
markdown.gsub!(%r{
.*?}m) do |match| md5 = Digest::MD5.hexdigest(match) extractions[md5] = match "{gfm-extraction-#{md5}}" end # prevent foo_bar_baz from ending up with an italic word in the middle markdown.gsub!(/(^(?! {4}|\t)\w+_\w+_\w[\w_]*)/) do |x| x.gsub('_', '\_') if x.split('').sort.to_s[0..1] == '__' end # in very clear cases, let newlines become