latexpand
Expand LaTeX documents by inlining included files
TLDR
Simplify the specified source file and save the result to the specified output file
Do not remove comments
Do not expand \includes, \inputs etc.
Expand \usepackages as far as the corresponding STY files can be found
Inline the specified BBL file
SYNOPSIS
latexpand [options] [input.tex [input.tex ...]]
PARAMETERS
-h, --help
Show help message and exit.
-o OUTFILE, --output=OUTFILE
Write output to OUTFILE (default: stdout).
-p, --preamble
Preserve preamble (before \begin{document}).
-s, --keep-comments
Retain comments during expansion.
-k, --keep-labels
Keep \label{} and \ref{} commands.
-t, --top-level
Expand only top-level files, not recursed ones.
-m, --missing
Include missing files as empty blocks.
-i, --indent
Indent expanded content for readability.
-f FILE, --font-file=FILE
Specify file for font substitutions.
-l LOGFILE, --logfile=LOGFILE
Log expansion details to file.
-1, --one-file
Output one file per input (default behavior).
-S, --sort
Sort included files alphabetically.
-v, --version
Display version information and exit.
DESCRIPTION
latexpand is a powerful Perl-based command-line tool for preprocessing LaTeX documents. It recursively expands macros (\def, \newcommand, \renewenvironment), includes (\input, \include, \subimport), TikZ libraries, and other directives into a single, self-contained .tex file.
This flattening process aids debugging by isolating errors, enables use with tools lacking include support (e.g., syntax checkers), and simplifies documents for processing or archiving. It preserves document structure while optionally retaining comments, labels, preamble, or indentation.
Key strengths include handling nested includes, substituting variables, and logging expansions. Users specify input files; output defaults to stdout or a named file. It's lightweight, fast for most documents, and integrates into Makefiles or CI pipelines for reproducible builds.
Limitations apply to highly dynamic or conditional content, but options like --top-level or --missing offer control. Widely used in academic and publishing workflows for clean, expanded sources.
CAVEATS
May struggle with circular includes, conditional code (\if), or verbatim environments. Produces large files for big projects; test on subsets first. Not a full LaTeX compiler.
EXAMPLES
latexpand -o expanded.tex main.tex
latexpand -p -s -i thesis.tex > flat_thesis.tex
EXIT STATUS
0: success.
1: errors (e.g., missing files, parse failures).
2: usage errors.
HISTORY
Developed by David Rhead in 2011 as a Perl script. Maintained on GitHub; version 1.4+ adds TikZ and subimport support. Common in Debian/Ubuntu repos since 2012.


