Skip to content

Instantly share code, notes, and snippets.

@timcheadle
Created June 6, 2014 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timcheadle/2da86309988e13e2227d to your computer and use it in GitHub Desktop.
Save timcheadle/2da86309988e13e2227d to your computer and use it in GitHub Desktop.
Fixed redcarpet view helper in Rails using :with_toc_data. Works around vmg/redcarpet#385
module ApplicationHelper
def markdown_toc(&block)
output = []
content = capture(&block)
unsafe_chars_regex = /[ $&+,\/:;=?@\"<>#%{}|\^~\[\]`]+/o
# Render the Table of Contents
renderer = Redcarpet::Render::HTML_TOC
toc_text = Redcarpet::Markdown.new(renderer).render(content)
# Fix redcarpet anchor links; see bug
# https://github.com/vmg/redcarpet/issues/385
toc_text.gsub!(/<a href="(.*)#(.*)">/) do |match|
link_url = $1
fixed_anchor = CGI.unescapeHTML($2).gsub(unsafe_chars_regex, '')
"<a href=\"#{link_url}##{fixed_anchor}\">"
end
output << toc_text
# Then render the content
renderer = Redcarpet::Render::HTML.new(with_toc_data: true)
body_text = Redcarpet::Markdown.new(renderer).render(content)
# Fix redcarpet header IDs user for anchors; see bug
# https://github.com/vmg/redcarpet/issues/385
body_text.gsub!(/<h([1-6]) id="(.*)"/) do |match|
header_level = $1
fixed_anchor = CGI.unescapeHTML($2).gsub!(unsafe_chars_regex, '')
"<h#{header_level} id=\"#{fixed_anchor}\""
end
output << body_text
output.join('').html_safe
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment