-
Notifications
You must be signed in to change notification settings - Fork 1
/
ghmath2codecogs.py
executable file
·74 lines (63 loc) · 2.29 KB
/
ghmath2codecogs.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
#!/usr/bin/env python3
import re
URL = "https://latex.codecogs.com/svg.image?%s"
def main(input, output):
lines = []
with open(input) as f:
for line in f:
lines.append(line)
with open(output, 'w') as f:
math = None
ws = None
for line in lines:
if math is None:
m = re.match('(\s*)```\s*math', line)
if m:
# start collecting math lines
math = []
ws = m.group(1)
else:
f.write(line)
else:
m = re.match('(\s*)```', line)
if m:
# merge all math, removing newlines
math = ''.join(m[:-1]+' ' for m in math)
# deduplicate a whitespace, but whitespace is
# important so keep one space
math = re.sub('\s+', ' ', math)
# and strip
math = math.strip()
# create the codecogs link
f.write('%s<p align="center">\n' % ws)
f.write('%s<img\n' % ws)
f.write('%s alt="%s"\n' % (ws, math))
f.write('%s src="%s"\n' % (ws, URL % ''.join(
# for codecogs we need to url-encode our latex
c if re.match('[a-zA-Z_]', c)
else '%%%02x' % ord(c)
for c in math)))
f.write('%s>\n' % ws)
f.write('%s</p>\n' % ws)
# reset
math = None
ws = None
else:
math.append(line)
if __name__ == "__main__":
import sys
import argparse
parser = argparse.ArgumentParser(
description="Rewrite a markdown file so GitHub math blocks "
"are replaced with embedded images generated by codecogs.",
allow_abbrev=False)
parser.add_argument(
'input',
help="Input markdown file.")
parser.add_argument(
'-o', '--output',
required=True,
help="Output markdown file.")
sys.exit(main(**{k: v
for k, v in vars(parser.parse_args()).items()
if v is not None}))