Last active
December 16, 2015 15:19
-
-
Save courtenay/5454972 to your computer and use it in GitHub Desktop.
add the "<a name" and span icon there as well, so you can style it with a cute little hoverable link
This file contains 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 Custom < Base | |
def header(title, level) | |
@headers ||= [] | |
# you can use this permalink style: 1-foo-bar with the level in it | |
# permalink = "#{level}-#{title.gsub(/\W+/, "-")}" | |
# .. or just use title. you might like a better regex here, too | |
permalink = title.gsub(/\W+/, "-") | |
# for extra credit: implement this as its own method | |
if @headers.include?(permalink) | |
permalink += "_1" | |
# my brain hurts | |
loop do | |
break if !@headers.include?(permalink) | |
# generate titles like foo-bar_1, foo-bar_2 | |
permalink.gsub!(/\_(\d+)$/, "_#{$1.to_i + 1}") | |
end | |
end | |
@headers << permalink | |
%(\n<a name="#{permalink}" class="anchor" href="##{permalink}"><span class="anchor-icon"></span></a><h#{level} id=\"#{permalink}\">#{title}</h#{level}>\n) | |
end | |
end | |
end |
This file contains 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
# output | |
> gh = Redcarpet::Render::GithubStyleTitles.new | |
> 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" class="anchor" href="#test-1"><span class="anchor-icon"></span></a><h1 id="test-1">test 1</h1> | |
<a name="test-2" class="anchor" href="#test-2"><span class="anchor-icon"></span></a><h1 id="test-2">test 2</h1> | |
<a name="test-1_1" class="anchor" href="#test-1_1"><span class="anchor-icon"></span></a><h1 id="test-1_1">test 1</h1> | |
<a name="test-1_2" class="anchor" href="#test-1_2"><span class="anchor-icon"></span></a><h1 id="test-1_2">test 1</h1> |
A more simple implementation
def header(title, level)
@headers ||= []
permalink = title.gsub(/\W+/, '-')
if @headers.include? permalink
permalink += '_1'
permalink = permalink.succ while @headers.include? permalink
end
@headers << permalink
%(
<h#{level} id=\"#{permalink}\"><a name="#{permalink}" class="anchor" href="##{permalink}"></a>#{title}</h#{level}>
)
end
Thanks for this gist. 🍰 I have further refined @jcemer's modifications in my fork. And strictly speaking, we're generating URI fragments here, not permalinks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I made the behavior of nested links within titles and the header-anchor-link-elements nesting order match Github's in my fork here