This note outlines a method to automatically recompile LaTeX documents when source files are modified using entr and Zsh functions.


Core Components

  1. entr: A command-line utility to run arbitrary commands when files change. You can install it via a package manager like Homebrew (brew install entr) or APT (sudo apt-get install entr).
  2. Zsh Functions: Shell functions defined in ~/.zshrc to encapsulate the compilation and file-watching logic.

Zsh Configuration (~/.zshrc)

Add the following functions to your ~/.zshrc file for a complete automated LaTeX workflow.

## --- LaTeX Workflow Functions ---
 
# 1. Core compile chain
# This function runs the standard sequence of commands to build a LaTeX document, including BibTeX for bibliographies.
function pdflatexchain() {
  if [[ -z "$1" ]]; then
    echo "Usage: pdflatexchain <filename_without_extension>"
    return 1
  fi
  pdflatex "$1.tex" && bibtex "$1" && pdflatex "$1.tex" && pdflatex "$1.tex"
}
 
# 2. Watch ONE specific file and compile it (for single-file projects)
# Usage: pdflatexwatch my_document
function pdflatexwatch() {
  if [[ -z "$1" ]]; then
    echo "Usage: pdflatexwatch <filename_without_extension>"
    return 1
  fi
  # `entr` is launched in a new shell that sources .zshrc to find the pdflatexchain function.
  echo "$1.tex" | entr zsh -c "source ~/.zshrc && pdflatexchain $1"
}
 
# 3. Watch ALL .tex files and compile the MAIN document (for multi-file projects)
# Usage: pdflatexwatch_all main_document
function pdflatexwatch_all() {
  if [[ -z "$1" ]]; then
    echo "Usage: pdflatexwatch_all <main_filename_without_extension>"
    return 1
  fi
  ls *.tex | entr zsh -c "source ~/.zshrc && pdflatexchain $1"
}

How It Works

The entr zsh -c "..." command is the key to making this work. It solves a common issue where entr fails because it runs in a minimal environment that doesn’t have access to your custom shell functions.

  • entr: Starts the file watcher.
  • zsh -c "...": Tells entr to execute the command string in a new Zsh shell.
  • source ~/.zshrc: Inside the new shell, this command loads your configuration, making your custom pdflatexchain function available.
  • && pdflatexchain $1: After the configuration is loaded, it executes the compile chain command.

After adding this code to your .zshrc, reload your shell with exec zsh to activate the new functions.