Created
December 2, 2023 13:34
-
-
Save mistivia/b81b937e8c50e03a8d6f8a3e72d86f1d to your computer and use it in GitHub Desktop.
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 python3 | |
| # Render equations in $$...$$ or $...$ in markdown to svg | |
| # Depend on command `tex2svg` | |
| # To install: `sudo npm install -g mathjax-node-cli` | |
| import sys | |
| instr = sys.stdin.read() | |
| instr = instr.replace("\\$", "\xfff0") | |
| outstr = str() | |
| l1 = instr.split("$$") | |
| if len(l1) % 2 == 0: | |
| raise RuntimeError("error, $$ not paired") | |
| def parseText(instr): | |
| l1 = instr.split("$") | |
| if len(l1) % 2 == 0: | |
| print(l1) | |
| raise RuntimeError("error, $ not paired") | |
| outstr = str() | |
| for i in range(len(l1)): | |
| if i % 2 == 0: | |
| outstr = outstr + l1[i] | |
| if i % 2 == 1: | |
| outstr = outstr + parseTexInline(l1[i]) | |
| return outstr | |
| import subprocess | |
| def parseTexBlock(instr): | |
| ret = subprocess.check_output(['tex2svg', "--", instr.strip()]) | |
| ret = ret.decode("utf-8") | |
| if len(ret) == 0: | |
| raise RuntimeError("invalid math: " + instr) | |
| ret = ret.replace("\n", "") | |
| ret = ret.replace("\r", "") | |
| ret = ret.strip() | |
| return ret | |
| def parseTexInline(instr): | |
| ret = subprocess.check_output(['tex2svg', "--inline", "--", instr.strip()]) | |
| ret = ret.decode("utf-8") | |
| if len(ret) == 0: | |
| raise RuntimeError("invalid math: " + instr) | |
| ret = ret.replace("\n", "") | |
| ret = ret.replace("\r", "") | |
| ret = ret.strip() | |
| return ret | |
| for i in range(len(l1)): | |
| if i % 2 == 0: | |
| outstr = outstr + parseText(l1[i]) | |
| if i % 2 == 1: | |
| outstr = outstr + parseTexBlock(l1[i]) | |
| outstr = outstr.replace('\xfff0', "$") | |
| print(outstr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment