summary refs log tree commit diff
path: root/bin/latexmk
blob: 966e058384674cbbd0900e876622bc6f449f1ae1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/bin/bash

set -e
[ -n "$DEBUG" ] && set -x

ENGINE=${ENGINE:-tectonic}
ENGINE_ARGS=${ENGINE_ARGS:-}
VIEWER=${VIEWER:-zathura}

pidfile=/tmp/latexmk.pid
once=
reexec=
nocolor=
while getopts 1Rnh opt; do
	case "$opt" in
		1) once=1 ;;
		R) reexec=1 ;;
		n) nocolor=1 ;;
		h | ?)
			printf "usage: %s [-h]\n" "$(basename "$0")"
			printf "\n"
			printf "  -1 \t only run once\n"
			printf "  -n \t no color\n"
			printf "\n"
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))

[ -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
	pdf=$(_realpath "$(printf "%s" "$1" | sed 's/\.tex/\.pdf/')")
	log() {
		if [ -n "${nocolor}" ]; then
			printf "%s!==>%s %s\n" "$(tput setaf 2)" "$(tput sgr0)" "$1"
		else
			printf "==> %s\n" "$1"
		fi
	}

	# compile the document
	log "running ${ENGINE}"
	# shellcheck disable=SC2086
	${ENGINE} ${ENGINE_ARGS} "$1"

	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 [ -z "$1" ]; then
	ls ./*.tex
else
	[ -f "$1" ] && printf "%s\n" "$1"
	ls ./*.tex
fi | entr ${entr_args} -ns 'latexmk -R $0'