summary refs log tree commit diff
path: root/bin/latexmk
blob: 8d42d9828e8f111051ea7985eb6f5de214e525ce (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/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