Created
May 22, 2014 16:09
-
-
Save jonblack/c7b1ff966c5927a78d53 to your computer and use it in GitHub Desktop.
Convert inline links to reference links in markdown
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
import os | |
import re | |
import sys | |
RE_MD_INLINE_LINK = re.compile(' \[(?P<name>[\w -_]*)\]\((?P<link>[\w \-/\.:]*)\)') | |
if __name__ == "__main__": | |
src_path = sys.argv[1] | |
assert os.path.exists(src_path) | |
links = {} | |
with open(src_path, 'r') as src: | |
dst_path = src_path + ".new" | |
with open(dst_path, 'w') as dst: | |
link_id = 1 | |
for line in src: | |
r = RE_MD_INLINE_LINK.search(line) | |
if r is None: | |
dst.write(line) | |
continue | |
output_link_id = None | |
if r.groupdict()['link'] not in links: | |
links[r.groupdict()['link']] = link_id | |
output_link_id = link_id | |
link_id = link_id + 1 | |
else: | |
output_link_id = links[r.groupdict()['link']] | |
line = re.sub(RE_MD_INLINE_LINK, | |
r' [\g<name>][{}]'.format(output_link_id), | |
line) | |
dst.write(line) | |
# Now output the links at the bottom of the page | |
for link, id_ in sorted(links.iteritems(), | |
key=lambda (k, v): (v, k)): | |
dst.write('[{}]: {}\n'.format(id_, link)) | |
print "[{}]: {}".format(id_, link) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment