#!/bin/bash set -e [ -n "$DEBUG" ] && set -x # save args for passing into reexec vargs=$* ENGINE=${ENGINE:-tectonic} VIEWER=${VIEWER:-zathura} pidfile=/tmp/latexmk.pid once= reexec= nocolor= quiet= while getopts 1RV:E:qnhpvcf opt; do case "$opt" in R) reexec=1 ;; 1) once=1 ;; n) nocolor=1 ;; q) quiet=1 ;; V) VIEWER=$OPTARG ;; E) ENGINE=$OPTARG ;; # noop, compat p) ;; v) ;; c) ;; f) ;; h | ?) printf "usage: %s [-h]\n" "$(basename "$0")" printf "\n" printf " -1 only run once\n" printf " -n no color\n" printf " -q be quiet\n" printf " -V VIEWER pdf viewer (default: %s)\n" "$VIEWER" printf " -E ENGINE latex engine (default: %s)\n" "$ENGINE" printf "\n" exit 2 ;; esac done shift $((OPTIND - 1)) # check requirements for tool in entr realpath pgrep $ENGINE $VIEWER; do if ! command -v "$tool" >/dev/null; then printf "%s: %s not installed but required\n" "$(basename "$0")" "$tool" >&2 exit 1 fi done [ -n "${once}" ] && entr_args='-z' # http://stackoverflow.com/a/18443300/441757 _realpath() { OURPWD=$PWD cd "$(dirname "$1")" LINK=$(readlink "$(basename "$1")") while [ "$LINK" ]; do cd "$(dirname "$LINK")" LINK=$(readlink "$(basename "$1")") done REALPATH="$PWD/$(basename "$1")" cd "$OURPWD" echo "$REALPATH" } if [ -n "${reexec}" ]; then tex=$1 [ -z "$tex" ] || [ ! -f "$tex" ] && [ -f main.tex ] && tex=main.tex pdf=$(_realpath "$(printf "%s" "$tex" | sed 's/\.tex/\.pdf/')") log() { [ -n "${quiet}" ] && return if [ -n "${nocolor}" ]; then printf "%s!==>%s %s\n" "$(tput setaf 2)" "$(tput sgr0)" "$1" else printf "==> %s\n" "$tex" fi } # compile the document log "running ${ENGINE}" if [ -n "${quiet}" ]; then ${ENGINE} "$tex" >/dev/null 2>&1 else ${ENGINE} "$tex" fi if ! pgrep -fx "${VIEWER} $pdf" >/dev/null; then # spawn the viewer log "running ${VIEWER}" (${VIEWER} "$pdf" >/dev/null 2>&1) & fi exit 0 fi if [ -z "${once}" ]; then # make sure we only run once if [ -f "${pidfile}" ]; then kill -TERM "$(cat "${pidfile}")" || rm "${pidfile}" fi printf "%d" "$$" >${pidfile} trap '{ rm "${pidfile}"; }' EXIT fi ( if command -v fd >/dev/null 2>&1; then fd -e tex -e cls -e jpg -e png -e svg . . 2>/dev/null else ls ./**/*.{tex,cls,jpg,png,svg} 2>/dev/null fi ) | entr ${entr_args} -ns "latexmk -R $vargs >&2" >/dev/null