Skip to content

Instantly share code, notes, and snippets.

@mistivia
Created December 2, 2023 13:34
Show Gist options
  • Select an option

  • Save mistivia/b81b937e8c50e03a8d6f8a3e72d86f1d to your computer and use it in GitHub Desktop.

Select an option

Save mistivia/b81b937e8c50e03a8d6f8a3e72d86f1d to your computer and use it in GitHub Desktop.
#!/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