Created
June 28, 2011 11:34
-
-
Save fedelebron/1050959 to your computer and use it in GitHub Desktop.
How I vertically align my LaTeX on my Django-based blog
This file contains 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
import tempfile | |
import sys | |
import os | |
import hashlib | |
import shutil | |
import re | |
from subprocess import Popen, PIPE | |
pattern = re.compile(r'\$(.*?)\$') | |
pattern2 = re.compile(r'\[`(.*?)`\]', re.DOTALL) | |
depthmatch = re.compile(r'\[\d depth=(\d+)\]') | |
def wrap_formula(txt): | |
return r""" | |
\documentclass{article} | |
\usepackage{amsmath} | |
\usepackage{amsthm} | |
\usepackage{amssymb} | |
\usepackage[active,textmath]{preview} | |
\usepackage{bm} | |
\pagestyle{empty} | |
\begin{document} | |
%(txt)s | |
\end{document} | |
""" % locals(); | |
def render_formula(formula, folder): | |
hash = hashlib.md5(formula).hexdigest() | |
if os.path.exists(os.path.join(folder, hash + ".png")): | |
f = open(os.path.join(folder, hash + "_baseline.txt"), 'r') | |
baseline = f.readline() | |
f.close() | |
return (hash + ".png", baseline) | |
tempdir = tempfile.mkdtemp() | |
curpath = os.getcwd() | |
os.chdir(tempdir) | |
f = file('formula.tex', 'w') | |
f.write(wrap_formula(formula)) | |
f.close() | |
status = os.system("latex --interaction=nonstopmode formula.tex > /dev/null 2>&1") | |
assert 0==status, tempdir | |
proc = Popen(["dvipng", "-T", "tight", "-x", "1200", "-z", "9", "-bg", "transparent", "formula.dvi", "-o", "formula.png", "--depth"], stdout=PIPE) | |
result = proc.communicate()[0] | |
depth = depthmatch.search(result).group(1) | |
status = proc.returncode | |
assert 0==status, tempdir | |
os.chdir(curpath) | |
shutil.copyfile(os.path.join(tempdir, "formula.png"), os.path.join(folder, hash + ".png")) | |
f = open(os.path.join(folder, hash + "_baseline.txt"), 'w') | |
f.write(depth) | |
f.close() | |
shutil.rmtree(tempdir) | |
return (hash+".png", depth) | |
def formatter(text): | |
def replacement(s): | |
sg = s.group() | |
tup = render_formula(sg, "/home/flebron/sites/fedelebron.com/static/latex/") | |
return "<img src=\"/static/latex/"+tup[0]+"\" style=\"vertical-align: -"+str(tup[1])+"pt;\" alt=\""+sg+"\">" | |
def replacement2(s): | |
sg = s.group()[2:-2] | |
form = r'\begin{math}' + sg + r'\end{math}' | |
tup = render_formula(form, "/home/flebron/sites/fedelebron.com/static/latex/") | |
return "<div class='block_tex'><img src=\"/static/latex/"+tup[0]+"\" style=\"vertical-align: -"+str(tup[1])+"pt;\" alt=\""+sg+"\"></div>" | |
text = pattern.sub(replacement, text) | |
text = pattern2.sub(replacement2, text) | |
return text |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment