texi2dvi 56.7 KB
Newer Older
1
2
#! /bin/sh
# texi2dvi --- produce DVI (or PDF) files from Texinfo (or (La)TeX) sources.
3
# $Id: texi2dvi,v 1.173 2012/04/20 18:52:48 karl Exp $
4
#
5
6
7
# Copyright 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2001, 2002,
# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
# Free Software Foundation, Inc.
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License,
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Originally written by Noah Friedman.
#
# Please send bug reports, etc. to bug-texinfo@gnu.org.
# If possible, please send a copy of the output of the script called with
# the `--debug' option when making a bug report.

test -f /bin/ksh && test -z "$RUNNING_KSH" \
  && { UNAMES=`uname -s`; test "x$UNAMES" = xULTRIX; } 2>/dev/null \
  && { RUNNING_KSH=true; export RUNNING_KSH; exec /bin/ksh $0 ${1+"$@"}; }
unset RUNNING_KSH

# No failure shall remain unpunished.
set -e

# This string is expanded automatically when this file is checked out.
37
rcs_revision='$Revision: 1.173 $'
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
rcs_version=`set - $rcs_revision; echo $2`
program=`echo $0 | sed -e 's!.*/!!'`

build_mode=${TEXI2DVI_BUILD_MODE:-local}
build_dir=${TEXI2DVI_BUILD_DIRECTORY:-.}

# Initialize variables for option overriding and otherwise.
# Don't use `unset' since old bourne shells don't have this command.
# Instead, assign them an empty value.
action=compile
batch=false     # interact normally
catcode_special=maybe
debug=false
escape="\\"
expand=false    # true for expansion via makeinfo
includes=
line_error=true # pass --file-line-error to TeX
max_iters=-1    # keep going forever
oname=          # --output
out_lang=dvi
quiet=false     # let the tools' message be displayed
recode=false
set_language=
src_specials=
62
shell_escape=
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
latex2html=hevea  # or set to tex4ht
textra=         # Extra TeX commands to insert in the input file.
txiprereq=19990129 # minimum texinfo.tex version with macro expansion
verb=false      # true for verbose mode
translate_file= # name of charset translation file
recode_from=    # if not empty, recode from this encoding to @documentencoding

orig_pwd=`pwd`

# We have to initialize IFS to space tab newline since we save and
# restore IFS and apparently POSIX allows stupid/broken behavior with
# empty-but-set IFS.
# http://lists.gnu.org/archive/html/automake-patches/2006-05/msg00008.html
# We need space, tab and new line, in precisely that order.  And don't leave
# trailing blanks.
space=' '
tab='	'
newline='
'
IFS="$space$tab$newline"

# In case someone pedantic insists on using grep -E.
: ${EGREP=egrep}

# Systems which define $COMSPEC or $ComSpec use semicolons to separate
# directories in TEXINPUTS -- except for Cygwin et al., where COMSPEC
# might be inherited, but : is used.
if test -n "$COMSPEC$ComSpec" \
   && uname | $EGREP -iv 'cygwin|mingw|djgpp' >/dev/null; then
  path_sep=";"
else
  path_sep=":"
fi

# Pacify verbose cds.
CDPATH=${ZSH_VERSION+.}$path_sep

# If $TEX is set to a directory, don't use it.
test -n "$TEX" && test -d "$TEX" && unset TEX

# 
## --------------------- ##
## Auxiliary functions.  ##
## --------------------- ##

# In case `local' is not supported by the shell, provide a function
# that simulates it by simply performing the assignments.  This means
# that we must not expect `local' to work, i.e., we must not (i) rely
# on it during recursion, and (ii) have two local declarations of the
# same variable.  (ii) is easy to check statically, and our test suite
# does make sure there is never twice a static local declaration of a
# variable.  (i) cannot be checked easily, so just be careful.
#
# Note that since we might use a function simulating `local', we can
# no longer rely on the fact that no IFS-splitting is performed.  So,
# while
#
# foo=$bar
#
# is fine (no IFS-splitting), never write
#
# local foo=$bar
#
# but rather
#
# local foo="$bar"
(
  foo=bar
  test_local () {
    local foo=foo
  }
134
  test_local >/dev/null 2>&1
135
  test $foo = bar
136
137
) || eval '
local () {
138
139
140
141
  case $1 in
    *=*) eval "$1";;
  esac
}
142
'
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192


# cd_orig
# -------
# Return to the original directory.
cd_orig ()
{
  # In case $orig_pwd is on a different drive (for DOS).
  cd /

  # Return to the original directory so that
  # - the next file is processed in correct conditions
  # - the temporary file can be removed
  cd "$orig_pwd" || exit 1
}

# func_dirname FILE
# -----------------
# Return the directory part of FILE.
func_dirname ()
{
  dirname "$1" 2>/dev/null \
  || { echo "$1" | sed 's!/[^/]*$!!;s!^$!.!'; }
}


# noexit FILE
# -----------
# Return FILE with one extension remove.  foo.bar.baz -> foo.bar.
noext ()
{
  echo "$1" | sed -e 's/\.[^/.][^/.]*$//'
}


# absolute NAME -> ABS-NAME
# -------------------------
# Return an absolute path to NAME.
absolute ()
{
  case $1 in
   [\\/]* | ?:[\\/]*)
      # Absolute paths don't need to be expanded.
      echo "$1"
      ;;
   *) local slashes
      slashes=`echo "$1" | sed -n 's,.*[^/]\(/*\)$,\1,p'`
      local rel
      rel=$orig_pwd/`func_dirname "$1"`
      if test -d "$rel"; then
193
194
        (cd "$rel" 2>/dev/null \
         && local n
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
         n=`pwd`/`basename "$1"`"$slashes"
         echo "$n")
      else
        error 1 "not a directory: $rel"
      fi
      ;;
  esac
}


# ensure_dir DIR1 DIR2...
# -----------------------
# Make sure the directories exist.
ensure_dir ()
{
  for dir
  do
    # Beware that in parallel builds we may have several concurrent
    # attempts to create the directory.  So fail only if "mkdir"
    # failed *and* the directory still does not exist.
    test -d "$dir" \
      || mkdir "$dir" \
      || test -d "$dir" \
      || error 1 "cannot create directory: $dir"
  done
}


# error EXIT_STATUS LINE1 LINE2...
# --------------------------------
225
# Report an error and exit with failure if EXIT_STATUS is non-null.
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
error ()
{
  local s="$1"
  shift
  report "$@"
  if test "$s" != 0; then
    exit $s
  fi
}


# findprog PROG
# -------------
# Return true if PROG is somewhere in PATH, else false.
findprog ()
{
  local saveIFS="$IFS"
  IFS=$path_sep  # break path components at the path separator
  for dir in $PATH; do
    IFS=$saveIFS
    # The basic test for an executable is `test -f $f && test -x $f'.
    # (`test -x' is not enough, because it can also be true for directories.)
    # We have to try this both for $1 and $1.exe.
    #
    # Note: On Cygwin and DJGPP, `test -x' also looks for .exe.  On Cygwin,
    # also `test -f' has this enhancement, but not on DJGPP.  (Both are
    # design decisions, so there is little chance to make them consistent.)
    # Thusly, it seems to be difficult to make use of these enhancements.
    #
255
256
    if   { test -f "$dir/$1"     && test -x "$dir/$1"; } \
      || { test -f "$dir/$1.exe" && test -x "$dir/$1.exe"; }; then
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
      return 0
    fi
  done
  return 1
}

# report LINE1 LINE2...
# ---------------------
# Report some information on stderr.
report ()
{
  for i in "$@"
  do
    echo >&2 "$0: $i"
  done
}


# run COMMAND-LINE
# ----------------
# Run the COMMAND-LINE verbosely, and catching errors as failures.
run ()
{
  verbose "Running $@"
281
282
  "$@" 2>&5 1>&2 \
  || error 1 "$1 failed"
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
}


# usage
# -----
# Display usage and exit successfully.
usage ()
{
  # We used to simply have `echo "$usage"', but coping with the
  # changing behavior of `echo' is much harder than simply using a
  # here-doc.
  #
  #             echo '\noto'   echo '\\noto'   echo -e '\\noto'
  # bash 3.1      \noto           \\noto          \noto
  # bash 3.2       %oto           \noto           -e \noto
  #
  # where % denotes the eol character.
  cat <<EOF
Usage: $program [OPTION]... FILE...
302
303
  or:  texi2pdf [OPTION]... FILE...
  or:  pdftexi2dvi [OPTION]... FILE...
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322

Run each Texinfo or (La)TeX FILE through TeX in turn until all
cross-references are resolved, building all indices.  The directory
containing each FILE is searched for included files.  The suffix of FILE
is used to determine its language ((La)TeX or Texinfo).  To process
(e)plain TeX files, set the environment variable LATEX=tex.

In order to make texi2dvi a drop-in replacement of TeX/LaTeX in AUC-TeX,
the FILE may also be composed of the following simple TeX commands.
  \`\\input{FILE}'     the actual file to compile
  \`\\nonstopmode'     same as --batch

When invoked as \`texi2pdf' or \`pdftexi2dvi', or given the option --pdf
or --dvipdf, generate PDF output.  Otherwise, generate DVI.

General options:
  -b, --batch         no interaction
  -D, --debug         turn on shell debugging (set -x)
  -h, --help          display this help and exit successfully
323
  -o, --output=OFILE  leave output in OFILE; only one input FILE is allowed
324
325
326
327
328
  -q, --quiet         no output unless errors (implies --batch)
  -s, --silent        same as --quiet
  -v, --version       display version information and exit successfully
  -V, --verbose       report on what is done

329
330
331
332
333
334
335
336
337
Output format:
      --dvi     output a DVI file [default]
      --dvipdf  output a PDF file via DVI (using a dvi-to-pdf program)
      --html    output an HTML file from LaTeX, using HeVeA
      --info    output an Info file from LaTeX, using HeVeA
  -p, --pdf     use pdftex or pdflatex for processing
      --ps      output a PostScript file via DVI (using dvips)
      --text    output a plain text file from LaTeX, using HeVeA

338
339
340
341
342
343
344
345
TeX tuning:
  -@                         use @input instead of \input for preloaded Texinfo
  -e, -E, --expand           force macro expansion using makeinfo
  -I DIR                     search DIR for Texinfo files
  -l, --language=LANG        specify LANG for FILE, either latex or texinfo
      --no-line-error        do not pass --file-line-error to TeX
  -r, --recode               call recode before TeX to translate input
      --recode-from=ENC      recode from ENC to the @documentencoding
346
      --shell-escape         pass --shell-escape to TeX
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
      --src-specials         pass --src-specials to TeX
  -t, --command=CMD          insert CMD in copy of input file
   or --texinfo=CMD          multiple values accumulate
      --translate-file=FILE  use given charset translation file for TeX

Build modes:
  --build=MODE         specify the treatment of auxiliary files [$build_mode]
      --tidy           same as --build=tidy
  -c, --clean          same as --build=clean
      --build-dir=DIR  specify where the tidy compilation is performed;
                         implies --tidy;
                         defaults to TEXI2DVI_BUILD_DIRECTORY [$build_dir]
  --mostly-clean       remove the auxiliary files and directories
                         but not the output
  --max-iterations=N   don't process files more than N times

The MODE specifies where the TeX compilation takes place, and, as a
consequence, how auxiliary files are treated.  The build mode
can also be set using the environment variable TEXI2DVI_BUILD_MODE.

Valid MODEs are:
  \`local'      compile in the current directory, leaving all the auxiliary
               files around.  This is the traditional TeX use.
  \`tidy'       compile in a local *.t2d directory, where the auxiliary files
               are left.  Output files are copied back to the original file.
  \`clean'      same as \`tidy', but remove the auxiliary directory afterwards.
               Every compilation therefore requires the full cycle.

Using the \`tidy' mode brings several advantages:
  - the current directory is not cluttered with plethora of temporary files.
  - clutter can be even further reduced using --build-dir=dir: all the *.t2d
    directories are stored there.
  - clutter can be reduced to zero using, e.g., --build-dir=/tmp/\$USER.t2d
    or --build-dir=\$HOME/.t2d.
381
  - the output file is updated after every successful TeX run, for
382
383
384
385
386
387
388
389
390
    sake of concurrent visualization of the output.  In a \`local' build
    the viewer stops during the whole TeX run.
  - if the compilation fails, the previous state of the output file
    is preserved.
  - PDF and DVI compilation are kept in separate subdirectories
    preventing any possibility of auxiliary file incompatibility.

On the other hand, because \`tidy' compilation takes place in another
directory, occasionally TeX won't be able to find some files (e.g., when
391
using \\graphicspath): in that case, use -I to specify the additional
392
393
directories to consider.

394
395
396
397
398
399
400
401
402
403
The values of the BIBTEX, DVIPDF, DVIPS, HEVEA, LATEX, MAKEINDEX,
MAKEINFO, PDFLATEX, PDFTEX, T4HT, TEX, TEX4HT, TEXINDEX, and THUMBPDF
environment variables are used to run those commands, if they are set.

Regarding --dvipdf, if DVIPDF is not set in the environment, the
following programs are looked for (in this order): dvipdfmx dvipdfm
dvipdf dvi2pdf dvitopdf.

Any CMD strings are added after @setfilename for Texinfo input, or in
the first line for LaTeX input.
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426

Report bugs to bug-texinfo@gnu.org,
general questions and discussion to help-texinfo@gnu.org.
GNU Texinfo home page: <http://www.gnu.org/software/texinfo/>
General help using GNU software: <http://www.gnu.org/gethelp/>
EOF
  exit 0
}


# verbose WORD1 WORD2
# -------------------
# Report some verbose information.
verbose ()
{
  if $verb; then
    echo >&2 "$0: $@"
  fi
}


# version
# -------
427
# Display version info and exit successfully.
428
429
430
version ()
{
  cat <<EOF
431
texi2dvi (GNU Texinfo 4.13+dev) $rcs_version
432

433
Copyright (C) 2012 Free Software Foundation, Inc.
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
EOF
  exit 0
}


## ---------------- ##
## Handling lists.  ##
## ---------------- ##


# list_append LIST-NAME ELEM
# --------------------------
# Set LIST-NAME to its former contents, with ELEM appended.
list_append ()
{
  local la_l="$1"
  shift
  eval set X \$$la_l "$@"
  shift
  eval $la_l=\""$@"\"
}


# list_concat_dirs LIST-NAME DIR-LIST
# -----------------------------------
# Append to LIST-NAME all the components (included empty) from
# the $path_sep separated list DIR-LIST.  Make the paths absolute.
list_concat_dirs ()
{
  local lcd_list="$1"
  # Empty path components are meaningful to tex.  We rewrite them as
  # `EMPTY' so they don't get lost when we split on $path_sep.
  # Hopefully no one will have an actual directory named EMPTY.
  local replace_EMPTY="-e 's/^$path_sep/EMPTY$path_sep/g' \
                       -e 's/$path_sep\$/${path_sep}EMPTY/g' \
                       -e 's/$path_sep$path_sep/${path_sep}EMPTY:/g'"
  save_IFS=$IFS
  IFS=$path_sep
  set x `echo "$2" | eval sed $replace_EMPTY`; shift
  IFS=$save_IFS
  local dir
  for dir
  do
    case $dir in
      EMPTY)
       list_append $lcd_list ""
       ;;
      *)
       if test -d $dir; then
          dir=`absolute "$dir"`
         list_append $lcd_list "$dir"
       fi
       ;;
    esac
  done
}


# list_prefix LIST-NAME SEP -> STRING
# -----------------------------------
# Return a string that is composed of the LIST-NAME with each item
# preceded by SEP.
list_prefix ()
{
  local lp_p="$2"
  eval set X \$$1
  shift
  local lp_res
  for i
  do
    lp_res="$lp_res \"$lp_p\" \"$i\""
  done
  echo "$lp_res"
}

# list_infix LIST-NAME SEP -> STRING
# ----------------------------------
# Same as list_prefix, but a separator.
list_infix ()
{
  eval set X \$$1
  shift
  local la_IFS="$IFS"
  IFS=$path_sep
  echo "$*"
  IFS=$la_IFS
}

# list_dir_to_abs LIST-NAME
# -------------------------
# Convert the list to using only absolute dir names.
# Currently unused, but should replace absolute_filenames some day.
list_dir_to_abs ()
{
  local ld_l="$1"
  eval set X \$$ld_l
  shift
  local ld_res
  for dir
  do
    dir=`absolute "$dir"`
    test -d "$dir" || continue
    ld_res="$ld_res \"$dir\""
  done
  set X $ld_res; shift
  eval $ld_l=\"$@\"
}


## ------------------------------ ##
## Language auxiliary functions.  ##
## ------------------------------ ##


# out_lang_set LANG
# -----------------
out_lang_set ()
{
  case $1 in
    dvi|dvipdf|html|info|pdf|ps|text) out_lang=$1;;
    *) error 1 "invalid output format: $1";;
  esac
}


# out_lang_tex
# ------------
# Return the tex output language (DVI or PDF) for $OUT_LANG.
out_lang_tex ()
{
  case $out_lang in
    dvi | ps | dvipdf ) echo dvi;;
    pdf ) echo $out_lang;;
    html | info | text ) echo $out_lang;;
    *)    error 1 "invalid out_lang: $1";;
  esac
}


# out_lang_ext
# ------------
# Return the extension for $OUT_LANG.
out_lang_ext ()
{
  case $out_lang in
    dvipdf ) echo pdf;;
    dvi | html | info | pdf | ps | text ) echo $out_lang;;
    *)    error 1 "invalid out_lang: $1";;
  esac
}


## ------------------------- ##
## TeX auxiliary functions.  ##
## ------------------------- ##

# Save TEXINPUTS so we can construct a new TEXINPUTS path for each file.
# Likewise for bibtex and makeindex.
tex_envvars="BIBINPUTS BSTINPUTS DVIPSHEADERS INDEXSTYLE MFINPUTS MPINPUTS \
TEXINPUTS TFMFONTS"
for var in $tex_envvars; do
  eval ${var}_orig=\$$var
  export $var
done


# absolute_filenames TEX-PATH -> TEX-PATH
# ---------------------------------------
# Convert relative paths to absolute paths, so we can run in another
# directory (e.g., in tidy build mode, or during the macro-support
# detection).  Prepend ".".
absolute_filenames ()
{
  # Empty path components are meaningful to tex.  We rewrite them as
  # `EMPTY' so they don't get lost when we split on $path_sep.
  # Hopefully no one will have an actual directory named EMPTY.
  local replace_empty="-e 's/^$path_sep/EMPTY$path_sep/g' \
                       -e 's/$path_sep\$/${path_sep}EMPTY/g' \
                       -e 's/$path_sep$path_sep/${path_sep}EMPTY:/g'"
  local res
  res=`echo "$1" | eval sed $replace_empty`
  save_IFS=$IFS
  IFS=$path_sep
  set x $res; shift
  res=.
  for dir
  do
    case $dir in
      EMPTY)
        res=$res$path_sep
        ;;
      *)
        if test -d "$dir"; then
          res=$res$path_sep`absolute "$dir"`
        else
          # Even if $dir is not a directory, preserve it in the path.
          # It might contain metacharacters that TeX will expand in
          # turn, e.g., /some/path/{a,b,c}.  This will not get the
          # implicit absolutification of the path, but we can't help that.
          res=$res$path_sep$dir
        fi
        ;;
    esac
  done
  echo "$res"
}


# output_base_name FILE
# ---------------------
# The name of FILE, possibly renamed to satisfy --output.
# FILE is local, there is no directory part.
output_base_name ()
{
  case $oname in
    '') echo "$1";;
     *) local out_noext
        out_noext=`noext "$oname"`
        local file_ext
        file_ext=`echo "$1" | sed 's/^.*\.//'`
        echo "$out_noext.$file_ext"
      ;;
  esac
}


# destdir
# -------
# Return the name of the directory where the output is expected.
destdir ()
{
  case $oname in
    '')  echo "$orig_pwd";;
    *)   dirname "$oname";;
  esac
}


# move_to_dest FILE...
# --------------------
# Move FILE to the place where the user expects it.  Truly move it, that
# is, it must not remain in its build location unless that is also the
# output location.  (Otherwise it might appear as an extra file in make
# distcheck.)
#
# FILE can be the principal output (in which case -o directly applies), or
# an auxiliary file with the same base name.
move_to_dest ()
{
686
687
688
689
#  echo "move_to_dest $*, tidy=$tidy, oname=$oname"

  # If we built in place and have no output name, there is nothing to
  # do, so just return.
690
691
692
693
694
695
696
697
698
699
700
701
  case $tidy:$oname in
    false:) return;;
  esac

  local destfile
  local destdir
  local destbase
  local sourcedir
  local sourcebase

  for file
  do
702
703
    test -f "$file" \
    || error 1 "no such file or directory: $file"
704
705
706
    case $tidy:$oname in
      true:)  destdir=$orig_pwd
              destfile=$destdir/$file;;
707
      true:*) destfile=`output_base_name "$file"`
708
              destdir=`dirname "$destfile"`;;
709
710
      false:*) destfile=$oname
               destdir=`dirname "$destfile"`;;
711
    esac
712
 
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    # We want to compare the source location and the output location,
    # and if they are different, do the move.  But if they are the
    # same, we must preserve the source.  Since we can't assume
    # stat(1) or test -ef is available, resort to comparing the
    # directory names, canonicalized with pwd.  We can't use cmp -s
    # since the output file might not actually change from run to run;
    # e.g., TeX DVI output is timestamped to only the nearest minute.
    destdir=`cd "$destdir" && pwd`
    destbase=`basename "$destfile"`

    sourcedir=`dirname "$file"`
    sourcedir=`cd "$sourcedir" && pwd`
    sourcebase=`basename "$file"`

    if test "$sourcedir/$sourcebase" != "$destdir/$destbase"; then
      verbose "Moving $file to $destfile"
      rm -f "$destfile"
      mv "$file" "$destfile"
    fi
  done
}


## --------------------- ##
## Managing xref files.  ##
## --------------------- ##

# aux_file_p FILE
# ---------------
# Return with success if FILE is an aux file.
aux_file_p ()
{
  test -f "$1" || return 1
  case $1 in
    *.aux) return 0;;
    *)     return 1;;
  esac
}

# bibaux_file_p FILE
# ------------------
# Return with success if FILE is an aux file containing citation
# requests.
bibaux_file_p ()
{
  test -s "$1" || return 1
  if (grep '^\\bibstyle[{]' "$1"   \
      && grep '^\\bibdata[{]' "$1" \
      ## The following line is suspicious: fails when there
      ## are citations in sub aux files.  We need to be
      ## smarter in this case.
      ## && grep '^\\citation[{]' "$f"
      ) >&6 2>&1;
  then
    return 0
  fi
  return 1
}

# index_file_p FILE
# -----------------
# Return with success if FILE is an index file.
index_file_p ()
{
  test -f "$1" || return 1
  case $in_lang:$latex2html:`out_lang_tex`:`sed '1q' "$1"` in
    # When working with TeX4HT, *.idx are created by LaTeX.  They must
    # be processed to produce *.4ix, *.4dx files.  The *.4dx file is
    # passed to makeindex to produce the *.ind file.  This sequence is
    # handled by run_index, so we are only interested in the *.idx
    # files, which have each "\indexentry" preceded by a
    # "\beforeentry".
    latex:tex4ht:html:"\\beforeentry {"*) return 0;;

    # When index.sty is used, there is a space before the brace.
    latex:*:*:"\\indexentry{"*|latex:*:*:"\\indexentry {"*) return 0;;

    texinfo:*:*:"\\entry{"*) return 0;;

    *) return 1;;
  esac
}

# xref_file_p FILE
# ----------------
# Return with success if FILE is an xref file (indexes, tables and lists).
xref_file_p ()
{
  test -f "$1" || return 1
  # If the file is not suitable to be an index or xref file, don't
  # process it.  It's suitable if the first character is a
  # backslash or right quote or at, as long as the first line isn't
  # \input texinfo.
  case `sed '1q' "$1"` in
    "\\input texinfo"*) return 1;;
    [\\''@]*)           return 0;;
           *)           return 1;;
  esac
}


# generated_files_get FILENAME-NOEXT [PREDICATE-FILTER]
# -----------------------------------------------------
# Return the list of files generated by the TeX compilation of FILENAME-NOEXT.
generated_files_get ()
{
  local filter=true
  if test -n "$2"; then
    filter=$2
  fi

  # Gather the files created by TeX.
  (
    if test -f "$1.log"; then
      sed -n -e "s,^\\\\openout.* = \`\\(.*\\)'\\.,\\1,p" "$1.log"
    fi
    echo "$1.log"
  ) |
  # Depending on these files, infer outputs from other tools.
  while read file; do
    echo $file
    case $in_lang in
      texinfo)
        # texindex: texinfo.cp -> texinfo.cps
       if index_file_p $file; then
         echo ${file}s
       fi
       ;;
      latex)
        if aux_file_p $file; then
          # bibtex: *.aux -> *.bbl and *.blg.
          echo $file | sed 's/^\(.*\)\.aux$/\1.bbl/'
          echo $file | sed 's/^\(.*\)\.aux$/\1.blg/'
          # -recorder: .fls
          echo $file | sed 's/^\(.*\)\.aux$/\1.fls/'
       fi
       ;;
    esac
  done |
  # Filter existing files matching the criterion.
  #
  # With an input file name containing a space, this produces a
  # "command not found" message (and filtering is ineffective).
  # The situation with a newline is presumably even worse.
  while read file; do
    if $filter "$file"; then
      echo $file
    fi
  done |
  sort |
  # Some files are opened several times, e.g., listings.sty's *.vrb.
  uniq
}


# xref_files_save
# ---------------
# Save the xref files.
xref_files_save ()
{
  # Save copies of auxiliary files for later comparison.
  xref_files_orig=`generated_files_get "$in_noext" xref_file_p`
  if test -n "$xref_files_orig"; then
    verbose "Backing up xref files: $xref_files_orig"
    # The following line improves `cp $xref_files_orig "$work_bak"'
    # by preserving the directory parts.  Think of
    # cp chap1/main.aux chap2/main.aux $work_bak.
    #
    # Users may have, e.g., --keep-old-files.  Don't let this interfere.
    # (Don't use unset for the sake of ancient shells.)
    TAR_OPTIONS=; export TAR_OPTIONS
    tar cf - $xref_files_orig | (cd "$work_bak" && tar xf -)
  fi
}


# xref_files_changed
# ------------------
# Whether the xref files were changed since the previous run.
xref_files_changed ()
{
  # LaTeX (and the package changebar) report in the LOG file if it
  # should be rerun.  This is needed for files included from
  # subdirs, since texi2dvi does not try to compare xref files in
  # subdirs.  Performing xref files test is still good since LaTeX
  # does not report changes in xref files.
  if grep "Rerun to get" "$in_noext.log" >&6 2>&1; then
    return 0
  fi

  # If old and new lists don't at least have the same file list,
  # then one file or another has definitely changed.
  xref_files_new=`generated_files_get "$in_noext" xref_file_p`
  verbose "Original xref files = $xref_files_orig"
  verbose "New xref files      = $xref_files_new"
  if test "x$xref_files_orig" != "x$xref_files_new"; then
    return 0
  fi

  # Compare each file until we find a difference.
  for this_file in $xref_files_new; do
    verbose "Comparing xref file `echo $this_file | sed 's|\./||g'` ..."
    # cmp -s returns nonzero exit status if files differ.
    if cmp -s "$this_file" "$work_bak/$this_file"; then :; else
      verbose "xref file `echo $this_file | sed 's|\./||g'` differed ..."
      if $debug; then
        diff -u "$work_bak/$this_file" "$this_file"
      fi
      return 0
    fi
  done

  # No change.
  return 1
}



## ----------------------- ##
## Running the TeX suite.  ##
## ----------------------- ##



# run_tex ()
# ----------
# Run TeX as "$tex $in_input", taking care of errors and logs.
run_tex ()
{
  case $in_lang:$latex2html:`out_lang_tex` in
    latex:*:dvi|latex:tex4ht:html)
        tex=${LATEX:-latex};;
    latex:*:pdf)
        tex=${PDFLATEX:-pdflatex};;
    texinfo:*:dvi)
        # MetaPost also uses the TEX environment variable.  If the user
        # has set TEX=latex for that reason, don't bomb out.
        case $TEX in
          *latex) tex=tex;; # don't bother trying to find etex
               *) tex=$TEX
        esac;;
    texinfo:*:pdf) tex=$PDFTEX;;

    *) error 1 "$out_lang not supported for $in_lang";;
  esac

  # do the special catcode trick for ~ in filenames only for Texinfo,
  # not LaTeX.
  if test x"$in_lang" = xtexinfo && test $catcode_special = maybe; then
    catcode_special=true
  else
    catcode_special=false
  fi

  # Beware of aux files in subdirectories that require the
  # subdirectory to exist.
  case $in_lang:$tidy in
    latex:true)
       sed -n 's|^[ ]*\\include{\(.*\)/.*}.*|\1|p' "$in_input" |
       sort -u |
       while read d
       do
         ensure_dir "$work_build/$d"
       done
       ;;
  esac

  # Note that this will be used via an eval: quote properly.
  local cmd="$tex"

  # If possible, make TeX report error locations in GNU format.
  if $line_error; then
    if test "${tex_help:+set}" != set; then
      # Go to a temporary directory to try --help, since old versions that
      # don't accept --help will generate a texput.log.
      tex_help_dir=$t2ddir/tex_help
      ensure_dir "$tex_help_dir"
      tex_help=`cd "$tex_help_dir" >&6 && $tex --help </dev/null 2>&1 || true`
    fi
    # The mk program and perhaps others want to parse TeX's
    # original error messages.
    case $tex_help in
      *file-line-error*) cmd="$cmd --file-line-error";;
    esac
  fi

  # Tell TeX about TCX file, if specified.
  test -n "$translate_file" && cmd="$cmd --translate-file=$translate_file"