Skip to content

Instantly share code, notes, and snippets.

@cloneofsimo
Created October 25, 2024 22:18
Show Gist options
  • Save cloneofsimo/27d081c46031e3dddbbf0a4aa7674da0 to your computer and use it in GitHub Desktop.
Save cloneofsimo/27d081c46031e3dddbbf0a4aa7674da0 to your computer and use it in GitHub Desktop.
latex-watcher
#!/bin/bash
# Install required packages if not present
check_and_install_dependencies() {
local packages=("inotify-tools" "texlive" "texlive-latex-extra" "biber")
echo "Checking and installing dependencies..."
for package in "${packages[@]}"; do
if ! dpkg -l | grep -q "^ii $package "; then
sudo apt-get install -y "$package"
fi
done
}
# Create the auto-compilation script
create_watcher_script() {
local watch_script="/usr/local/bin/latex-autocompile"
echo "Creating LaTeX auto-compilation script..."
sudo tee "$watch_script" > /dev/null << 'EOF'
#!/bin/bash
if [ $# -ne 1 ]; then
echo "Usage: $0 <tex-file>"
exit 1
fi
TEX_FILE="$1"
DIR=$(dirname "$TEX_FILE")
FILENAME=$(basename "$TEX_FILE")
BASE="${FILENAME%.tex}"
cd "$DIR"
# Initial compilation
pdflatex -interaction=nonstopmode "$FILENAME"
biber "$BASE"
pdflatex -interaction=nonstopmode "$FILENAME"
pdflatex -interaction=nonstopmode "$FILENAME"
echo "Watching for changes in $TEX_FILE..."
inotifywait -m -e modify "$TEX_FILE" |
while read -r directory events filename; do
echo "Change detected, recompiling..."
pdflatex -interaction=nonstopmode "$FILENAME"
# Check if bibliography changed
if grep -q "\\bibliography{" "$FILENAME"; then
biber "$BASE"
pdflatex -interaction=nonstopmode "$FILENAME"
fi
pdflatex -interaction=nonstopmode "$FILENAME"
echo "Compilation complete!"
# wait for 1 second before next compilation
sleep 1
done
EOF
# Make the script executable
sudo chmod +x "$watch_script"
}
# Create a systemd service for autostart (optional)
create_systemd_service() {
local service_file="/etc/systemd/system/[email protected]"
echo "Creating systemd service..."
sudo tee "$service_file" > /dev/null << 'EOF'
[Unit]
Description=LaTeX Auto-compilation Service for %I
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/latex-autocompile %I
Restart=always
User=%u
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
}
# Main setup
main() {
echo "Setting up LaTeX auto-compilation..."
check_and_install_dependencies
create_watcher_script
create_systemd_service
echo -e "\nSetup complete! You can now use latex-autocompile in two ways:"
echo "1. Direct usage: latex-autocompile path/to/your/file.tex"
echo "2. As a service: sudo systemctl enable --now latex-autocompile@/absolute/path/to/your/file.tex"
echo -e "\nHappy TeXing! 📚"
}
main
@cloneofsimo
Copy link
Author

Claude made this btw, its insane

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment