-
-
Save sunaku/6913731 to your computer and use it in GitHub Desktop.
Further refinement of @jcemer's modifications at <https://gist.github.com/courtenay/5454972#comment-912976> Strictly speaking, we're generating [URI fragments](http://en.wikipedia.org/wiki/Fragment_identifier), not permalinks.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'redcarpet' | |
module Redcarpet::Render | |
class GithubStyleTitles < Base | |
# | |
# FIXME: this is a temporary workaround until the | |
# following (merged) pull request is included | |
# in the next gem release of Redcarpet 3: | |
# https://github.com/vmg/redcarpet/pull/186 | |
# | |
def header(title, level) | |
fragment = title.downcase.gsub(/\W+/, '-') | |
# make the fragment unique by appending an incremented counter | |
@fragments ||= [] | |
if @fragments.include? fragment | |
fragment += '_1' | |
fragment = fragment.next while @fragments.include? fragment | |
end | |
@fragments << fragment | |
# generate HTML for this header containing the above fragment | |
[?\n, | |
%{<a name="#{fragment}" href="##{fragment}" class="anchor">}, | |
%{<span class="anchor-icon">}, | |
'</span>', | |
'</a>', | |
%{<h#{level} id="#{fragment}">}, | |
title, | |
"</h#{level}>", | |
?\n].join | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ irb | |
## ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux] | |
>> require './github_style_titles.rb' | |
true | |
>> gh = Redcarpet::Render::GithubStyleTitles.new | |
#<Redcarpet::Render::GithubStyleTitles:0x00000001cc3a48> | |
>> puts Redcarpet::Markdown.new(gh).render "test\n\n# test 1\n\n# test 2\n\n# test 1\n\n# test 1" | |
<a name="test-1" href="#test-1" class="anchor"><span class="anchor-icon"></span></a><h1 id="test-1">test 1</h1> | |
<a name="test-2" href="#test-2" class="anchor"><span class="anchor-icon"></span></a><h1 id="test-2">test 2</h1> | |
<a name="test-1_1" href="#test-1_1" class="anchor"><span class="anchor-icon"></span></a><h1 id="test-1_1">test 1</h1> | |
<a name="test-1_2" href="#test-1_2" class="anchor"><span class="anchor-icon"></span></a><h1 id="test-1_2">test 1</h1> | |
nil | |
>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks dude, worked like a charm for my use case!