-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmathjax-support.py
More file actions
82 lines (69 loc) · 2.15 KB
/
mathjax-support.py
File metadata and controls
82 lines (69 loc) · 2.15 KB
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
#!/usr/bin/env python3
import json
import sys
import re
if len(sys.argv) > 1:
if sys.argv[1] == 'supports':
# sys.argv[2] is the renderer name
sys.exit(0)
context, book = json.load(sys.stdin)
p = re.compile(r'([^$]|^)\$(?P<inner>[^$]+)\$(?=[^$]|$)')
q = re.compile(r'([^$]|^)\$\$(?P<inner>[^$]+)\$\$(?=[^$]|$)')
mid = re.compile(r'([^|])\|')
def inner_replace_rules(inner):
inner = inner.replace(r'\\', r'\\\\')
inner = inner.replace(r'\{', r'\\{')
inner = inner.replace(r'\}', r'\\}')
inner = mid.sub(r'\1\\vert ', inner)
inner = inner.replace('_', r'\_')
inner = inner.replace('*', r'\*')
return inner
def handle_chapter(chapter):
sys.stderr.write("Chapter: " + chapter["name"] + "\n")
content = chapter["content"]
# Substitutes single dollar sign to \\( and \\).
result = ""
start = 0
for match in p.finditer(content):
l, r = match.span()
# sys.stderr.write(str(match) + "\n")
result += content[start : l]
result += match.group(1)
result += r"\\("
inner = match.group(2)
inner = inner_replace_rules(inner)
result += inner
result += r"\\)"
start = r
result += content[start:]
# Substitutes double dollar sign pair to \\[ and \\].
content = result
result = ""
start = 0
for match in q.finditer(content):
l, r = match.span()
# sys.stderr.write(str(match) + "\n")
result += content[start : l]
result += match.group(1)
result += "\\\\["
inner = match.group(2)
inner = inner_replace_rules(inner)
result += inner
result += "\\\\]"
start = r
result += content[start:]
# result = p.sub(r'\1\\\\(\g<inner>\\\\)\3', content)
# sys.stderr.write(result[:500] + "\n\n")
# Modify content to the substituted results.
chapter["content"] = result
for sub_item in chapter["sub_items"]:
sub_chapter = sub_item["Chapter"]
handle_chapter(sub_chapter)
sections = book["sections"]
for section in sections:
chapter = section["Chapter"]
handle_chapter(chapter)
# sys.stderr.write("Chapter %d\n" % i)
# sys.stderr.write("\n".join(list(chapter.keys())))
# sys.stderr.write(json.dumps(chapter, indent=2))
json.dump(book, sys.stdout)