-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpandoc_static_katex.py
54 lines (41 loc) · 1.1 KB
/
pandoc_static_katex.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
#!/usr/bin/env python
"""
A pandoc filter that renders math at build time using KaTeX.
KaTeX is assumed to be installed with npm and the command
```
npx katex
```
is assumed to exist in the PATH.
"""
__version__ = '0.1.3'
import subprocess
import html
import shutil
import pandocfilters
npx = shutil.which('npx')
if npx is None:
raise RuntimeError("npx executable not found.")
def katex(key, value, format, meta):
if key != "Math":
return None
fmt, code = value
if not isinstance(fmt, dict) and 't' not in fmt:
return None
display = fmt['t'] == 'DisplayMath'
call = subprocess.run(
[npx, 'katex', '--no-throw-on-error', '--display-mode' if display else ''],
input=code,
text=True,
capture_output=True,
check=True,
encoding='utf-8',
)
return pandocfilters.RawInline(
'html',
f'<span class="math {"display" if display else "inline"}" '
f'data-latex-input="{html.escape(code)}">{call.stdout}</span>',
)
def main():
pandocfilters.toJSONFilter(katex)
if __name__ == '__main__':
main()