I've recently discovered TexSoup, a Python module to parse Latex files inspired by BeatifulSoup. It makes really easy to work with .tex files in a very straightforward way. For instance it allows to target specific Latex commands such as \input{} in just few lines of codes.
Suppose you have a main.tex file in your folder which reads as follows:
\documentclass[12pt]{article}
\begin{document}
% ..other commands here..
\section{First part}
\input{file1}
\section{Second part}
\input{file2}
% ..other commands here..
\end{document}
If the files file1.tex and file2.tex are in the same folder just save the script at the bottom in a file named flatten.py and execute the command:
python flatten.py main.tex expanded.tex
to get the expanded file.
#!/usr/bin/env python3
import sys
from TexSoup import TexSoup
def soupify(file):
"""
Load file in TexSoup object.
"""
with open(file, 'r') as file_to_read:
content = file_to_read.read()
soup = TexSoup(content)
return soup
def flatten(soup):
"""
Expand \input{} commands in a tex file.
"""
while soup.input:
soup.input.replace(flatten(soupify(soup.input.args[0]+'.tex')))
return soup
if __name__ == "__main__":
file = sys.argv[1]
expanded_tex = flatten(soupify(file))
if len(sys.argv) > 2:
output_file = sys.argv[2]
else:
output_file = 'output.tex'
with open(output_file, 'w') as output:
output.write(repr(expanded_tex))
pass
Notice: this work for Python 3 only and you have to install TexSoup before (pip install TexSoup). If you have both Python 2 and 3 installed on the same machine you may need to launch the command using python3 instead of python as first word.
flatten. I don't think he mind having the Python version in the same directory. – Martin Scharrer May 12 '12 at 16:36latexpandseems to be part of TexLive (confirmed with v2012) and also of MikTex – Hotschke Apr 04 '13 at 08:48perlthough it may not include all necessary modules or be the latest version. For most purposes it is usually fine, though. [Caveat: My knowledge is not current but it is hard to imagine they wouldn't still need it.] – cfr Feb 01 '14 at 04:39\inputand\include? Otherwise the new file might give different results as the original source – cgnieder Jul 30 '14 at 17:08TEXINPUTSenvironment variable for me – Mark Sep 14 '14 at 21:41find /usr/local/texlive/2020basic -name \*expand\*doesn't return anything. @Hotschke which OS are you on? – Shankari Oct 26 '20 at 21:53