Created
September 27, 2013 15:39
-
-
Save philipbl/6730610 to your computer and use it in GitHub Desktop.
Converts markdown inline links to reference links. Inspired by Brett Terpstra's to reference service, written in Ruby. This can be used as an OS X service or in a Editorial workflow.
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 python | |
import re | |
import operator | |
import re | |
RE_REF = "\\[(.+?)\\]:\\s*(\\S+(\\s+?\".*\")?)\\s*" | |
RE_LINK = "\\((https?://(.+?))\\)" | |
def replace_links(input_, done): | |
def replace_links(match): | |
url = match.group(1) | |
if url not in (x['url'] for x in done): | |
parts = match.group(2).split('.') | |
name = parts[0] if len(parts) == 1 or len(parts) == 2 else parts[1] | |
while name in (x['name'] for x in done): | |
num = re.search("(.+?) ([0-9]+?)$", name) | |
name = name + " 2" if not num else num.group(1) + " " + str(int(num.group(2)) + 1) | |
done.append({'url': url, 'name': name}) | |
else: | |
name = [x['name'] for x in done if x['url'] == url][0] | |
return "[{}]".format(name) | |
output_ = re.sub(RE_LINK, replace_links, input_) | |
return output_, done | |
def replace_refs(input_, done): | |
def replace_refs(match): | |
name = match.group(1) | |
url = match.group(2) | |
done.append({'url': url, 'name': name}) | |
return None | |
output_ = re.sub(RE_REF, replace_refs, input_) | |
return output_, done | |
def start(input_): | |
input_, done = replace_links(*replace_refs(input_, [])) | |
if len(done) > 0: | |
return input_ + '\n' + '\n'.join(['[{}]: {}'.format(d['name'], d['url']) for d in done]) | |
else: | |
return input_ | |
try: | |
import editor | |
import workflow | |
input_ = workflow.get_input() | |
output_ = start(input_) | |
workflow.set_output(output_) | |
except ImportError: | |
import sys | |
input_ = sys.stdin.read() | |
output_ = start(input_) | |
print output_ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment