1#! /bin/sh
2# texi2dvi --- produce DVI (or PDF) files from Texinfo (or LaTeX) sources.
3# Id: texi2dvi,v 1.34 2004/12/01 18:35:36 karl Exp 
4#
5# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2001,
6# 2002, 2003, 2004 Free Software Foundation, Inc.
7#
8# This program is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2, or (at your option)
11# any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with this program; if not, you can either send email to this
20# program's maintainer or write to: The Free Software Foundation,
21# Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA.
22#
23# Original author: Noah Friedman.
24#
25# Please send bug reports, etc. to bug-texinfo@gnu.org.
26# If possible, please send a copy of the output of the script called with
27# the `--debug' option when making a bug report.
28
29# This string is expanded by rcs automatically when this file is checked out.
30rcs_revision='Revision: 1.34 '
31rcs_version=`set - $rcs_revision; echo $2`
32program=`echo $0 | sed -e 's!.*/!!'`
33version="texi2dvi (GNU Texinfo 4.8) $rcs_version
34
35Copyright (C) 2004 Free Software Foundation, Inc.
36There is NO warranty.  You may redistribute this software
37under the terms of the GNU General Public License.
38For more information about these matters, see the files named COPYING."
39
40usage="Usage: $program [OPTION]... FILE...
41
42Run each Texinfo or LaTeX FILE through TeX in turn until all
43cross-references are resolved, building all indices.  The directory
44containing each FILE is searched for included files.  The suffix of FILE
45is used to determine its language (LaTeX or Texinfo).
46
47Makeinfo is used to perform Texinfo macro expansion before running TeX
48when needed.
49
50Operation modes:
51  -b, --batch         no interaction
52  -c, --clean         remove all auxiliary files
53  -D, --debug         turn on shell debugging (set -x)
54  -h, --help          display this help and exit successfully
55  -o, --output=OFILE  leave output in OFILE (implies --clean);
56                      Only one input FILE may be specified in this case
57  -q, --quiet         no output unless errors (implies --batch)
58  -s, --silent        same as --quiet
59  -v, --version       display version information and exit successfully
60  -V, --verbose       report on what is done
61
62TeX tuning:
63  -@                   use @input instead of \input; for preloaded Texinfo
64  -e, -E, --expand     force macro expansion using makeinfo
65  -I DIR               search DIR for Texinfo files
66  -l, --language=LANG  specify the LANG of FILE (LaTeX or Texinfo)
67  -p, --pdf            use pdftex or pdflatex for processing
68  -r, --recode         call recode before TeX to translate input characters
69  -t, --command=CMD    insert CMD in copy of input file
70   or --texinfo=CMD    multiple values accumulate
71
72The values of the BIBTEX, LATEX (or PDFLATEX), MAKEINDEX, MAKEINFO,
73TEX (or PDFTEX), TEXINDEX, and THUMBPDF environment variables are used
74to run those commands, if they are set.  Any CMD strings are added
75after @setfilename for Texinfo input, in the first line for LaTeX input.
76
77Email bug reports to <bug-texinfo@gnu.org>,
78general questions and discussion to <help-texinfo@gnu.org>.
79Texinfo home page: http://www.gnu.org/software/texinfo/"
80
81# Initialize variables for option overriding and otherwise.
82# Don't use `unset' since old bourne shells don't have this command.
83# Instead, assign them an empty value.
84batch=false     # eval for batch mode
85clean=
86debug=
87escape='\'
88expand=         # t for expansion via makeinfo
89miincludes=     # makeinfo include path
90oformat=dvi
91oname=          # --output
92quiet=          # by default let the tools' message be displayed
93recode=false
94set_language=
95textra=         # Extra TeX commands to insert in the input file.
96textra_cmd=     # sed command to insert TEXTRA where appropriate
97tmpdir=${TMPDIR:-/tmp}/t2d$$  # avoid collisions on 8.3 filesystems.
98txincludes=     # TEXINPUTS extensions, with trailing colon
99txiprereq=19990129 # minimum texinfo.tex version with macro expansion
100verbose=false   # echo for verbose mode
101
102orig_pwd=`pwd`
103
104# Systems which define $COMSPEC or $ComSpec use semicolons to separate
105# directories in TEXINPUTS.
106if test -n "$COMSPEC$ComSpec"; then
107  path_sep=";"
108else
109  path_sep=":"
110fi
111
112# Pacify verbose cds.
113CDPATH=${ZSH_VERSION+.}$path_sep
114
115# In case someone crazy insists on using grep -E.
116: ${EGREP=egrep}
117
118# return true if program $1 is somewhere in PATH, else false.
119#
120findprog () {
121  foundprog=false
122  for dir in `echo $PATH | tr "$path_sep" " "`; do
123    if test -x "$dir/$1"; then  # does anyone still need test -f?
124      foundprog=true
125      break
126    fi
127  done
128  $foundprog
129}
130
131# Report an error and exit with failure.
132fatal () {
133  echo "$0: $*" >&2
134  exit 1
135}
136
137# Save TEXINPUTS so we can construct a new TEXINPUTS path for each file.
138# Likewise for bibtex and makeindex.
139tex_envvars="BIBINPUTS BSTINPUTS INDEXSTYLE TEXINPUTS"
140for var in $tex_envvars; do
141  eval ${var}_orig=\$$var
142  export $var
143done
144
145
146# Push a token among the arguments that will be used to notice when we
147# ended options/arguments parsing.
148# Use "set dummy ...; shift" rather than 'set - ..." because on
149# Solaris set - turns off set -x (but keeps set -e).
150# Use ${1+"$@"} rather than "$@" because Digital Unix and Ultrix 4.3
151# still expand "$@" to a single argument (the empty string) rather
152# than nothing at all.
153arg_sep="$$--$$"
154set dummy ${1+"$@"} "$arg_sep"; shift
155
156# 
157# Parse command line arguments.
158while test x"$1" != x"$arg_sep"; do
159
160  # Handle --option=value by splitting apart and putting back on argv.
161  case "$1" in
162    --*=*)
163      opt=`echo "$1" | sed -e 's/=.*//'`
164      val=`echo "$1" | sed -e 's/[^=]*=//'`
165      shift
166      set dummy "$opt" "$val" ${1+"$@"}; shift
167      ;;
168  esac
169
170  # This recognizes --quark as --quiet.  So what.
171  case "$1" in
172    -@ ) escape=@;;
173    # Silently and without documentation accept -b and --b[atch] as synonyms.
174    -b | --b*) batch=true;;
175    -c | --c*) clean=t;;
176    -D | --d*) debug=t;;
177    -e | -E | --e*) expand=t;;
178    -h | --h*) echo "$usage"; exit 0;;
179    -I | --I*)
180      shift
181      miincludes="$miincludes -I $1"
182      txincludes="$txincludes$1$path_sep"
183      ;;
184    -l | --l*) shift; set_language=$1;;
185    -o | --o*)
186      shift
187      clean=t
188      case "$1" in
189        /* | ?:/*) oname=$1;;
190                *) oname="$orig_pwd/$1";;
191      esac;;
192    -p | --p*) oformat=pdf;;
193    -q | -s | --q* | --s*) quiet=t; batch=true;;
194    -r | --r*) recode=true;;
195    -t | --tex* | --com* ) shift; textra="$textra\\
196"`echo "$1" | sed 's/\\\\/\\\\\\\\/g'`;;
197    -v | --vers*) echo "$version"; exit 0;;
198    -V | --verb*) verbose=echo;;
199    --) # What remains are not options.
200      shift
201      while test x"$1" != x"$arg_sep"; do
202        set dummy ${1+"$@"} "$1"; shift
203        shift
204      done
205      break;;
206    -*)
207      echo "$0: Unknown or ambiguous option \`$1'." >&2
208      echo "$0: Try \`--help' for more information." >&2
209      exit 1;;
210    *) set dummy ${1+"$@"} "$1"; shift;;
211   esac
212   shift
213done
214# Pop the token
215shift
216
217# Interpret remaining command line args as filenames.
218case $# in
219 0)
220  echo "$0: Missing file arguments." >&2
221  echo "$0: Try \`--help' for more information." >&2
222  exit 2
223  ;;
224 1) ;;
225 *)
226  if test -n "$oname"; then
227    echo "$0: Can't use option \`--output' with more than one argument." >&2
228    exit 2
229  fi
230  ;;
231esac
232
233
234# We can't do much without tex.
235#
236if findprog ${TEX:-tex}; then :; else cat <<EOM
237You don't have a working TeX binary (${TEX:-tex}) installed anywhere in
238your PATH, and texi2dvi cannot proceed without one.  If you want to use
239this script, you'll need to install TeX (if you don't have it) or change
240your PATH or TEX environment variable (if you do).  See the --help
241output for more details.
242
243For information about obtaining TeX, please see http://www.tug.org.  If
244you happen to be using Debian, you can get it with this command:
245  apt-get install tetex-bin
246EOM
247  exit 1
248fi
249
250
251# We want to use etex (or pdftex) if they are available, and the user
252# didn't explicitly specify.  We don't check for elatex and pdfelatex
253# because (as of 2003), the LaTeX team has asked that new distributions
254# use etex by default anyway.
255#
256# End up with the TEX and PDFTEX variables set to what we are going to use.
257if test -z "$TEX"; then
258  if findprog etex; then TEX=etex; else TEX=tex; fi
259fi
260#
261if test -z "$PDFTEX"; then
262  if findprog pdfetex; then PDFTEX=pdfetex; else PDFTEX=pdftex; fi
263fi
264
265
266# Prepare the temporary directory.  Remove it at exit, unless debugging.
267if test -z "$debug"; then
268  trap "cd / && rm -rf $tmpdir" 0 1 2 15
269fi
270
271# Create the temporary directory with strict rights
272(umask 077 && mkdir $tmpdir) || exit 1
273
274# Prepare the tools we might need.  This may be extra work in some
275# cases, but improves the readability of the script.
276utildir=$tmpdir/utils
277mkdir $utildir || exit 1
278
279# A sed script that preprocesses Texinfo sources in order to keep the
280# iftex sections only.  We want to remove non TeX sections, and comment
281# (with `@c texi2dvi') TeX sections so that makeinfo does not try to
282# parse them.  Nevertheless, while commenting TeX sections, don't
283# comment @macro/@end macro so that makeinfo does propagate them.
284# Unfortunately makeinfo --iftex --no-ifinfo doesn't work well enough
285# (yet), makeinfo can't parse the TeX commands, so work around with sed.
286#
287comment_iftex_sed=$utildir/comment.sed
288cat <<EOF >$comment_iftex_sed
289/^@tex/,/^@end tex/{
290  s/^/@c texi2dvi/
291}
292/^@iftex/,/^@end iftex/{
293  s/^/@c texi2dvi/
294  /^@c texi2dvi@macro/,/^@c texi2dvi@end macro/{
295    s/^@c texi2dvi//
296  }
297}
298/^@ifnottex/,/^@end ifnottex/{
299  s/^/@c (texi2dvi)/
300}
301/^@ifinfo/,/^@end ifinfo/{
302  /^@node/p
303  /^@menu/,/^@end menu/p
304  t
305  s/^/@c (texi2dvi)/
306}
307s/^@ifnotinfo/@c texi2dvi@ifnotinfo/
308s/^@end ifnotinfo/@c texi2dvi@end ifnotinfo/
309EOF
310# Uncommenting is simple: Remove any leading `@c texi2dvi'.
311uncomment_iftex_sed=$utildir/uncomment.sed
312cat <<EOF >$uncomment_iftex_sed
313s/^@c texi2dvi//
314EOF
315
316# Compute the list of xref files.
317# Takes the filename (without extension) of which we look for xref
318# files as argument.  The index files must be reported last.
319get_xref_files ()
320{
321  # Get list of xref files (indexes, tables and lists).
322  # Find all files having root filename with a two-letter extension,
323  # saves the ones that are really Texinfo-related files.  .?o? catches
324  # many files: .toc, .log, LaTeX tables and lists, FiXme's .lox, maybe more.
325  for this_file in "$1".?o? "$1".aux "$1".?? "$1".idx; do
326    # If file is empty, skip it.
327    test -s "$this_file" || continue
328    # If the file is not suitable to be an index or xref file, don't
329    # process it.  It's suitable if the first character is a
330    # backslash or right quote or at, as long as the first line isn't
331    # \input texinfo.
332    first_character=`sed -n '1s/^\(.\).*$/\1/p;q' $this_file`
333    if (test "x$first_character" = "x\\" \
334        && sed 1q $this_file | grep -v '^\\input *texinfo' >/dev/null) \
335       || test "x$first_character" = "x'" \
336       || test "x$first_character" = "x@"; then
337      xref_files="$xref_files ./$this_file"
338    fi
339  done
340  echo "$xref_files"
341}
342
343# File descriptor usage:
344# 0 standard input
345# 1 standard output (--verbose messages)
346# 2 standard error
347# 3 some systems may open it to /dev/tty
348# 4 used on the Kubota Titan
349# 5 tools output (turned off by --quiet)
350
351# Tools' output.  If quiet, discard, else redirect to the message flow.
352if test "$quiet" = t; then
353  exec 5>/dev/null
354else
355  exec 5>&1
356fi
357
358# Enable tracing
359if test "$debug" = t; then
360  exec 6>&1
361  set -x
362else
363  exec 6>/dev/null
364fi
365
366# 
367# TeXify files.
368
369for command_line_filename in ${1+"$@"}; do
370  $verbose "Processing $command_line_filename ..."
371
372  # If the COMMAND_LINE_FILENAME is not absolute (e.g., --debug.tex),
373  # prepend `./' in order to avoid that the tools take it as an option.
374  echo "$command_line_filename" | $EGREP '^(/|[A-z]:/)' >&6 \
375  || command_line_filename="./$command_line_filename"
376
377  # See if the file exists.  If it doesn't we're in trouble since, even
378  # though the user may be able to reenter a valid filename at the tex
379  # prompt (assuming they're attending the terminal), this script won't
380  # be able to find the right xref files and so forth.
381  if test ! -r "$command_line_filename"; then
382    echo "$0: Could not read $command_line_filename, skipping." >&2
383    continue
384  fi
385
386  # Get the name of the current directory.  We want the full path
387  # because in clean mode we are in tmp, in which case a relative
388  # path has no meaning.
389  filename_dir=`echo $command_line_filename | sed 's!/[^/]*$!!;s!^$!.!'`
390  filename_dir=`cd "$filename_dir" >/dev/null && pwd`
391
392  # Strip directory part but leave extension.
393  filename_ext=`basename "$command_line_filename"`
394  # Strip extension.
395  filename_noext=`echo "$filename_ext" | sed 's/\.[^.]*$//'`
396  ext=`echo "$filename_ext" | sed 's/^.*\.//'`
397
398  # _src.  Use same basename since we want to generate aux files with
399  # the same basename as the manual.  If --expand, then output the
400  # macro-expanded file to here, else copy the original file.
401  tmpdir_src=$tmpdir/src
402  filename_src=$tmpdir_src/$filename_noext.$ext
403
404  # _xtr.  The file with the user's extra commands.
405  tmpdir_xtr=$tmpdir/xtr
406  filename_xtr=$tmpdir_xtr/$filename_noext.$ext
407
408  # _rcd.  The Texinfo file recoded in 7bit.
409  tmpdir_rcd=$tmpdir/rcd
410  filename_rcd=$tmpdir_rcd/$filename_noext.$ext
411
412  # _bak.  Copies of the previous xref files (another round is run if
413  # they differ from the new one).
414  tmpdir_bak=$tmpdir/bak
415
416  # Make all those directories and give up if we can't succeed.
417  mkdir $tmpdir_src $tmpdir_xtr $tmpdir_rcd $tmpdir_bak || exit 1
418
419  # Source file might include additional sources.
420  # We want `.:$orig_pwd' before anything else.  (We'll add `.:' later
421  # after all other directories have been turned into absolute paths.)
422  # `.' goes first to ensure that any old .aux, .cps,
423  # etc. files in ${directory} don't get used in preference to fresher
424  # files in `.'.  Include orig_pwd in case we are in clean mode, where
425  # we've cd'd to a temp directory.
426  common="$orig_pwd$path_sep$filename_dir$path_sep$txincludes"
427  for var in $tex_envvars; do
428    eval ${var}="\$common\$${var}_orig"
429    export $var
430  done
431
432  # Convert relative paths to absolute paths, so we can run in another
433  # directory (e.g., in --clean mode, or during the macro-support detection.)
434  #
435  # Empty path components are meaningful to tex.  We rewrite them
436  # as `EMPTY' so they don't get lost when we split on $path_sep.
437  # Hopefully no one will have an actual directory named EMPTY.
438  replace_empty="-e 's/^$path_sep/EMPTY$path_sep/g' \
439                 -e 's/$path_sep\$/${path_sep}EMPTY/g' \
440                 -e 's/$path_sep$path_sep/${path_sep}EMPTY:/g'"
441   TEXINPUTS=`echo $TEXINPUTS  | eval sed $replace_empty`
442  INDEXSTYLE=`echo $INDEXSTYLE | eval sed $replace_empty`
443  save_IFS=$IFS
444  IFS=$path_sep
445  set x $TEXINPUTS; shift
446  TEXINPUTS=.
447  for dir
448  do
449    case $dir in
450      EMPTY)
451        TEXINPUTS=$TEXINPUTS$path_sep
452        ;;
453      [\\/]* | ?:[\\/]*)        # Absolute paths don't need to be expanded.
454        TEXINPUTS=$TEXINPUTS$path_sep$dir
455        ;;
456      *)
457        abs=`cd "$dir" && pwd` && TEXINPUTS=$TEXINPUTS$path_sep$abs
458        ;;
459    esac
460  done
461  set x $INDEXSTYLE; shift
462  INDEXSTYLE=.
463  for dir
464  do
465    case $dir in
466      EMPTY)
467        INDEXSTYLE=$INDEXSTYLE$path_sep
468        ;;
469      [\\/]* | ?:[\\/]*)        # Absolute paths don't need to be expansed.
470        INDEXSTYLE=$INDEXSTYLE$path_sep$dir
471        ;;
472      *)
473        abs=`cd "$dir" && pwd` && INDEXSTYLE=$INDEXSTYLE$path_sep$abs
474        ;;
475    esac
476  done
477  IFS=$save_IFS
478
479  # If the user explicitly specified the language, use that.
480  # Otherwise, if the first line is \input texinfo, assume it's texinfo.
481  # Otherwise, guess from the file extension.
482  if test -n "$set_language"; then
483    language=$set_language
484  elif sed 1q "$command_line_filename" | grep 'input texinfo' >&6; then
485    language=texinfo
486  else
487    language=
488  fi
489
490  # Get the type of the file (latex or texinfo) from the given language
491  # we just guessed, or from the file extension if not set yet.
492  case ${language:-$filename_ext} in
493    [lL]a[tT]e[xX] | *.ltx | *.tex)
494      # Assume a LaTeX file.  LaTeX needs bibtex and uses latex for
495      # compilation.  No makeinfo.
496      language=latex
497      bibtex=${BIBTEX:-bibtex}
498      makeinfo= # no point in running makeinfo on latex source.
499      texindex=${MAKEINDEX:-makeindex}
500      textra_cmd=1i
501      if test $oformat = dvi; then
502        tex=${LATEX:-latex}
503      else
504        tex=${PDFLATEX:-pdflatex}
505      fi
506      thumbpdf=${THUMBPDF:-thumbpdf}
507      ;;
508
509    *)
510      # Assume a Texinfo file.  Texinfo files need makeinfo, texindex and tex.
511      language=texinfo
512      bibtex=
513      texindex=${TEXINDEX:-texindex}
514      textra_cmd='/^@setfilename/a'
515      if test $oformat = dvi; then
516        # MetaPost also uses the TEX environment variable.  If the user
517        # has set TEX=latex for that reason, don't bomb out.
518        if echo $TEX | grep 'latex$' >/dev/null; then
519          tex=tex  # don't bother trying to find etex
520        else
521          tex=$TEX
522        fi
523      else
524        tex=$PDFTEX
525      fi
526      # Unless required by the user, makeinfo expansion is wanted only
527      # if texinfo.tex is too old.
528      if test "$expand" = t; then
529        makeinfo=${MAKEINFO:-makeinfo}
530      else
531        # Check if texinfo.tex performs macro expansion by looking for
532        # its version.  The version is a date of the form YEAR-MO-DA.
533        # We don't need to use [0-9] to match the digits since anyway
534        # the comparison with $txiprereq, a number, will fail with non
535        # digits.
536        # Run in the tmpdir to avoid leaving files.
537	(
538           cd $tmpdir
539	   echo '\input texinfo.tex @bye' >txiversion.tex
540	   # Be sure that if tex wants to fail, it is not interactive:
541	   # close stdin.
542           $tex txiversion.tex </dev/null
543	) >$tmpdir/txiversion.out 2>$tmpdir/txiversion.err
544	if test $? != 0; then
545	  cat $tmpdir/txiversion.out
546	  cat $tmpdir/txiversion.err >&2
547	  fatal "texinfo.tex appears to be broken, quitting."
548        fi
549	eval `sed -n 's/^.*\[\(.*\)version \(....\)-\(..\)-\(..\).*$/txiformat=\1 txiversion="\2\3\4"/p' $tmpdir/txiversion.out`
550        $verbose "texinfo.tex preloaded as \`$txiformat', version is \`$txiversion' ..."
551        if test "$txiprereq" -le "$txiversion" >/dev/null 2>&1; then
552          makeinfo=
553        else
554          makeinfo=${MAKEINFO:-makeinfo}
555        fi
556        # As long as we had to run TeX, offer the user this convenience:
557        test "$txiformat" = Texinfo && escape=@
558      fi
559      thumbpdf=${THUMBPDF:-thumbpdf}
560      ;;
561  esac
562
563  # Go to $tmpdir to try --help, since old versions that don't accept
564  # --help will generate a texput.log.
565  tex_help=`cd $tmpdir >/dev/null && $tex --help </dev/null 2>&1`
566
567  # If possible, make TeX report error locations in GNU format.
568  tex_args=
569  case $tex_help in
570    *file-line-error*) tex_args="$tex_args --file-line-error";;
571  esac
572
573  # Tell TeX to be batch if requested.  (\batchmode does not show
574  # terminal output at all, so we don't want that.)
575  $batch && tex_args="$tex_args ${escape}nonstopmode ${escape}input"
576
577  # Expand macro commands in the original source file using Makeinfo.
578  # Always use `end' footnote style, since the `separate' style
579  #   generates different output (arguably this is a bug in -E).
580  # Discard main info output, the user asked to run TeX, not makeinfo.
581  if test -n "$makeinfo"; then
582    $verbose "Macro-expanding $command_line_filename to $filename_src ..."
583    sed -f $comment_iftex_sed "$command_line_filename" \
584      | $makeinfo --footnote-style=end -I "$filename_dir" $miincludes \
585        -o /dev/null --macro-expand=- \
586      | sed -f $uncomment_iftex_sed >"$filename_src"
587    filename_input=$filename_src
588  fi
589
590  # If makeinfo failed (or was not even run), use the original file as input.
591  if test $? -ne 0 \
592     || test ! -r "$filename_src"; then
593    $verbose "Reverting to $command_line_filename ..."
594    filename_input=$filename_dir/$filename_ext
595  fi
596
597  # Used most commonly for @finalout, @smallbook, etc.
598  if test -n "$textra"; then
599    $verbose "Inserting extra commands: $textra"
600    sed "$textra_cmd\\
601$textra" "$filename_input" >"$filename_xtr"
602    filename_input=$filename_xtr
603  fi
604
605  # If this is a Texinfo file with a specified input encoding, and
606  # recode is available, then recode to plain 7 bit Texinfo.
607  if test $language = texinfo; then
608    pgm='s/\(^\|.* \)@documentencoding  *\([^ ][^ ]*\)\( .*\|$\)/\2/
609	t found
610	d
611	:found
612	q'
613    encoding=`sed -e "$pgm" "$filename_input"`
614    if $recode && test -n "$encoding" && findprog recode; then
615      $verbose "Recoding from $encoding to Texinfo."
616      if recode "$encoding"..texinfo <"$filename_input" >"$filename_rcd" \
617         && test -s "$filename_rcd"; then
618        filename_input=$filename_rcd
619      else
620        $verbose "Recoding failed, using original input."
621      fi
622    fi
623  fi
624
625  # If clean mode was specified, then move to the temporary directory.
626  if test "$clean" = t; then
627    $verbose "cd $tmpdir_src"
628    cd "$tmpdir_src" || exit 1
629  fi
630
631  while :; do # will break out of loop below
632    orig_xref_files=`get_xref_files "$filename_noext"`
633
634    # Save copies of originals for later comparison.
635    if test -n "$orig_xref_files"; then
636      $verbose "Backing up xref files: `echo $orig_xref_files | sed 's|\./||g'`"
637      cp $orig_xref_files $tmpdir_bak
638    fi
639
640    # Run bibtex on current file.
641    # - If its input (AUX) exists.
642    # - If AUX contains both `\bibdata' and `\bibstyle'.
643    # - If some citations are missing (LOG contains `Citation').
644    #   or the LOG complains of a missing .bbl
645    #
646    # We run bibtex first, because I can see reasons for the indexes
647    # to change after bibtex is run, but I see no reason for the
648    # converse.
649    #
650    # Don't try to be too smart.  Running bibtex only if the bbl file
651    # exists and is older than the LaTeX file is wrong, since the
652    # document might include files that have changed.  Because there
653    # can be several AUX (if there are \include's), but a single LOG,
654    # looking for missing citations in LOG is easier, though we take
655    # the risk to match false messages.
656    if test -n "$bibtex" \
657       && test -r "$filename_noext.aux" \
658       && test -r "$filename_noext.log" \
659       && (grep '^\\bibdata[{]'  "$filename_noext.aux" \
660           && grep '^\\bibstyle[{]' "$filename_noext.aux" \
661           && (grep 'Warning:.*Citation.*undefined' "$filename_noext.log" \
662               || grep 'No file .*\.bbl\.' "$filename_noext.log")) \
663          >&6 2>&1; \
664    then
665      $verbose "Running $bibtex $filename_noext ..."
666      $bibtex "$filename_noext" >&5 ||
667        fatal "$bibtex exited with bad status, quitting."
668    fi
669
670    # What we'll run texindex on -- exclude non-index files.
671    # Since we know index files are last, it is correct to remove everything
672    # before .aux and .?o?.  But don't really do <anything>o<anything>
673    # -- don't match whitespace as <anything>.
674    # Otherwise, if orig_xref_files contains something like
675    #   foo.xo foo.whatever
676    # the space after the o will get matched.
677    index_files=`echo "$orig_xref_files" \
678                 | sed "s!.*\.aux!!g;
679                        s!./$filename_noext\.[^ ]o[^ ]!!g;
680                        s/^[ ]*//;s/[ ]*$//"`
681    # Run texindex (or makeindex) on current index files.  If they
682    # already exist, and after running TeX a first time the index
683    # files don't change, then there's no reason to run TeX again.
684    # But we won't know that if the index files are out of date or
685    # nonexistent.
686    if test -n "$texindex" && test -n "$index_files"; then
687      $verbose "Running $texindex $index_files ..."
688      $texindex $index_files 2>&5 1>&2 ||
689         fatal "$texindex exited with bad status, quitting."
690    fi
691
692    # Finally, run TeX.
693    cmd="$tex $tex_args"
694    $verbose "Running $cmd ..."
695    if $cmd "$filename_input" >&5; then :; else
696      echo "$0: TeX failed. If the above said 'tex: not found', " >&2
697      echo "$0: you may need to install TeX;" >&2
698      echo "$0: it is available from the pkgsrc system in print/teTeX." >&2
699      echo "$0: If TeX is installed, make sure it is in your $PATH, or" >&2
700      echo "$0: set the environment variable $TEX to its location." >&2
701      echo "$0: $tex exited with bad status, quitting." >&2
702      echo "$0: see $filename_noext.log for errors." >&2
703      test "$clean" = t \
704        && cp "$filename_noext.log" "$orig_pwd"
705      exit 1
706    fi
707
708
709    # Decide if looping again is needed.
710    finished=t
711
712    # LaTeX (and the package changebar) report in the LOG file if it
713    # should be rerun.  This is needed for files included from
714    # subdirs, since texi2dvi does not try to compare xref files in
715    # subdirs.  Performing xref files test is still good since LaTeX
716    # does not report changes in xref files.
717    if grep "Rerun to get" "$filename_noext.log" >&6 2>&1; then
718      finished=
719    fi
720
721    # Check if xref files changed.
722    new_xref_files=`get_xref_files "$filename_noext"`
723    $verbose "Original xref files = `echo $orig_xref_files | sed 's|\./||g'`"
724    $verbose "New xref files      = `echo $new_xref_files | sed 's|\./||g'`"
725
726    # If old and new lists don't at least have the same file list,
727    # then one file or another has definitely changed.
728    test "x$orig_xref_files" != "x$new_xref_files" && finished=
729
730    # File list is the same.  We must compare each file until we find
731    # a difference.
732    if test -n "$finished"; then
733      for this_file in $new_xref_files; do
734        $verbose "Comparing xref file `echo $this_file | sed 's|\./||g'` ..."
735        # cmp -s returns nonzero exit status if files differ.
736        if cmp -s "$this_file" "$tmpdir_bak/$this_file"; then :; else
737          # We only need to keep comparing until we find one that
738          # differs, because we'll have to run texindex & tex again no
739          # matter how many more there might be.
740          finished=
741          $verbose "xref file `echo $this_file | sed 's|\./||g'` differed ..."
742          test "$debug" = t && diff -c "$tmpdir_bak/$this_file" "$this_file"
743          break
744        fi
745      done
746    fi
747
748    # If finished, exit the loop, else rerun the loop.
749    test -n "$finished" && break
750  done # while :;
751
752  # If we were using thumbpdf and producing PDF, then run thumbpdf
753  # and TeX one last time.
754  if test $oformat = pdf \
755     && test -r "$filename_noext.log" \
756     && grep 'thumbpdf\.sty'  "$filename_noext.log" >&6 2>&1; \
757  then
758    $verbose "Running $thumbpdf $filename_noext ..."
759    $thumbpdf "$filename_noext" >&5 ||
760      fatal "$thumbpdf exited with bad status, quitting."
761
762    $verbose "Running $cmd $filename_input..."
763    if $cmd "$filename_input" >&5; then :; else
764      echo "$0: $tex exited with bad status, quitting." >&2
765      echo "$0: see $filename_noext.log for errors." >&2
766      test "$clean" = t \
767	&& cp "$filename_noext.log" "$orig_pwd"
768      exit 1
769    fi
770  fi
771
772
773  # If we were in clean mode, compilation was in a tmp directory.
774  # Copy the DVI (or PDF) file into the directory where the compilation
775  # has been done.  (The temp dir is about to get removed anyway.)
776  # We also return to the original directory so that
777  # - the next file is processed in correct conditions
778  # - the temporary file can be removed
779  if test -n "$clean"; then
780    if test -n "$oname"; then
781       dest=$oname
782    else
783       dest=$orig_pwd
784    fi
785    $verbose "Copying $oformat file from `pwd` to $dest"
786    cp -p "./$filename_noext.$oformat" "$dest"
787    cd / # in case $orig_pwd is on a different drive (for DOS)
788    cd $orig_pwd || exit 1
789  fi
790
791  # Remove temporary files.
792  if test "x$debug" = "x"; then
793    $verbose "Removing $tmpdir_src $tmpdir_xtr $tmpdir_bak ..."
794    cd /
795    rm -rf $tmpdir_src $tmpdir_xtr $tmpdir_bak
796  fi
797done
798
799$verbose "$0: done."
800exit 0 # exit successfully, not however we ended the loop.
801