1#! /bin/sh
2# texi2dvi --- produce DVI (or PDF) files from Texinfo (or (La)TeX) sources.
3# $Id: texi2dvi,v 1.1.1.1 2023/03/21 16:41:16 christos Exp $
4#
5# Copyright 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2001, 2002,
6# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014
7# Free Software Foundation, Inc.
8#
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 3 of the License,
12# or (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program.  If not, see <http://www.gnu.org/licenses/>.
21#
22# Originally written by Noah Friedman.
23#
24# Please send bug reports, etc. to bug-texinfo@gnu.org.
25# If possible, please send a copy of the output of the script called with
26# the `--debug' option when making a bug report.
27
28test -f /bin/ksh && test -z "$RUNNING_KSH" \
29  && { UNAMES=`uname -s`; test "x$UNAMES" = xULTRIX; } 2>/dev/null \
30  && { RUNNING_KSH=true; export RUNNING_KSH; exec /bin/ksh $0 ${1+"$@"}; }
31unset RUNNING_KSH
32
33# No failure shall remain unpunished.
34set -e
35
36# In case the default sed doesn't suffice.
37: ${SED=sed}
38
39# This string is expanded automatically when this file is checked out.
40rcs_revision='$Revision: 1.1.1.1 $'
41rcs_version=`set - $rcs_revision; echo $2`
42program=`echo $0 | $SED -e 's!.*/!!'`
43
44build_mode=${TEXI2DVI_BUILD_MODE:-local}
45build_dir=${TEXI2DVI_BUILD_DIRECTORY:-.}
46
47# Initialize variables for option overriding and otherwise.
48# Don't use `unset' since old bourne shells don't have this command.
49# Instead, assign them an empty value.
50action=compile
51batch=false     # interact normally
52catcode_special=maybe
53debug=false
54escape="\\"
55expand=false    # true for expansion via makeinfo
56includes=
57line_error=true # pass --file-line-error to TeX
58max_iters=7     # when to quit
59oname=          # --output
60out_lang=dvi
61quiet=false     # let the tools' message be displayed
62set_language=
63src_specials=
64shell_escape=
65latex2html=hevea  # or set to tex4ht
66textra=         # Extra TeX commands to insert in the input file.
67txiprereq=19990129 # minimum texinfo.tex version with macro expansion
68verb=false      # true for verbose mode
69translate_file= # name of charset translation file
70
71orig_pwd=`pwd`
72
73# We have to initialize IFS to space tab newline since we save and
74# restore IFS and apparently POSIX allows stupid/broken behavior with
75# empty-but-set IFS.
76# http://lists.gnu.org/archive/html/automake-patches/2006-05/msg00008.html
77# We need space, tab and new line, in precisely that order.  And don't leave
78# trailing blanks.
79space=' '
80tab='	'
81newline='
82'
83IFS="$space$tab$newline"
84
85# In case someone pedantic insists on using grep -E.
86: ${EGREP=egrep}
87
88# Systems which define $COMSPEC or $ComSpec use semicolons to separate
89# directories in TEXINPUTS -- except for Cygwin et al., where COMSPEC
90# might be inherited, but : is used.
91if test -n "$COMSPEC$ComSpec" \
92   && uname | $EGREP -iv 'cygwin|mingw|djgpp' >/dev/null; then
93  path_sep=";"
94else
95  path_sep=":"
96fi
97
98# Pacify verbose cds.
99CDPATH=${ZSH_VERSION+.}$path_sep
100
101# If $TEX is set to a directory, don't use it.
102test -n "$TEX" && test -d "$TEX" && unset TEX
103
104# 
105## --------------------- ##
106## Auxiliary functions.  ##
107## --------------------- ##
108
109# In case `local' is not supported by the shell, provide a function
110# that simulates it by simply performing the assignments.  This means
111# that we must not expect `local' to work, i.e., we must not (i) rely
112# on it during recursion, and (ii) have two local declarations of the
113# same variable.  (ii) is easy to check statically, and our test suite
114# does make sure there is never twice a static local declaration of a
115# variable.  (i) cannot be checked easily, so just be careful.
116#
117# Note that since we might use a function simulating `local', we can
118# no longer rely on the fact that no IFS-splitting is performed.  So,
119# while
120#
121# foo=$bar
122#
123# is fine (no IFS-splitting), never write
124#
125# local foo=$bar
126#
127# but rather
128#
129# local foo="$bar"
130(
131  foo=bar
132  test_local () {
133    local foo=foo
134  }
135  test_local >/dev/null 2>&1
136  test $foo = bar
137) || eval '
138local () {
139  case $1 in
140    *=*) eval "$1";;
141  esac
142}
143'
144
145
146# cd_orig
147# -------
148# Return to the original directory.
149cd_orig ()
150{
151  # In case $orig_pwd is on a different drive (for DOS).
152  cd /
153
154  # Return to the original directory so that
155  # - the next file is processed in correct conditions
156  # - the temporary file can be removed
157  cd "$orig_pwd" || exit 1
158}
159
160# func_dirname FILE
161# -----------------
162# Return the directory part of FILE.
163func_dirname ()
164{
165  dirname "$1" 2>/dev/null \
166  || { echo "$1" | $SED 's!/[^/]*$!!;s!^$!.!'; }
167}
168
169
170# noexit FILE
171# -----------
172# Return FILE with one extension remove.  foo.bar.baz -> foo.bar.
173noext ()
174{
175  echo "$1" | $SED -e 's/\.[^/.][^/.]*$//'
176}
177
178
179# absolute NAME -> ABS-NAME
180# -------------------------
181# Return an absolute path to NAME.
182absolute ()
183{
184  case $1 in
185   [\\/]* | ?:[\\/]*)
186      # Absolute paths don't need to be expanded.
187      echo "$1"
188      ;;
189   *) local slashes
190      slashes=`echo "$1" | $SED -n 's,.*[^/]\(/*\)$,\1,p'`
191      local rel
192      rel=$orig_pwd/`func_dirname "$1"`
193      if test -d "$rel"; then
194        (cd "$rel" 2>/dev/null \
195         && local n
196         n=`pwd`/`basename "$1"`"$slashes"
197         echo "$n")
198      else
199        error 1 "not a directory: $rel"
200      fi
201      ;;
202  esac
203}
204
205
206# ensure_dir DIR1 DIR2...
207# -----------------------
208# Make sure the directories exist.
209ensure_dir ()
210{
211  for dir
212  do
213    # Beware that in parallel builds we may have several concurrent
214    # attempts to create the directory.  So fail only if "mkdir"
215    # failed *and* the directory still does not exist.
216    test -d "$dir" \
217      || mkdir "$dir" \
218      || test -d "$dir" \
219      || error 1 "cannot create directory: $dir"
220  done
221}
222
223
224# error EXIT_STATUS LINE1 LINE2...
225# --------------------------------
226# Report an error and exit with failure if EXIT_STATUS is non-null.
227error ()
228{
229  local s="$1"
230  shift
231  report "$@"
232  if test "$s" != 0; then
233    exit $s
234  fi
235}
236
237
238# findprog PROG
239# -------------
240# Return true if PROG is somewhere in PATH, else false.
241findprog ()
242{
243  local saveIFS="$IFS"
244  IFS=$path_sep  # break path components at the path separator
245  for dir in $PATH; do
246    IFS=$saveIFS
247    # The basic test for an executable is `test -f $f && test -x $f'.
248    # (`test -x' is not enough, because it can also be true for directories.)
249    # We have to try this both for $1 and $1.exe.
250    #
251    # Note: On Cygwin and DJGPP, `test -x' also looks for .exe.  On Cygwin,
252    # also `test -f' has this enhancement, but not on DJGPP.  (Both are
253    # design decisions, so there is little chance to make them consistent.)
254    # Thusly, it seems to be difficult to make use of these enhancements.
255    #
256    if   { test -f "$dir/$1"     && test -x "$dir/$1"; } \
257      || { test -f "$dir/$1.exe" && test -x "$dir/$1.exe"; }; then
258      return 0
259    fi
260  done
261  return 1
262}
263
264# report LINE1 LINE2...
265# ---------------------
266# Report some information on stderr.
267report ()
268{
269  for i in "$@"
270  do
271    echo >&2 "$0: $i"
272  done
273}
274
275
276# run COMMAND-LINE
277# ----------------
278# Run the COMMAND-LINE verbosely, and catching errors as failures.
279run ()
280{
281  verbose "Running $@"
282  "$@" 2>&5 1>&2 \
283  || error 1 "$1 failed"
284}
285
286
287# usage
288# -----
289# Display usage and exit successfully.
290usage ()
291{
292  # We used to simply have `echo "$usage"', but coping with the
293  # changing behavior of `echo' is much harder than simply using a
294  # here-doc.
295  #
296  #             echo '\noto'   echo '\\noto'   echo -e '\\noto'
297  # bash 3.1      \noto           \\noto          \noto
298  # bash 3.2       %oto           \noto           -e \noto
299  #
300  # where % denotes the eol character.
301  cat <<EOF
302Usage: $program [OPTION]... FILE...
303  or:  texi2pdf [OPTION]... FILE...
304  or:  pdftexi2dvi [OPTION]... FILE...
305
306Run each Texinfo or (La)TeX FILE through TeX in turn until all
307cross-references are resolved, building all indices.  The directory
308containing each FILE is searched for included files.  The suffix of FILE
309is used to determine its language ((La)TeX or Texinfo).  To process
310(e)plain TeX files, set the environment variable LATEX=tex.
311
312In order to make texi2dvi a drop-in replacement of TeX/LaTeX in AUC-TeX,
313the FILE may also be composed of the following simple TeX commands.
314  \`\\input{FILE}'     the actual file to compile
315  \`\\nonstopmode'     same as --batch
316
317When invoked as \`texi2pdf' or \`pdftexi2dvi', or given the option --pdf
318or --dvipdf, generate PDF output.  Otherwise, generate DVI.
319
320General options:
321  -b, --batch         no interaction
322  -D, --debug         turn on shell debugging (set -x)
323  -h, --help          display this help and exit successfully
324  -o, --output=OFILE  leave output in OFILE; only one input FILE is allowed
325  -q, --quiet         no output unless errors (implies --batch)
326  -s, --silent        same as --quiet
327  -v, --version       display version information and exit successfully
328  -V, --verbose       report on what is done
329
330Output format:
331      --dvi     output a DVI file [default]
332      --dvipdf  output a PDF file via DVI (using a dvi-to-pdf program)
333      --html    output an HTML file from LaTeX, using HeVeA
334      --info    output an Info file from LaTeX, using HeVeA
335  -p, --pdf     use pdftex or pdflatex for processing
336      --ps      output a PostScript file via DVI (using dvips)
337      --text    output a plain text file from LaTeX, using HeVeA
338
339TeX tuning:
340  -@                         use @input instead of \input for preloaded Texinfo
341  -e, -E, --expand           force macro expansion using makeinfo
342  -I DIR                     search DIR for Texinfo files
343  -l, --language=LANG        specify LANG for FILE, either latex or texinfo
344      --no-line-error        do not pass --file-line-error to TeX
345      --shell-escape         pass --shell-escape to TeX
346      --src-specials         pass --src-specials to TeX
347  -t, --command=CMD          insert CMD in copy of input file
348   or --texinfo=CMD          multiple values accumulate
349      --translate-file=FILE  use given charset translation file for TeX
350
351Build modes:
352  --build=MODE         specify the treatment of auxiliary files [$build_mode]
353      --tidy           same as --build=tidy
354  -c, --clean          same as --build=clean
355      --build-dir=DIR  specify where the tidy compilation is performed;
356                         implies --tidy;
357                         defaults to TEXI2DVI_BUILD_DIRECTORY [$build_dir]
358  --mostly-clean       remove the auxiliary files and directories
359                         but not the output
360  --max-iterations=N   don't process files more than N times [$max_iters]
361
362The MODE specifies where the TeX compilation takes place, and, as a
363consequence, how auxiliary files are treated.  The build mode
364can also be set using the environment variable TEXI2DVI_BUILD_MODE.
365
366Valid MODEs are:
367  \`local'      compile in the current directory, leaving all the auxiliary
368               files around.  This is the traditional TeX use.
369  \`tidy'       compile in a local *.t2d directory, where the auxiliary files
370               are left.  Output files are copied back to the original file.
371  \`clean'      same as \`tidy', but remove the auxiliary directory afterwards.
372               Every compilation therefore requires the full cycle.
373
374Using the \`tidy' mode brings several advantages:
375  - the current directory is not cluttered with plethora of temporary files.
376  - clutter can be even further reduced using --build-dir=dir: all the *.t2d
377    directories are stored there.
378  - clutter can be reduced to zero using, e.g., --build-dir=/tmp/\$USER.t2d
379    or --build-dir=\$HOME/.t2d.
380  - the output file is updated after every successful TeX run, for
381    sake of concurrent visualization of the output.  In a \`local' build
382    the viewer stops during the whole TeX run.
383  - if the compilation fails, the previous state of the output file
384    is preserved.
385  - PDF and DVI compilation are kept in separate subdirectories
386    preventing any possibility of auxiliary file incompatibility.
387
388On the other hand, because \`tidy' compilation takes place in another
389directory, occasionally TeX won't be able to find some files (e.g., when
390using \\graphicspath): in that case, use -I to specify the additional
391directories to consider.
392
393The values of the BIBER, BIBTEX, DVIPDF, DVIPS, HEVEA, LATEX, MAKEINDEX,
394MAKEINFO, PDFLATEX, PDFTEX, SED, T4HT, TEX, TEX4HT, TEXINDEX, and THUMBPDF_CMD
395environment variables are used to run those commands, if they are set.
396
397Regarding --dvipdf, if DVIPDF is not set in the environment, the
398following programs are looked for (in this order): dvipdfmx dvipdfm
399dvipdf dvi2pdf dvitopdf.
400
401Any CMD strings are added after @setfilename for Texinfo input, or in
402the first line for LaTeX input.
403
404Report bugs to bug-texinfo@gnu.org,
405general questions and discussion to help-texinfo@gnu.org.
406GNU Texinfo home page: <http://www.gnu.org/software/texinfo/>
407General help using GNU software: <http://www.gnu.org/gethelp/>
408EOF
409  exit 0
410}
411
412
413# verbose WORD1 WORD2
414# -------------------
415# Report some verbose information.
416verbose ()
417{
418  if $verb; then
419    echo >&2 "$0: $@"
420  fi
421}
422
423
424# version
425# -------
426# Display version info and exit successfully.
427version ()
428{
429  cat <<EOF
430texi2dvi (GNU Texinfo 5.2) $rcs_version
431
432Copyright (C) 2014 Free Software Foundation, Inc.
433License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
434This is free software: you are free to change and redistribute it.
435There is NO WARRANTY, to the extent permitted by law.
436EOF
437  exit 0
438}
439
440
441## ---------------- ##
442## Handling lists.  ##
443## ---------------- ##
444
445
446# list_append LIST-NAME ELEM
447# --------------------------
448# Set LIST-NAME to its former contents, with ELEM appended.
449list_append ()
450{
451  local la_l="$1"
452  shift
453  eval set X \$$la_l "$@"
454  shift
455  eval $la_l=\""$@"\"
456}
457
458
459# list_concat_dirs LIST-NAME DIR-LIST
460# -----------------------------------
461# Append to LIST-NAME all the components (included empty) from
462# the $path_sep separated list DIR-LIST.  Make the paths absolute.
463list_concat_dirs ()
464{
465  local lcd_list="$1"
466  # Empty path components are meaningful to tex.  We rewrite them as
467  # `EMPTY' so they don't get lost when we split on $path_sep.
468  # Hopefully no one will have an actual directory named EMPTY.
469  local replace_EMPTY="-e 's/^$path_sep/EMPTY$path_sep/g' \
470                       -e 's/$path_sep\$/${path_sep}EMPTY/g' \
471                       -e 's/$path_sep$path_sep/${path_sep}EMPTY:/g'"
472  save_IFS=$IFS
473  IFS=$path_sep
474  set x `echo "$2" | eval $SED $replace_EMPTY`; shift
475  IFS=$save_IFS
476  local dir
477  for dir
478  do
479    case $dir in
480      EMPTY)
481       list_append $lcd_list ""
482       ;;
483      *)
484       if test -d $dir; then
485          dir=`absolute "$dir"`
486         list_append $lcd_list "$dir"
487       fi
488       ;;
489    esac
490  done
491}
492
493
494# list_prefix LIST-NAME SEP -> STRING
495# -----------------------------------
496# Return a string that is composed of the LIST-NAME with each item
497# preceded by SEP.
498list_prefix ()
499{
500  local lp_p="$2"
501  eval set X \$$1
502  shift
503  local lp_res
504  for i
505  do
506    lp_res="$lp_res \"$lp_p\" \"$i\""
507  done
508  echo "$lp_res"
509}
510
511# list_infix LIST-NAME SEP -> STRING
512# ----------------------------------
513# Same as list_prefix, but a separator.
514list_infix ()
515{
516  eval set X \$$1
517  shift
518  local la_IFS="$IFS"
519  IFS=$path_sep
520  echo "$*"
521  IFS=$la_IFS
522}
523
524# list_dir_to_abs LIST-NAME
525# -------------------------
526# Convert the list to using only absolute dir names.
527# Currently unused, but should replace absolute_filenames some day.
528list_dir_to_abs ()
529{
530  local ld_l="$1"
531  eval set X \$$ld_l
532  shift
533  local ld_res
534  for dir
535  do
536    dir=`absolute "$dir"`
537    test -d "$dir" || continue
538    ld_res="$ld_res \"$dir\""
539  done
540  set X $ld_res; shift
541  eval $ld_l=\"$@\"
542}
543
544
545## ------------------------------ ##
546## Language auxiliary functions.  ##
547## ------------------------------ ##
548
549
550# out_lang_set LANG
551# -----------------
552out_lang_set ()
553{
554  case $1 in
555    dvi|dvipdf|html|info|pdf|ps|text) out_lang=$1;;
556    *) error 1 "invalid output format: $1";;
557  esac
558}
559
560
561# out_lang_tex
562# ------------
563# Return the tex output language (DVI or PDF) for $OUT_LANG.
564out_lang_tex ()
565{
566  case $out_lang in
567    dvi | ps | dvipdf ) echo dvi;;
568    pdf ) echo $out_lang;;
569    html | info | text ) echo $out_lang;;
570    *)    error 1 "invalid out_lang: $1";;
571  esac
572}
573
574
575# out_lang_ext
576# ------------
577# Return the extension for $OUT_LANG.
578out_lang_ext ()
579{
580  case $out_lang in
581    dvipdf ) echo pdf;;
582    dvi | html | info | pdf | ps | text ) echo $out_lang;;
583    *)    error 1 "invalid out_lang: $1";;
584  esac
585}
586
587
588## ------------------------- ##
589## TeX auxiliary functions.  ##
590## ------------------------- ##
591
592# Save TEXINPUTS so we can construct a new TEXINPUTS path for each file.
593# Likewise for bibtex and makeindex.
594tex_envvars="BIBINPUTS BSTINPUTS DVIPSHEADERS INDEXSTYLE MFINPUTS MPINPUTS \
595TEXINPUTS TFMFONTS"
596for var in $tex_envvars; do
597  eval ${var}_orig=\$$var
598  export $var
599done
600
601
602# absolute_filenames TEX-PATH -> TEX-PATH
603# ---------------------------------------
604# Convert relative paths to absolute paths, so we can run in another
605# directory (e.g., in tidy build mode, or during the macro-support
606# detection).  Prepend ".".
607absolute_filenames ()
608{
609  # Empty path components are meaningful to tex.  We rewrite them as
610  # `EMPTY' so they don't get lost when we split on $path_sep.
611  # Hopefully no one will have an actual directory named EMPTY.
612  local replace_empty="-e 's/^$path_sep/EMPTY$path_sep/g' \
613                       -e 's/$path_sep\$/${path_sep}EMPTY/g' \
614                       -e 's/$path_sep$path_sep/${path_sep}EMPTY:/g'"
615  local res
616  res=`echo "$1" | eval $SED $replace_empty`
617  save_IFS=$IFS
618  IFS=$path_sep
619  set x $res; shift
620  res=.
621  for dir
622  do
623    case $dir in
624      EMPTY)
625        res=$res$path_sep
626        ;;
627      *)
628        if test -d "$dir"; then
629          res=$res$path_sep`absolute "$dir"`
630        else
631          # Even if $dir is not a directory, preserve it in the path.
632          # It might contain metacharacters that TeX will expand in
633          # turn, e.g., /some/path/{a,b,c}.  This will not get the
634          # implicit absolutification of the path, but we can't help that.
635          res=$res$path_sep$dir
636        fi
637        ;;
638    esac
639  done
640  echo "$res"
641}
642
643
644# output_base_name FILE
645# ---------------------
646# The name of FILE, possibly renamed to satisfy --output.
647# FILE is local, there is no directory part.
648output_base_name ()
649{
650  case $oname in
651    '') echo "$1";;
652     *) local out_noext
653        out_noext=`noext "$oname"`
654        local file_ext
655        file_ext=`echo "$1" | $SED 's/^.*\.//'`
656        echo "$out_noext.$file_ext"
657      ;;
658  esac
659}
660
661
662# destdir
663# -------
664# Return the name of the directory where the output is expected.
665destdir ()
666{
667  case $oname in
668    '')  echo "$orig_pwd";;
669    *)   dirname "$oname";;
670  esac
671}
672
673
674# move_to_dest FILE...
675# --------------------
676# Move FILE to the place where the user expects it.  Truly move it, that
677# is, it must not remain in its build location unless that is also the
678# output location.  (Otherwise it might appear as an extra file in make
679# distcheck.)
680#
681# FILE can be the principal output (in which case -o directly applies), or
682# an auxiliary file with the same base name.
683move_to_dest ()
684{
685#  echo "move_to_dest $*, tidy=$tidy, oname=$oname"
686
687  # If we built in place and have no output name, there is nothing to
688  # do, so just return.
689  case $tidy:$oname in
690    false:) return;;
691  esac
692
693  local destfile
694  local destdir
695  local destbase
696  local sourcedir
697  local sourcebase
698
699  for file
700  do
701    test -f "$file" \
702    || error 1 "no such file or directory: $file"
703    case $tidy:$oname in
704      true:)  destdir=$orig_pwd
705              destfile=$destdir/$file;;
706      true:*) destfile=`output_base_name "$file"`
707              destdir=`dirname "$destfile"`;;
708      false:*) destfile=$oname
709               destdir=`dirname "$destfile"`;;
710    esac
711 
712    # We want to compare the source location and the output location,
713    # and if they are different, do the move.  But if they are the
714    # same, we must preserve the source.  Since we can't assume
715    # stat(1) or test -ef is available, resort to comparing the
716    # directory names, canonicalized with pwd.  We can't use cmp -s
717    # since the output file might not actually change from run to run;
718    # e.g., TeX DVI output is timestamped to only the nearest minute.
719    destdir=`cd "$destdir" && pwd`
720    destbase=`basename "$destfile"`
721
722    sourcedir=`dirname "$file"`
723    sourcedir=`cd "$sourcedir" && pwd`
724    sourcebase=`basename "$file"`
725
726    if test "$sourcedir/$sourcebase" != "$destdir/$destbase"; then
727      verbose "Moving $file to $destfile"
728      rm -f "$destfile"
729      mv "$file" "$destfile"
730    fi
731  done
732}
733
734
735## --------------------- ##
736## Managing xref files.  ##
737## --------------------- ##
738
739# aux_file_p FILE
740# ---------------
741# Return with success if FILE is an aux file.
742aux_file_p ()
743{
744  test -f "$1" || return 1
745  case $1 in
746    *.aux) return 0;;
747    *)     return 1;;
748  esac
749}
750
751# bibaux_file_p FILE
752# ------------------
753# Return with success if FILE is an aux file containing citation
754# requests.
755bibaux_file_p ()
756{
757  test -s "$1" || return 1
758  if (grep '^\\bibstyle[{]' "$1"   \
759      && grep '^\\bibdata[{]' "$1" \
760      ## The following line is suspicious: fails when there
761      ## are citations in sub aux files.  We need to be
762      ## smarter in this case.
763      ## && grep '^\\citation[{]' "$f"
764      ) >&6 2>&1;
765  then
766    return 0
767  fi
768  return 1
769}
770
771# index_file_p FILE
772# -----------------
773# Return with success if FILE is an index file.
774index_file_p ()
775{
776  test -f "$1" || return 1
777  case $in_lang:$latex2html:`out_lang_tex`:`$SED '1q' "$1"` in
778    # When working with TeX4HT, *.idx are created by LaTeX.  They must
779    # be processed to produce *.4ix, *.4dx files.  The *.4dx file is
780    # passed to makeindex to produce the *.ind file.  This sequence is
781    # handled by run_index, so we are only interested in the *.idx
782    # files, which have each "\indexentry" preceded by a
783    # "\beforeentry".
784    latex:tex4ht:html:"\\beforeentry {"*) return 0;;
785
786    # When index.sty is used, there is a space before the brace.
787    latex:*:*:"\\indexentry{"*|latex:*:*:"\\indexentry {"*) return 0;;
788
789    texinfo:*:*:"\\entry{"*) return 0;;
790
791    *) return 1;;
792  esac
793}
794
795# xref_file_p FILE
796# ----------------
797# Return with success if FILE is an xref file (indexes, tables and lists).
798xref_file_p ()
799{
800  test -f "$1" || return 1
801  # If the file is not suitable to be an index or xref file, don't
802  # process it.  It's suitable if the first character is a
803  # backslash or right quote or at, as long as the first line isn't
804  # \input texinfo.
805  case `$SED '1q' "$1"` in
806    "\\input texinfo"*) return 1;;
807    [\\''@]*)           return 0;;
808           *)           return 1;;
809  esac
810}
811
812
813# generated_files_get FILENAME-NOEXT [PREDICATE-FILTER]
814# -----------------------------------------------------
815# Return the list of files generated by the TeX compilation of FILENAME-NOEXT.
816generated_files_get ()
817{
818  local filter=true
819  if test -n "$2"; then
820    filter=$2
821  fi
822
823  # Gather the files created by TeX.
824  (
825    if test -f "$1.log"; then
826      $SED -n -e "s,^\\\\openout.* = \`\\(.*\\)'\\.,\\1,p" "$1.log"
827    fi
828    echo "$1.log"
829  ) |
830  # Depending on these files, infer outputs from other tools.
831  while read file; do
832    echo $file
833    case $in_lang in
834      texinfo)
835        # texindex: texinfo.cp -> texinfo.cps
836       if index_file_p $file; then
837         echo ${file}s
838       fi
839       ;;
840      latex)
841        if aux_file_p $file; then
842          # bibtex: *.aux -> *.bbl and *.blg.
843          echo $file | $SED 's/^\(.*\)\.aux$/\1.bbl/'
844          echo $file | $SED 's/^\(.*\)\.aux$/\1.blg/'
845          # -recorder: .fls
846          echo $file | $SED 's/^\(.*\)\.aux$/\1.fls/'
847       fi
848       ;;
849    esac
850  done |
851  # Filter existing files matching the criterion.
852  #
853  # With an input file name containing a space, this produces a
854  # "command not found" message (and filtering is ineffective).
855  # The situation with a newline is presumably even worse.
856  while read file; do
857    if $filter "$file"; then
858      echo $file
859    fi
860  done |
861  sort |
862  # Some files are opened several times, e.g., listings.sty's *.vrb.
863  uniq
864}
865
866
867# xref_files_save
868# ---------------
869# Save the xref files.
870xref_files_save ()
871{
872  # Save copies of auxiliary files for later comparison.
873  xref_files_orig=`generated_files_get "$in_noext" xref_file_p`
874  if test -n "$xref_files_orig"; then
875    verbose "Backing up xref files: $xref_files_orig"
876    # The following line improves `cp $xref_files_orig "$work_bak"'
877    # by preserving the directory parts.  Think of
878    # cp chap1/main.aux chap2/main.aux $work_bak.
879    #
880    # Users may have, e.g., --keep-old-files.  Don't let this interfere.
881    # (Don't use unset for the sake of ancient shells.)
882    TAR_OPTIONS=; export TAR_OPTIONS
883    tar cf - $xref_files_orig | (cd "$work_bak" && tar xf -)
884  fi
885}
886
887
888# xref_files_changed
889# ------------------
890# Whether the xref files were changed since the previous run.
891xref_files_changed ()
892{
893  # LaTeX (and the package changebar) report in the LOG file if it
894  # should be rerun.  This is needed for files included from
895  # subdirs, since texi2dvi does not try to compare xref files in
896  # subdirs.  Performing xref files test is still good since LaTeX
897  # does not report changes in xref files.
898  if grep "Rerun to get" "$in_noext.log" >&6 2>&1; then
899    return 0
900  fi
901  # biblatex report of whether rerunning is needed.
902  if grep "biblatex.*(re)run" "$in_noext.log" >&6 2>&1; then
903    return 0
904  fi
905
906  # If old and new lists don't have the same file list,
907  # then something has definitely changed.
908  xref_files_new=`generated_files_get "$in_noext" xref_file_p`
909  verbose "Original xref files = $xref_files_orig"
910  verbose "New xref files      = $xref_files_new"
911  if test "x$xref_files_orig" != "x$xref_files_new"; then
912    return 0
913  fi
914
915  # Compare each file until we find a difference.
916  for this_file in $xref_files_new; do
917    verbose "Comparing xref file `echo $this_file | $SED 's|\./||g'` ..."
918    # cmp -s returns nonzero exit status if files differ.
919    if cmp -s "$this_file" "$work_bak/$this_file"; then :; else
920      verbose "xref file `echo $this_file | $SED 's|\./||g'` differed ..."
921      if $debug; then
922        diff -u "$work_bak/$this_file" "$this_file"
923      fi
924      return 0
925    fi
926  done
927
928  # No change.
929  return 1
930}
931
932
933
934## ----------------------- ##
935## Running the TeX suite.  ##
936## ----------------------- ##
937
938
939
940# run_tex ()
941# ----------
942# Run TeX as "$tex $in_input", taking care of errors and logs.
943run_tex ()
944{
945  case $in_lang:$latex2html:`out_lang_tex` in
946    latex:*:dvi|latex:tex4ht:html)
947        tex=${LATEX:-latex};;
948    latex:*:pdf)
949        tex=${PDFLATEX:-pdflatex};;
950    texinfo:*:dvi)
951        # MetaPost also uses the TEX environment variable.  If the user
952        # has set TEX=latex for that reason, don't bomb out.
953        case $TEX in
954          *latex) tex=tex;; # don't bother trying to find etex
955               *) tex=$TEX
956        esac;;
957    texinfo:*:pdf) tex=$PDFTEX;;
958
959    *) error 1 "$out_lang not supported for $in_lang";;
960  esac
961
962  # do the special catcode trick for ~ in filenames only for Texinfo,
963  # not LaTeX.
964  if test x"$in_lang" = xtexinfo && test $catcode_special = maybe; then
965    catcode_special=true
966  else
967    catcode_special=false
968  fi
969
970  # Beware of aux files in subdirectories that require the
971  # subdirectory to exist.
972  case $in_lang:$tidy in
973    latex:true)
974       $SED -n 's|^[ ]*\\include{\(.*\)/.*}.*|\1|p' "$in_input" |
975       sort -u |
976       while read d
977       do
978         ensure_dir "$work_build/$d"
979       done
980       ;;
981  esac
982
983  # Note that this will be used via an eval: quote properly.
984  local cmd="$tex"
985
986  # If possible, make TeX report error locations in GNU format.
987  if $line_error; then
988    if test "${tex_help:+set}" != set; then
989      # Go to a temporary directory to try --help, since old versions that
990      # don't accept --help will generate a texput.log.
991      tex_help_dir=$t2ddir/tex_help
992      ensure_dir "$tex_help_dir"
993      tex_help=`cd "$tex_help_dir" >&6 && $tex --help </dev/null 2>&1 || true`
994    fi
995    # The mk program and perhaps others want to parse TeX's
996    # original error messages.
997    case $tex_help in
998      *file-line-error*) cmd="$cmd --file-line-error";;
999    esac
1000  fi
1001
1002  # Tell TeX about TCX file, if specified.
1003  test -n "$translate_file" && cmd="$cmd --translate-file=$translate_file"
1004
1005  # Tell TeX to make source specials (for backtracking from output to
1006  # source, given a sufficiently smart editor), if specified.
1007  test -n "$src_specials" && cmd="$cmd $src_specials"
1008
1009  # Tell TeX to allow running external executables
1010  test -n "$shell_escape" && cmd="$cmd $shell_escape"
1011
1012  # Tell TeX to be batch if requested.
1013  if $batch; then
1014    # \batchmode does not show terminal output at all, so we don't
1015    # want that.  And even in batch mode, TeX insists on having input
1016    # from the user.  Close its stdin to make it impossible.
1017    cmd="$cmd </dev/null '${escape}nonstopmode'"
1018  fi
1019
1020  # we'd like to handle arbitrary input file names, especially
1021  # foo~bar/a~b.tex, since Debian likes ~ characters.
1022  if $catcode_special; then
1023    # $normaltilde is just to reduce line length in this source file.
1024    # The idea is to define \normaltilde as a catcode other ~ character,
1025    # then make the active ~ be equivalent to that, instead of the plain
1026    # TeX tie.  Then when the active ~ appears in the filename, it will
1027    # be expanded to itself, as far as \input will see.  (This is the
1028    # same thing that texinfo.tex does in general, BTW.)
1029    normaltilde="${escape}catcode126=12 ${escape}def${escape}normaltilde{~}"
1030    cmd="$cmd '$normaltilde${escape}catcode126=13 ${escape}let~\normaltilde '"
1031  fi
1032  # Other special (non-active) characters could be supported by
1033  # resetting their catcodes to other on the command line and changing
1034  # texinfo.tex to initialize everything to plain catcodes.  Maybe someday.
1035
1036  # append the \input command.
1037  cmd="$cmd '${escape}input'"
1038
1039  # TeX's \input does not (easily or reliably) support whitespace
1040  # characters or other special characters in file names.  Our intensive
1041  # use of absolute file names makes this worse: the enclosing directory
1042  # names may include white spaces.  Improve the situation using a
1043  # symbolic link to the filename in the current directory, in tidy mode
1044  # only.  Do not alter in_input.
1045  #
1046  # The filename is almost always tokenized using plain TeX conventions
1047  # (the exception would be if the user made a texinfo.fmt file).  Not
1048  # all the plain TeX special characters cause trouble, but there's no
1049  # harm in making the link.
1050  #
1051  case $tidy:`func_dirname "$in_input"` in
1052    true:*["$space$tab$newline\"#\$%\\^_{}~"]*)
1053      _run_tex_file_name=`basename "$in_input"`
1054      if test ! -f "$_run_tex_file_name"; then
1055        # It might not be a file, clear it.
1056        run rm -f "$_run_tex_file_name"
1057        run ln -s "$in_input"
1058      fi
1059      cmd="$cmd '$_run_tex_file_name'"
1060      ;;
1061
1062    *)
1063      cmd="$cmd '$in_input'"
1064      ;;
1065  esac
1066
1067  verbose "$0: Running $cmd ..."
1068  if eval "$cmd" >&5; then
1069    case $out_lang in
1070      dvi | pdf ) move_to_dest "$in_noext.$out_lang";;
1071    esac
1072  else
1073    error 1 "$tex exited with bad status, quitting."
1074  fi
1075}
1076
1077# run_bibtex ()
1078# -------------
1079# Run bibtex on (or biber) current file.
1080# - If its input (AUX) exists.
1081# - If some citations are missing (LOG contains `Citation').
1082#   or the LOG complains of a missing .bbl
1083#
1084# Don't try to be too smart:
1085# 1. Running bibtex only if the bbl file exists and is older than
1086# the LaTeX file is wrong, since the document might include files
1087# that have changed.
1088#
1089# 3. Because there can be several AUX (if there are \include's),
1090# but a single LOG, looking for missing citations in LOG is
1091# easier, though we take the risk of matching false messages.
1092run_bibtex ()
1093{
1094  case $in_lang in
1095    latex)   bibtex=${BIBTEX:-bibtex};;
1096    texinfo) return;;
1097  esac
1098
1099  # "Citation undefined" is for LaTeX, "Undefined citation" for btxmac.tex.
1100  # The no .aux && \bibdata test is also for btxmac, in case it was the
1101  # first run of a bibtex-using document.  Otherwise, it's possible that
1102  # bibtex would never be run.
1103  if test -r "$in_noext.aux" \
1104     && test -r "$in_noext.log" \
1105     && ( (grep 'Warning:.*Citation.*undefined' "$in_noext.log" \
1106          || grep '.*Undefined citation' "$in_noext.log" \
1107          || grep 'No file .*\.bbl\.' "$in_noext.log") \
1108          || (grep 'No \.aux file' "$in_noext.log" \
1109              && grep '^\\bibdata' "$in_noext.aux") ) \
1110        >&6 2>&1; \
1111  then
1112    bibtex_aux=`generated_files_get "$in_noext" bibaux_file_p`
1113    for f in $bibtex_aux; do
1114      run $bibtex "$f"
1115    done
1116  fi
1117
1118  # biber(+biblatex) check.
1119  if test -r "$in_noext.bcf" \
1120     && grep '</bcf:controlfile>' "$in_noext.bcf" >/dev/null; then
1121    run ${BIBER:-biber} "$in_noext"
1122  fi
1123}
1124
1125# run_index ()
1126# ------------
1127# Run texindex (or makeindex or texindy) on current index files.  If
1128# they already exist, and after running TeX a first time the index
1129# files don't change, then there's no reason to run TeX again.  But we
1130# won't know that if the index files are out of date or nonexistent.
1131run_index ()
1132{
1133  local index_files
1134  index_files=`generated_files_get $in_noext index_file_p`
1135  test -n "$index_files" \
1136  || return 0
1137
1138  : ${MAKEINDEX:=makeindex}
1139  : ${TEXINDEX:=texindex}
1140  : ${TEXINDY:=texindy}
1141
1142  local index_file
1143  local index_noext
1144  case $in_lang:$latex2html:`out_lang_tex` in
1145    latex:tex4ht:html)
1146      for index_file in $index_files
1147      do
1148        index_noext=`noext "$index_file"`
1149        run tex \
1150            '\def\filename{{'"$index_noext"'}{idx}{4dx}{ind}}
1151             \input idxmake.4ht'
1152        run $MAKEINDEX -o $index_noext.ind $index_noext.4dx
1153      done
1154      ;;
1155
1156    latex:*)
1157      if $TEXINDY --version >&6 2>&1; then
1158        run $TEXINDY $index_files
1159      else
1160        run $MAKEINDEX $index_files
1161      fi
1162      ;;
1163
1164    texinfo:*)
1165      run $TEXINDEX $index_files
1166      ;;
1167  esac
1168}
1169
1170
1171# run_tex4ht ()
1172# -------------
1173# Run the last two phases of TeX4HT: tex4ht extracts the HTML from the
1174# instrumented DVI file, and t4ht converts the figures and installs
1175# the files when given -d.
1176#
1177# Because knowing exactly which files are created is complex (in
1178# addition the names are not simple to compute), which makes it
1179# difficult to install the output files in a second step, it is much
1180# simpler to install directly the output files.
1181run_tex4ht ()
1182{
1183  case $in_lang:$latex2html:`out_lang_tex` in
1184    latex:tex4ht:html)
1185      : ${TEX4HT:=tex4ht} ${T4HT:=t4ht}
1186      run "$TEX4HT" "-f/$in_noext"
1187      # Do not remove the / after the destdir.
1188      run "$T4HT" "-d`destdir`/" "-f/$in_noext"
1189      ;;
1190  esac
1191}
1192
1193
1194# run_thumbpdf ()
1195# ---------------
1196run_thumbpdf ()
1197{
1198  if test `out_lang_tex` = pdf \
1199     && test -r "$in_noext.log" \
1200     && grep 'thumbpdf\.sty'  "$in_noext.log" >&6 2>&1; \
1201  then
1202    thumbpdf=${THUMBPDF_CMD:-thumbpdf}
1203    thumbcmd="$thumbpdf $in_dir/$in_noext"
1204    verbose "Running $thumbcmd ..."
1205    if $thumbcmd >&5; then
1206      run_tex
1207    else
1208      report "$thumbpdf exited with bad status." \
1209             "Ignoring its output."
1210    fi
1211  fi
1212}
1213
1214
1215# run_dvipdf FILE.dvi
1216# -------------------
1217# Convert FILE.dvi to FILE.pdf.
1218run_dvipdf ()
1219{
1220  # Find which dvi->pdf program is available.
1221  if test -z "$dvipdf"; then
1222    for i in "$DVIPDF" dvipdfmx dvipdfm dvipdf dvi2pdf dvitopdf; do
1223      if findprog $i; then
1224        dvipdf=$i
1225      fi
1226    done
1227  fi
1228  # These tools have varying interfaces, some 'input output', others
1229  # 'input -o output'.  They all seem to accept 'input' only,
1230  # outputting using the expected file name.
1231  run $dvipdf "$1"
1232  if test ! -f `echo "$1" | $SED -e 's/\.dvi$/.pdf/'`; then
1233    error 1 "cannot find output file"
1234  fi
1235}
1236
1237# run_tex_suite ()
1238# ----------------
1239# Run the TeX tools until a fix point is reached.
1240run_tex_suite ()
1241{
1242  # Move to the working directory.
1243  if $tidy; then
1244    verbose "cd $work_build"
1245    cd "$work_build" || exit 1
1246  fi
1247
1248  # Count the number of cycles.
1249  local cycle=0
1250
1251  while :; do
1252    # check for probably LaTeX loop (e.g. varioref)
1253    if test $cycle -eq "$max_iters"; then
1254      error 0 "Maximum of $max_iters cycles exceeded"
1255      break
1256    fi
1257
1258    # report progress
1259    cycle=`expr $cycle + 1`
1260    verbose "Cycle $cycle for $command_line_filename"
1261
1262    xref_files_save
1263
1264    # We run bibtex first, because it's more likely for the indexes
1265    # to change after bibtex is run than the reverse, though either
1266    # would be rare.
1267    run_bibtex
1268    run_index
1269    run_core_conversion
1270
1271    xref_files_changed || break
1272  done
1273
1274  # If we were using thumbpdf and producing PDF, then run thumbpdf
1275  # and TeX one last time.
1276  run_thumbpdf
1277
1278  # If we are using tex4ht, call it.
1279  run_tex4ht
1280
1281  # Install the result if we didn't already (i.e., if the output is
1282  # dvipdf or ps).
1283  case $latex2html:$out_lang in
1284    *:dvipdf)
1285      run_dvipdf "$in_noext.`out_lang_tex`"
1286      move_to_dest "$in_noext.`out_lang_ext`"
1287      ;;
1288    *:ps)
1289      : ${DVIPS:=dvips}
1290      run $DVIPS -o "$in_noext.`out_lang_ext`" "$in_noext.`out_lang_tex`"
1291      move_to_dest "$in_noext.`out_lang_ext`"
1292      ;;
1293  esac
1294
1295  cd_orig
1296}
1297
1298## -------------------------------- ##
1299## TeX processing auxiliary tools.  ##
1300## -------------------------------- ##
1301
1302
1303# A sed script that preprocesses Texinfo sources in order to keep the
1304# iftex sections only.  We want to remove non-TeX sections, and comment
1305# (with `@c _texi2dvi') TeX sections so that makeinfo does not try to
1306# parse them.  Nevertheless, while commenting TeX sections, don't
1307# comment @macro/@end macro so that makeinfo does propagate them.
1308# Unfortunately makeinfo --iftex --no-ifinfo doesn't work well enough
1309# (yet), makeinfo can't parse the TeX commands, so work around with sed.
1310#
1311# We assume that `@c _texi2dvi' starting a line is not present in the
1312# document.
1313#
1314comment_iftex=\
1315'/^@tex/,/^@end tex/{
1316  s/^/@c _texi2dvi/
1317}
1318/^@iftex/,/^@end iftex/{
1319  s/^/@c _texi2dvi/
1320  /^@c _texi2dvi@macro/,/^@c _texi2dvi@end macro/{
1321    s/^@c _texi2dvi//
1322  }
1323}
1324/^@ifnottex/,/^@end ifnottex/{
1325  s/^/@c (_texi2dvi)/
1326}
1327/^@ifinfo/,/^@end ifinfo/{
1328  /^@node/p
1329  /^@menu/,/^@end menu/p
1330  t
1331  s/^/@c (_texi2dvi)/
1332}
1333s/^@ifnotinfo/@c _texi2dvi@ifnotinfo/
1334s/^@end ifnotinfo/@c _texi2dvi@end ifnotinfo/'
1335
1336# Uncommenting is simpler: remove any leading `@c texi2dvi'; repeated
1337# copies can sneak in via macro invocations.
1338uncomment_iftex='s/^@c _texi2dvi\(@c _texi2dvi\)*//'
1339
1340
1341# run_makeinfo ()
1342# ---------------
1343# Expand macro commands in the original source file using Makeinfo.
1344# Always use `end' footnote style, since the `separate' style
1345# generates different output (arguably this is a bug in -E).  Discard
1346# main info output, the user asked to run TeX, not makeinfo.
1347run_makeinfo ()
1348{
1349  test $in_lang = texinfo \
1350    || return 0
1351
1352  # Unless required by the user, makeinfo expansion is wanted only
1353  # if texinfo.tex is too old.
1354  if $expand; then
1355    makeinfo=${MAKEINFO:-makeinfo}
1356  else
1357    # Check if texinfo.tex performs macro expansion by looking for
1358    # its version.  The version is a date of the form YEAR-MO-DA.
1359    # We don't need to use [0-9] to match the digits since anyway
1360    # the comparison with $txiprereq, a number, will fail with non-digits.
1361    # Run in a temporary directory to avoid leaving files.
1362    version_test_dir=$t2ddir/version_test
1363    ensure_dir "$version_test_dir"
1364    if (
1365       cd "$version_test_dir"
1366       echo '\input texinfo.tex @bye' >txiversion.tex
1367       # Be sure that if tex wants to fail, it is not interactive:
1368       # close stdin.
1369       $TEX txiversion.tex </dev/null >txiversion.out 2>txiversion.err
1370    ); then :; else
1371      report "texinfo.tex appears to be broken.
1372This may be due to the environment variable TEX set to something
1373other than (plain) tex, a corrupt texinfo.tex file, or 
1374to tex itself simply not working."
1375      cat "$version_test_dir/txiversion.out"
1376      cat "$version_test_dir/txiversion.err" >&2
1377      error 1 "quitting."
1378    fi
1379    eval `$SED -n 's/^.*\[\(.*\)version \(....\)-\(..\)-\(..\).*$/txiformat=\1 txiversion="\2\3\4"/p' "$version_test_dir/txiversion.out"`
1380    verbose "texinfo.tex preloaded as \`$txiformat', version is \`$txiversion' ..."
1381    if test "$txiprereq" -le "$txiversion" >&6 2>&1; then
1382      makeinfo=
1383    else
1384      makeinfo=${MAKEINFO:-makeinfo}
1385    fi
1386    # If TeX is preloaded, offer the user this convenience:
1387    if test "$txiformat" = Texinfo; then
1388      escape=@
1389    fi
1390  fi
1391
1392  if test -n "$makeinfo"; then
1393    # in_src: the file with macros expanded.
1394    # Use the same basename to generate the same aux file names.
1395    work_src=$workdir/src
1396    ensure_dir "$work_src"
1397    in_src=$work_src/$in_base
1398    local miincludes
1399    miincludes=`list_prefix includes -I`
1400    verbose "Macro-expanding $command_line_filename to $in_src ..."
1401    # eval $makeinfo because it might be defined as something complex
1402    # (running missing) and then we end up with things like '"-I"',
1403    # and "-I" (including the quotes) is not an option name.  This
1404    # happens with gettext 0.14.5, at least.
1405    $SED "$comment_iftex" "$command_line_filename" \
1406      | eval $makeinfo --footnote-style=end -I "$in_dir" $miincludes \
1407        -o /dev/null --macro-expand=- \
1408      | $SED "$uncomment_iftex" >"$in_src"
1409    # Continue only if everything succeeded.
1410    if test $? -ne 0 \
1411       || test ! -r "$in_src"; then
1412      verbose "Expansion failed, ignored...";
1413    else
1414      in_input=$in_src
1415    fi
1416  fi
1417}
1418
1419# insert_commands ()
1420# ------------------
1421# Used most commonly for @finalout, @smallbook, etc.
1422insert_commands ()
1423{
1424  if test -n "$textra"; then
1425    # _xtr.  The file with the user's extra commands.
1426    work_xtr=$workdir/xtr
1427    in_xtr=$work_xtr/$in_base
1428    ensure_dir "$work_xtr"
1429    verbose "Inserting extra commands: $textra"
1430    local textra_cmd
1431    case $in_lang in
1432      latex)   textra_cmd=1i;;
1433      texinfo) textra_cmd='/^@setfilename/a';;
1434      *)       error 1 "internal error, unknown language: $in_lang";;
1435    esac
1436    $SED "$textra_cmd\\
1437$textra" "$in_input" >"$in_xtr"
1438    in_input=$in_xtr
1439  fi
1440
1441  case $in_lang:$latex2html:`out_lang_tex` in
1442    latex:tex4ht:html)
1443      # _tex4ht.  The file with the added \usepackage{tex4ht}.
1444      work_tex4ht=$workdir/tex4ht
1445      in_tex4ht=$work_tex4ht/$in_base
1446      ensure_dir "$work_tex4ht"
1447      verbose "Inserting \\usepackage{tex4ht}"
1448      perl -pe 's<\\documentclass(?:\[.*\])?{.*}>
1449                 <$&\\usepackage[xhtml]{tex4ht}>' \
1450        "$in_input" >"$in_tex4ht"
1451      in_input=$in_tex4ht
1452      ;;
1453  esac
1454}
1455
1456# compute_language FILENAME
1457# -------------------------
1458# Return the short string describing the language in which FILENAME
1459# is written: `texinfo' or `latex'.
1460compute_language ()
1461{
1462  # If the user explicitly specified the language, use that.
1463  # Otherwise, if the first line is \input texinfo, assume it's texinfo.
1464  # Otherwise, guess from the file extension.
1465  if test -n "$set_language"; then
1466    echo $set_language
1467  elif $SED 1q "$1" | grep 'input texinfo' >&6; then
1468    echo texinfo
1469  else
1470    # Get the type of the file (latex or texinfo) from the given language
1471    # we just guessed, or from the file extension if not set yet.
1472    case $1 in
1473      *.ltx | *.tex | *.drv | *.dtx) echo latex;;
1474      *)                             echo texinfo;;
1475    esac
1476  fi
1477}
1478
1479
1480# run_hevea (MODE)
1481# ----------------
1482# Convert to HTML/INFO/TEXT.
1483#
1484# Don't pass `-noiso' to hevea: it's useless in HTML since anyway the
1485# charset is set to latin1, and troublesome in other modes since
1486# accented characters loose their accents.
1487#
1488# Don't pass `-o DEST' to hevea because in that case it leaves all its
1489# auxiliary files there too...  Too bad, because it means we will need
1490# to handle images some day.
1491run_hevea ()
1492{
1493  local hevea="${HEVEA:-hevea}"
1494  local run_hevea="$hevea"
1495
1496  case $1 in
1497    html) ;;
1498    text|info) run_hevea="$run_hevea -$1";;
1499    *) error 1 "run_hevea: invalid argument: $1";;
1500  esac
1501
1502  # Compiling to the tmp directory enables to preserve a previous
1503  # successful compilation.
1504  run_hevea="$run_hevea -fix -O -o '$out_base'"
1505  run_hevea="$run_hevea `list_prefix includes -I` -I '$orig_pwd' "
1506  run_hevea="$run_hevea '$in_input'"
1507
1508  if $debug; then
1509    run_hevea="$run_hevea -v -v"
1510  fi
1511
1512  verbose "running $run_hevea"
1513  if eval "$run_hevea" >&5; then
1514    # hevea leaves trailing white spaces, this is annoying.
1515    case $1 in text|info)
1516      perl -pi -e 's/[ \t]+$//g' "$out_base"*;;
1517    esac
1518    case $1 in
1519    html|text) move_to_dest "$out_base";;
1520    info) # There can be foo.info-1, foo.info-2 etc.
1521               move_to_dest "$out_base"*;;
1522    esac
1523  else
1524    error 1 "$hevea exited with bad status, quitting."
1525  fi
1526}
1527
1528
1529# run_core_conversion ()
1530# ----------------------
1531# Run the TeX (or HeVeA).
1532run_core_conversion ()
1533{
1534  case $in_lang:$latex2html:`out_lang_tex` in
1535    *:dvi|*:pdf|latex:tex4ht:html)
1536        run_tex;;
1537    latex:*:html|latex:*:text|latex:*:info)
1538        run_hevea $out_lang;;
1539    *)
1540        error 1 "invalid input/output combination: $in_lang/$out_lang";;
1541  esac
1542}
1543
1544
1545# compile ()
1546# ----------
1547# Run the full compilation chain, from pre-processing to installation
1548# of the output at its expected location.
1549compile ()
1550{
1551  # Source file might include additional sources.
1552  # We want `.:$orig_pwd' before anything else.  (We'll add `.:' later
1553  # after all other directories have been turned into absolute paths.)
1554  # `.' goes first to ensure that any old .aux, .cps,
1555  # etc. files in ${directory} don't get used in preference to fresher
1556  # files in `.'.  Include orig_pwd in case we are in clean build mode, where
1557  # we have cd'd to a temp directory.
1558  common="$orig_pwd$path_sep$in_dir$path_sep"
1559  #
1560  # If we have any includes, put those at the end.
1561  # Keep a final path_sep to get the default (system) TeX directories included.
1562  txincludes=`list_infix includes $path_sep`
1563  test -n "$txincludes" && common="$common$txincludes$path_sep"
1564  #
1565  for var in $tex_envvars; do
1566    eval val="\$common\$${var}_orig"
1567    # Convert relative paths to absolute paths, so we can run in another
1568    # directory (e.g., in clean build mode, or during the macro-support
1569    # detection). ".:" is added here.
1570    val=`absolute_filenames "$val"`
1571    eval $var="\"$val\""
1572    export $var
1573    eval verbose \"$var=\'\$${var}\'\"
1574  done
1575
1576  # --expand
1577  run_makeinfo
1578
1579  # --command, --texinfo
1580  insert_commands
1581
1582  # Run until a fix point is reached.
1583  run_tex_suite
1584}
1585
1586
1587# remove FILES
1588# ------------
1589remove ()
1590{
1591  verbose "Removing" "$@"
1592  rm -rf "$@"
1593}
1594
1595
1596# mostly_clean
1597# ------------
1598# Remove auxiliary files and directories.  Changes the current directory.
1599mostly_clean ()
1600{
1601  cd_orig
1602  set X "$t2ddir"
1603  shift
1604  $tidy || {
1605    local log="$work_build/$in_noext.log"
1606    set X ${1+"$@"} "$log" `generated_files_get "$work_build/$in_noext"`
1607    shift
1608  }
1609  remove ${1+"$@"}
1610}
1611
1612
1613# cleanup ()
1614# ----------
1615# Remove what should be removed according to options.
1616# Called at the end of each compilation cycle, and at the end of
1617# the script.  Changes the current directory.
1618cleanup ()
1619{
1620  case $build_mode in
1621    local) cd_orig; remove "$t2ddir";;
1622    clean) mostly_clean;;
1623    tidy)  ;;
1624  esac
1625}
1626
1627
1628
1629## ---------------------- ##
1630## Command line parsing.  ##
1631## ---------------------- ##
1632
1633# Push a token among the arguments that will be used to notice when we
1634# ended options/arguments parsing.
1635# Use "set dummy ...; shift" rather than 'set - ..." because on
1636# Solaris set - turns off set -x (but keeps set -e).
1637# Use ${1+"$@"} rather than "$@" because Digital Unix and Ultrix 4.3
1638# still expand "$@" to a single argument (the empty string) rather
1639# than nothing at all.
1640arg_sep="$$--$$"
1641set dummy ${1+"$@"} "$arg_sep"; shift
1642
1643# 
1644# Parse command line arguments.
1645while test x"$1" != x"$arg_sep"; do
1646
1647  # Handle --option=value by splitting apart and putting back on argv.
1648  case "$1" in
1649    --*=*)
1650      opt=`echo "$1" | $SED -e 's/=.*//'`
1651      val=`echo "$1" | $SED -e 's/[^=]*=//'`
1652      shift
1653      set dummy "$opt" "$val" ${1+"$@"}; shift
1654      ;;
1655  esac
1656
1657  case "$1" in
1658    -@ ) escape=@;;
1659    -~ ) catcode_special=false;;
1660    # Silently and without documentation accept -b and --b[atch] as synonyms.
1661    -b | --batch) batch=true;;
1662         --build)      shift; build_mode=$1;;
1663         --build-dir)  shift; build_dir=$1; build_mode=tidy;;
1664    -c | --clean) build_mode=clean;;
1665    -D | --debug) debug=true;;
1666    -e | -E | --expand) expand=true;;
1667    -h | --help) usage;;
1668    -I)   shift; list_concat_dirs includes "$1";;
1669    -l | --lang | --language) shift; set_language=$1;;
1670    --mostly-clean) action=mostly-clean;;
1671    --no-line-error) line_error=false;;
1672    --max-iterations) shift; max_iters=$1;;
1673    -o | --out  | --output)
1674      shift
1675      # Make it absolute, just in case we also have --clean, or whatever.
1676      oname=`absolute "$1"`;;
1677
1678    # Output formats.
1679    -O|--output-format) shift; out_lang_set "$1";;
1680       --dvi|--dvipdf|--html|--info|--pdf|--ps|--text)
1681       out_lang_set `echo "x$1" | $SED 's/^x--//'`;;
1682
1683    -p) out_lang_set pdf;;
1684    -q | -s | --quiet | --silent) quiet=true; batch=true;;
1685    --src-specials) src_specials=--src-specials;;
1686    --shell-escape) shell_escape=--shell-escape;;  
1687    --tex4ht) latex2html=tex4ht;;
1688    -t | --texinfo | --command ) shift; textra="$textra\\
1689"`echo "$1" | $SED 's/\\\\/\\\\\\\\/g'`;;
1690    --translate-file ) shift; translate_file="$1";;
1691    --tidy) build_mode=tidy;;
1692    -v | --vers*) version;;
1693    -V | --verb*) verb=true;;
1694    --) # What remains are not options.
1695      shift
1696      while test x"$1" != x"$arg_sep"; do
1697        set dummy ${1+"$@"} "$1"; shift
1698        shift
1699      done
1700      break;;
1701    -*)
1702      error 1 "Unknown or ambiguous option \`$1'." \
1703              "Try \`--help' for more information."
1704      ;;
1705    *) set dummy ${1+"$@"} "$1"; shift;;
1706   esac
1707   shift
1708done
1709# Pop the token
1710shift
1711
1712# $tidy:  compile in a t2d directory.
1713# $clean: remove all the aux files.
1714case $build_mode in
1715  local) clean=false; tidy=false;;
1716  tidy)  clean=false; tidy=true;;
1717  clean) clean=true;  tidy=true;;
1718      *) error 1 "invalid build mode: $build_mode";;
1719esac
1720
1721# Interpret remaining command line args as filenames.
1722case $# in
1723 0)
1724  error 2 "Missing file arguments." "Try \`--help' for more information."
1725  ;;
1726 1) ;;
1727 *)
1728  if test -n "$oname"; then
1729    error 2 "Can't use option \`--output' with more than one argument."
1730  fi
1731  ;;
1732esac
1733
1734
1735# We can't do much without tex.
1736#
1737if findprog ${TEX:-tex}; then :; else cat <<EOM
1738You don't have a working TeX binary (${TEX:-tex}) installed anywhere in
1739your PATH, and texi2dvi cannot proceed without one.  If you want to use
1740this script, you'll need to install TeX (if you don't have it) or change
1741your PATH or TEX environment variable (if you do).  See the --help
1742output for more details.
1743
1744For information about obtaining TeX, please see http://tug.org/texlive,
1745or do a web search for TeX and your operating system or distro.
1746EOM
1747  exit 1
1748fi
1749
1750
1751# We want to use etex (or pdftex) if they are available, and the user
1752# didn't explicitly specify.  We don't check for elatex and pdfelatex
1753# because (as of 2003), the LaTeX team has asked that new distributions
1754# use etex by default anyway.
1755#
1756# End up with the TEX and PDFTEX variables set to what we are going to use.
1757if test -z "$TEX"; then
1758  if findprog etex; then TEX=etex; else TEX=tex; fi
1759fi
1760#
1761if test -z "$PDFTEX"; then
1762  if findprog pdfetex; then PDFTEX=pdfetex; else PDFTEX=pdftex; fi
1763fi
1764
1765
1766# File descriptor usage:
1767# 0 standard input
1768# 1 standard output (--verbose messages)
1769# 2 standard error
1770# 3 some systems may open it to /dev/tty
1771# 4 used on the Kubota Titan
1772# 5 tools output (turned off by --quiet)
1773# 6 tracing/debugging (set -x output, etc.)
1774
1775
1776# Main tools' output (TeX, etc.) that TeX users are used to seeing.
1777#
1778# If quiet, discard, else redirect to the message flow.
1779if $quiet; then
1780  exec 5>/dev/null
1781else
1782  exec 5>&1
1783fi
1784
1785
1786# Enable tracing, and auxiliary tools output.
1787# 
1788# This fd should be used where you'd typically use /dev/null to throw
1789# output away.  But sometimes it is convenient to see that output (e.g.,
1790# from a grep) to aid debugging.  Especially debugging at distance, via
1791# the user.
1792# 
1793if $debug; then
1794  exec 6>&1
1795  set -vx
1796else
1797  exec 6>/dev/null
1798fi
1799
1800# 
1801
1802# input_file_name_decode
1803# ----------------------
1804# Decode COMMAND_LINE_FILENAME, and compute:
1805# - COMMAND_LINE_FILENAME clean of TeX commands
1806# - IN_DIR
1807#   The directory to the input file, possibly absolute if needed.
1808# - IN_DIR_ABS
1809#   The absolute directory of the input file.
1810# - IN_BASE
1811#   The input file base name (no directory part).
1812# - IN_NOEXT
1813#   The input file name without extensions (nor directory part).
1814# - IN_INPUT
1815#   Defaults to COMMAND_LINE_FILENAME, but might change if the
1816#   input is preprocessed.  With directory, possibly absolute.
1817input_file_name_decode ()
1818{
1819  # See if we are run from within AUC-Tex, in which case we are
1820  # passed `\input{FOO.tex}' or even `\nonstopmode\input{FOO.tex}'.
1821  case $command_line_filename in
1822    *\\nonstopmode*)
1823      batch=true;;
1824  esac
1825  case $command_line_filename in
1826    *\\input{*}*)
1827      # Let AUC-TeX error parser deal with line numbers.
1828      line_error=false
1829      command_line_filename=`\
1830        expr X"$command_line_filename" : X'.*input{\([^}]*\)}'`
1831      ;;
1832  esac
1833
1834  # If the COMMAND_LINE_FILENAME is not absolute (e.g., --debug.tex),
1835  # prepend `./' in order to avoid that the tools take it as an option.
1836  echo "$command_line_filename" | LC_ALL=C $EGREP '^(/|[A-Za-z]:/)' >&6 \
1837  || command_line_filename="./$command_line_filename"
1838
1839  # See if the file exists.  If it doesn't we're in trouble since, even
1840  # though the user may be able to reenter a valid filename at the tex
1841  # prompt (assuming they're attending the terminal), this script won't
1842  # be able to find the right xref files and so forth.
1843  test -r "$command_line_filename" \
1844  || error 1 "cannot read $command_line_filename, skipping."
1845
1846  # Get the name of the current directory.
1847  in_dir=`func_dirname "$command_line_filename"`
1848  in_dir_abs=`absolute "$in_dir"`
1849  # In a clean build, we `cd', so get an absolute file name.
1850  if $tidy; then
1851    in_dir=$in_dir_abs
1852  fi
1853
1854  # Strip directory part but leave extension.
1855  in_base=`basename "$command_line_filename"`
1856  # Strip extension.
1857  in_noext=`noext "$in_base"`
1858
1859  # The normalized file name to compile.  Must always point to the
1860  # file to actually compile (in case of recoding, macro-expansion etc.).
1861  in_input=$in_dir/$in_base
1862
1863
1864  # Compute the output file name.
1865  if test x"$oname" != x; then
1866    out_name=$oname
1867  else
1868    out_name=$in_noext.`out_lang_ext`
1869  fi
1870  out_dir=`func_dirname "$out_name"`
1871  out_dir_abs=`absolute "$out_dir"`
1872  out_base=`basename "$out_name"`
1873  out_noext=`noext "$out_base"`
1874}
1875
1876
1877## -------------- ##
1878## TeXify files.  ##
1879## -------------- ##
1880
1881for command_line_filename
1882do
1883  verbose "Processing $command_line_filename ..."
1884
1885  input_file_name_decode
1886
1887  # `texinfo' or `latex'?
1888  in_lang=`compute_language "$command_line_filename"`
1889
1890  # An auxiliary directory used for all the auxiliary tasks involved
1891  # in compiling this document.
1892  case $build_dir in
1893      '' | . ) t2ddir=$out_noext.t2d ;;
1894      *) # Avoid collisions between multiple occurrences of the same
1895         # file, so depend on the output path.  Remove leading `./',
1896         # at least to avoid creating a file starting with `.!', i.e.,
1897         # an invisible file. The sed expression is fragile if the cwd
1898         # has active characters.  Transform / into ! so that we don't
1899         # need `mkdir -p'.  It might be something to reconsider.
1900         t2ddir=$build_dir/`echo "$out_dir_abs/$out_noext.t2d" |
1901             $SED "s,^$orig_pwd/,,;s,^\./,,;s,/,!,g"`
1902  esac
1903  # Remove it at exit if clean mode.
1904  trap "cleanup" 0 1 2 15
1905
1906  ensure_dir "$build_dir" "$t2ddir"
1907
1908  # We will change directory, better work with an absolute path...
1909  t2ddir=`absolute "$t2ddir"`
1910  # Sometimes there are incompatibilities between auxiliary files for
1911  # DVI and PDF.  The contents can also change whether we work on PDF
1912  # and/or DVI.  So keep separate spaces for each.
1913  workdir=$t2ddir/`out_lang_tex`
1914  ensure_dir "$workdir"
1915
1916  # _build.  In a tidy build, where the auxiliary files are output.
1917  if $tidy; then
1918    work_build=$workdir/build
1919  else
1920    work_build=.
1921  fi
1922
1923  # _bak.  Copies of the previous auxiliary files (another round is
1924  # run if they differ from the new ones).
1925  work_bak=$workdir/bak
1926
1927  # Make those directories.
1928  ensure_dir "$work_build" "$work_bak"
1929
1930  case $action in
1931    compile)
1932      # Compile the document.
1933      compile
1934      cleanup
1935      ;;
1936
1937    mostly-clean)
1938      mostly_clean
1939      ;;
1940  esac
1941done
1942
1943verbose "done."
1944exit 0 # exit successfully, not however we ended the loop.
1945