#! /bin/bash
#
# This is TeXWatch, by Neven Villani (https://github.com/Vanille-N)
# It can execute a PDFLaTeX Make target and transfer any error
# messages to notify-send
# This enables a workflow with real-time recompilation after each
# write to disk.

if [[ $# = 0 ]]; then
    echo "LaTeX real-time compiler"
    echo "Usage: texwatch [MAKE-TARGET]"
    exit 1
fi

target="$1"
shift

logfile="/tmp/texwatch.log"

while true; do
    make "$target" > "$logfile"
    if grep Fatal "$logfile" &>/dev/null; then
        msg=`cat "$logfile"`
        msg="${msg#*!}"
        msg=`printf "%q\n" "$msg"`
        notify-send "LaTeX Error" "$msg" -t 5000
        sleep 4
    fi
    sleep 1
done


# Typical usage:
#
# Makefile
#   | main: main.tex
#   |     pdflatex main.tex
#   |
#   | loop:
#   |     ./texwatch main
#
# $ make loop &>/dev/null
# $ xdg-open main.pdf &>/dev/null
# $ $EDITOR main.tex
