#!/bin/bash -
parent=$_

# view a LaTeX document without leaving clutter
#	H.A.Trujillo
#	v3.6
# Last Change:     10 Oct 2019

#TL_BUILD=x86_64-darwinlegacy	# nat 
#TL_BUILD=x86_64-darwin		# cbz-4
TL_BUILD=x86_64-darwin:/texlive/bin/x86_64-darwinlegacy	# for switching

#READER=Skim			# pdf reader to use
READER=Preview			


PATH=/texlive/bin/$TL_BUILD:/bin:/usr/bin:/opt/local/bin:/usr/local/bin
TEXMFOUTPUT=/tmp 
export PATH TEXMFOUTPUT

prog=${0##*/}
ul=$'\e[4m'
pl=$'\e[m'	# plain text
uy=$'\e[4;33m'	# yellow underlined
red=$'\e[31m'

# Send output to /dev/null if invoked through Finder
if [[ x$parent =~ LaTeXview.app ]] ; then 
    exec 1> /dev/null
    exec 2>&1
fi


# GetLast:   returns path to last file processed
function GetLast() { #{{{
    read file1 file2 < /tmp/$prog.$USER.last
    if [ -e $file1 ] ; then
	    echo "$file1"  
	elif [ -e "$file2" ] ; then
	    echo "$file2" 
	else
	    echo "$prog:  input file $ul${file1}$pl not found" >&2
	    exit 1
    fi
} #}}}

# HelpText:  prints help blurb
function HelpText() { #{{{
    cat << END_OF_HELP_TEXT

  $uy${prog}:$pl

		    $prog  [-dehlpt]  file

    A script to process and view LaTeX files, leaving all ancillary files
    in /tmp.

    Although $ul$prog$pl defaults to using LaTeX/dvips, it will use pdfLaTeX if
    non-postscript graphic files are present.  The processing method may
    also be specified with the -d and -p flags.

    Graphics may be compressed as eps.gz or eps.xz files.

    A preamble line of the form
    	%TeXInputs=xxx:yyy	
    will add add xxx and yyy to the TEXINPUTS path.    
		(eg, for \input references to another directory)

  ${ul}Options$pl

	-t  Process a file twice

	-l  Reprocess the last file

    	-e  Edit the last file processed
		(see note for -l flag.)

  	-d  Force processing through a dvi file  ( LaTeX / dvipdf )
	
	-p  Force processing through pdfLaTeX

	-h  Display this message.

  ${ul}Environment$pl

	RESTORE_WINDOW = 1 
		restores focus to the Terminal window from which $ul$prog$pl was called.
	EDITOR	is consulted when the -e flag is used.


  ${ul}Exit Status$pl
  	 0  Success
	 1  Missing File errors
	 2  LaTeX errors

END_OF_HELP_TEXT
}	#}}}

while [ $1 ]; do
    case _${1}_ in
	
	__)	echo "$prog:  no input file" ; exit 1 ;;

	_-l_)	infile="$(GetLast)" ;;

	_-e_)	file="$(GetLast)"
		    if [ $? == 0 ] ; then ${EDITOR:-vi} "$file" ; fi
		    exit ;;

	_-t_)	twice=1 ;;

	_-p_)	explicit=pdf ;;

	_-d_)	explicit=dvi ;;

	_-h_)	HelpText ; exit ;;

	*)	infile="$1" ;;
    esac
    shift
done


test -e "$infile" || { echo "$prog:  no such file -- $infile" ; exit 1 ; }

# Save filename into cache-file.
echo "$infile	$(pwd)/$infile" > /tmp/$prog.$USER.last

filespc=${infile##*/}				# get basename of input file
fileroot=${filespc%.*}				# get root of input file

[ "$infile" != "$filespc" ] && cd ${infile%/*}	# cd to directory containing file


# Does LaTeX file contain a "%TeXInPuT=" line?  
# If so, add to TEXINPUTS
AddToLtxPath=$( grep '^% *TeXInput' "$filespc"	\
	| sed -e 's/[         ]*=[    ]*/=/'	\
	| cut -f2 -d= | cut -f1 -d" "		\
	| tr -C '[[:alnum:]./_:-]\n' X )	# sanitize data


if ( [ ! -z $AddToLtxPath ] && 			# something to add to TEXINPUTS ?
	[ -z $FileParsedForPath ] ) then	# prevent looping

	for dir in ${AddToLtxPath//:/ }; do	
	    if [ -d $dir ] 			# avoid executables
	    then
		PathAddns=${PathAddns}${dir}:
	    else
		echo "	$dir is not a directory -- not adding to TEXINPUTS"
		exit
	    fi
	done

	echo "	ADDING $PathAddns to TEXINPUTS"
	cd $OLDPWD
	FileParsedForPath=1 TEXINPUTS=$PathAddns exec $0 $@
	exit
fi


# Guess whether to use LaTeX/dvipdf or pdfLaTeX
implicit=dvi
#	 Are there jpg/gif/... graphics in the input?
graphics1=$( grep '\\includegraphics' "$filespc" \
	| sed 's/includeg/%/'| cut -f2 -d'%' | cut -f2 -d\{ | cut -f1 -d\} )
graphics2=$( for grfile in ${graphics1[*]%.*} ; do
		ls ${grfile}.{pdf,png,jpg,gif} 2> /dev/null
	     done )
#	 if so, make pdf directly (dvipdf) rather than passing through dvi
test "$graphics2" && implicit=pdf


# Are there compressed graphics?
#    if so, must let dvips be promiscuous
graphics3=$( for grffile in ${graphics1[@]} ; do
		ls ${grffile%.*.gz}.{eps,ps}.gz 2> /dev/null
		ls ${grffile%.*.xz}.{eps,ps}.xz 2> /dev/null
	    done )
test "$graphics3" && Ropt=-R0


# perform the appropriate LaTeX processing:
case ${explicit:-$implicit} in

    dvi)    if [ ! -p /tmp/${fileroot}.ps ] ; then
		mkfifo /tmp/${fileroot}.ps
	    fi
	    if latex -halt-on-error -output-directory /tmp "$filespc" 
	      then

		if [ $twice ] ; then
		    printf -- '-----\n  Processing a second time...\n'
		    latex -halt-on-error -output-directory /tmp "$filespc" > /dev/null
		fi
		echo "-----"
		dvips  $Ropt -o/tmp/${fileroot}.ps "/tmp/$fileroot" &
		cd /tmp
		ps2pdf ${fileroot}.ps 
		wait $!
		open -a $READER ${fileroot}.pdf 
	      else
		read -p "	${red}Press Enter to Continue$pl " 
		exit 2 
	    fi
	    ;;

    pdf)    if pdflatex -halt-on-error -output-directory /tmp "$filespc" 
	      then
		if [ $twice ] ; then
		    printf -- '-----\n  Processing a second time...\n'
		    pdflatex -halt-on-error -output-directory /tmp "$filespc" \
		    	> /dev/null
		fi
		echo "-----"
		open -a $READER "/tmp/${fileroot}.pdf"
	      else
		read -p "	${red}Press Enter to Continue$pl " 
		exit 2 
	    fi
	    ;;
esac

# restore Terminal Window to foreground, if lview called from within vim.
if [ "$RESTORE_WINDOW" == 1 ] ; then
  open -a Terminal
fi

exit 0

______________________________


v1     28apr10	Plain and simple				

v2     ??  	Smarter version, but went poof with hard-drive crash

v3     19may11  Re-creation of v2, in bash, with niceties:
		   - abort on LaTeX errors
		   - reprocess last file

v3.1   27nov12	Added backup-path for -l flag		

v3.1a  28oct13	Removed "-g" flag from open ( = open pdf in bkg) to make 
		(OS_10.8) Preview refresh when document is changed

v3.2   27jun14	Preview window no longer hogs focus	

v3.3    8jul14	PATH tidied to something saner
		Cleaner error-handling
		  - No longer spews log-file contents into dialog box on error
		    when used through the finder
		  - No longer waits for EOT on error

v3.4	6feb15	Temp(?) solution to uncompress eps.gz files

v3.5   22mar15	%TeXInput line parsed

v3.5.1 13may15	$parent tweaked

v3.5.2 19jun15	xz-compressed graphics now recognized

v3.5.3 30nov15	"-e" option added
       29jun17  "TL-Build" tweaked now that OS 8.5 takes "DarwinLegacy"

v3.5.4  7feb19 	$READER added to facilitate use of readers other than Preview.app

v3.6	9oct19	ps file now a named pipe, to avoid writing huge .ps files.
		-d flag

#						 vim: tw=0 ft=sh


