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