Created
December 27, 2012 16:25
-
-
Save kontrafiktion/4389569 to your computer and use it in GitHub Desktop.
Alternate script to convert MultiMarkdown inline links to references (based on script by Brett Terpstra -- http://brettterpstra.com/project/markdown-service-tools/)
Uses the link text instead of the URLs to create the reference names.
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
#!/usr/bin/env ruby | |
def e_sh(str) | |
str.to_s.gsub(/(?=[^a-zA-Z0-9_.\/\-\x7F-\xFF\n])/n, '\\').gsub(/\n/, "'\n'").sub(/^$/, "''") | |
end | |
def mmd_linkname(str) | |
str.gsub(/[^a-zA-Z0-9]/n, '') | |
end | |
def find_headers(lines) | |
in_headers = false | |
lines.each_with_index {|line, i| | |
if line =~ /^\S[^\:]+\:( .*?)?$/ | |
in_headers = true | |
elsif in_headers === true | |
return i | |
else | |
return false | |
end | |
} | |
end | |
input = STDIN.read | |
links=input.scan(/\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/) | |
refs = input.scan(/^\[([^\]]+)\]: (\S+)$/) | |
lines = input.split("\n") | |
bottom = lines[0..-1].join("\n").gsub(/^\[([^\]]+)\]: (\S+)\n?/,'') | |
norepeat = [] | |
norepeatlinks = [] | |
output = [] | |
refs.each {|ref| | |
name = ref[0] | |
puts "name: " + name | |
next if norepeatlinks.include? ref[1] | |
while norepeat.include? name | |
if name =~ / ?[0-9]$/ | |
name.next! | |
else | |
name = name + " 2" | |
end | |
end | |
output << {'orig' => ref[0], 'title' => name, 'link' => ref[1]} | |
norepeat.push name | |
norepeatlinks.push ref[1] | |
} | |
links.each {|link| | |
name = mmd_linkname(link[0]) | |
url = link[1] | |
next if norepeatlinks.include? url | |
while norepeat.include? name | |
if name =~ / ?[0-9]$/ | |
name.next! | |
else | |
name = name + " 2" | |
end | |
end | |
output << {'orig' => url, 'title' => name, 'link' => url } | |
norepeat.push name | |
norepeatlinks.push url | |
} | |
output = output.sort {|a,b| a['title'] <=> b['title']} | |
o = [] | |
output.each_with_index { |x,i| | |
o.push("[#{x['title']}]: #{x['link']}") | |
bottom = bottom.gsub(/\((#{e_sh x['orig']}|#{e_sh x['link']})\)/,"[#{x['title']}]").gsub(/\[#{e_sh x['orig']}\]/,"[#{x['title']}]") | |
} | |
puts bottom + "\n\n#{o.join("\n")}\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment