Skip to content

Instantly share code, notes, and snippets.

@nishio
Created April 13, 2011 02:10
Show Gist options
  • Save nishio/916838 to your computer and use it in GitHub Desktop.
Save nishio/916838 to your computer and use it in GitHub Desktop.
"""
pp4tex
preprocessor for TeX
usage: python pp4tex.py foobar.tex && platex foobat_pp.tex
"""
import sys
import os
import re
target = sys.argv[1]
path, fn = os.path.split(target)
trunk, ext = os.path.splitext(fn)
target = os.path.join(path, "%s.%s" % (trunk, "tex"))
outfile = os.path.join(path, "%s_pp.%s" % (trunk, "tex"))
fi = open(target)
fo = open(outfile, "w")
class Namespace(dict):
def __init__(self, parent=None, **kw):
super(Namespace, self).__init__(**kw)
self.child = None
self.parent = parent
if parent != None:
parent.child = self
def get(self, key):
v = super(Namespace, self).get(key)
if not v:
if not self.parent:
return None
v = self.parent.get(key)
return v
def set(self, key, value):
#if self.get(key):
# raise KeyError("Duplicated: %s" % key)
self[key] = value
ns = Namespace()
top = ns
PUSH_PAT = re.compile("\s*% push")
POP_PAT = re.compile("\s*% pop")
DEFINE_PAT = re.compile("\s*% define ([^\s]+)\s+(.*)")
for lno, line in enumerate(fi):
if PUSH_PAT.match(line):
ns = Namespace(parent=ns)
continue
if POP_PAT.match(line):
ns = ns.parent
continue
m = DEFINE_PAT.match(line)
if m:
frm, to = m.groups()
ns.set(frm, to)
continue
p = top
while p != None:
for k in p:
line = line.replace(k, p[k])
p = p.child
fo.write(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment