Skip to content

Instantly share code, notes, and snippets.

@cscorley
Created February 29, 2012 03: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 cscorley/1937382 to your computer and use it in GitHub Desktop.
Save cscorley/1937382 to your computer and use it in GitHub Desktop.
Merge a tex file with all of it's \inputs recursively.
#!/usr/bin/env python3
import sys
def merge(input_tex):
new_lines = []
for c_line in input_tex:
# check for line comment
line = c_line
more = ''
for i in range(0, len(c_line)):
if c_line[i] == '%' and c_line[i-1] != '\\':
line = c_line[:i]
more = c_line[i:].replace('\n','')
break
line = line.replace('\n','')
if "\\input{" in line:
begIdx = line.index("\\input{")
endIdx = line.index("}", begIdx)
source = line[begIdx+7:endIdx] + '.tex'
# append text before \input{source}
new_lines.append(line[:begIdx])
# append lines from input source
input_lines = []
with open(source, 'r') as f:
input_lines = f.readlines()
# recursively process inputs.
[new_lines.append(l) for l in merge(input_lines)]
# append lines after \input{source}
new_lines.append(line[endIdx+1:])
else:
new_lines.append(line)
# reattach comment portion of line
if len(more) > 0:
new_lines[-1] = new_lines[-1] + more
return new_lines
if __name__ == '__main__':
for input_file in sys.argv:
if not input_file.endswith('.tex'):
continue
with open(input_file, 'r') as f:
lines = f.readlines()
[print(line) for line in merge(lines)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment