Skip to content

Instantly share code, notes, and snippets.

@zceemja
Created July 19, 2024 14:36
Show Gist options
  • Select an option

  • Save zceemja/a53fcead3186d679356da91f2dd70354 to your computer and use it in GitHub Desktop.

Select an option

Save zceemja/a53fcead3186d679356da91f2dd70354 to your computer and use it in GitHub Desktop.
Latex project cleaner
#!/bin/bash -e
# Latex project cleaner.
# This script takes latex project, compacts it into single tex file using latexpand,
# replaces all \tikzsetnextfilename{fname}\begin{tikzpicture} ... \end{tikzpicture} with \includegraphics{prefix/fname},
# figures out which other files are required for making .tex, and puts only those files to a zip file.
#
# Alse see:
# https://ctan.org/pkg/latexpand
# https://github.com/google-research/arxiv-latex-cleaner
#
#
# Author: [email protected]
#
if [ ! -f "$1" ] || [ ! "${1##*.}" = "tex" ]; then
echo "File $1 not found, please specify .tex file"
exit 1
fi
function cleantex() {
rm -rfv "$1.aux" "$1.auxlock" "$1.log" "$1.pdf" "$1.out" "$1.blg" "$1.bcf" "$1.fls" "$1.fdb_latexmk" "$1.run.xml"
}
echo Compiling $1
texfile=$(basename $1)
texname="${texfile%.*}"
cd $(dirname $1)
cleantex "$texname"
# compiling first time to generate .bbl
latexmk -pdf -pdflatex="pdflatex -interaction=nonstopmode -shell-escape" -f -use-make "$texfile"
# Use either --biber or --expand-bbl
latexpand --biber "$texname.bbl" "$texfile" > "$texname.expand.tex"
cleantex "$texname"
python <<EOL
import re, sys
with open('$texname.expand.tex', 'r') as f:
data = f.read()
figdir = re.findall(r'\\\\tikzexternalize\\[[\\w, ]*prefix=(\\S+)[,\\]]', data)[0]
data = re.sub(r'\\\\tikzsetnextfilename{(\\w+)}\\s*\\\\begin{tikzpicture}[\\s\\S]*?\\\\end{tikzpicture}', r'\\\\includegraphics{' + figdir + r'\\1.pdf}', data)
with open('$texname.expand.tex', 'w') as f:
f.write(re.sub(r'\\n{3,}', '\\n\\n', data))
EOL
# Generate final file
latexmk -pdf -pdflatex="pdflatex -interaction=nonstopmode" -f -use-make "$texname.expand.tex"
# Figure out which files are included to main .tex from latexmk log
mapfile -t extfiles < <(cat "$texname.expand.log" | grep -Po '^PGFPlots: reading {([\w./]+)}$' | cut -d "{" -f2 | cut -d "}" -f1)
mapfile -t extfiles2 < <(cat "$texname.expand.log" | grep -Po '\(./[\w.]+' | cut -d "(" -f2)
mapfile -t extfiles3 < <(cat "$texname.expand.log" | grep -Po '^<use ([\w./]+)>$' | cut -c 5- | cut -d ">" -f1)
for fname in ${extfiles2[@]}; do
if [ "${fname##*.}" = "tex" ] || [ "${fname##*.}" = "cls" ] || [ "${fname##*.}" = "sty" ]; then
extfiles+=($fname)
fi
done
extfiles+=(${extfiles3[@]})
for i in ${extfiles[@]}; do echo Including file: $i; done
zip -r cleaned.zip ${extfiles[@]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment