Skip to content

Instantly share code, notes, and snippets.

@amuramatsu
Created May 12, 2020 01:42
Show Gist options
  • Save amuramatsu/29584d77cf475a10f7506b2c75877835 to your computer and use it in GitHub Desktop.
Save amuramatsu/29584d77cf475a10f7506b2c75877835 to your computer and use it in GitHub Desktop.
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import subprocess
import io
BLAHTEX = "blahtex"
def convert(latex: str,
xmlns: str = "http://www.w3.org/1998/Math/MathML",
display: str = "inline") -> str:
if display not in ("inline", "display"):
raise Exception(
"display argument is supported only 'inline' or 'display', " +
"but with '{}'".format(display))
args = [ BLAHTEX, "--mathml", "--spacing", "relaxed" ]
if display == "display":
args.append("--display-math")
with subprocess.Popen(
args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) as proc:
outbuf, _ = proc.communicate(latex.encode("utf-8"))
return (('<math xmlns="{}">'.format(xmlns) if xmlns else "<math>") +
"".join(outbuf.decode("utf-8").split("\n")[3:-4]) +
"</math>")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"-d", "--display", action="store_true",
help="use display style math")
parser.add_argument(
"--omml", action="store_true",
help="display OMML output")
parser.add_argument(
"LATEX",
help="LaTeX formatted formula")
opts = parser.parse_args()
mathml = convert(opts.LATEX,
display="display" if opts.display else "inline")
print(mathml)
if opts.omml:
import mathml2omml
print(mathml2omml.convert(mathml))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment