Skip to content

Instantly share code, notes, and snippets.

@sunaku
Forked from courtenay/STDOUT
Last active May 25, 2018 20:48
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 sunaku/6913731 to your computer and use it in GitHub Desktop.
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.
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
$ 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
>>
@Zhao-Andy
Copy link

Thanks dude, worked like a charm for my use case!

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