Skip to content

Instantly share code, notes, and snippets.

@schlamar
Created May 10, 2012 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schlamar/2652543 to your computer and use it in GitHub Desktop.
Save schlamar/2652543 to your computer and use it in GitHub Desktop.
Find the root document of a given LaTeX file
import glob
import os
import re
MAIN_PATTERN = re.compile(r'\\begin{document}')
def is_main(tex_file):
with open(tex_file) as fobj:
for line in fobj:
if MAIN_PATTERN.search(line):
return True
def get_tex_root(tex_file):
if is_main(tex_file):
return tex_file
path, _ = os.path.split(tex_file)
path = os.path.abspath(path)
while True:
for fname in glob.iglob(os.path.join(path, '*.tex')):
if fname == tex_file:
continue
if is_main(fname):
return fname
parent_path = os.path.abspath(os.path.join(path, '..'))
if path == parent_path:
raise ValueError('Main tex file not found.')
path = parent_path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment