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