Skip to content

Instantly share code, notes, and snippets.

@courtenay
Last active December 16, 2015 15:19
Show Gist options
  • Save courtenay/5454972 to your computer and use it in GitHub Desktop.
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
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
# 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>
@suan
Copy link

suan commented Jun 2, 2013

I made the behavior of nested links within titles and the header-anchor-link-elements nesting order match Github's in my fork here

@jcemer
Copy link

jcemer commented Sep 22, 2013

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

@sunaku
Copy link

sunaku commented Oct 10, 2013

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. :neckbeard:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment