Skip to content

Instantly share code, notes, and snippets.

@klieret
Last active January 4, 2018 14:28
Show Gist options
  • Save klieret/91d4c37b99eaf44acb086dc482ff9ecf to your computer and use it in GitHub Desktop.
Save klieret/91d4c37b99eaf44acb086dc482ff9ecf to your computer and use it in GitHub Desktop.
Fixes/Workarounds for bugs in Mathematica's LaTeX Export: Problems with Subsuperscript and with nonsensical \left and \right tags.
#!/usr/bin/env pyton3
import re
import sys
subsup_regex = re.compile(r"\\text\{Subsuperscript\}\[([^\],]*),([^\],]*),([^\],]*)\]")
minimal_braces = True
def replace_subsup(string):
"""Replace one subsuperscript with correct LaTeX code.
Returns (replaced string, bool: did we replace something)
"""
match = subsup_regex.search(string)
if not match:
return string, False
expr, sub, sup = match.groups()
if len(expr) > 1 or not minimal_braces:
expr = "{"+expr+"}"
if len(sub) > 1 or not minimal_braces:
sub = "{"+sub+"}"
if len(sup) > 1 or not minimal_braces:
sup = "{"+sup+"}"
matched = match.string[match.span()[0]:match.span()[1]]
replacement = r"{expr}_{sub}^{sup}".format(expr=expr, sub=sub, sup=sup)
return string.replace(matched, replacement), True
def replace_no_delim(string):
""" E.g. when doing TeXForm[Abs[1+Subscript[g,A]]^2], Mathematica
produces
\\left\\left| g_A+1\\right\\right| {}^2
with superfluous \\left, \\right with no delimeter.
Here we try to delete those.
"""
string=string.replace("\\left\\","\\")
string=string.replace("\\right\\","\\")
return string
def replace_all(string):
"""Generates correct LaTeX code"""
string = replace_no_delim(string)
continue_ = True
while continue_:
string, continue_ = replace_subsup(string)
return string
if __name__ == "__main__":
if len(sys.argv) == 1:
print(replace_all(str(sys.stdin.read())))
else:
print(replace_all("\n\n".join(sys.argv[1:])))
fixLatexErrors[string_]:=
Module[{ret},
ret=RunProcess[{"python3",FileNameJoin[{ToString@NotebookDirectory[],"texexpression.py"}], string},"StandardOutput"];
Return[StringTake[ret,;;-2]];(*split last newline*)
];
@klieret
Copy link
Author

klieret commented Jan 4, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment