Skip to content

Instantly share code, notes, and snippets.

@jcbagneris
Created March 19, 2017 11:19
Show Gist options
  • Save jcbagneris/54816001005fd965ae61dcae373a641c to your computer and use it in GitHub Desktop.
Save jcbagneris/54816001005fd965ae61dcae373a641c to your computer and use it in GitHub Desktop.
Flatten tex files by following all the \input{foobar} statements
#!/usr/bin/env python3.6
# -*- encoding: utf-8 -*-
"""
flatten.py
Flatten tex files by following all the \input{foobar}
Returns the flattened file on stdout
Usage: flatten.py < first.tex > flattened.tex
"""
import sys
import re
target = re.compile(r'^\\input{(.*)}')
def flatten(lf=[]):
if lf:
fsource = open(lf[-1],'rt')
else:
fsource = sys.stdin
for line in fsource:
mtarget = re.match(target, line)
if mtarget:
ftarget = mtarget.group(1)
if not ftarget.endswith('.tex'):
ftarget = f"{ftarget}.tex"
if ftarget in lf:
yield f"Circular error in {line.split()}: {ftarget} already parsed in {lf}.\n"
else:
yield from flatten(lf + [ftarget])
else:
yield line
for line in flatten():
sys.stdout.write(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment