-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmdLinkConverter.py
executable file
·93 lines (69 loc) · 2.86 KB
/
mdLinkConverter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/local/bin/python3
import re
from math import log, floor
def convertReferenceLinkToInlineLink(content):
ARCHORS_PATTERN = r"\n\[(.+)\]\: (.+)"
links = re.finditer(ARCHORS_PATTERN, content, re.MULTILINE)
for i, l in enumerate(links):
referenceLinkPattern = '\[(.+)\]\[{}\]'.format(l.group(1))
pattern = re.compile(referenceLinkPattern)
def replacer(obj):
return "[{}]({})".format(obj.group(1), l.group(2))
content = re.sub(pattern, replacer, content)
content = l.re.sub('', content)
content = content.replace("\n<!-- reference links -->\n\n", "")
return content
def convertInlineLinkToReferenceLink(content):
MARKDOWN_LINK_PATTERN = r"\[\!\[([^\[]+?)\]\(([^\#].+?)\)\]\(([^\#].+?)\)|\[([^\[]+?)\]\(([^\#].+?)\)"
IMAGE_REFERENCE_FORMAT = "[@{:0{pad}d}-img]: {}"
IMAGE_URL_REFERENCE_FORMAT = "[@{:0{pad}d}-url]: {}"
IMAGE_LINK_FORMAT = "[![{}][@{:0{pad}d}-img]][@{:0{pad}d}-url]"
archors = []
index = 0
mdlinks = re.finditer(MARKDOWN_LINK_PATTERN, content)
lst = list(mdlinks)
size = len(lst)
for i, link in enumerate(lst):
index += 1
pad = int(floor(log(max(size, 1), 10))) + 1
if link.group(1):
formattedArchorImageString = IMAGE_REFERENCE_FORMAT.format(
index, link.group(2), pad=pad)
formattedArchorLinkString = IMAGE_URL_REFERENCE_FORMAT.format(
index, link.group(3), pad=pad)
archors.append(formattedArchorImageString)
archors.append(formattedArchorLinkString)
formattedString = IMAGE_LINK_FORMAT.format(
link.group(1), index, index, pad=pad)
else:
formattedArchorString = "[@{:0{pad}d}]: {}".format(
index, link.group(5), pad=pad)
archors.append(formattedArchorString)
formattedString = "[{}][@{:0{pad}d}]".format(
link.group(4), index, pad=pad)
content = content.replace(link.group(0), formattedString)
content += "\n<!-- reference links -->\n\n"
for a in archors:
content += a + "\n"
return content
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Markdown Link converter')
group = parser.add_mutually_exclusive_group()
group.add_argument(
'-r', '--reference',
help='convert reference link to inline link',
action="store_true"
)
group.add_argument(
'-i', '--inline',
help='convert inline link to reference link',
action='store_true'
)
parser.add_argument('content', help="Markdown content")
args = parser.parse_args()
if args.reference:
result = convertReferenceLinkToInlineLink(args.content)
elif args.inline:
result = convertInlineLinkToReferenceLink(args.content)
print(result, end='')