myTeX - Make Latex Auto-compile on the Commandline

LaTeX is great. It has become the de-facto standard for (scientific) writing software LaTeX. I love writing these documents in vim because, first of all, it is easy, and secondly, I feel like a proper computer scientist doing so. However, switching between vim and the command line to compile documents after every change can be draining. So, here is a simple script that will watch your project directory for changing files and recompile after every change. This means that every time you type :w in vim, your document will be recompiled.

I have added this as an alias to my .zshrc, but you can also make it an independent script. You'll need the fswatch tool. If you are on Linux, the inotifywait tool, which comes pre-installed on many distros, can also work.

Version with fswatch (Linux, Mac OS X)

# Put this function into your ~/.zshrc
function mytex(){
    # Check for argument
    if [[ $# -eq 0 ]] ; then
        echo "Error: No main latex file found"
        echo "Usage: mytex <LATEX_MAIN_FILE>"
    else
        DIR=$(pwd)
        MAIN=$1
        FILE_EXTENSION=".tex"
        echo "Monitoring directory: $DIR"
        echo "Main file: $MAIN"
        cd $DIR
        fswatch -r $DIR | while read -r line
        do
            if [[ $line == *$FILE_EXTENSION ]];
            then
                xelatex -interaction=nonstopmode $MAIN
            fi
        done
    fi
}

Version with inotifywait (Linux)

# Put this function into your ~/.zshrc
function mytex(){
    # Check for argument
    if [[ $# -eq 0 ]] ; then
        echo "Error: No main latex file found"
        echo "Usage: mytex <LATEX_MAIN_FILE>"
    else
        DIR=$(pwd)
        MAIN=$1
        FILE_EXTENSION=".tex"
        echo "Monitoring directory: $DIR"
        echo "Main file: $MAIN"
        cd $DIR
        inotifywait -m -e modify,create,delete -r $DIR --format '%w%f' | grep --line-buffered $FILE_EXTENSION | while read -r line
        do
            xelatex -interaction=nonstopmode $MAIN
        done
    fi
}

Note that I use nonstop mode to keep the compiler from failing on every error. So if your document fails to compile, it will just try to get as far as it can and then wait for new changes.

Happy LaTeX-ing

Category: Blog

Built using Pelican. Fork this theme on github!