~ubuntu-branches/ubuntu/raring/latexmk/raring-proposed

« back to all changes in this revision

Viewing changes to latexmk.pl

  • Committer: Bazaar Package Importer
  • Author(s): OHURA Makoto
  • Date: 2010-03-14 17:10:22 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20100314171022-2j26yatde1fdq8ac
Tags: 1:4.13a-1
* New upstream release
* New maintainer. (Closes: #523193)
* debian/control:
  - Update Standards-Version.
  - Drop dependency on an obsolete package: tetex-bin.
  - Add dependency on ${misc:Depends} for debhelper.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
eval '(exit $?0)' && eval 'exec perl -x -S $0 ${1+"$@"}' && 
2
 
eval 'exec perl -x -S  $0 $argv:q'
3
 
if 0;
 
1
#!/usr/bin/env perl
 
2
# On a UNIX-like system, the above enables latexmk to run independently
 
3
#   of the location of the perl executable.  This line relies on the 
 
4
#   existence of the program /usr/bin/env
 
5
# If there is a problem for any reason, you can replace the first line of 
 
6
#   this file by:
 
7
 
4
8
#!/usr/bin/perl -w
5
 
#!/opt/local/bin/perl -w
6
 
#!/usr/local/bin/perl -w
 
9
 
 
10
# with the path of the perl executable adjusted for your system. 
 
11
 
 
12
 
 
13
use warnings;
 
14
 
 
15
# Delete #??!! when working
 
16
 
 
17
# See ?? <===============================
 
18
 
 
19
## ?? Issues with clean-up
 
20
## List of aux files deleted is those read, not those generated.
 
21
## Other files are generated by (pdf)latex; should they be deleted?
 
22
## (I have hooks for this).
 
23
 
 
24
 
 
25
#=======================================
 
26
 
 
27
 
 
28
#??  Force mode doesn't appear to do force (if error in latex file)
 
29
#??? Get banner back in.
 
30
#??  CORRECT DIAGNOSTICS ON CHANGED FILES IF THEY DIDN'T EXIST BEFORE
 
31
#??  Further corrections to deal with disappeared source files for custom dependencies.
 
32
#       Message repeatedly appears about remake when source file of cusdep doesn't exist.
 
33
#??  logfile w/o fdb file: don't set changed file, perhaps for generated exts.
 
34
#    Reconsider
 
35
#??  Do proper run-stuff for bibtex, makeindex, cus-deps.  OK I think
 
36
#    Parse and correctly find bst and ist files
 
37
 
 
38
 
 
39
# ATTEMPT TO ALLOW FILENAMES WITH SPACES:
 
40
#    (as of 1 Apr 2006, and then 14 Sep. 2007)
 
41
 
 
42
# Problems:
 
43
# A.  Quoting filenames will not always work.  
 
44
#        a.  Under UNIX, quotes are legal in filenames, so when PERL
 
45
#            directly runs a binary, a quoted filename will be treated as
 
46
#            as a filename containing a quote character.  But when it calls
 
47
#            a shell, the quotes are handled by the shell as quotes.
 
48
#        b.  Under MSWin32, quotes are illegal filename characters, and tend
 
49
#            to be handled correctly.
 
50
#        c.  But under cygwin, results are not so clear (there are many 
 
51
#            combinations: native v. cygwin perl, native v cygwin programs
 
52
#            NT v. unix scripts, which shell is called.
 
53
# B.  TeX doesn't always handle filenames with spaces gracefully.
 
54
#        a.  UNIX/LINUX: The version on gluon2 Mar 31, 2006 to Sep. 2007) 
 
55
#            doesn't handle them at all.  (TeX treats space as separator.)
 
56
#        b.  At least some later versions actually do (Brad Miller e-mail, 
 
57
#            Sep. 2007).
 
58
#        c.  fptex [[e-TeXk, Version 3.141592-2.1 (Web2c 7.5.2)] does, on 
 
59
#            my MSWin at home.  In \input the filename must be in quotes.
 
60
#        d.  Bibtex [BibTeX (Web2c 7.5.2) 0.99c on my MSWin system at home,
 
61
#            Sep. 2007] does not allow names of bibfiles to have spaces.
 
62
# C.  =====> Using the shell for command lines is not safe, since special 
 
63
#     characters can cause lots of mayhem.
 
64
#     It will therefore be a good idea to sanitize filenames. 
 
65
#
 
66
# I've sanitized all calls out:
 
67
#     a. system and exec use a single argument, which forces
 
68
#        use of shell, under all circumstances
 
69
#        Thus I can safely use quotes on filenames:  They will be handled by 
 
70
#        the shell under UNIX, and simply passed on to the program under MSWin32.
 
71
#     b. I reorganized Run, Run_Detached to use single command line
 
72
#     c. All calls to Run and Run_Detached have quoted filenames.
 
73
#     d. So if a space-free filename with wildcards is given on latexmk's
 
74
#        command line, and it globs to space-containing filename(s), that
 
75
#        works (fptex on home computer, native NT tex)
 
76
#     e. ====> But globbing fails: the glob function takes space as filename 
 
77
#        separator.   ====================
7
78
 
8
79
#================= TO DO ================
9
80
#
10
 
# 1.  Check file of bug reports and requests
11
 
 
12
 
 
13
 
# The above code allows this script to be run under UNIX/LINUX without
14
 
# the need to adjust the path to the perl program in a "shebang" line.
15
 
# (The location of perl changes between different installations, and
16
 
# may even be different when several computers running different
17
 
# flavors of UNIX/LINUX share a copy of latex or other scripts.)  The
18
 
# script is started under the default command interpreter sh, and the
19
 
# evals in the first two lines restart the script under perl, and work
20
 
# under various flavors of sh.  The -x switch tells perl to start the
21
 
# script at the first #! line containing "perl".  The "if 0;" on the
22
 
# 3rd line converts the first two lines into a valid perl statement
23
 
# that does nothing.
 
81
# 1.  See ??  ESPECIALLY $MSWin_fudge_break
 
82
# 2.  Check fudged conditions in looping and make_files 
 
83
# 3.  Should not completely abort after a run that ends in failure from latex
 
84
#     Missing input files (including via custom dependency) should be checked for
 
85
#     a change in status
 
86
#         If sources for missing files from custom dependency 
 
87
#             are available, then do a rerun
 
88
#         If sources of any kind become available rerun (esp. for pvc)
 
89
#             rerun
 
90
#         Must parse log_file after unsuccessful run of latex: it may give
 
91
#             information about missing files. 
 
92
# 4.  Check file of bug reports and requests
 
93
# 5.  Rationalize bibtex warnings and errors.  Two almost identical routines.
 
94
#         Should 1. Use single routine
 
95
#                2. Convert errors to failure only in calling routine
 
96
#                3. Save first warning/error.
 
97
 
 
98
# ?? Use of generated_exts arrays and hashes needs rationalization
24
99
 
25
100
# To do: 
26
101
#   Rationalize again handling of include files.
27
 
#     Perhaps use kpsewhich to do searches.
 
102
#     Now I use kpsewhich to do searches, if file not found
28
103
#        (How do I avoid getting slowed down too much?)
29
 
#     Better parsing of log file for includes.
30
 
#   Do I handle the recursive dependence of bbl and aux files sensibly.
31
 
#     Perhaps some appropriate touching of the .aux and .bbl files would help?
32
104
#   Document the assumptions at each stage of processing algorithm.
33
105
#   Option to restart previewer automatically, if it dies under -pvc
34
106
#   Test for already running previewer gets wrong answer if another
35
107
#     process has the viewed file in its command line
36
108
 
37
 
$version_num = '3.07a';
38
 
$version_details = 'latexmk, John Collins, 2 June 2004';
39
 
 
 
109
$my_name = 'latexmk';
 
110
$My_name = 'Latexmk';
 
111
$version_num = '4.13a';
 
112
$version_details = "$My_name, John Collins, 16 January 2010";
 
113
 
 
114
 
 
115
use Config;
40
116
use File::Copy;
41
117
use File::Basename;
42
118
use FileHandle;
43
119
use File::Find;
44
 
 
45
 
## Copyright John Collins 1998-2004
 
120
use Cwd;            # To be able to change cwd
 
121
use Cwd "chdir";    # Ensure $ENV{PWD}  tracks cwd
 
122
use Digest;
 
123
 
 
124
#use strict;
 
125
 
 
126
# The following variables are assigned once and then used in symbolic 
 
127
#     references, so we need to avoid warnings 'name used only once':
 
128
use vars qw( $dvi_update_command $ps_update_command $pdf_update_command );
 
129
 
 
130
# Translation of signal names to numbers and vv:
 
131
%signo = ();
 
132
@signame = ();
 
133
if ( defined $Config{sig_name} ) {
 
134
   $i = 0;
 
135
   foreach $name (split(' ', $Config{sig_name})) {
 
136
      $signo{$name} = $i;
 
137
      $signame[$i] = $name;
 
138
      $i++;
 
139
   }
 
140
}
 
141
else {
 
142
   warn "Something wrong with the perl configuration: No signals?\n";
 
143
}
 
144
 
 
145
## Copyright John Collins 1998-2010
46
146
##           (username collins at node phys.psu.edu)
47
147
##      (and thanks to David Coppit (username david at node coppit.org) 
48
148
##           for suggestions) 
64
164
##    You should have received a copy of the GNU General Public License
65
165
##    along with this program; if not, write to the Free Software
66
166
##    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
67
 
 
68
 
 
69
 
##
70
 
##
71
 
##   For Win95 et al.:  Remaining items on list.
72
 
##     1.  See specific flags
73
 
##     6.  Need to check out all calls to system
74
 
##     8.  Now check that I do the bibtex and index stuff correctly.
75
 
##     9.  Convert routines to have arguments.
76
 
##    12.  Need to have default filetypes for graphics includes.
77
 
##         To make that rational, the find_file routine, etc must be modified,
78
 
##         otherwise there will be much duplication of code.
 
167
##
79
168
##
80
169
##
81
170
##   NEW FEATURES, since v. 2.0:
82
171
##     1.  Correct algorithm for deciding how many times to run latex:
83
 
##         based on whether the aux file changes between runs
 
172
##         based on whether source file(s) change between runs
84
173
##     2.  Continuous preview works, and can be of ps file or dvi file
85
174
##     3.  pdf creation by pdflatex possible
86
175
##     4.  Defaults for commands are OS dependent.
87
176
##     5.  Parsing of log file instead of source file is used to
88
177
##         obtain dependencies, by default.
89
 
##     6.  Meta-commands in source file
90
 
##
91
 
##           %#{}raw
92
 
##           %#{}begin.raw
93
 
##              Start section of raw LaTeX: treat as %#{latex}begin.ignore.
94
 
##
95
 
##           %#{}end.raw     
96
 
##              End section of raw LaTeX: treat as %#{latex}end.ignore.
97
 
##
98
 
##           %#{latexmk}ignore
99
 
##           %#{latexmk}begin.ignore
100
 
##              Start section that is to be ignored in scanning dependencies. 
101
 
##           %#{latexmk}end.ignore
102
 
##              End section that is to be ignored in scanning dependencies. 
103
 
##
104
 
##           %#{latexmk}include.file FILE
105
 
##           %#{latexmk}input.file FILE
106
 
##              Add FILE to list of include files.  (FILE is separated from 
107
 
##              the keyword "include.file" or "input.file" by white space, 
108
 
##              and is terminated by end-of-line or whitespace.)
109
 
##
110
 
##
111
 
##
112
 
##   Modified 
113
 
##
114
 
##
115
 
##       2 Jun 2004, John Collins
116
 
##         Correct bug in parsing of log files from pdflatex
117
 
##      17 May 2004, John Collins
118
 
##      16 May 2004, John Collins
119
 
##         Correct bug in using $print_type eq 'pdf'
120
 
##         Command line switches for print_type
121
 
##      14 May 2004, John Collins
122
 
##      11 May 2004, John Collins
123
 
##         Correct parse_log bug 
124
 
##       3 May 2004, John Collins
125
 
##         Correct bug
126
 
##       2 May 2004, John Collins
127
 
##         Redo handling of errors in -pvc mode: $force_mode off.
128
 
##         Deal with dying in caller of &make_files (etc)
129
 
##       1 May 2004, John Collins
130
 
##         Go mode applies to custom dependencies
131
 
##         Rerun custom dependency and latex when previously non-found
132
 
##           files are found.
133
 
##      30 Apr 2004, John Collins
134
 
##         Fix bug in make_dependents
135
 
##         Add messages about up-to-date files when doing nothing
136
 
##         Silence more informational messages in silent mode.
137
 
##         In list of dependent files generated from .log file
138
 
##            excluded those whose extenstions are in @generated_exts.
139
 
##            This removes generated files from the dependency list.
140
 
##      29 Apr 2004, John Collins
141
 
##      28 Apr 2004, John Collins
142
 
##         Rationalize default file-list to be in @default_files, etc
143
 
##         Change behavior about lack of command line files:
144
 
##             Files specified on command-line but none found: error
145
 
##             No files specified on command-line: 
146
 
##                Try @default_files (with wildcards)
147
 
##                If still none: error
148
 
##         Also apply sort and uniq to globbed list, to eliminate duplicates
149
 
##      27 Apr 2004, John Collins
150
 
##         Correct parsing of filenames in log file and in aux file
151
 
##      26 Apr 2004, John Collins
152
 
##         Correct calls to open, to be OK under perl 5.005 (on SUN)
153
 
##      25 Apr 2004, John Collins
154
 
##         Cleanup of comments, some error messages, etc
155
 
##         Change terminology 'include' to 'input' where appropriate
156
 
##         Switches to turn off modes: -F-, -g-, -i-, -I-, -pv-, -pvc-
157
 
##         -pv and -pvc override each other.  (Easier than making them
158
 
##            incompatible, and particularly necessary when one is
159
 
##            specified in a startup file.)
160
 
##         Die if incorrect option specified on command line.
161
 
##         Turn off bibtex mode if no .bib files specified in .aux
162
 
##            file. That would be the situation if a .bbl file was
163
 
##            input by an input command, so that the user is not 
164
 
##            expecting to use bibtex. 
165
 
##         Add a condition for rerun to include a change in the list
166
 
##            of input files. 
167
 
##         In force_mode, don't die when files are not found; they may
168
 
##            be in a search path where I don't look.  (But I have only
169
 
##            done this for the case that I parse the log file.)
170
 
##         When files for viewing, converting (dvi to ps, etc), etc are 
171
 
##            not found, give a warning rather than trying to continue.
172
 
##         Revise parsing in .log file to allow filenames with spaces.
173
 
##         Use arrays for all lists of filenames.
174
 
##       5 Apr 2004, John Collins
175
 
##         If latexmk exits because of an error with latex, bibtex 
176
 
##            or makeindex, then give a non-zero exit code.
177
 
##       4 Apr 2004, John Collins
178
 
##         All options can be introduced by -- or -
179
 
##         Attempt to treat cygwin correctly
180
 
##         Complete the list of commands printed with -commands
181
 
##         Correct commands for postscript mode written to .dep file
182
 
##       3 Apr 2004, John Collins
183
 
##         V. 3.07 started
184
 
##       2 Mar 2004, John Collins
185
 
##         Obfuscate e-mail addresses so that they aren't picked up by
186
 
##            worms and spammers
187
 
##      17 Jun 2003, John Collins
188
 
##         For pdf viewing set $viewer_update_method to $pdf_update_method
189
 
##            Previously it was set wrongly to $ps_update_method
190
 
##      10 Dec 2002, John Collins
191
 
##         Recursive search of BIBINPUTS and TEXINPUTS
192
 
##         Thanks to Nevin Kapur
193
 
##       5 Nov 2002, John Collins
194
 
##         Reorganize handling of filename specification, so that 
195
 
##         filenames can be specified in an rc file. E.g.,
196
 
##              @file_list = ("paper");
197
 
##      26 Oct 2002, John Collins
198
 
##         In -pvc mode keep going (i.e., -f switch), but have and -f- 
199
 
##            option to turn it off.
200
 
##      25 Oct 2002, John Collins
201
 
##         Correct bug in splitting of command line
202
 
##      24 Oct 2002, John Collins
203
 
##         pdfdvi option
204
 
##         For -pvc take PID of viewer from fork.
205
 
##      22 Oct 2002, John Collins
206
 
##         Change pscmd on linux
207
 
##      12--15 Oct 2002, John Collins
208
 
##         Improve error messages.  
209
 
##         Add "_switch" to names of configuration variables giving switches
210
 
##           (to avoid confusion with variables specifying commands).
211
 
##           E.g., latex_silent_switch
212
 
##         -P pdf switch on dvips, to ensure correct type 1 font generation
213
 
##           (otherwise pdf files have type 3 fonts, and look bad on screen).
214
 
##         Correct running of ps filter.  
215
 
##             It now only runs when ps file is updated.
216
 
##         Some clean-ups of code.
217
 
##         Allow preview of multiple files
218
 
##         Option to generate pdf file by ps2pdf (switch -pdfps)
219
 
##         Prevent detached previewer from responding to ctrl/C given to
220
 
##             parent latemk process.
221
 
##         Under MS Windows, wildcards allowed in file names.
222
 
##      14 Apr 2002, John Collins
223
 
##         Ver. 3.05
224
 
##      24 Nov 2001, John Collins
225
 
##         Ver. 3.04.  Released on CTAN
226
 
##      11 Jun 2001, John Collins
227
 
##         Ver. 3.00.  Misc cleanup.
228
 
##
229
 
##   1998-2001, John Collins.  Many improvements and fixes.
 
178
##
 
179
##   Modification log from 25 Nov 2009 onwards in detail
 
180
##
 
181
##     16 Jan 2010, John Collins  V. 4.13a. 
 
182
##                                Correct bug in deleting extra files (I wasn't 
 
183
##                                  consistent about periods in file extensions)
 
184
##                                Delete unused subroutines
 
185
##     13 Jan 2010, John Collins  V. 4.13 
 
186
##     27 Dec 2009, John Collins  Correct position of inserting bbl into list 
 
187
##                                   of generated extensions.
 
188
##                                Correct clean_up.  It stopped deleting aux 
 
189
##                                   file.
 
190
##                                $bibtex_use defaults to 1.
 
191
##     15 Dec 2009, John Collins  Option not to do bibtex
 
192
##                                   (to allow for case that bbl files
 
193
##                                   are available, but no bibtex).
 
194
##     27 Nov 2009, John Collins  Solve problem that changes in \include 
 
195
##                                   files weren't reflected in changes
 
196
##                                   in bibtex source files.
 
197
##                                Remove excess recalculations of md5 in 
 
198
##                                   startup and when initializing rule 
 
199
##                                   from fdb_latexmk file.
 
200
##                                Fdb_latexmk now has data for all rules
 
201
##                                   need for making target files,
 
202
##                                   not just rules accessible from primary
 
203
##                                   rules.
 
204
##     26 Nov 2009, John Collins  In testing for changes, when filetime
 
205
##                                   has changed, but file is unchanged,
 
206
##                                   update filetime in rule.
 
207
##                                   This saves excessive md5 calculations.
 
208
##     25 Nov 2009, John Collins  Fixed issue with fdb_get and 1-second
 
209
##                                   granularity of file timestamps.
 
210
##                                   The issue was that if runs of
 
211
##                                   latex (etc) occur within the
 
212
##                                   1-second time granularity, file
 
213
##                                   contents can change even though
 
214
##                                   the file's time and size are
 
215
##                                   unchanged, falsifying an
 
216
##                                   assumption made by fdb_get, but
 
217
##                                   only when the old time is the
 
218
##                                   same as the run time of a command
 
219
##                                   that uses the file.
 
220
##                                Avoided excess md5 calculations at
 
221
##                                   startup.
 
222
##
 
223
##   1998-2009, John Collins.  Many improvements and fixes.
 
224
##       See CHANGE-log.txt for full list, and CHANGES for summary
230
225
##
231
226
##   Modified by Evan McLean (no longer available for support)
232
227
##   Original script (RCS version 2.3) called "go" written by David J. Musliner
310
305
##-----------------------------------------------------------------------
311
306
 
312
307
 
 
308
## Explicit exit codes: 
 
309
##             10 = bad command line arguments
 
310
##             11 = file specified on command line not found
 
311
##                  or other file not found
 
312
##             12 = failure in some part of making files
 
313
##             13 = error in initialization file
 
314
##             20 = probable bug
 
315
##             or retcode from called program.
 
316
 
 
317
 
313
318
#Line length in log file that indicates wrapping.  
314
319
# This number EXCLUDES line-end characters, and is one-based
 
320
# It is the parameter max_print_line in the TeX program.  (tex.web)
315
321
$log_wrap = 79;
316
322
 
317
323
#########################################################################
 
324
## Default parsing and file-handling settings
 
325
 
 
326
## Array of reg-exps for patterns in log-file for file-not-found
 
327
## Each item is the string in a regexp, without the enclosing slashes.
 
328
## First parenthesized part is the filename.
 
329
## Note the need to quote slashes and single right quotes to make them 
 
330
## appear in the regexp.
 
331
## Add items by push, e.g.,
 
332
##     push @file_not_found, '^No data file found `([^\\\']*)\\\'';
 
333
## will give match to line starting "No data file found `filename'"
 
334
@file_not_found = (
 
335
    '^No file\\s*(.*)\\.$',
 
336
    '^\\! LaTeX Error: File `([^\\\']*)\\\' not found\\.',
 
337
    '.*?:\\d*: LaTeX Error: File `([^\\\']*)\\\' not found\\.',
 
338
    '^LaTeX Warning: File `([^\\\']*)\\\' not found',
 
339
    '^Package .* [fF]ile `([^\\\']*)\\\' not found',
 
340
    'Error: pdflatex \(file ([^\)]*)\): cannot find image file',
 
341
);
 
342
 
 
343
## Hash mapping file extension (w/o period, e.g., 'eps') to a single regexp,
 
344
#  whose matching by a line in a file with that extension indicates that the 
 
345
#  line is to be ignored in the calculation of the hash number (md5 checksum)
 
346
#  for the file.  Typically used for ignoring datestamps in testing whether 
 
347
#  a file has changed.
 
348
#  Add items e.g., by
 
349
#     $hash_calc_ignore_pattern{'eps'} = '^%%CreationDate: ';
 
350
#  This makes the hash calculation for an eps file ignore lines starting with
 
351
#  '%%CreationDate: '
 
352
#  ?? Note that a file will be considered changed if 
 
353
#       (a) its size changes
 
354
#    or (b) its hash changes
 
355
#  So it is useful to ignore lines in the hash calculation only if they
 
356
#  are of a fixed size (as with a date/time stamp).
 
357
%hash_calc_ignore_pattern =();
 
358
 
 
359
#########################################################################
318
360
## Default document processing programs, and related settings,
319
361
## These are mostly the same on all systems.
320
362
## Most of these variables represents the external command needed to 
321
363
## perform a certain action.  Some represent switches.
322
364
 
323
365
## Commands to invoke latex, pdflatex
324
 
$latex  = 'latex';
325
 
$pdflatex = 'pdflatex';
 
366
$latex  = 'latex %O %S';
 
367
$pdflatex = 'pdflatex %O %S';
326
368
## Switch(es) to make them silent:
327
369
$latex_silent_switch  = '-interaction=batchmode';
328
370
$pdflatex_silent_switch  = '-interaction=batchmode';
329
371
 
 
372
# %input_extensions maps primary_rule_name to pointer to hash of file extensions
 
373
#    used for extensionless files specified in the source file by constructs
 
374
#    like \input{file}  \includegraphics{file}
 
375
#  Could write
 
376
#%input_extensions = ( 'latex' => { 'tex' => 1, 'eps' => 1 };, 
 
377
#        'pdflatex' => { 'tex' => 1, 'pdf' => 1, 'jpg' => 1, 'png' => 1 }; );
 
378
# Instead we'll exercise the user-friendly access routines:
 
379
add_input_ext( 'latex', 'tex', 'eps' );
 
380
add_input_ext( 'pdflatex', 'tex', 'jpg', 'pdf' );
 
381
#show_input_ext( 'latex' ); show_input_ext( 'pdflatex' );
 
382
 
330
383
## Command to invoke bibtex
331
 
$bibtex  = 'bibtex';
 
384
$bibtex  = 'bibtex %O %B';
332
385
# Switch(es) to make bibtex silent:
333
386
$bibtex_silent_switch  = '-terse';
 
387
$bibtex_use = 1;   # Whether to actually run bibtex to update bbl files
 
388
                   # 0:  Never run bibtex
 
389
                   # 1:  Run bibtex only if the bibfiles exists 
 
390
                   #     according to kpsewhich, and the bbl files
 
391
                   #     appear to be out-of-date
 
392
                   # 2:  Run bibtex when the bbl files are out-of-date
 
393
                   # In any event bibtex is only run if the log file
 
394
                   #   indicates that the document uses bbl files.
334
395
 
335
396
## Command to invoke makeindex
336
 
$makeindex  = 'makeindex';
 
397
$makeindex  = 'makeindex %O -o %D %S';
 
398
# Switch(es) to make makeinex silent:
 
399
$makeindex_silent_switch  = '-q';
337
400
 
338
401
## Command to convert dvi file to pdf file directly:
339
 
$dvipdf  = 'dvipdf';
 
402
$dvipdf  = 'dvipdf %O %S %D';
340
403
 
341
404
## Command to convert dvi file to ps file:
342
 
$dvips  = 'dvips';
 
405
$dvips  = 'dvips %O -o %D %S';
343
406
## Command to convert dvi file to ps file in landscape format:
344
 
$dvips_landscape = 'dvips -tlandscape';
 
407
$dvips_landscape = 'dvips -tlandscape %O -o %D %S';
345
408
# Switch(es) to get dvips to make ps file suitable for conversion to good pdf:
346
409
#    (If this is not used, ps file and hence pdf file contains bitmap fonts
347
410
#       (type 3), which look horrible under acroread.  An appropriate switch
352
415
$dvips_silent_switch  = '-q';
353
416
 
354
417
## Command to convert ps file to pdf file:
355
 
$ps2pdf = 'ps2pdf';
 
418
$ps2pdf = 'ps2pdf  %O %S %D';
 
419
 
 
420
## Command to search for tex-related files
 
421
$kpsewhich = 'kpsewhich %S';
 
422
 
356
423
 
357
424
##Printing:
358
425
$print_type = 'ps';     # When printing, print the postscript file.
365
432
## Current tex's treat extensions like UNIX teTeX:
366
433
$extension_treatment = 'unix';
367
434
 
 
435
$dvi_update_signal = undef;
 
436
$ps_update_signal = undef;
 
437
$pdf_update_signal = undef;
 
438
 
 
439
$dvi_update_command = undef;
 
440
$ps_update_command = undef;
 
441
$pdf_update_command = undef;
 
442
 
 
443
$new_viewer_always = 0;     # If 1, always open a new viewer in pvc mode.
 
444
                            # If 0, only open a new viewer if no previous
 
445
                            #     viewer for the same file is detected.
 
446
 
 
447
$quote_filenames = 1;       # Quote filenames in external commands
 
448
 
368
449
#########################################################################
369
450
 
 
451
################################################################
 
452
##  Special variables for system-dependent fudges, etc.
 
453
$log_file_binary = 0;   # Whether to treat log file as binary
 
454
                        # Normally not, since the log file SHOULD be pure text.
 
455
                        # But Miktex 2.7 sometimes puts binary characters
 
456
                        #    in it.  (Typically in construct \OML ... after
 
457
                        #    overfull box with mathmode.)
 
458
                        # Sometimes there is ctrl/Z, which is not only non-text, 
 
459
                        #    but is end-of-file marker for MS-Win in text mode.  
 
460
 
 
461
$MSWin_fudge_break = 1; # Give special treatment to ctrl/C and ctrl/break
 
462
                        #    in -pvc mode under MSWin
 
463
                        # Under MSWin32 (at least with perl 5.8 and WinXP)
 
464
                        #   when latemk is running another program, and the 
 
465
                        #   user gives ctrl/C or ctrl/break, to stop the 
 
466
                        #   daughter program, not only does it reach
 
467
                        #   the daughter, but also latexmk/perl, so
 
468
                        #   latexmk is stopped also.  In -pvc mode,
 
469
                        #   this is not normally desired.  So when the
 
470
                        #   $MSWin_fudge_break variable is set,
 
471
                        #   latexmk arranges to ignore ctrl/C and
 
472
                        #   ctrl/break during processing of files;
 
473
                        #   only the daughter programs receive them.
 
474
                        # This fudge is not applied in other
 
475
                        #   situations, since then having latexmk also
 
476
                        #   stopping because of the ctrl/C or
 
477
                        #   ctrl/break signal is desirable.
 
478
                        # The fudge is not needed under UNIX (at least
 
479
                        #   with Perl 5.005 on Solaris 8).  Only the
 
480
                        #   daughter programs receive the signal.  In
 
481
                        #   fact the inverse would be useful: In
 
482
                        #   normal processing, as opposed to -pvc, if
 
483
                        #   force mode (-f) is set, a ctrl/C is
 
484
                        #   received by a daughter program does not
 
485
                        #   also stop latexmk.  Under tcsh, we get
 
486
                        #   back to a command prompt, while latexmk
 
487
                        #   keeps running in the background!
 
488
 
 
489
 
 
490
################################################################
 
491
 
 
492
 
370
493
# System-dependent overrides:
371
494
if ( $^O eq "MSWin32" ) {
372
495
# Pure MSWindows configuration
373
496
    ## Configuration parameters:
374
 
    $tmpdir = "$ENV{TEMP}";
 
497
 
 
498
    ## Use first existing case for $tmpdir:
 
499
    $tmpdir = $ENV{TMPDIR} || $ENV{TEMP} || '.';
 
500
    $log_file_binary = 1;   # Protect against ctrl/Z in log file from
 
501
                            # Miktex 2.7.
375
502
 
376
503
    ## List of possibilities for the system-wide initialization file.  
377
504
    ## The first one found (if any) is used.
385
512
 
386
513
    # For a pdf-file, "start x.pdf" starts the pdf viewer associated with
387
514
    #   pdf files, so no program name is needed:
388
 
    $pdf_previewer = 'start';
389
 
    $ps_previewer  = 'start';
390
 
    $ps_previewer_landscape  = "$ps_previewer";
391
 
    $dvi_previewer  = 'start';
 
515
    $pdf_previewer = 'start %O %S';
 
516
    $ps_previewer  = 'start %O %S';
 
517
    $ps_previewer_landscape  = $ps_previewer;
 
518
    $dvi_previewer  = 'start %O %S';
392
519
    $dvi_previewer_landscape = "$dvi_previewer";
393
520
    # Viewer update methods: 
394
521
    #    0 => auto update: viewer watches file (e.g., gv)
395
522
    #    1 => manual update: user must do something: e.g., click on window.
396
523
    #         (e.g., ghostview, MSWIN previewers, acroread under UNIX)
397
 
    #    2 => send SIGUSR1 signal (xdvi)
 
524
    #    2 => send signal.  Number of signal in $dvi_update_signal,
 
525
    #                         $ps_update_signal, $pdf_update_signal
398
526
    #    3 => viewer can't update, because it locks the file and the file 
399
527
    #         cannot be updated.  (acroread under MSWIN)
 
528
    #    4 => run a command to force the update.  The commands are 
 
529
    #         specified by the variables $dvi_update_command, 
 
530
    #         $ps_update_command, $pdf_update_command
400
531
    $dvi_update_method = 1;
401
532
    $ps_update_method = 1;
402
533
    $pdf_update_method = 3; # acroread locks the pdf file
403
 
    $lpr  = 'NONE lpr';        # Use NONE as flag that I am not implementing this
404
 
    $lpr_dvi  = 'NONE lpr_dvi';# Use NONE as flag that I am not implementing this
405
 
    $lpr_pdf  = 'NONE lpr_pdf';# Use NONE as flag that I am not implementing this
 
534
    # Use NONE as flag that I am not implementing some commands:
 
535
    $lpr =
 
536
        'NONE $lpr variable is not configured to allow printing of ps files';
 
537
    $lpr_dvi =
 
538
        'NONE $lpr_dvi variable is not configured to allow printing of dvi files';
 
539
    $lpr_pdf =
 
540
        'NONE $lpr_pdf variable is not configured to allow printing of pdf files';
406
541
    # The $pscmd below holds a command to list running processes.  It
407
542
    # is used to find the process ID of the viewer looking at the
408
543
    # current output file.  The output of the command must include the
409
544
    # process number and the command line of the processes, since the
410
545
    # relevant process is identified by the name of file to be viewed.
411
546
    # Its use is not essential.
412
 
    $pscmd = 'NONE pscmd';  # Use NONE as flag that I am not implementing this
 
547
    $pscmd = 
 
548
        'NONE $pscmd variable is not configured to detect running processes';
413
549
    $pid_position = -1;     # offset of PID in output of pscmd.  
414
550
                            # Negative means I cannot use ps
415
551
}
465
601
    # This may fail: perl converts MSWin temp directory name to cygwin
466
602
    # format. Names containing this string cannot be handled by native
467
603
    # NT executables.
468
 
    $tmpdir = "$ENV{TEMP}";
 
604
    $tmpdir = $ENV{TMPDIR} || $ENV{TEMP} || '.';
469
605
 
470
606
    ## List of possibilities for the system-wide initialization file.  
471
607
    ## The first one found (if any) is used.
486
622
    #  NT-native start command of a cmd.exe is used.
487
623
    # For a pdf-file, "start x.pdf" starts the pdf viewer associated with
488
624
    #   pdf files, so no program name is needed:
489
 
    $start_NT = "cmd /c start";
490
 
    $pdf_previewer = "$start_NT";
491
 
    $ps_previewer  = "$start_NT";
492
 
    $ps_previewer_landscape  = "$ps_previewer";
493
 
    $dvi_previewer  = "$start_NT";
494
 
    $dvi_previewer_landscape = "$dvi_previewer";
 
625
    $start_NT = "cmd /c start \"\"";
 
626
    $pdf_previewer = "$start_NT %O %S";
 
627
    $ps_previewer  = "$start_NT %O %S";
 
628
    $ps_previewer_landscape  = $ps_previewer;
 
629
    $dvi_previewer  = "$start_NT %O %S";
 
630
    $dvi_previewer_landscape = $dvi_previewer;
495
631
    # Viewer update methods: 
496
632
    #    0 => auto update: viewer watches file (e.g., gv)
497
633
    #    1 => manual update: user must do something: e.g., click on window.
498
634
    #         (e.g., ghostview, MSWIN previewers, acroread under UNIX)
499
 
    #    2 => send SIGUSR1 signal (xdvi)
 
635
    #    2 => send signal.  Number of signal in $dvi_update_signal,
 
636
    #                         $ps_update_signal, $pdf_update_signal
500
637
    #    3 => viewer can't update, because it locks the file and the file 
501
638
    #         cannot be updated.  (acroread under MSWIN)
502
639
    $dvi_update_method = 1;
503
640
    $ps_update_method = 1;
504
641
    $pdf_update_method = 3; # acroread locks the pdf file
505
 
    $lpr  = 'NONE lpr';     # Use NONE as flag that I am not implementing this
506
 
    $lpr_dvi  = 'NONE lpr_dvi';# Use NONE as flag that I am not implementing this
507
 
    $lpr_pdf  = 'NONE lpr_pdf';# Use NONE as flag that I am not implementing this
 
642
    # Use NONE as flag that I am not implementing some commands:
 
643
    $lpr =
 
644
        'NONE $lpr variable is not configured to allow printing of ps files';
 
645
    $lpr_dvi =
 
646
        'NONE $lpr_dvi variable is not configured to allow printing of dvi files';
 
647
    $lpr_pdf =
 
648
        'NONE $lpr_pdf variable is not configured to allow printing of pdf files';
508
649
    # The $pscmd below holds a command to list running processes.  It
509
650
    # is used to find the process ID of the viewer looking at the
510
651
    # current output file.  The output of the command must include the
520
661
    # Only the user, not latemk knows which, so we default to not
521
662
    # using the ps command.  The user can override this in a
522
663
    # configuration file. 
523
 
    $pscmd = 'NONE pscmd';  # Use NONE as flag that I am not implementing this
 
664
    $pscmd = 
 
665
        'NONE $pscmd variable is not configured to detect running processes';
524
666
    $pid_position = -1;     # offset of PID in output of pscmd.  
525
667
                            # Negative means I cannot use ps
526
668
}
528
670
    # Assume anything else is UNIX or clone
529
671
 
530
672
    ## Configuration parameters:
531
 
    $tmpdir = '/tmp';
 
673
 
 
674
 
 
675
    ## Use first existing case for $tmpdir:
 
676
    $tmpdir = $ENV{TMPDIR} || '/tmp';
532
677
 
533
678
    ## List of possibilities for the system-wide initialization file.  
534
679
    ## The first one found (if any) is used.
542
687
       '/usr/local/lib/latexmk/LatexMk' );
543
688
 
544
689
    $search_path_separator = ':';  # Separator of elements in search_path
 
690
 
 
691
    $dvi_update_signal = $signo{USR1} 
 
692
         if ( defined $signo{USR1} ); # Suitable for xdvi
 
693
    $ps_update_signal = $signo{HUP} 
 
694
         if ( defined $signo{HUP} );  # Suitable for gv
 
695
    $pdf_update_signal = $signo{HUP} 
 
696
         if ( defined $signo{HUP} );  # Suitable for gv
545
697
    ## default document processing programs.
546
 
    $pdf_previewer = 'start acroread';
547
 
    ## The following are corrects for the SUNs at phys.psu.edu:
548
 
    #$ps_previewer  = 'start ghostview';
549
 
    #$ps_previewer_landscape  = 'start ghostview -swap';
550
 
    $ps_previewer  = 'start gv -watch';
551
 
    $ps_previewer_landscape  = 'start gv -swap -watch';
552
 
    $dvi_previewer  = 'start xdvi';
553
 
    $dvi_previewer_landscape = 'start xdvi -paper usr';
554
698
    # Viewer update methods: 
555
699
    #    0 => auto update: viewer watches file (e.g., gv)
556
700
    #    1 => manual update: user must do something: e.g., click on window.
557
701
    #         (e.g., ghostview, MSWIN previewers, acroread under UNIX)
558
 
    #    2 => send SIGUSR1 signal (xdvi)
 
702
    #    2 => send signal.  Number of signal in $dvi_update_signal,
 
703
    #                         $ps_update_signal, $pdf_update_signal
559
704
    #    3 => viewer can't update, because it locks the file and the file 
560
705
    #         cannot be updated.  (acroread under MSWIN)
561
 
    $dvi_update_method = 2;  # xdvi responds to SIGUSR1 to update
562
 
    $ps_update_method = 0;   # gv -watch watches the ps file
 
706
    #    4 => Run command to update.  Command in $dvi_update_command, 
 
707
    #    $ps_update_command, $pdf_update_command.
 
708
    $dvi_previewer  = 'start xdvi %O %S';
 
709
    $dvi_previewer_landscape = 'start xdvi -paper usr %O %S';
 
710
    if ( defined $dvi_update_signal ) { 
 
711
        $dvi_update_method = 2;  # xdvi responds to signal to update
 
712
    } else {
 
713
        $dvi_update_method = 1;  
 
714
    }
 
715
#    if ( defined $ps_update_signal ) { 
 
716
#        $ps_update_method = 2;  # gv responds to signal to update
 
717
#        $ps_previewer  = 'start gv -nowatch';
 
718
#        $ps_previewer_landscape  = 'start gv -swap -nowatch';
 
719
#    } else {
 
720
#        $ps_update_method = 0;  # gv -watch watches the ps file
 
721
#        $ps_previewer  = 'start gv -watch';
 
722
#        $ps_previewer_landscape  = 'start gv -swap -watch';
 
723
#    }
 
724
    # Turn off the fancy options for gv.  Regular gv likes -watch etc
 
725
    #   GNU gv likes --watch etc.  User must configure
 
726
    $ps_update_method = 0;  # gv -watch watches the ps file
 
727
    $ps_previewer  = 'start gv %O %S';
 
728
    $ps_previewer_landscape  = 'start gv -swap %O %S';
 
729
    $pdf_previewer = 'start acroread %O %S';
563
730
    $pdf_update_method = 1;  # acroread under unix needs manual update
564
 
    $lpr = 'lpr';         # Assume lpr command prints postscript files correctly
565
 
    $lpr_dvi  = 'NONE lpr_dvi';# Use NONE as flag that I am not implementing this
566
 
    $lpr_pdf  = 'NONE lpr_pdf';# Use NONE as flag that I am not implementing this
 
731
    $lpr = 'lpr %O %S';         # Assume lpr command prints postscript files correctly
 
732
    $lpr_dvi =
 
733
        'NONE $lpr_dvi variable is not configured to allow printing of dvi files';
 
734
    $lpr_pdf =
 
735
        'NONE $lpr_pdf variable is not configured to allow printing of pdf files';
567
736
    # The $pscmd below holds a command to list running processes.  It
568
737
    # is used to find the process ID of the viewer looking at the
569
738
    # current output file.  The output of the command must include the
592
761
        #    systems, e.g., Solaris 8.
593
762
        $pscmd = "ps --width 200 -f -u $ENV{USER}"; 
594
763
    }
 
764
    elsif ( $^O eq "darwin" ) {
 
765
        # OS-X on Macintosh
 
766
        $lpr_pdf  = 'lpr %O %S';  
 
767
        $pscmd = "ps -ww -u $ENV{USER}"; 
 
768
    }
595
769
}
596
770
 
597
771
## default parameters
624
798
                        # no files are specified on the command line.
625
799
                        # Wildcards allowed
626
800
                        # Best used for project specific files.
 
801
@default_excluded_files = ( );   
 
802
                        # Array of LaTeX files to exclude when using
 
803
                        # @default_files, i.e., when no files are specified
 
804
                        # on the command line.
 
805
                        # Wildcards allowed
 
806
                        # Best used for project specific files.
627
807
$texfile_search = "";   # Specification for extra files to search for
628
808
                        # when no files are specified on the command line
629
 
                        # and the @file_list variable is empty.
 
809
                        # and the @default_files variable is empty.
630
810
                        # Space separated, and wildcards allowed.
631
811
                        # These files are IN ADDITION to *.tex in current 
632
812
                        # directory. 
633
813
                        # This variable is obsolete, and only in here for
634
814
                        # backward compatibility.
635
815
 
 
816
$fdb_ext = 'fdb_latexmk'; # Extension for the file for latexmk's
 
817
                          # file-database
 
818
                          # Make it long to avoid possible collisions.
 
819
$fdb_ver = 2;             # Version number for kind of fdb_file.
 
820
 
 
821
$jobname = '';          # Jobname: as with current tex, etc indicates
 
822
                        # basename of generated files.
 
823
                        # Defined so that --jobname=STRING on latexmk's
 
824
                        # command line has same effect as with current
 
825
                        # tex, etc.  (If $jobname is non-empty, then
 
826
                        # the --jobname=... option is used on tex.)
 
827
 
636
828
 
637
829
## default flag settings.
638
830
$silent = 0;            # silence latex's messages?
639
 
$bibtex_mode = 0;       # is there a bibliography needing bibtexing?
640
 
$index_mode = 0;        # is there an index needing makeindex run?
641
831
$landscape_mode = 0;    # default to portrait mode
642
 
# The following contains a list of extensions for files that may be read in 
643
 
# during a LaTeX run but that are generated in the previous run.  They should be 
644
 
# excluded from the dependents, since NORMALLY they are not true source files. 
645
 
# This list can be overridden in a configuration file if it causes problems.
646
 
# The extensions "aux" and "bbl" are always excluded from the dependents,
647
 
# because they get special treatment.
648
 
@generated_exts = ( 'lof', 'lot', 'toc');
 
832
 
 
833
# The following two arrays contain lists of extensions (without
 
834
# period) for files that are read in during a (pdf)LaTeX run but that
 
835
# are generated automatically from the previous run, as opposed to
 
836
# being user generated files (directly or indirectly from a custom
 
837
# dependency).  These files get two kinds of special treatment:
 
838
#     1.  In clean up, where depending on the kind of clean up, some
 
839
#         or all of these generated files are deleted.
 
840
#         (Note that special treatment is given to aux files.)
 
841
#     2.  In analyzing the results of a run of (pdf)LaTeX, to
 
842
#         determine if another run is needed.  With an error free run,
 
843
#         a rerun should be provoked by a change in any source file,
 
844
#         whether a user file or a generated file.  But with a run
 
845
#         that ends in an error, only a change in a user file during
 
846
#         the run (which might correct the error) should provoke a
 
847
#         rerun, but a change in a generated file should not.
 
848
# These arrays can be user-configured.
 
849
 
 
850
@generated_exts = ( 'aux', 'idx', 'ind', 'lof', 'lot', 'out', 'toc' );
 
851
     # N.B. 'out' is generated by hyperref package
 
852
 
649
853
# Which kinds of file do I have requests to make?
650
854
# If no requests at all are made, then I will make dvi file
651
855
# If particular requests are made then other files may also have to be
664
868
$banner_scale = 220;    # Original default scale
665
869
$banner_intensity = 0.95;  # Darkness of the banner message
666
870
$banner_message = 'DRAFT'; # Original default message
667
 
$cleanup_mode = 0;      # No cleanup of nonessential files.
 
871
$do_cd = 0;     # Do not do cd to directory of source file.
 
872
                #   Thus behave like latex.
 
873
$dependents_list = 0;   # Whether to display list(s) of dependencies
 
874
@dir_stack = (); # Stack of pushed directories.
 
875
$cleanup_mode = 0;      # No cleanup of nonessential LaTex-related files.
668
876
                        # $cleanup_mode = 0: no cleanup
669
877
                        # $cleanup_mode = 1: full cleanup 
670
 
                        # $cleanup_mode = 2: cleanup except for dvi and ps
671
 
                        # $cleanup_mode = 3: cleanup except for dep and aux
 
878
                        # $cleanup_mode = 2: cleanup except for dvi,
 
879
                        #                    dviF, pdf, ps, & psF 
 
880
$cleanup_fdb  = 0;      # No removal of file for latexmk's file-database
 
881
$cleanup_only = 0;      # When doing cleanup, do not go-on to making files
 
882
$cleanup_includes_generated = 0; 
 
883
                        # Determines whether cleanup deletes files generated by
 
884
                        #    (pdf)latex (found from \openout lines in log file).
672
885
$diagnostics = 0;
673
886
$dvi_filter = '';       # DVI filter command
674
887
$ps_filter = '';        # Postscript filter command
675
888
 
676
 
$includes_from_log = 1;  # =1 to work on log file to find dependencies
677
889
$force_mode = 0;        # =1 to force processing past errors
678
 
$force_include_mode = 0;# =1 to ignore non-existent files when making
679
 
                        # dependency files.
 
890
$force_include_mode = 0;# =1 to ignore non-existent files when testing
 
891
                        # for dependency.  (I.e., don't treat them as error)
680
892
$go_mode = 0;           # =1 to force processing regardless of time-stamps
681
893
                        # =2 full clean-up first
682
894
$preview_mode = 0;
683
895
$preview_continuous_mode  = 0;
684
896
$printout_mode = 0;     # Don't print the file
685
 
@bib_files = ();
686
897
 
 
898
# Do we make view file in temporary then move to final destination?
 
899
#  (To avoid premature updating by viewer).
 
900
$always_view_file_via_temporary = 0;      # Set to 1 if  viewed file is always
 
901
                                   #    made through a temporary.
 
902
$pvc_view_file_via_temporary = 1;  # Set to 1 if only in -pvc mode is viewed 
 
903
                                   #    file made through a temporary.
687
904
 
688
905
# State variables initialized here:
689
906
 
690
907
$updated = 0;           # Flags when something has been remade
691
908
                        # Used to allow convenient user message in -pvc mode
692
 
 
 
909
$waiting = 0;           # Flags whether we are in loop waiting for an event
 
910
                        # Used to avoid unnecessary repeated o/p in wait loop
693
911
 
694
912
# Used for some results of parsing log file:
695
913
$reference_changed = 0;
697
915
$bad_citation = 0;
698
916
 
699
917
 
700
 
# Get search paths for includes.
 
918
# Set search paths for includes.
 
919
# Set them early so that they can be overridden
 
920
$BIBINPUTS = $ENV{'BIBINPUTS'};
 
921
if (!$BIBINPUTS) { $BIBINPUTS = '.'; }
 
922
#?? OBSOLETE
701
923
$TEXINPUTS = $ENV{'TEXINPUTS'};
702
924
if (!$TEXINPUTS) { $TEXINPUTS = '.'; }
703
 
$BIBINPUTS = $ENV{'BIBINPUTS'};
704
 
if (!$BIBINPUTS) { $BIBINPUTS = '.'; }
705
 
 
706
 
@psfigsearchpath = ('.');
707
925
 
708
926
# Convert search paths to arrays:
709
927
# If any of the paths end in '//' then recursively search the
710
 
# directory.  After these operations, @BIBINPUTS and @TEXINPUTS should
 
928
# directory.  After these operations, @BIBINPUTS  should
711
929
# have all the directories that need to be searched
712
930
 
713
 
@TEXINPUTS = find_dirs1 ($TEXINPUTS);
714
931
@BIBINPUTS = find_dirs1 ($BIBINPUTS);
715
932
 
716
 
#show_array ("TEXINPUTS", @TEXINPUTS); show_array ("BIBINPUTS", @BIBINPUTS); die;
717
 
 
 
933
 
 
934
######################################################################
 
935
######################################################################
 
936
#
 
937
#  ???  UPDATE THE FOLLOWING!!
 
938
#
 
939
# We will need to determine whether source files for runs of various
 
940
# programs are out of date.  In a normal situation, this is done by
 
941
# asking whether the times of the source files are later than the
 
942
# destination files.  But this won't work for us, since a common
 
943
# situation is that a file is written on one run of latex, for
 
944
# example, and read back in on the next run (e.g., an .aux file).
 
945
# Some situations of this kind are standard in latex generally; others
 
946
# occur with particular macro packages or with particular
 
947
# postprocessors. 
 
948
#
 
949
# The correct criterion for whether a source is out-of-date is
 
950
# therefore NOT that its modification time is later than the
 
951
# destination file, but whether the contents of the source file have
 
952
# changed since the last successful run.  This also handles the case
 
953
# that the user undoes some changes to a source file by replacing the
 
954
# source file by reverting to an earlier version, which may well have
 
955
# an older time stamp.  Since a direct comparison of old and new files
 
956
# would involve storage and access of a large number of backup files,
 
957
# we instead use the md5 signature of the files.  (Previous versions
 
958
# of latexmk used the backup file method, but restricted to the case
 
959
# of .aux and .idx files, sufficient for most, but not all,
 
960
# situations.)
 
961
#
 
962
# We will have a database of (time, size, md5) for the relevant
 
963
# files. If the time and size of a file haven't changed, then the file
 
964
# is assumed not to have changed; this saves us from having to
 
965
# determine its md5 signature, which would involve reading the whole 
 
966
# file, which is naturally time-consuming, especially if network file
 
967
# access to a server is needed, and many files are involved, when most
 
968
# of them don't change.  It is of course possible to change a file
 
969
# without changing its size, but then to adjust its timestamp 
 
970
# to what it was previously; this requires a certain amount of
 
971
# perversity.  We can safely assume that if the user edits a file or
 
972
# changes its contents, then the file's timestamp changes.  The
 
973
# interesting case is that the timestamp does change, because the file
 
974
# has actually been written to, but that the contents do not change;
 
975
# it is for this that we use the md5 signature.  However, since
 
976
# computing the md5 signature involves reading the whole file, which
 
977
# may be large, we should avoid computing it more than necessary. 
 
978
#
 
979
# So we get the following structure:
 
980
#
 
981
#     1.  For each relevant run (latex, pdflatex, each instance of a
 
982
#         custom dependency) we have a database of the state of the
 
983
#         source files that were last used by the run.
 
984
#     2.  On an initial startup, the database for a primary tex file
 
985
#         is read that was created by a previous run of latex or
 
986
#         pdflatex, if this exists.  
 
987
#     3.  If the file doesn't exist, then the criterion for
 
988
#         out-of-dateness for an initial run is that it goes by file
 
989
#         timestamps, as in previous versions of latexmk, with due
 
990
#         (dis)regard to those files that are known to be generated by
 
991
#         latex and re-read on the next run.
 
992
#     4.  Immediately before a run, the database is updated to
 
993
#         represent the current conditions of the run's source files.
 
994
#     5.  After the run, it is determined whether any of the source
 
995
#         files have changed.  This covers both files written by the
 
996
#         run, which are therefore in a dependency loop, and files that
 
997
#         the user may have updated during the run.  (The last often
 
998
#         happens when latex takes a long time, for a big document,
 
999
#         and the user makes edits before latex has finished.  This is
 
1000
#         particularly prevalent when latexmk is used with
 
1001
#         preview-continuous mode.)
 
1002
#     6.  In the case of latex or pdflatex, the custom dependencies
 
1003
#         must also be checked and redone if out-of-date.
 
1004
#     7.  If any source files have changed, the run is redone,
 
1005
#         starting at step 1.
 
1006
#     8.  There is naturally a limit on the number of reruns, to avoid
 
1007
#         infinite loops from bugs and from pathological or unforeseen
 
1008
#         conditions. 
 
1009
#     9.  After the run is done, the run's file database is updated.
 
1010
#         (By hypothesis, the sizes and md5s are correct, if the run
 
1011
#         is successful.)
 
1012
#    10.  To allow reuse of data from previous runs, the file database
 
1013
#         is written to a file after every complete set of passes
 
1014
#         through latex or pdflatex.  (Note that there is separate
 
1015
#         information for latex and pdflatex; the necessary
 
1016
#         information won't coincide: Out-of-dateness for the files
 
1017
#         for each program concerns the properties of the files when
 
1018
#         the other program was run, and the set of source files could
 
1019
#         be different, e.g., for graphics files.)  
 
1020
#
 
1021
# We therefore maintain the following data structures.:
 
1022
#
 
1023
#     a.  For each run (latex, pdflatex, each custom dependency) a
 
1024
#         database is maintained.  This is a hash from filenames to a
 
1025
#         reference to an array:  [time, size, md5].  The semantics of
 
1026
#         the database is that it represents the state of the source
 
1027
#         files used in the run.  During a run it represents the state
 
1028
#         immediately before the run; after a run, with all reruns, it
 
1029
#         represents the state of the files used, modified by having
 
1030
#         the latest timestamps for generated files.
 
1031
#     b.  There is a global database for all files, which represents
 
1032
#         the current state.  This saves having to recompute the md5
 
1033
#         signatures of a changed file used in more than one run
 
1034
#         (e.g., latex and pdflatex).
 
1035
#     c.  Each of latex and pdflatex has a list of the relevant custom
 
1036
#         dependencies. 
 
1037
#
 
1038
# In all the following a fdb-hash is a hash of the form:
 
1039
#                      filename -> [time, size, md5] 
 
1040
# If a file is found to disappear, its entry is removed from the hash.
 
1041
# In returns from fdb access routines, a size entry of -1 indicates a
 
1042
# non-existent file.
 
1043
 
 
1044
 
 
1045
# List of known rules.  Rule types: primary, 
 
1046
#     external (calls program), internal (calls routine), cusdep.
 
1047
 
 
1048
%possible_primaries = ( 'latex'  => 'primary',  'pdflatex'  => 'primary' );
 
1049
%primaries = ();    # Hash of rules for primary part of make.  Keys are 
 
1050
                    # currently 'latex', 'pdflatex' or both.  Value is
 
1051
                    # currently irrelevant.  Use hash for ease of lookup
 
1052
   # Make remove this later, if use makeB
 
1053
 
 
1054
# Hashes, whose keys give names of particular kinds of rule.  We use
 
1055
# hashes for ease of lookup.
 
1056
%possible_one_time = ( 'view' => 1, 'print' => 1, 'update_view' => 1,  );
 
1057
%requested_filerules = ();  # Hash for rules corresponding to requested files.  
 
1058
                    # The keys are the rulenames and the value is 
 
1059
                    # currently irrelevant.
 
1060
%one_time = ();     # Hash for requested one-time-only rules, currently
 
1061
                    # possible values 'print' and 'view'.  
 
1062
 
 
1063
 
 
1064
%rule_db = ();      # Database of all rules:
 
1065
                    # Hash: rulename -> [array of rule data]
 
1066
                    # Rule data:
 
1067
                    #   0: [ cmd_type, ext_cmd, int_cmd, test_kind, 
 
1068
                    #       source, dest, base, out_of_date,
 
1069
                    #       out_of_date_user, time_of_last_run,
 
1070
                    #       last_result, last_message
 
1071
                    #      ]
 
1072
                    # where 
 
1073
                    #     cmd_type is 'primary', 'external', or 'cusdep'
 
1074
                    #     ext_cmd is string for associated external command
 
1075
                    #       with substitutions (%D for destination, %S
 
1076
                    #       for source, %B for base of current rule,
 
1077
                    #       %R for base of primary tex file, %T for
 
1078
                    #       texfile name, and %O for options.
 
1079
                    #     int_cmd specifies any internal command to be
 
1080
                    #       used to implement the application of the
 
1081
                    #       rule.  If this is present, it overrides
 
1082
                    #       the external command, and it is the
 
1083
                    #       responsibility of the perl subroutine
 
1084
                    #       specified in intcmd to execute the
 
1085
                    #       external command if this is appropriate.
 
1086
                    #       This variable intcmd is a reference to an array,  
 
1087
                    #       $$intcmd[0] = internal routine
 
1088
                    #       $$intcmd[1...] = its arguments (if any)
 
1089
                    #     test_kind specifies method of determining
 
1090
                    #       whether a file is out-of-date:
 
1091
                    #         0 for never
 
1092
                    #         1 for usual: whether there is a source
 
1093
                    #              file change 
 
1094
                    #         2 for dest earlier than source
 
1095
                    #         3 for method 2 at first run, 1 thereafter
 
1096
                    #              (used when don't have file data from
 
1097
                    #              previous run).
 
1098
                    #     source = name of primary source file, if any
 
1099
                    #     dest   = name of primary destination file,
 
1100
                    #              if any
 
1101
                    #     base   = base name, if any, of files for
 
1102
                    #              this rule
 
1103
                    #     out_of_date = 1 if it has been detected that
 
1104
                    #                     this rule needs to be run
 
1105
                    #                     (typically because a source
 
1106
                    #                     file has changed).
 
1107
                    #                   0 otherwise
 
1108
                    #     out_of_date_user is like out_of_date, except
 
1109
                    #         that the detection of out-of-dateness
 
1110
                    #         has been made from a change of a
 
1111
                    #         putative user file, i.e., one that is
 
1112
                    #         not a generated file (e.g., aux). This
 
1113
                    #         kind of out-of-dateness should provoke a
 
1114
                    #         rerun where or not there was an error
 
1115
                    #         during a run of (pdf)LaTeX.  Normally,
 
1116
                    #         if there is an error, one should wait
 
1117
                    #         for the user to correct the error.  But
 
1118
                    #         it is possible the error condition is
 
1119
                    #         already corrected during the run, e.g.,
 
1120
                    #         by the user changing a source file in
 
1121
                    #         response to an error message. 
 
1122
                    #     time_of_last_run = time that this rule was
 
1123
                    #              last applied.  (In standard units
 
1124
                    #              from perl, to be directly compared
 
1125
                    #              with file modification times.)
 
1126
                    #     changed flags whether special changes have been made
 
1127
                    #          that require file-existence status to be ignored
 
1128
                    #     last_result is 
 
1129
                    #                 -1 if no run has been made,
 
1130
                    #                  0 if the last run was successful
 
1131
                    #                  1 if last run was successful, but
 
1132
                    #                    failed to create an output file
 
1133
                    #                  2 if last run failed
 
1134
                    #     last_message is error message for last run
 
1135
                    #   1: {Hash sourcefile -> [source-file data] }
 
1136
                    # Source-file data array: 
 
1137
                    #   0: time
 
1138
                    #   1: size
 
1139
                    #   2: md5
 
1140
                    #   3: name of rule to make this file
 
1141
                    #   4: whether the file is of the kind made by epstopdf.sty 
 
1142
                    #      during a primary run.  It will have been read during
 
1143
                    #      the run, so that even though the file changes during
 
1144
                    #      a primary run, there is no need to trigger another 
 
1145
                    #      run because of this.
 
1146
                    #  Size and md5 correspond to the values at the last run.
 
1147
                    #  But time may be updated to correspond to the time
 
1148
                    #  for the file, if the file is otherwise unchanged.
 
1149
                    #  This saves excessive md5 calculations, which would
 
1150
                    #  otherwise be done everytime the file is checked, 
 
1151
                    #  in the following situation:
 
1152
                    #     When the file has been rewritten after a run
 
1153
                    #     has started (commonly aux, bbl files etc),
 
1154
                    #     but the actual file contents haven't
 
1155
                    #     changed.  Then because the filetime has
 
1156
                    #     changed, on every file-change check latexmk
 
1157
                    #     would normally redo the md5 calculation to
 
1158
                    #     test for actual changes.  Once one such
 
1159
                    #     check is done, and the contents are
 
1160
                    #     unchanged, later checks are superfluous, and
 
1161
                    #     can be avoided by changing the file's time
 
1162
                    #     in the source-file list.
 
1163
 
 
1164
%fdb_current = ();  # Fdb-hash for all files used.
 
1165
 
 
1166
 
 
1167
#==================================================
718
1168
## Read rc files:
719
1169
 
720
 
# Read first system rc file that is found:
721
 
SYSTEM_RC_FILE:
722
 
foreach $rc_file ( @rc_system_files )
723
 
{
724
 
   # print "===Testing for system rc file \"$rc_file\" ...\n";
725
 
   if ( -e $rc_file )
726
 
   {
727
 
      # print "===Reading system rc file \"$rc_file\" ...\n";
728
 
      # Read the system rc file
729
 
      do "$rc_file";
730
 
      last SYSTEM_RC_FILE;
731
 
   }
732
 
}
733
 
 
 
1170
# User's home directory
 
1171
$HOME = '';
 
1172
if (exists $ENV{'HOME'} ) {
 
1173
    $HOME = $ENV{'HOME'};
 
1174
}
 
1175
elsif (exists $ENV{'USERPROFILE'} ) {
 
1176
    $HOME = $ENV{'USERPROFILE'};
 
1177
}
 
1178
 
 
1179
 
 
1180
 
 
1181
sub read_first_rc_file_in_list {
 
1182
    foreach my $rc_file ( @_ ) {
 
1183
        #print "===Testing for rc file \"$rc_file\" ...\n";
 
1184
        if ( -e $rc_file ) {
 
1185
            #print "===Reading rc file \"$rc_file\" ...\n";
 
1186
            process_rc_file( $rc_file );
 
1187
            return;
 
1188
        }
 
1189
    }
 
1190
}
 
1191
 
 
1192
# Read system rc file:
 
1193
read_first_rc_file_in_list( @rc_system_files );
734
1194
# Read user rc file.
735
 
$rc_file = "$ENV{'HOME'}/.latexmkrc";
736
 
if ( -e $rc_file )
737
 
{
738
 
  # Read the user rc file
739
 
  do "$rc_file";
740
 
}
741
 
 
 
1195
read_first_rc_file_in_list( "$HOME/.latexmkrc" );
742
1196
# Read rc file in current directory.
743
 
$rc_file = "latexmkrc";
744
 
if ( -e $rc_file )
745
 
{
746
 
  # Read the user rc file
747
 
  do "$rc_file";
 
1197
read_first_rc_file_in_list( "latexmkrc", ".latexmkrc" );
 
1198
 
 
1199
#==================================================
 
1200
 
 
1201
if ($bibtex_use > 1) {
 
1202
    push @generated_exts, 'bbl';
748
1203
}
749
1204
 
 
1205
#show_array ("BIBINPUTS", @BIBINPUTS); die;
 
1206
 
750
1207
## Process command line args.
751
1208
@command_line_file_list = ();
752
1209
$bad_options = 0;
 
1210
 
 
1211
#print "Command line arguments:\n"; for ($i = 0; $i <= $#ARGV; $i++ ) {  print "$i: '$ARGV[$i]'\n"; }
 
1212
 
753
1213
while ($_ = $ARGV[0])
754
1214
{
755
1215
  # Make -- and - equivalent at beginning of option:
756
1216
  s/^--/-/;
757
1217
  shift;
758
 
  if (/^-c$/)        { $cleanup_mode = 2; }
 
1218
  if (/^-bibtex$/) { $bibtex_use = 2; }
 
1219
  elsif (/^-bibtex-$/) { $bibtex_use = 0; }
 
1220
  elsif (/^-nobibtex$/) { $bibtex_use = 0; }
 
1221
  elsif (/^-bibtex-cond$/) { $bibtex_use = 1; }
 
1222
  elsif (/^-c$/)        { $cleanup_mode = 2; $cleanup_fdb = 1; $cleanup_only = 1; }
 
1223
  elsif (/^-C$/ || /^-CA$/ ) { $cleanup_mode = 1; $cleanup_fdb = 1; $cleanup_only = 1; }
 
1224
  elsif (/^-CF$/)    { $cleanup_fdb = 1; }
 
1225
  elsif (/^-cd$/)    { $do_cd = 1; }
 
1226
  elsif (/^-cd-$/)   { $do_cd = 0; }
759
1227
  elsif (/^-commands$/) { &print_commands; exit; }
760
 
  elsif (/^-C$/)     { $cleanup_mode = 1; }
761
 
  elsif (/^-c1$/)    { $cleanup_mode = 3; }
762
1228
  elsif (/^-d$/)     { $banner = 1; }
 
1229
  elsif (/^-dependents$/) { $dependents_list = 1; }
 
1230
  elsif (/^-nodependents$/ || /^-dependents-$/) { $dependents_list = 0; }
763
1231
  elsif (/^-dvi$/)   { $dvi_mode = 1; }
764
1232
  elsif (/^-dvi-$/)  { $dvi_mode = 0; }
 
1233
  elsif (/^-F$/)     { $force_include_mode = 1; }
 
1234
  elsif (/^-F-$/)    { $force_include_mode = 0; }
765
1235
  elsif (/^-f$/)     { $force_mode = 1; }
766
1236
  elsif (/^-f-$/)    { $force_mode = 0; }
767
 
  elsif (/^-F$/)     { $force_include_mode = 1; }
768
 
  elsif (/^-F-$/)    { $force_include_mode = 0; }
769
1237
  elsif (/^-g$/)     { $go_mode = 1; }
770
1238
  elsif (/^-g-$/)    { $go_mode = 0; }
771
 
  elsif ( /^-h$/ || /^-help$/ )   { &print_help; }
772
 
  elsif (/^-il$/)    { $includes_from_log = 1; }
773
 
  elsif (/^-it$/)    { $includes_from_log = 0; }
774
 
  elsif (/^-i$/)     { $generate_and_save_includes = 1; }
775
 
  elsif (/^-i-$/)    { $generate_and_save_includes = 0; }
776
 
  elsif (/^-I$/)     { $force_generate_and_save_includes = 1; }
777
 
  elsif (/^-I-$/)    { $force_generate_and_save_includes = 0; }
 
1239
  elsif (/^-gg$/)    { 
 
1240
     $go_mode = 2; $cleanup_mode = 1; $cleanup_fdb = 1; $cleanup_only = 0; 
 
1241
  }
 
1242
  elsif ( /^-h$/ || /^-help$/ )   { &print_help; exit;}
778
1243
  elsif (/^-diagnostics/) { $diagnostics = 1; }
 
1244
  elsif (/^-jobname=(.*)$/) {
 
1245
      $jobname = $1;
 
1246
  }
779
1247
  elsif (/^-l$/)     { $landscape_mode = 1; }
780
1248
  elsif (/^-l-$/)    { $landscape_mode = 0; }
 
1249
  elsif (/^-new-viewer$/) {
 
1250
                       $new_viewer_always = 1; 
 
1251
  }
 
1252
  elsif (/^-new-viewer-$/) {
 
1253
                       $new_viewer_always = 0; 
 
1254
  }
781
1255
  elsif (/^-p$/)     { $printout_mode = 1; 
782
1256
                       $preview_continuous_mode = 0; # to avoid conflicts
783
1257
                       $preview_mode = 0;  
794
1268
          $printout_mode = 1;
795
1269
      }
796
1270
      else {
797
 
          &die_help("Latexmk: unknown print type '$value' in option '$_'");
 
1271
          &exit_help("$My_name: unknown print type '$value' in option '$_'");
798
1272
      }
799
1273
  }
800
1274
  elsif (/^-ps$/)    { $postscript_mode = 1; }
818
1292
  elsif (/^-verbose$/)  { $silent = 0; }
819
1293
  elsif (/^-view=default$/) { $view = "default";}
820
1294
  elsif (/^-view=dvi$/)     { $view = "dvi";}
 
1295
  elsif (/^-view=none$/)    { $view = "none";}
821
1296
  elsif (/^-view=ps$/)      { $view = "ps";}
822
1297
  elsif (/^-view=pdf$/)     { $view = "pdf"; }
 
1298
  elsif (/^-e$/) {  
 
1299
     if ( $#ARGV < 0 ) {
 
1300
        &exit_help( "No code to execute specified after -e switch"); 
 
1301
     }
 
1302
     execute_code_string( $ARGV[0] );
 
1303
     shift;
 
1304
  }
823
1305
  elsif (/^-r$/) {  
824
1306
     if ( $ARGV[0] eq '' ) {
825
 
        &die_help( "Latexmk: No RC file specified after -r switch"); 
 
1307
        &exit_help( "No RC file specified after -r switch"); 
826
1308
     }
827
1309
     if ( -e $ARGV[0] ) {
828
 
        do "$ARGV[0]"; } else {
829
 
        die "Latexmk: RC file [$ARGV[0]] does not exist\n"; 
 
1310
        process_rc_file( $ARGV[0] );
 
1311
     } 
 
1312
     else {
 
1313
        $! = 11;
 
1314
        die "$My_name: RC file [$ARGV[0]] does not exist\n"; 
830
1315
     }
831
1316
     shift; 
832
1317
  }
833
1318
  elsif (/^-bm$/) {
834
1319
     if ( $ARGV[0] eq '' ) {
835
 
        &die_help( "Latexmk: No message specified after -bm switch");
 
1320
        &exit_help( "No message specified after -bm switch");
836
1321
     }
837
1322
     $banner = 1; $banner_message = $ARGV[0];
838
1323
     shift; 
839
1324
  }
840
1325
  elsif (/^-bi$/) {
841
1326
     if ( $ARGV[0] eq '' ) {
842
 
        &die_help( "Latexmk: No intensity specified after -bi switch");
 
1327
        &exit_help( "No intensity specified after -bi switch");
843
1328
     }
844
1329
     $banner_intensity = $ARGV[0];
845
1330
     shift; 
846
1331
  }
847
1332
  elsif (/^-bs$/) {
848
1333
     if ( $ARGV[0] eq '' ) {
849
 
        &die_help( "Latexmk: No scale specified after -bs switch");
 
1334
        &exit_help( "No scale specified after -bs switch");
850
1335
     }
851
1336
     $banner_scale = $ARGV[0];
852
1337
     shift; 
853
1338
  }
854
1339
  elsif (/^-dF$/) {
855
1340
     if ( $ARGV[0] eq '' ) {
856
 
        &die_help( "Latexmk: No dvi filter specified after -dF switch");
 
1341
        &exit_help( "No dvi filter specified after -dF switch");
857
1342
     }
858
1343
     $dvi_filter = $ARGV[0];
859
1344
     shift; 
860
1345
  }
861
1346
  elsif (/^-pF$/) {
862
1347
     if ( $ARGV[0] eq '' ) {
863
 
        &die_help( "Latexmk: No ps filter specified after -pF switch");
 
1348
        &exit_help( "No ps filter specified after -pF switch");
864
1349
     }
865
1350
     $ps_filter = $ARGV[0];
866
1351
     shift; 
867
1352
  }
868
1353
  elsif (/^-/) {
869
 
     warn "Latexmk: $_ bad option\n"; 
 
1354
     warn "$My_name: $_ bad option\n"; 
870
1355
     $bad_options++;
871
1356
  }
872
1357
  else {
875
1360
}
876
1361
 
877
1362
if ( $bad_options > 0 ) {
878
 
    &die_help( "Bad options specified" );
 
1363
    &exit_help( "Bad options specified" );
879
1364
}
880
1365
 
881
 
warn "This is $version_details, version: $version_num.\n",
 
1366
warn "$My_name: This is $version_details, version: $version_num.\n",
882
1367
     "**** Report bugs etc to John Collins <collins at phys.psu.edu>. ****\n"
883
1368
   unless $silent;
884
1369
 
889
1374
    @default_files = split / /, "*.tex $texfile_search";
890
1375
}
891
1376
 
 
1377
#printA "A: Command line file list:\n";
 
1378
#for ($i = 0; $i <= $#command_line_file_list; $i++ ) {  print "$i: '$command_line_file_list[$i]'\n"; }
 
1379
 
892
1380
#Glob the filenames command line if the script was not invoked under a 
893
1381
#   UNIX-like environment.
894
1382
#   Cases: (1) MS/MSwin native    Glob
900
1388
#          (3) UNIX               Don't glob (cmd interpreter does it)
901
1389
#                      (Currently, I assume this is everything else)
902
1390
if ( ($^O eq "MSWin32") || ($^O eq "cygwin") ) {
903
 
    @file_list = glob_list(@command_line_file_list);
 
1391
    # Preserve ordering of files
 
1392
    @file_list = glob_list1(@command_line_file_list);
 
1393
#print "A1:File list:\n";
 
1394
#for ($i = 0; $i <= $#file_list; $i++ ) {  print "$i: '$file_list[$i]'\n"; }
904
1395
}
905
1396
else {
906
 
    @file_list = uniq( sort(@command_line_file_list) );
 
1397
    @file_list = @command_line_file_list;
 
1398
#print "A2:File list:\n";
 
1399
#for ($i = 0; $i <= $#file_list; $i++ ) {  print "$i: '$file_list[$i]'\n"; }
907
1400
}
 
1401
@file_list = uniq1( @file_list );
 
1402
 
908
1403
 
909
1404
# Check we haven't selected mutually exclusive modes.
910
1405
# Note that -c overides all other options, but doesn't cause
915
1410
  # Each of the options -p, -pv, -pvc turns the other off.
916
1411
  # So the only reason to arrive here is an incorrect inititalization
917
1412
  #   file, or a bug.
918
 
  &die_help( "Latexmk: Conflicting options (print, preview, preview_continuous) selected");
 
1413
  &exit_help( "Conflicting options (print, preview, preview_continuous) selected");
919
1414
}
920
1415
 
921
1416
if ( @command_line_file_list ) {   
922
1417
    # At least one file specified on command line (before possible globbing).
923
1418
    if ( !@file_list ) {
924
 
        &die_help( "Latexmk: Wildcards in file names didn't match any files");
 
1419
        &exit_help( "Wildcards in file names didn't match any files");
925
1420
    }
926
1421
}
927
1422
else {
928
1423
    # No files specified on command line, try and find some
929
 
    @file_list = glob_list(@default_files);
 
1424
    # Evaluate in order specified.  The user may have some special
 
1425
    #   for wanting processing in a particular order, especially
 
1426
    #   if there are no wild cards.
 
1427
    # Preserve ordering of files
 
1428
    my @file_list1 = uniq1( glob_list1(@default_files) );
 
1429
    my @excluded_file_list = uniq1( glob_list1(@default_excluded_files) );
 
1430
    # Make hash of excluded files, for easy checking:
 
1431
    my %excl = ();
 
1432
    foreach my $file (@excluded_file_list) {
 
1433
        $excl{$file} = '';
 
1434
    }
 
1435
    foreach my $file (@file_list1) {
 
1436
        push( @file_list, $file)  unless ( exists $excl{$file} );
 
1437
    }    
930
1438
    if ( !@file_list ) {
931
 
        &die_help( "Latexmk: No file name specified, and I couldn't find any");
 
1439
        &exit_help( "No file name specified, and I couldn't find any");
932
1440
    }
933
1441
}
934
1442
 
935
1443
$num_files = $#file_list + 1;
936
1444
$num_specified = $#command_line_file_list + 1;
937
1445
 
 
1446
#print "Command line file list:\n";
 
1447
#for ($i = 0; $i <= $#command_line_file_list; $i++ ) {  print "$i: '$command_line_file_list[$i]'\n"; }
 
1448
#print "File list:\n";
 
1449
#for ($i = 0; $i <= $#file_list; $i++ ) {  print "$i: '$file_list[$i]'\n"; }
 
1450
 
 
1451
 
938
1452
# If selected a preview-continuous mode, make sure exactly one filename was specified
939
1453
if ($preview_continuous_mode && ($num_files != 1) ) {
940
 
    if ($num_specified > 0) {
941
 
        &die_help( 
942
 
          "Latexmk: Need to specify exactly one filename for ".
 
1454
    if ($num_specified > 1) {
 
1455
        &exit_help( 
 
1456
          "Need to specify exactly one filename for ".
943
1457
              "preview-continuous mode\n".
944
1458
          "    but $num_specified were specified"
945
1459
        );
946
1460
    }
947
1461
    elsif ($num_specified == 1) {
948
 
        &die_help( 
949
 
          "Latexmk: Need to specify exactly one filename for ".
 
1462
        &exit_help( 
 
1463
          "Need to specify exactly one filename for ".
950
1464
              "preview-continuous mode\n".
951
1465
          "    but wildcarding produced $num_files files"
952
1466
        );
953
1467
    }
954
1468
    else {
955
 
        &die_help( 
956
 
          "Latexmk: Need to specify exactly one filename for ".
 
1469
        &exit_help( 
 
1470
          "Need to specify exactly one filename for ".
957
1471
              "preview-continuous mode.\n".
958
1472
          "    Since none were specified on the command line, I looked for \n".
959
1473
          "    files in '@default_files'.\n".
962
1476
    }
963
1477
}
964
1478
 
 
1479
# If selected jobname, can only apply that to one file:
 
1480
if ( ($jobname ne '') && ($num_files > 1) ) {
 
1481
    &exit_help( 
 
1482
          "Need to specify at most one filename if ".
 
1483
          "jobname specified, \n".
 
1484
          "    but $num_files were found (after defaults and wildcarding)."
 
1485
        );
 
1486
}
 
1487
 
 
1488
 
 
1489
# Normalize the commands, to have place-holders for source, dest etc:
 
1490
&fix_cmds;
965
1491
 
966
1492
# If landscape mode, change dvips processor, and the previewers:
967
1493
if ( $landscape_mode )
972
1498
}
973
1499
 
974
1500
if ( $silent ) { 
975
 
    $latex .= " $latex_silent_switch"; 
976
 
    $pdflatex .= " $pdflatex_silent_switch"; 
977
 
    $bibtex .= " $bibtex_silent_switch"; 
978
 
    $dvips .= " $dvips_silent_switch"; 
979
 
}
980
 
 
981
 
# Which files do we need to make?
982
 
$need_dvi = $need_ps = $need_pdf = 0;
 
1501
    add_option( \$latex, " $latex_silent_switch" ); 
 
1502
    add_option( \$pdflatex, " $pdflatex_silent_switch" ); 
 
1503
    add_option( \$bibtex, " $bibtex_silent_switch" ); 
 
1504
    add_option( \$makeindex, " $makeindex_silent_switch" ); 
 
1505
    add_option( \$dvips, " $dvips_silent_switch" ); 
 
1506
}
 
1507
 
 
1508
if ( $jobname ne '' ) { 
 
1509
    $jobstring = "--jobname=$jobname";
 
1510
    add_option( \$latex, " $jobstring" ); 
 
1511
    add_option( \$pdflatex, " $jobstring" ); 
 
1512
}
 
1513
 
983
1514
# Which kind of file do we preview?
984
1515
if ( $view eq "default" ) {
985
1516
    # If default viewer requested, use "highest" of dvi, ps and pdf
990
1521
    if ( $pdf_mode ) { $view = "pdf"; }
991
1522
}
992
1523
 
993
 
# Now check all the requirements that force us to make files.
994
 
$need_dvi = $dvi_mode;
995
 
$need_ps  = $postscript_mode;
996
 
$need_pdf = $pdf_mode;
997
 
if ( $preview_continuous_mode || $preview_mode ) {
998
 
    if ( $view eq "dvi" ) {$need_dvi = 1; }
999
 
    if ( $view eq "ps" )  {$need_ps = 1; }
1000
 
    if ( $view eq "pdf" ) {
1001
 
        # Which of the two ways to make pdf files do we use?
1002
 
        if ( $need_pdf ) {
1003
 
            # We already have been told how to make pdf files
1004
 
        }
1005
 
        else {
1006
 
            # Use pdflatex route:
1007
 
            $need_pdf = 1; 
1008
 
        }
1009
 
    }
1010
 
}
1011
 
 
1012
 
# What implicit requests are made?
1013
 
if ( length($dvi_filter) != 0 ) {$need_dvi = 1; }
1014
 
if ( length($ps_filter) != 0 )  {$need_ps = 1; }
1015
 
if ( $banner ) { $need_ps = 1; }
1016
 
# printout => need ps
1017
 
if ( $printout_mode ) { 
1018
 
    ## May be wrong if print from other kinds of file
1019
 
    if ( $print_type eq 'dvi' ) {
1020
 
        $need_dvi = 1; 
1021
 
    }
1022
 
    elsif ( $print_type eq 'none' ) {
1023
 
        # Nothing
1024
 
    }
1025
 
    elsif ( $print_type eq 'pdf' ) {
1026
 
        # Will need a pdf file, but there are several methods to make it
1027
 
        # Respect a previous request, otherwise get pdf by pdflatex
1028
 
        if ( $need_pdf == 0 ) {
1029
 
            $need_pdf = 1; 
1030
 
        }
1031
 
    }
1032
 
    elsif ( $print_type eq 'ps' ) {
1033
 
        $need_ps = 1; 
1034
 
    }
1035
 
    else {
1036
 
     die "Latexmk: incorrect value \"$print_type\" for type of file to print\n".
1037
 
         "Allowed values are \"dvi\", \"pdf\", \"ps\", \"none\"\n"
1038
 
    }
1039
 
}
1040
 
 
1041
 
# pdf file by ps2pdf => ps file needed. 
1042
 
if ( $need_pdf == 3 ) { $need_dvi = 1; }
1043
 
if ( $need_pdf == 2 ) { $need_ps = 1; }
1044
 
# postscript file => dvi file needed. 
1045
 
if ( $need_ps ) { $need_dvi = 1; }
1046
 
 
1047
 
# If no files requested, default to dvi:
1048
 
if ( ! ($need_dvi || $need_ps || $need_pdf) ) { $need_dvi = 1; }
1049
 
 
1050
 
if ( $need_pdf == 2 ) {
 
1524
# Make sure we make the kind of file we want to view:
 
1525
if ($view eq 'dvi') { $dvi_mode = 1; }
 
1526
if ($view eq 'ps') { $postscript_mode = 1; }
 
1527
if ( ($view eq 'pdf') && ($pdf_mode == 0) ) { 
 
1528
    $pdf_mode = 1; 
 
1529
}
 
1530
 
 
1531
# Make sure that we make something if all requests are turned off
 
1532
if ( ! ( $dvi_mode || $pdf_mode || $postscript_mode || $printout_mode) ) {
 
1533
    print "No specific requests made, so default to dvi by latex\n";
 
1534
    $dvi_mode = 1;
 
1535
}
 
1536
 
 
1537
# Set new-style requested rules:
 
1538
if ( $dvi_mode ) { $requested_filerules{'latex'} = 1; }
 
1539
if ( $pdf_mode == 1 ) { $requested_filerules{'pdflatex'} = 1; }
 
1540
elsif ( $pdf_mode == 2 ) { 
 
1541
   $requested_filerules{'latex'} = 1;
 
1542
   $requested_filerules{'dvips'} = 1;
 
1543
   $requested_filerules{'ps2pdf'} = 1; 
 
1544
}
 
1545
elsif ( $pdf_mode == 3 ) { 
 
1546
   $requested_filerules{'latex'} = 1;
 
1547
   $requested_filerules{'dvipdf'} = 1; 
 
1548
}
 
1549
if ( $postscript_mode ) { 
 
1550
   $requested_filerules{'latex'} = 1; 
 
1551
   $requested_filerules{'dvips'} = 1; 
 
1552
}
 
1553
if ( $printout_mode ) { $one_time{'print'} = 1; }
 
1554
if ( $preview_continuous_mode || $preview_mode ) { $one_time{'view'} = 1; }
 
1555
if ( length($dvi_filter) != 0 ) { $requested_filerules{'dvi_filter'} = 1; }
 
1556
if ( length($ps_filter) != 0 )  { $requested_filerules{'ps_filter'} = 1; }
 
1557
if ( $banner ) { $requested_filerules{'dvips'} = 1; }
 
1558
 
 
1559
 
 
1560
if ( $pdf_mode == 2 ) {
1051
1561
    # We generate pdf from ps.  Make sure we have the correct kind of ps.
1052
 
    $dvips .= " $dvips_pdf_switch";
 
1562
    add_option( \$dvips, " $dvips_pdf_switch" );
1053
1563
}
1054
1564
 
1055
 
# Which conversions do we need to make?
1056
 
$tex_to_dvi = $dvi_to_ps = $ps_to_pdf = $dvi_to_pdf = $tex_to_pdf = 0;
1057
 
if ($need_dvi) { $tex_to_dvi = 1; }
1058
 
if ($need_ps) { $dvi_to_ps = 1; }
1059
 
if ($need_pdf == 1) { $tex_to_pdf = 1; }
1060
 
if ($need_pdf == 2) { $ps_to_pdf = 1; }
1061
 
if ($need_pdf == 3) { $dvi_to_pdf = 1; }
1062
1565
 
1063
1566
# Make convenient forms for lookup.
1064
1567
# Extensions always have period.
1065
1568
 
1066
 
# Convert @generated_exts to a hash for ease of look up, with exts preceeded 
1067
 
# by a '.'
1068
 
%generated_exts = ();
1069
 
foreach (@generated_exts) {
1070
 
    $generated_exts{".$_"} = 1;
 
1569
# Convert @generated_exts to a hash for ease of look up and deletion
 
1570
# Keep extension without period!
 
1571
%generated_exts_all = ();
 
1572
foreach (@generated_exts ) {
 
1573
    $generated_exts_all{$_} = 1;
1071
1574
}
1072
1575
 
1073
1576
$quell_uptodate_msgs = $silent; 
1077
1580
# Process for each file.
1078
1581
# The value of $bibtex_mode set in an initialization file may get
1079
1582
# overridden, during file processing, so save it:
1080
 
$save_bibtex_mode = $bibtex_mode;
 
1583
#?? Unneeded now: $save_bibtex_mode = $bibtex_mode;
1081
1584
 
 
1585
$failure_count = 0;
 
1586
$last_failed = 0;    # Flag whether failed on making last file
 
1587
                     # This is used for showing suitable error diagnostics
1082
1588
FILE:
1083
1589
foreach $filename ( @file_list )
1084
1590
{
 
1591
    # Global variables for making of current file:
 
1592
    $updated = 0;
1085
1593
    $failure = 0;        # Set nonzero to indicate failure at some point of 
1086
1594
                         # a make.  Use value as exit code if I exit.
1087
1595
    $failure_msg = '';   # Indicate reason for failure
1088
 
    $bibtex_mode = $save_bibtex_mode;
 
1596
 
 
1597
    if ( $do_cd ) {
 
1598
       ($filename, $path) = fileparse( $filename );
 
1599
       warn "$My_name: Changing directory to '$path'\n";
 
1600
       pushd( $path );
 
1601
    }
 
1602
    else {
 
1603
        $path = '';
 
1604
    }
 
1605
 
 
1606
 
1089
1607
    ## remove extension from filename if was given.
1090
1608
    if ( &find_basename($filename, $root_filename, $texfile_name) )
1091
1609
    {
1092
1610
        if ( $force_mode ) {
1093
 
           warn "Latexmk: Could not find file [$texfile_name]\n";
 
1611
           warn "$My_name: Could not find file [$texfile_name]\n";
1094
1612
        }
1095
1613
        else {
 
1614
            &ifcd_popd;
1096
1615
            &exit_msg1( "Could not find file [$texfile_name]",
1097
 
                        1);
1098
 
        }
1099
 
    }
1100
 
 
1101
 
    if ($cleanup_mode > 0)
1102
 
    {
1103
 
        ## Do clean if necessary
1104
 
        &cleanup_basic;
1105
 
        if ( $cleanup_mode != 2 ) { &cleanup_dvi_ps_pdf; }
1106
 
        if ( $cleanup_mode != 3 ) { &cleanup_aux_dep; }
1107
 
        next FILE;
1108
 
    }
1109
 
    if ($go_mode == 2) {
1110
 
        warn "Latexmk: Removing all generated files\n" unless $silent;
1111
 
        &cleanup_dvi_ps_pdf;
1112
 
        &cleanup_aux_dep;
1113
 
    }
1114
 
    #Default aux file list:
1115
 
    @aux_files = ("$root_filename.aux");
1116
 
    ## Make file. ##
1117
 
    ## Find includes.
1118
 
    @includes = ();         # Input files 
1119
 
    %includes_missing = (); # Possible input files, status problematic:
1120
 
        # filename => [wherefrom, fullname]
1121
 
        # wherefrom  0: exact name known. 
1122
 
        #            1: name for non-existent file, from logfile, possibly 
1123
 
        #                   bad parse, possibly it's been deleted.
1124
 
        #            2: not necessarily fullname, from logfile, probably OK
1125
 
        #                   (graphics file, typically).  
1126
 
        #                   File not found by latexmk.
1127
 
        #            3: possibly incomplete (pathless, possibly extension-less)
1128
 
        #                   name from error message in .log file
1129
 
        #            4: non-found file from .tex file: either non-existent file
1130
 
        #                   or I didn't find it.
1131
 
    $read_depend = 0;  # True to read depend file, false to generate it.
1132
 
    $dep_file = "$root_filename.dep";
1133
 
 
1134
 
    ## Figure out if we read the dependency file or generate a new one.
1135
 
    if ( ! $force_generate_and_save_includes )
1136
 
    {
1137
 
      if ( $generate_and_save_includes )
1138
 
      {
1139
 
        if ( -e $dep_file )
1140
 
        {
1141
 
          # Compare timestamp of dependency file and root tex file.
1142
 
          $dep_mtime = &get_mtime("$dep_file");
1143
 
          $tex_mtime = &get_mtime("$texfile_name");
1144
 
          if ( $tex_mtime < $dep_mtime )
1145
 
          {
1146
 
            $read_depend = 1;
1147
 
          }
1148
 
        }
1149
 
      }
1150
 
      elsif ( -e $dep_file )  # If dependency file already exists.
1151
 
      {
1152
 
        $read_depend = 1;
1153
 
      }
1154
 
    }
1155
 
 
1156
 
    if ( $includes_from_log )
1157
 
    {
1158
 
       &parse_log;
1159
 
       if ( $force_generate_and_save_includes 
1160
 
            || ($generate_and_save_includes && $read_depend == 0 )
1161
 
          )
1162
 
       {
1163
 
          &update_depend_file;
1164
 
       }
1165
 
    }
1166
 
    elsif ( $read_depend )
1167
 
    {
1168
 
      # Read the dependency file
1169
 
      open(dep_file) || die "Latexmk: Couldn't open dependency file [$root_filename.dep]\n";
1170
 
      while(<dep_file>) { eval; }
1171
 
      close(dep_file);
1172
 
    }
1173
 
    else
1174
 
    {
1175
 
      # Generate dependency file.
1176
 
      &scan_for_includes("$texfile_name"); 
1177
 
      &update_depend_file;
1178
 
    }
1179
 
 
1180
 
#    warn "====@includes===\n";
 
1616
                        11);
 
1617
        }
 
1618
    }
 
1619
    if ($jobname ne '' ) {
 
1620
        $root_filename = $jobname;
 
1621
    }
 
1622
 
 
1623
    # Initialize basic dependency information:
 
1624
 
 
1625
    # For use under error conditions:
 
1626
    @default_includes = ($texfile_name, "$root_filename.aux");  
 
1627
 
 
1628
    $fdb_file = "$root_filename.$fdb_ext";
 
1629
    
 
1630
    if ( $cleanup_mode > 0 ) {
 
1631
        # Use parse_logB to get names of generated files.
 
1632
        # It returns its results in the following variables:
 
1633
        local %dependents = ();    # Maps files to status
 
1634
        local @bbl_files = ();
 
1635
        local %idx_files = ();     # Maps idx_file to (ind_file, base)
 
1636
        local %generated_log = (); # Lists generated files
 
1637
        local $primary_out = '';   # Actual output file (dvi or pdf)
 
1638
        local %conversions = ();   # (pdf)latex-performed conversions.
 
1639
                     # Maps output file created and read by (pdf)latex
 
1640
                     #    to source file of conversion.
 
1641
        print "$My_name: Examining log file for generated files...\n";
 
1642
        &parse_logB;
 
1643
 
 
1644
        my @index_bibtex_generated = ();
 
1645
        my @aux_files = ();
 
1646
        my %other_generated = %generated_log;
 
1647
 
 
1648
        rdb_read_generatedB( $fdb_file, \@index_bibtex_generated, \@aux_files, 
 
1649
                             \%other_generated );
 
1650
        if ( ($go_mode == 2) && !$silent ) {
 
1651
            warn "$My_name: Removing all generated files\n" unless $silent;
 
1652
        }
 
1653
        if ($bibtex_use < 2) { 
 
1654
           delete $generated_exts_all{'bbl'}; 
 
1655
        }
 
1656
        my %index_bibtex_generated = ();
 
1657
        my %aux_files = ();
 
1658
        foreach (@index_bibtex_generated) {
 
1659
            $index_bibtex_generated{$_} = 1
 
1660
             unless ( /\.bbl$/ && ($bibtex_use < 2) );
 
1661
            delete( $other_generated{$_} );
 
1662
        }
 
1663
        foreach (@aux_files) {
 
1664
            $aux_files{$_} = 1;
 
1665
            delete( $other_generated{$_} );
 
1666
        }
 
1667
        if ($diagnostics) {
 
1668
            show_array( "For deletion:\n"
 
1669
                       ." Generated (from makeindex and bibtex):", 
 
1670
                        keys %index_bibtex_generated );
 
1671
            show_array( " Aux files:", keys %aux_files );
 
1672
            show_array( "Other generated files:\n"
 
1673
                       ." (only deleted if \$cleanup_includes_generated is set): ",
 
1674
                        keys %other_generated );
 
1675
        }
 
1676
        # Add to the generated files, some log file and some backup
 
1677
        #    files used in previous versions of latexmk
 
1678
        &cleanup1( $fdb_ext, 'blg', 'ilg', 'log', 'aux.bak', 'idx.bak', 
 
1679
                   split(' ',$clean_ext), 
 
1680
                   keys %generated_exts_all 
 
1681
                 );
 
1682
        unlink( 'texput.log', "texput.aux", 
 
1683
                keys %index_bibtex_generated, 
 
1684
                keys %aux_files );
 
1685
        if ($cleanup_includes_generated) {
 
1686
            unlink( keys %other_generated );
 
1687
        }
 
1688
        if ( $cleanup_mode == 1 ) { 
 
1689
            &cleanup1( 'dvi', 'dviF', 'ps', 'psF', 'pdf',
 
1690
                       split(' ', $clean_full_ext)
 
1691
                     );
 
1692
        }
 
1693
    }
 
1694
    if ($cleanup_fdb) { unlink $fdb_file; }
 
1695
    if ($cleanup_only) { next FILE; }
 
1696
 
 
1697
    # Initialize file and rule databases.
 
1698
    %rule_list = ();
 
1699
    &rdb_make_rule_list;
 
1700
    &rdb_set_rules(\%rule_list);
 
1701
 
 
1702
 
 
1703
#??? The following are not needed if use makeB.  
 
1704
#    ?? They may be set too early?
 
1705
# Arrays and hashes for picking out accessible rules.
 
1706
# Distinguish rules for making files and others
 
1707
    @accessible_all = sort ( &rdb_accessible( keys %requested_filerules, keys %one_time ));
 
1708
    %accessible_filerules = ();
 
1709
    foreach (@accessible_all) {
 
1710
        unless ( /view/ || /print/ ) { $accessible_filerules{$_} = 1; }
 
1711
    }
 
1712
    @accessible_filerules = sort  keys %accessible_filerules;
 
1713
 
 
1714
#    show_array ( "=======All rules used", @accessible_all );
 
1715
#    show_array ( "=======Requested file rules", sort keys %requested_filerules );
 
1716
#    show_array ( "=======Rules for files", @accessible_filerules );
 
1717
 
 
1718
    if ( $diagnostics ) {
 
1719
       print "$My_name: Rules after start up for '$texfile_name'\n";
 
1720
       rdb_show();
 
1721
    }
 
1722
 
 
1723
    %primaries = ();
 
1724
    foreach (@accessible_all) {
 
1725
        if ( ($_ eq 'latex') || ($_ eq 'pdflatex') ) { $primaries{$_} = 1; }
 
1726
    }
 
1727
 
 
1728
    $have_fdb = 0;
 
1729
    if ( (! -e $fdb_file) && (! -e "$root_filename.aux") ) {
 
1730
        # No aux and no fdb file => set up trivial aux file 
 
1731
        #    and corresponding fdb_file.  Arrange them to provoke one run 
 
1732
        #    as minimum, but no more if actual aux file is trivial.
 
1733
        #    (Useful on big files without cross references.)
 
1734
        &set_trivial_aux_fdb;
 
1735
    }
 
1736
 
 
1737
    if ( -e $fdb_file ) {
 
1738
        $rdb_errors = rdb_read( $fdb_file );
 
1739
        $have_fdb = ($rdb_errors == 0);
 
1740
    }
 
1741
    if (!$have_fdb) { 
 
1742
        # We didn't get a valid set of data on files used in
 
1743
        # previous run.  So use filetime criterion for make
 
1744
        # instead of change from previous run, until we have
 
1745
        # done our own make.
 
1746
        rdb_recurseA( [keys %possible_primaries],
 
1747
                      sub{ if ( $$Ptest_kind == 1 ) { $$Ptest_kind = 3;} }
 
1748
        );
 
1749
        if ( -e "$root_filename.log" ) {
 
1750
            rdb_for_some( [keys %possible_primaries], \&rdb_set_from_logB );
 
1751
        }
 
1752
    }
 
1753
    foreach $rule ( rdb_accessible( uniq1( keys %requested_filerules  )  ) ){
 
1754
        # For all source files of all accessible rules, 
 
1755
        #    if the file data are not already set (e.g., from fdb_latexmk
 
1756
        #    file, set them from disk.
 
1757
        rdb_one_rule ($rule, undef, 
 
1758
                      sub{ if ( $$Ptime == 0) { &rdb_update1; } }
 
1759
        );
 
1760
    }
 
1761
 
 
1762
    if ($go_mode) {
 
1763
        # Force everything to be remade.
 
1764
        rdb_recurseA( [keys %requested_filerules], sub{$$Pout_of_date=1;}  );
 
1765
    }
 
1766
 
 
1767
 
 
1768
    if ( $diagnostics ) {
 
1769
       print "$My_name: Rules after initialization\n";
 
1770
       rdb_show();
 
1771
    }
1181
1772
 
1182
1773
    #************************************************************
1183
1774
 
1184
 
    # Ensure bbl file up-to-date.  
1185
 
    # Also remake the bbl file if there is a bad citation, or if we
1186
 
    #     use go_mode (which says to remake everything)
1187
 
    # The call to &make_bbl will also remake the bbl file if it is
1188
 
    #    out-of-date with respect to the bib files
1189
 
    # But ignore the return code from make_bbl, since the bbl file depends 
1190
 
    # on the aux file, which may in fact be out of date if the tex file has
1191
 
    # changed, and we are about to re-latex it.
1192
 
    if ($bibtex_mode) { 
1193
 
        &make_bbl($bad_citation || $go_mode); 
1194
 
        if ( ($failure > 0) && !$force_mode && ! $preview_continuous_mode) {
1195
 
            goto END_FIRST;
1196
 
        }
1197
 
    }
1198
 
 
1199
 
    # Similarly for ind file.  This is simpler because it only depends
1200
 
    # on the idx file.
1201
 
    if ($index_mode) {
1202
 
        &make_ind($go_mode); 
1203
 
        if ( ($failure > 0) && !$force_mode && ! $preview_continuous_mode) {
1204
 
            goto END_FIRST;
1205
 
        }
1206
 
    }
1207
 
 
1208
 
    $dest_condition_ignore = 0;  #According to this setting
1209
 
                  # &make_latex_dvi_pdf will or will not examine whether destination
1210
 
                  # files exist when deciding to make latex
1211
 
    &make_files($go_mode);
1212
 
END_FIRST:
1213
 
    if ( ($failure > 0) && !$force_mode && ! $preview_continuous_mode) {
1214
 
        &exit_msg1( $failure_msg, $failure );
1215
 
    }
1216
1775
    if ( $preview_continuous_mode ) { 
1217
 
       &make_preview_continous; 
1218
 
    }
1219
 
    elsif ( $preview_mode ) { 
1220
 
        &make_preview; 
1221
 
        if ( ($failure > 0) && !$force_mode ) {
1222
 
           &exit_msg1( $failure_msg, $failure );
1223
 
        }
1224
 
    }
1225
 
    elsif ( $printout_mode) { 
1226
 
        &make_printout; 
1227
 
        if ( ($failure > 0) && !$force_mode ) {
1228
 
           &exit_msg1( $failure_msg, $failure );
1229
 
        }
1230
 
    }
1231
 
} # end FILES
 
1776
        &make_preview_continuousB; 
 
1777
        # Will probably exit by ctrl/C and never arrive here.
 
1778
        next FILE;
 
1779
    }
 
1780
 
 
1781
 
 
1782
## Handling of failures:
 
1783
##    Variable $failure is set to indicate a failure, with information
 
1784
##       put in $failure_msg.  
 
1785
##    These variables should be set to 0 and '' at any point at which it
 
1786
##       should be assumed that no failures have occurred.
 
1787
##    When after a routine is called it is found that $failure is set, then
 
1788
##       processing should normally be aborted, e.g., by return.
 
1789
##    Then there is a cascade of returns back to the outermost level whose 
 
1790
##       responsibility is to handle the error.
 
1791
##    Exception: An outer level routine may reset $failure and $failure_msg
 
1792
##       after initial processing, when the error condition may get 
 
1793
##       ameliorated later.
 
1794
    #Initialize failure flags now.
 
1795
    $failure = 0;
 
1796
    $failure_msg = '';
 
1797
    $failure = rdb_makeB( keys %requested_filerules );
 
1798
    if ($failure > 0) { next FILE; }
 
1799
    rdb_for_some( [keys %one_time], \&rdb_run1 );
 
1800
} # end FILE
 
1801
continue {
 
1802
    if ($dependents_list) { rdb_list(); }
 
1803
    # Handle any errors
 
1804
    $error_message_count = rdb_show_rule_errors();
 
1805
    if ( ($error_message_count == 0) || ($failure > 0) ) {
 
1806
        if ( $failure_msg ) {
 
1807
            #Remove trailing space
 
1808
            $failure_msg =~ s/\s*$//;
 
1809
            warn "$My_name: Did not finish processing file:\n   $failure_msg\n";
 
1810
            $failure = 1;
 
1811
        }
 
1812
    }
 
1813
    if ( ($failure > 0) || ($error_message_count > 0) ) {
 
1814
        $failure_count ++;
 
1815
        $last_failed = 1;
 
1816
    }
 
1817
    else {
 
1818
        $last_failed = 0;
 
1819
    }
 
1820
    &ifcd_popd;
 
1821
}
 
1822
# If we get here without going through the continue section:
 
1823
if ( $do_cd && ($#dir_stack > -1) ) {
 
1824
   # Just in case we did an abnormal exit from the loop
 
1825
   warn "$My_name: Potential bug: dir_stack not yet unwound, undoing all directory changes now\n";
 
1826
   &finish_dir_stack;
 
1827
}
 
1828
 
 
1829
if ($failure_count > 0) {
 
1830
    if ( $last_failed <= 0 ) {
 
1831
        # Error occured, but not on last file, so
 
1832
        #     user may not have seen error messages
 
1833
        warn "\n------------\n";
 
1834
        warn "$My_name: Some operations failed.\n";
 
1835
    }
 
1836
    if ( !$force_mode ) {
 
1837
      warn "$My_name: Use the -f option to force complete processing.\n";
 
1838
    }
 
1839
    exit 12;
 
1840
}
 
1841
 
 
1842
 
 
1843
 
 
1844
# end MAIN PROGRAM
 
1845
#############################################################
 
1846
 
 
1847
sub fix_cmds {
 
1848
   # If commands do not have placeholders for %S etc, put them in
 
1849
    foreach ($latex, $pdflatex, $lpr, $lpr_dvi, $lpr_pdf,
 
1850
             $pdf_previewer, $ps_previewer, $ps_previewer_landscape,
 
1851
             $dvi_previewer, $dvi_previewer_landscape,
 
1852
             $kpsewhich
 
1853
    ) {
 
1854
        # Source only
 
1855
        if ( $_ && ! /%/ ) { $_ .= " %O %S"; }
 
1856
    }
 
1857
    foreach ($bibtex) {
 
1858
        # Base only
 
1859
        if ( $_ && ! /%/ ) { $_ .= " %O %B"; }
 
1860
    }
 
1861
    foreach ($dvipdf, $ps2pdf) {
 
1862
        # Source and dest without flag for destination
 
1863
        if ( $_ && ! /%/ ) { $_ .= " %O %S %D"; }
 
1864
    }
 
1865
    foreach ($dvips, $makeindex) {
 
1866
        # Source and dest with -o dest before source
 
1867
        if ( $_ && ! /%/ ) { $_ .= " %O -o %D %S"; }
 
1868
    }
 
1869
    foreach ($dvi_filter, $ps_filter) {
 
1870
        # Source and dest, but as filters
 
1871
        if ( $_ && ! /%/ ) { $_ .= " %O <%S >%D"; }
 
1872
    }
 
1873
} #END fix_cmds
 
1874
 
 
1875
#############################################################
 
1876
 
 
1877
sub add_option {
 
1878
    # Call add_option( \$cmd, $opt )
 
1879
    # Add option to command
 
1880
    if ( ${$_[0]} !~ /%/ ) { &fix_cmds; }
 
1881
    ${$_[0]} =~ s/%O/$_[1] %O/;
 
1882
} #END add_option
 
1883
 
 
1884
#############################################################
 
1885
 
 
1886
sub rdb_make_rule_list {
 
1887
# Substitutions: %S = source, %D = dest, %B = this rule's base
 
1888
#                %T = texfile, %R = root = base for latex.
 
1889
 
 
1890
    # Defaults for dvi, ps, and pdf files
 
1891
    # Use local, not my, so these variables can be referenced
 
1892
    local $dvi_final = "%R.dvi";
 
1893
    local $ps_final  = "%R.ps";
 
1894
    local $pdf_final = "%R.pdf";
 
1895
    if ( length($dvi_filter) > 0) {
 
1896
        $dvi_final = "%R.dviF";
 
1897
    }
 
1898
    if ( length($ps_filter) > 0) {
 
1899
        $ps_final = "%R.psF";
 
1900
    }
 
1901
 
 
1902
    my $print_file = '';
 
1903
    my $print_cmd = '';
 
1904
    if ( $print_type eq 'dvi' ) {
 
1905
        $print_file = $dvi_final;
 
1906
        $print_cmd = $lpr_dvi;
 
1907
    }
 
1908
    elsif ( $print_type eq 'pdf' ) {
 
1909
        $print_file = $pdf_final;
 
1910
        $print_cmd = $lpr_pdf;
 
1911
    }
 
1912
    elsif ( $print_type eq 'ps' ) {
 
1913
        $print_file = $ps_final;
 
1914
        $print_cmd = $lpr;
 
1915
    }
 
1916
 
 
1917
    my $view_file = '';
 
1918
    my $viewer = '';
 
1919
    my $viewer_update_method = 0;
 
1920
    my $viewer_update_signal = undef;
 
1921
    my $viewer_update_command = undef;
 
1922
 
 
1923
    if ( ($view eq 'dvi') || ($view eq 'pdf') || ($view eq 'ps') ) { 
 
1924
        $view_file = ${$view.'_final'};
 
1925
        $viewer = ${$view.'_previewer'};
 
1926
        $viewer_update_method = ${$view.'_update_method'};
 
1927
        $viewer_update_signal = ${$view.'_update_signal'};
 
1928
        if (defined ${$view.'_update_command'}) {
 
1929
           $viewer_update_command = ${$view.'_update_command'};
 
1930
        }
 
1931
    }
 
1932
    # Specification of internal command for viewer update:
 
1933
    my $PA_update = ['do_update_view', $viewer_update_method, $viewer_update_signal, 0, 1];
 
1934
 
 
1935
# For test_kind: Use file contents for latex and friends, but file time for the others.
 
1936
# This is because, especially for dvi file, the contents of the file may contain
 
1937
#    a pointer to a file to be included, not the contents of the file! 
 
1938
    %rule_list = (
 
1939
        'latex'    => [ 'primary',  "$latex",     '',            "%T",        "%B.dvi",  "%R", 1 ],
 
1940
        'pdflatex' => [ 'primary',  "$pdflatex",  '',            "%T",        "%B.pdf",  "%R", 1 ],
 
1941
        'dvipdf'   => [ 'external', "$dvipdf",    'do_viewfile', $dvi_final,  "%B.pdf",  "%R", 2 ],
 
1942
        'dvips'    => [ 'external', "$dvips",     'do_viewfile', $dvi_final,  "%B.ps",   "%R", 2 ],
 
1943
        'dvifilter'=> [ 'external', $dvi_filter,  'do_viewfile', "%B.dvi",    "%B.dviF", "%R", 2 ],
 
1944
        'ps2pdf'   => [ 'external', "$ps2pdf",    'do_viewfile', $ps_final,   "%B.pdf",  "%R", 2 ],
 
1945
        'psfilter' => [ 'external', $ps_filter,   'do_viewfile', "%B.ps",     "%B.psF",  "%R", 2 ],
 
1946
        'print'    => [ 'external', "$print_cmd", 'if_source',   $print_file, "",        "",   2 ],
 
1947
        'update_view' => [ 'external', $viewer_update_command, $PA_update,
 
1948
                               $view_file,  "",        "",   2 ],
 
1949
        'view'     => [ 'external', "$viewer",    'if_source',   $view_file,  "",        "",   2 ],
 
1950
    );
 
1951
    %source_list = ();
 
1952
    foreach my $rule (keys %rule_list) {
 
1953
        $source_list{$rule} = [];
 
1954
        my $PAsources = $source_list{$rule};
 
1955
        my ( $cmd_type, $cmd, $source, $dest, $root ) = @{$rule_list{$rule}};
 
1956
        if ($source) {
 
1957
            push @$PAsources, [ $rule, $source, '' ];
 
1958
        }
 
1959
    }
 
1960
 
 
1961
# Ensure we only have one way to make pdf file, and that it is appropriate:
 
1962
    if ($pdf_mode == 1) { delete $rule_list{'dvipdf'}; delete $rule_list{'ps2pdf'}; }
 
1963
    elsif ($pdf_mode == 2) { delete $rule_list{'dvipdf'}; delete $rule_list{'pdflatex'}; }
 
1964
    else { delete $rule_list{'pdflatex'}; delete $rule_list{'ps2pdf'}; }
 
1965
 
 
1966
} # END rdb_make_rule_list 
 
1967
 
 
1968
#************************************************************
 
1969
 
 
1970
sub rdb_set_rules {
 
1971
    # Call rdb_set_rules( \%rule_list, ...)
 
1972
    # Set up rule database from definitions
 
1973
 
 
1974
    # Map of files to rules that MAKE them:
 
1975
    %rule_db = ();
 
1976
 
 
1977
    foreach my $Prule_list (@_) {
 
1978
        foreach my $rule ( keys %$Prule_list) {
 
1979
            my ( $cmd_type, $ext_cmd, $int_cmd, $source, $dest, $base, $test_kind ) = @{$$Prule_list{$rule}};
 
1980
            my $needs_making = 0;
 
1981
            # Substitute in the filename variables, since we will use
 
1982
            # those for determining filenames.  But delay expanding $cmd 
 
1983
            # until run time, in case of changes.
 
1984
            foreach ($base, $source, $dest ) { 
 
1985
                s/%R/$root_filename/;
 
1986
            }
 
1987
            foreach ($source, $dest ) { 
 
1988
                s/%B/$base/;
 
1989
                s/%T/$texfile_name/;
 
1990
            }
 
1991
    #        print "$rule: $cmd_type, EC='$ext_cmd', IC='$int_cmd', $test_kind,\n",
 
1992
    #              "    S='$source', D='$dest', B='$base' $needs_making\n";
 
1993
            rdb_create_rule( $rule, $cmd_type, $ext_cmd, $int_cmd, $test_kind, 
 
1994
                             $source, $dest, $base,
 
1995
                             $needs_making, undef, 1 );
 
1996
# !! ?? Last line was
 
1997
#                            $needs_making, undef, ($test_kind==1) );
 
1998
        }
 
1999
    } # End arguments of subroutine
 
2000
    &rdb_make_links;
 
2001
} # END rdb_set_rules
 
2002
 
 
2003
#************************************************************
 
2004
 
 
2005
sub rdb_make_links {
 
2006
# ?? Problem if there are multiple rules for getting a file.  Notably pdf.
 
2007
#    Which one to choose?
 
2008
    # Create $from_rule if there's a suitable rule.
 
2009
    # Map files to rules:
 
2010
    local %from_rules = ();
 
2011
    rdb_for_all( sub{ if($$Pdest){$from_rules{$$Pdest} = $rule;} } );
 
2012
#??    foreach (sort keys %from_rules) {print "D='$_' F='$from_rules{$_}\n";}
 
2013
    rdb_for_all( 
 
2014
        0,
 
2015
        sub{ 
 
2016
            if ( exists $from_rules{$file} ) { $$Pfrom_rule = $from_rules{$file}; }
 
2017
#??            print "$rule: $file, $$Pfrom_rule\n";
 
2018
        }
 
2019
    );
 
2020
    rdb_for_all( 
 
2021
        0,
 
2022
        sub{ 
 
2023
            if ( exists $from_rules{$file} ) { 
 
2024
                $$Pfrom_rule = $from_rules{$file}; 
 
2025
            }
 
2026
            if ( $$Pfrom_rule && (! rdb_rule_exists( $$Pfrom_rule ) ) ) {
 
2027
                $$Pfrom_rule = '';
 
2028
            }
 
2029
#??            print "$rule: $file, $$Pfrom_rule\n";
 
2030
        }
 
2031
    );
 
2032
} # END rdb_make_links
 
2033
 
 
2034
#************************************************************
 
2035
 
 
2036
sub set_trivial_aux_fdb {
 
2037
    # 1. Write aux file EXACTLY as would be written if the tex file
 
2038
    #    had no cross references, etc. I.e., a minimal .aux file. 
 
2039
    # 2. Write a corresponding fdb file
 
2040
    # 3. Provoke a run of (pdf)latex (actually of all primaries). 
 
2041
 
 
2042
    local $aux_file = "$root_filename.aux";
 
2043
    open( aux_file, '>', $aux_file )
 
2044
        or die "Cannot write file '$aux_file'\n";
 
2045
    print aux_file "\\relax \n";
 
2046
    close(aux_file);
 
2047
 
 
2048
    foreach my $rule (keys %primaries ) { 
 
2049
        rdb_ensure_file( $rule, $texfile_name );
 
2050
        rdb_ensure_file( $rule, $aux_file );
 
2051
        rdb_one_rule(  $rule,  
 
2052
                       sub{ $$Pout_of_date = 1; }
 
2053
                    );
 
2054
    }
 
2055
    &rdb_write( $fdb_file );
 
2056
} #END set_trivial_aux_fdb
 
2057
 
 
2058
#************************************************************
 
2059
#### Particular actions
 
2060
#************************************************************
 
2061
#************************************************************
 
2062
 
 
2063
sub do_cusdep {
 
2064
    # Unconditional application of custom-dependency
 
2065
    # except that rule is not applied if the source file source 
 
2066
    # does not exist, and an error is returned if the dest is not made.
 
2067
    #
 
2068
    # Assumes rule context for the custom-dependency, and that my first 
 
2069
    # argument is the name of the subroutine to apply
 
2070
    my $func_name = $_[0];
 
2071
    my $return = 0;
 
2072
    if ( !-e $$Psource ) {
 
2073
        # Source does not exist.  Users of this rule will need to turn
 
2074
        # it off when custom dependencies are reset
 
2075
        if ( !$silent ) {
 
2076
## ??? Was commented out.  1 Sep. 2008 restored, for cusdep no-file-exists issue
 
2077
            warn "$My_name: In trying to apply custom-dependency rule\n",
 
2078
            "  to make '$$Pdest' from '$$Psource'\n",
 
2079
            "  the source file has disappeared since the last run\n";
 
2080
        }
 
2081
        # Treat as successful
 
2082
    }
 
2083
    elsif ( !$func_name ) {
 
2084
        warn "$My_name: Possible misconfiguration or bug:\n",
 
2085
        "  In trying to apply custom-dependency rule\n",
 
2086
        "  to make '$$Pdest' from '$$Psource'\n",
 
2087
        "  the function name is blank.\n";
 
2088
    }
 
2089
    elsif ( ! defined &$func_name ) {
 
2090
        warn "$My_name: Misconfiguration or bug,",
 
2091
        " in trying to apply custom-dependency rule\n",
 
2092
        "  to make '$$Pdest' from '$$Psource'\n",
 
2093
        "  function name '$func_name' does not exists.\n";
 
2094
    }
 
2095
    else {
 
2096
        my $cusdep_ret = &$func_name( $$Pbase );
 
2097
        if ( defined $cusdep_ret && ($cusdep_ret != 0) ) {
 
2098
            $return = $cusdep_ret;
 
2099
            if ($return) {
 
2100
                warn "Rule '$rule', function '$func_name'\n",
 
2101
                     "   failed with return code = $return\n";
 
2102
            }
 
2103
        }
 
2104
        elsif ( !-e $$Pdest ) {
 
2105
            # Destination non-existent, but routine failed to give an error
 
2106
            warn "$My_name: In running custom-dependency rule\n",
 
2107
            "  to make '$$Pdest' from '$$Psource'\n",
 
2108
            "  function '$func_name' did not make the destination.\n";
 
2109
            $return = -1;
 
2110
        }
 
2111
    }
 
2112
    return $return;
 
2113
}  # END do_cusdep
 
2114
 
 
2115
#************************************************************
 
2116
 
 
2117
sub do_viewfile {
 
2118
    # Unconditionally make file for viewing, going through temporary file if
 
2119
    # Assumes rule context
 
2120
 
 
2121
    my $return = 0;
 
2122
    my ($base, $path, $ext) = fileparseA( $$Pdest );
 
2123
    if ( &view_file_via_temporary ) {
 
2124
        my $tmpfile = tempfile1( "${root_filename}_tmp", $ext );
 
2125
        $return = &rdb_ext_cmd1( '', '', $tmpfile );
 
2126
        unlink $$Pdest;
 
2127
        move( $tmpfile, $$Pdest );
 
2128
    }
 
2129
    else {
 
2130
        $return = &rdb_ext_cmd;
 
2131
    }
 
2132
    return $return;
 
2133
} #END do_viewfile
 
2134
 
 
2135
#************************************************************
 
2136
 
 
2137
sub do_update_view {
 
2138
    # Update viewer
 
2139
    # Assumes rule context
 
2140
    # Arguments: (method, signal, viewer_process)
 
2141
 
 
2142
    my $return = 0;
 
2143
 
 
2144
    # Although the process is passed as an argument, we'll need to update it.
 
2145
    # So (FUDGE??) bypass the standard interface for the process.
 
2146
    # We might as well do this for all the arguments.
 
2147
    my $viewer_update_method = ${$PAint_cmd}[1];
 
2148
    my $viewer_update_signal = ${$PAint_cmd}[2];
 
2149
    my $Pviewer_process             = \${$PAint_cmd}[3];
 
2150
    my $Pneed_to_get_viewer_process = \${$PAint_cmd}[4];
 
2151
    
 
2152
    if ($viewer_update_method == 2) {
 
2153
        if ($$Pneed_to_get_viewer_process) {
 
2154
            $$Pviewer_process = &find_process_id( $$Psource );
 
2155
            if ($$Pviewer_process != 0) {
 
2156
                $$Pneed_to_get_viewer_process = 0;
 
2157
            }
 
2158
        }
 
2159
        if ($$Pviewer_process == 0) {
 
2160
            print "$My_name: need to signal viewer for file '$$Psource', but didn't get \n",
 
2161
                  "   process ID for some reason, e.g., no viewer, bad configuration, bug\n"
 
2162
                if $diagnostics ;             
 
2163
        }
 
2164
        elsif ( defined $viewer_update_signal) {
 
2165
            print "$My_name: signalling viewer, process ID $$Pviewer_process\n"
 
2166
                if $diagnostics ;
 
2167
            kill $viewer_update_signal, $$Pviewer_process;
 
2168
        }
 
2169
        else {
 
2170
            warn "$My_name: viewer is supposed to be sent a signal\n",
 
2171
                 "  but no signal is defined.  Misconfiguration or bug?\n";
 
2172
            $return = 1;
 
2173
        }
 
2174
    }
 
2175
    elsif ($viewer_update_method == 4) {
 
2176
        if (defined $$Pext_cmd) {
 
2177
            $return = &rdb_ext_cmd;
 
2178
        }
 
2179
        else {
 
2180
            warn "$My_name: viewer is supposed to be updated by running a command,\n",
 
2181
                 "  but no command is defined.  Misconfiguration or bug?\n";
 
2182
        }
 
2183
    }
 
2184
    return $return;
 
2185
} #END do_update_view
 
2186
 
 
2187
#************************************************************
 
2188
 
 
2189
sub if_source {
 
2190
    # Unconditionally apply rule if source file exists.
 
2191
    # Assumes rule context
 
2192
    if ( -e $$Psource ) {
 
2193
        return &rdb_ext_cmd;
 
2194
    }
 
2195
    else {
 
2196
        return -1;
 
2197
    }
 
2198
} #END if_source
1232
2199
 
1233
2200
#************************************************************
1234
2201
#### Subroutines
1235
2202
#************************************************************
1236
 
 
1237
 
#************************************************************
1238
 
#### Highest level
1239
 
 
1240
 
 
1241
 
sub make_files
1242
 
{
1243
 
    my $do_build = $_[0];
1244
 
    my $new_files 
1245
 
       = &find_new_files;
1246
 
    my $new_deps 
1247
 
       = &make_dependents($do_build);
1248
 
    if ($failure > 0) {return;}
1249
 
    if ( ($new_files > 0) || ($new_deps > 0) ) {
1250
 
        $do_build = 1;
1251
 
    }
1252
 
    if ($need_dvi)
1253
 
    {
1254
 
        &make_latex_dvi_pdf($do_build, 'dvi');
1255
 
        if ($failure > 0) {return;}
1256
 
    } 
1257
 
    if ( $need_ps ) {
1258
 
        &make_postscript; 
1259
 
        if ($failure > 0) {return;}
1260
 
    }
1261
 
    if ( $need_pdf == 1 ) {
1262
 
        &make_latex_dvi_pdf($do_build, 'pdf'); 
1263
 
        if ($failure > 0) {return;}
1264
 
    }
1265
 
    if ( $need_pdf == 2 ) {
1266
 
        &make_pdf2; 
1267
 
        if ($failure > 0) {return;}
1268
 
    }
1269
 
    if ( $need_pdf == 3 ) {
1270
 
        &make_pdf3; 
1271
 
        if ($failure > 0) {return;}
1272
 
    }
1273
 
}
1274
 
 
1275
 
#************************************************************
1276
 
 
1277
 
sub make_latex_dvi_pdf
1278
 
{
1279
 
  my $do_build = $_[0];
1280
 
  my $dest_type = $_[1];
1281
 
  my $dest;
1282
 
  my $processor;
1283
 
  if ( $dest_type eq 'dvi' ) { 
1284
 
      $dest = "$root_filename.dvi"; 
1285
 
      $processor = $latex;
1286
 
  } elsif ( $dest_type eq 'pdf' ) { 
1287
 
      $dest = "$root_filename.pdf"; 
1288
 
      $processor = $pdflatex; 
1289
 
  } else {
1290
 
      die("Latexmk: BUG: undefined destination type $dest_type in make_latex_dvi_pdf\n");
1291
 
  }
1292
 
 
1293
 
  ## get initial last modified times.
1294
 
  my $tex_mtime = &get_latest_mtime(@includes);
1295
 
  my $dest_mtime= &get_mtime("$dest");
1296
 
  my $aux_mtime = &get_mtime("$root_filename.aux");
1297
 
  my $bib_mtime = &get_latest_mtime(@bib_files);
1298
 
  my $bbl_mtime = &get_mtime("$root_filename.bbl");
1299
 
  my $ilg_mtime = &get_mtime("$root_filename.ilg");
1300
 
  my $ind_mtime = &get_mtime("$root_filename.ind");
1301
 
 
1302
 
  ## - if no destination file (dvi or pdf), 
1303
 
  ##      or .aux older than tex file or bib file or anything they input, 
1304
 
  ##   then run latex.
1305
 
 
1306
 
  #&list_conditions (
1307
 
  #   $do_build, 
1308
 
  #   !(-e "$root_filename.aux"),
1309
 
  #   ($aux_mtime < $tex_mtime),
1310
 
  #   !(-e "$dest"),
1311
 
  #   ( (-e "$root_filename.bbl") && ($aux_mtime < $bbl_mtime) ),
1312
 
  #   ($dest_mtime < $tex_mtime),
1313
 
  #   ( (-e "$root_filename.ilg") && ($aux_mtime < $ilg_mtime) ),
1314
 
  #   ( (-e "$root_filename.ind") && ($aux_mtime < $ind_mtime) ),
1315
 
  #   ( $includes_from_log && ! -e "$root_filename.log" )
1316
 
  #);
1317
 
  my $dest_bad =  !(-e "$dest") || ($dest_mtime < $tex_mtime) ;
1318
 
  if ($dest_condition_ignore) {$dest_bad = 0;}
1319
 
  if ( $do_build
1320
 
    || !(-e "$root_filename.aux")
1321
 
    || ($aux_mtime < $tex_mtime)
1322
 
    || $dest_bad
1323
 
    || ( (-e "$root_filename.bbl") && ($aux_mtime < $bbl_mtime) )
1324
 
    || ( (-e "$root_filename.ilg") && ($aux_mtime < $ilg_mtime) )
1325
 
    || ( (-e "$root_filename.ind") && ($aux_mtime < $ind_mtime) )
1326
 
    || ( $includes_from_log && ! -e "$root_filename.log" )
1327
 
   )
1328
 
   { 
1329
 
      &build_latex_dvi_pdf($processor);
1330
 
      if ($failure > 0) {return;}
1331
 
      if ( $dest_type eq 'dvi') {
1332
 
         &make_dvi_filtered;
1333
 
         if ($failure > 0) {return;}
1334
 
      }
1335
 
   }
1336
 
   else
1337
 
   { 
1338
 
       warn "Latexmk: File '$dest' is up to date\n" 
1339
 
          if !$quell_uptodate_msgs;
1340
 
   }
1341
 
}
1342
 
 
1343
 
sub list_conditions {
1344
 
    my $on = 0;
1345
 
    foreach (@_) {
1346
 
        if ($_) {$on = 1;}
1347
 
    }
1348
 
    if (!$on) {return;}
1349
 
    print "On conditions: ";
1350
 
    for ($i = 1; $i <= $#_+1; $i++) {
1351
 
        if ($_[$i-1]) {print "$i ";}
1352
 
    }
1353
 
    print "===\n";
1354
 
}
1355
 
 
1356
 
#************************************************************
1357
 
 
1358
 
sub build_latex_dvi_pdf { 
1359
 
    # Argument: 0 = processor (e.g., 'latex' or 'pdflatex')
1360
 
    #
1361
 
    # I don't need to know whether I run latex or pdflatex!
1362
 
    #
1363
 
    # Repeat running latex as many times as needed to resolve cross
1364
 
    # references, also running bibtex and makeindex as necessary.  The
1365
 
    # algorithm for determining whether latex needs to be run again is
1366
 
    # whether certain generated files have changed since the previous
1367
 
    # run.  A limit (contained in $max_repeat) is applied on the
1368
 
    # number of runs, to avoid infinite loops in pathological cases or
1369
 
    # in the case of a bug.  $max_repeat should be at least 4, to
1370
 
    # allow for the maximum number of repeats under normal
1371
 
    # circumstances, which is 3, plus one for unusual cases of page
1372
 
    # breaks moving around.  
1373
 
    #
1374
 
    # The criterion for needing a rerun is that one or both of the
1375
 
    # .aux file and the .idx file has changed.  To prove this: observe
1376
 
    # that reruns are necessary because information that needs to be
1377
 
    # read in from a file does not correspond to the current
1378
 
    # conditions.  The relevant files are: the .aux file, and possibly
1379
 
    # one or more of: the index files, the table of contents file
1380
 
    # (.toc), the list of figures file (.lof), the list of tables file
1381
 
    # (.lot).  The information read in is: cross reference
1382
 
    # definitions, page references, tables of contents, figures and
1383
 
    # tables.  Note that the list of figures (for example) may itself
1384
 
    # contain undefined references or incorrect page references.  If
1385
 
    # there is any incorrectness, changed information will be written
1386
 
    # to the corresponding file on the current run, and therefore one
1387
 
    # or more of the auxiliary files will have changed.  
1388
 
    #
1389
 
    # In fact the lines in the .toc, .lof and .lot files correspond to
1390
 
    # entries in the .aux file, so it is not necessary to check the
1391
 
    # .toc, .lof and .lot files (if any).  However WHETHER these files 
1392
 
    # are input by latex is not determined by the aux file, but does
1393
 
    # affect the output.  It is possible for the tex file to change
1394
 
    # the state of one of the .toc, .lof, or .lot files between begin
1395
 
    # required and not required.  The same could happen for other
1396
 
    # input files.  
1397
 
    #
1398
 
    # For example, initially suppose no TOC is required, and that all
1399
 
    # generated files are up-to-date.  The .toc file is either not
1400
 
    # present or is out-of-date.  Then change the source file so
1401
 
    # that a TOC is requested.  Run latex; it uses wrong TOC
1402
 
    # information, but the .aux file might not change.  
1403
 
    #
1404
 
    # Two possibilities: (a) check .toc, .lof, .lot (possibly etc!)
1405
 
    # files for changes; (b) check for a change in the list of input
1406
 
    # files.  We'll choose the second: since it requires less file
1407
 
    # checking and is more general.  It applies in all situations
1408
 
    # where the extra auxiliary input files (e.g., .toc) correspond in
1409
 
    # contents to the state of the .aux file, but only if these files
1410
 
    # are used. 
1411
 
    #
1412
 
    # Therefore a correct algorithm is to require a rerun if either of
1413
 
    # the following is true:
1414
 
    #
1415
 
    #    1.  The .aux file has changed from the previous run.
1416
 
    #    2.  The .idx file has changed from the previous run.
1417
 
    #    3.  The set of input files has changed from the previous run.
1418
 
    #
1419
 
    # Of course, if a previous version of one of these files did not
1420
 
    # exist (as on a first run), then that implies a rerun is
1421
 
    # necessary. And if a .aux file or a .idx file is not generated,
1422
 
    # there is no point in testing it against a previous version.
1423
 
    #
1424
 
    # Assume on entry that the .ind and .bbl files are up-to-date with 
1425
 
    # respect to the already existing .idx and .aux files.  This will
1426
 
    # be the case if latexmk was used to make them.
1427
 
 
1428
 
    my $aux_file;
1429
 
    my $processor = $_[0];
1430
 
 
1431
 
    my $count_latex = 0;
1432
 
    my $repeat = 0;
1433
 
    
1434
 
    do {
1435
 
        # Arrival here means that a new run of latex/pdflatex is requested
1436
 
        # Assume that the .ind file (if any) corresponds to the .idx file
1437
 
        #    from the previous run
1438
 
        # and that the .bbl file (if any) corresponds to the .aux file from
1439
 
        #    the previous run.
1440
 
 
1441
 
        $repeat = 0;     # Assume no repeat necessary.
1442
 
        $count_latex++;  # Count the number of passes through latex
1443
 
        warn "------------\nRun number $count_latex of ",
1444
 
             "$processor [$texfile_name]\n------------\n";
1445
 
        foreach $aux_file (@aux_files) 
1446
 
        {
1447
 
            if ( -e $aux_file ) {
1448
 
                warn "Saving old .aux file \"$aux_file\"\n" unless $silent;
1449
 
                copy_file_and_time ( "$aux_file", "$aux_file.bak");
1450
 
            }
1451
 
        }
1452
 
        if ( (! -e "$root_filename.aux") && (! -e "$root_filename.aux.bak") ) {
1453
 
            # Arrive here if neither of the .aux and the .aux.bak files exists
1454
 
            # for the base file.
1455
 
            # I make minimal .aux.bak file, containing a single line "\relax "
1456
 
            # This is the same as the aux file generated for a latex file
1457
 
            # which does not need any cross references, etc.  Generating this
1458
 
            # .aux.bak file will save a pass through latex on simple files.
1459
 
            local $aux_bak_file = ">$root_filename.aux.bak";
1460
 
            open(aux_bak_file) || die "Cannot write file $aux_bak_file\n";
1461
 
            print aux_bak_file "\\relax \n";
1462
 
            close(aux_bak_file);
1463
 
        }
1464
 
        if ( (-e "$root_filename.aux") && $bibtex_mode) { 
1465
 
           # We have assumed that the bbl file is up-to-date 
1466
 
           #    with respect to the previous aux file.  However
1467
 
           #    it may be out-of-date with respect to the bib file(s).
1468
 
           # So run bibtex in this case
1469
 
           my $bibtex_return_code = &make_bbl(0);
1470
 
           if ( ($bibtex_return_code eq 2) & !$force_mode )
1471
 
           {
1472
 
               $failure = 1;
1473
 
               $failure_msg = 'Bibtex reported an error';
1474
 
               return;
1475
 
           }
1476
 
        }
1477
 
 
1478
 
        if ( -e "$root_filename.idx" ) {
1479
 
            warn "Saving old .idx file\n" unless $silent;
1480
 
            copy_file_and_time ( "$root_filename.idx", "$root_filename.idx.bak");
1481
 
        }
1482
 
 
1483
 
        my @includes_previous = @includes;
1484
 
        my ($pid, $return) = &Run("$processor $texfile_name"); 
1485
 
        $updated = 1;    # Flag that some dependent file has been remade
1486
 
        if ($return) {
1487
 
           if (!$force_mode) {
1488
 
               $failure = $return;
1489
 
               $failure_msg = 'Latex encountered an error';
1490
 
               &aux_restore;
1491
 
               return;
1492
 
           }
1493
 
           elsif ($silent) {
1494
 
               # User may not have seen error
1495
 
               warn "====Latex encountered an error: see .log file====\n";
1496
 
           }
1497
 
        }
1498
 
        $return = &parse_log;
1499
 
        my $aux_changed = 0;
1500
 
        my $idx_changed = 0;
1501
 
 
1502
 
        if ( $return == 0 ) 
1503
 
        {
1504
 
           $failure = 1;
1505
 
           $failure_msg = 'Latex failed to generate a log file';
1506
 
           &aux_restore;
1507
 
           return;
1508
 
        }
1509
 
        if ( $includes_from_log )
1510
 
        {
1511
 
           my @aux_files_previous = @aux_files;
1512
 
           if ( @aux_files ne @aux_files_previous ){
1513
 
               $aux_changed = 1;
1514
 
               warn "List of .aux files has changed. ",
1515
 
                    "I must run latex again\n"
1516
 
                    unless $silent;
1517
 
           }
1518
 
        }
1519
 
 
1520
 
        if ( !$aux_changed )
1521
 
        {
1522
 
           # Look for changes in the individual aux files.
1523
 
           foreach $aux_file (@aux_files)
1524
 
           {
1525
 
              if ( -e "$aux_file" ) {
1526
 
                  if ( &diff ("$aux_file", "$aux_file.bak") ) {
1527
 
                      warn ".aux file \"$aux_file\" changed.  ",
1528
 
                           "I must run latex again\n"
1529
 
                           unless $silent;
1530
 
                      $aux_changed = 1;
1531
 
                      last;
1532
 
                  }
1533
 
                  else {
1534
 
                      warn "File \"$aux_file\" has not changed, ",
1535
 
                           "so it is valid\n" unless $silent;
1536
 
                  }
1537
 
              }
1538
 
           }
1539
 
        }
1540
 
        if ( (!-e "$root_filename.aux") && (-e "$root_filename.aux.bak") ) {
1541
 
           warn "No aux file was generated, so I don't need .aux.bak file\n"
1542
 
              unless $silent;
1543
 
           unlink ("$root_filename.aux.bak");
1544
 
        }
1545
 
 
1546
 
        if ( (-e "$root_filename.aux") && $aux_changed && $bibtex_mode) { 
1547
 
            # Note running bibtex only makes sense if the aux file exists.
1548
 
            # If any aux file has changed, then the citations may
1549
 
            # have changed and we must run bibtex. 
1550
 
            # The argument to &make_bbl forces this.
1551
 
            # &make_bbl also checks whether the bbl file is
1552
 
            #   out-of-date with respect to the bib files.
1553
 
            my $bibtex_return_code = &make_bbl($aux_changed);
1554
 
            if ( ($bibtex_return_code eq 2) && !$force_mode ) 
1555
 
            {
1556
 
               $failure = 1;
1557
 
               $failure_msg = 'Bibtex reported an error';
1558
 
               return;
1559
 
            }
1560
 
        }
1561
 
 
1562
 
        if ( -e "$root_filename.idx" ) {
1563
 
           if ( &diff ("$root_filename.idx", "$root_filename.idx.bak") ) {
1564
 
               warn "The .idx file changed.  I must run latex again\n"
1565
 
                   unless $silent;
1566
 
               # idx file exists and has changed 
1567
 
               #    implies idx file written 
1568
 
               #    implies indexing being used
1569
 
               $index_mode = 1;
1570
 
               $idx_changed = 1;
1571
 
           } else {
1572
 
               warn "The .idx file has not changed, so it is valid\n"
1573
 
                  unless $silent;
1574
 
           }
1575
 
           if ($index_mode) {
1576
 
              my $makeindex_return_code = &make_ind($idx_changed);
1577
 
              if ( ($makeindex_return_code eq 2) && !$force_mode ) {
1578
 
                  $failure = 1;
1579
 
                  $failure_msg = 'Makeindex encountered an error';
1580
 
                  return;
1581
 
              }
1582
 
           }
1583
 
        } else {
1584
 
           if ($index_mode) {
1585
 
              warn "No .idx file was generated, but index_mode is set; ",
1586
 
                   "I will unset it"
1587
 
                 unless $silent;
1588
 
              $index_mode = 0;
1589
 
           }
1590
 
           if ( -e "$root_filename.idx.bak") {
1591
 
              warn "No idx file was generated. ",
1592
 
                   "So I delete unneeded .idx.bak file\n"
1593
 
                 unless $silent;
1594
 
              unlink ("$root_filename.idx.bak");
1595
 
           }
1596
 
        }
1597
 
 
1598
 
        if ( @includes ne @includes_previous ) { 
1599
 
            warn "The set of input files changed.  I must run latex again\n"
1600
 
              unless $silent;
1601
 
        }
1602
 
 
1603
 
        if ( $aux_changed 
1604
 
             || $idx_changed 
1605
 
             ||( @includes ne @includes_previous ) 
1606
 
           ) {
1607
 
            $repeat = 1;
1608
 
        }
1609
 
 
1610
 
        if ( $count_latex ge $max_repeat ) { 
1611
 
           # Avoid infinite loop by having a maximum repeat count
1612
 
           # Getting here represents some kind of weird error.
1613
 
           if ($repeat ) {
1614
 
              warn "Maximum runs of latex reached ",
1615
 
                   "without correctly resolving cross references\n";
1616
 
           }
1617
 
           $repeat = 0;
1618
 
        }
1619
 
    } until ($repeat == 0);
1620
 
 
1621
 
    if ($bibtex_mode) {
1622
 
        my $retcode = &check_for_bibtex_warnings;
1623
 
        if ($retcode == 1) {
1624
 
           print "See $root_filename.blg for details\n";
1625
 
        }
1626
 
        elsif ($retcode == 2) {
1627
 
           return;
1628
 
        }
1629
 
    }
1630
 
 
1631
 
    if (!$force_mode && $bad_reference) {
1632
 
        $failure = 1;
1633
 
        $failure_msg = 'Latex could not resolve all references';
1634
 
        return;
1635
 
    }
1636
 
 
1637
 
     if (!$force_mode && $bad_citation) {
1638
 
        $failure = 1;
1639
 
        $failure_msg = 'Latex could not resolve all citations or labels';
1640
 
        return;
1641
 
    }
1642
 
}
1643
 
 
1644
2203
#************************************************************
1645
2204
 
1646
2205
# Finds the basename of the root file
1654
2213
# The variable $extension_treatment determines which rules are used.
1655
2214
 
1656
2215
sub find_basename
 
2216
#?? Need to use kpsewhich, if possible
1657
2217
{
1658
2218
  local($given_name, $base_name, $ext, $path, $tex_name);
1659
2219
  $given_name = $_[0];
1673
2233
       #   Thus when the given filename is "\tmp\a.b.c", the tex
1674
2234
       #   filename is the same, and the basename is "a".
1675
2235
 
1676
 
       ($base_name, $path, $ext) = fileparse ($given_name, '\..*');
 
2236
       ($base_name, $path, $ext) = fileparse( $given_name, '\..*' );
1677
2237
       if ( "$ext" eq "") { $tex_name = "$given_name.tex"; }
1678
2238
       else { $tex_name = $given_name; }
1679
2239
       $_[1] = $base_name;
1705
2265
      else {
1706
2266
         $tex_name = "$given_name";
1707
2267
      }
1708
 
      ($base_name, $path, $ext) = fileparse ($tex_name, '\.[^\.]*');
 
2268
      ($base_name, $path, $ext) = fileparse( $tex_name, '\.[^\.]*' );
1709
2269
      $_[1] = $base_name;
1710
2270
      $_[2] = $tex_name;
1711
2271
  }
1712
2272
  else {
1713
 
     die "Latexmk: Incorrect configuration gives \$extension_treatment=",
1714
 
         "\"$extension_treatment\"\n";
 
2273
     die "$My_name: Incorrect configuration gives \$extension_treatment=",
 
2274
         "'$extension_treatment'\n";
1715
2275
  }
1716
2276
   if ($diagnostics) {
1717
 
      print "Given=\"$given_name\", tex=\"$tex_name\", base=\"$base_name\"\n";
 
2277
      print "Given='$given_name', tex='$tex_name', base='$base_name'\n";
1718
2278
  }
1719
2279
  return ! -e $tex_name;
1720
 
}
1721
 
 
1722
 
#************************************************************
1723
 
 
1724
 
sub make_bbl {
1725
 
# If necessary, make bbl file.  Assume bibtex mode on.
1726
 
# Force run if first argument is non-zero.
1727
 
# Return 0 if nothing made, 
1728
 
#        1 if bbl file made, 
1729
 
#        2 if bibtex reported an error
1730
 
#        3 if .blg file couldn't be opened
1731
 
#        4 if there was another error
1732
 
   my $bib_mtime = &get_latest_mtime(@bib_files);
1733
 
   my $bbl_mtime = &get_mtime("$root_filename.bbl");
1734
 
   ## if no .bbl or .bib changed since last bibtex run, run bibtex.
1735
 
   if ( !-e "$root_filename.aux" ) 
1736
 
   {
1737
 
      # bibtex reads aux file, so if there is no aux file, there is
1738
 
      # nothing to do
1739
 
       return 0;
1740
 
   }   
1741
 
   if (($_[0] != 0)
1742
 
       || !(-e "$root_filename.bbl")
1743
 
       || ($bbl_mtime < $bib_mtime)
1744
 
       )
1745
 
   {
1746
 
       warn "------------\nRunning $bibtex [$root_filename]",
1747
 
            "\n------------\n"
1748
 
         unless $silent;
1749
 
       my ($pid, $return) = &Run("$bibtex $root_filename"); 
1750
 
       $updated = 1;
1751
 
       $bbl_mtime = &get_mtime("$root_filename.bbl");
1752
 
       if ( $return != 0 ) 
1753
 
          {  return 2; }
1754
 
       $return = &check_for_bibtex_errors;
1755
 
       if ( $return == 0 ) 
1756
 
          { return 1;}
1757
 
       elsif ( $return == 1 ) 
1758
 
          { return 2;}
1759
 
       elsif ( $return == 2 ) 
1760
 
          { return 3;}
1761
 
       else 
1762
 
          { return 4; }
1763
 
   }
1764
 
   else 
1765
 
   { return 0; }
1766
 
}
1767
 
 
1768
 
#************************************************************
1769
 
 
1770
 
sub make_ind {
1771
 
# If necessary, make ind file.  Assume makeindex mode on.
1772
 
# Force run if first argument is non-zero.
1773
 
# Return 0 if nothing made, 
1774
 
#        1 if ind file made, 
1775
 
#        2 if makeindex reported an error
1776
 
   if ( !-e "$root_filename.idx" ) 
1777
 
   {
1778
 
      # makeindex reads idx file, so if there is no idx file, there is
1779
 
      # nothing to do
1780
 
      return 0;
1781
 
   }   
1782
 
   if ( ($_[0] != 0) || !(-e "$root_filename.ind") )
1783
 
   {
1784
 
      warn "------------\nRunning $makeindex [$root_filename]",
1785
 
           "\n------------\n"
1786
 
         unless $silent;
1787
 
      my ($pid, $return) = &Run("$makeindex $root_filename");
1788
 
      $updated = 1;
1789
 
      if ($return) 
1790
 
      {  
1791
 
          $failure = 1;
1792
 
          $failure_msg = 'Problem with makeindex';
1793
 
          return 2; 
1794
 
      }
1795
 
      else 
1796
 
      { return 1; }
1797
 
   }
1798
 
   else 
1799
 
   { return 0; }
1800
 
}
1801
 
 
1802
 
#************************************************************
1803
 
 
1804
 
sub find_new_files
1805
 
{
1806
 
    my @new_includes = ();
1807
 
MISSING_FILE:
1808
 
    foreach my $missing (sort keys %includes_missing) {
1809
 
       my ($base, $path, $ext) = fileparse ($missing, '\.[^\.]*');
1810
 
       if ( -e "$missing.tex" ) { 
1811
 
           push @new_includes, "$missing.tex";
1812
 
# It's probably best to try all possibilities, since
1813
 
# we don't know which one applies.  So go on to next case.
1814
 
#           next MISSING_FILE;
1815
 
       }
1816
 
       if ( -e $missing ) { 
1817
 
           push @new_includes, $missing;
1818
 
#           next MISSING_FILE;
1819
 
       }
1820
 
       if ( $ext ne "" ) {
1821
 
           foreach my $dep (@cus_dep_list){
1822
 
              my ($fromext,$toext) = split(' ',$dep);
1823
 
              if ( ( "$ext" eq ".$toext" )
1824
 
                   && ( -e "$path$base.$fromext" )
1825
 
                  )  {
1826
 
                  # Source file for the missing file exists
1827
 
                  # So we have a real include file, and it will be made
1828
 
                  # next time by &make_dependents
1829
 
                  push @new_includes, $missing ;
1830
 
#                  next MISSING_FILE;
1831
 
              }
1832
 
              # no point testing the $toext if the file doesn't exist.
1833
 
           }
1834
 
       }
1835
 
       else {
1836
 
           # $_ doesn't exist, $_.tex doesn't exist,
1837
 
           # and $_ doesn't have an extension
1838
 
           foreach my $dep (@cus_dep_list){
1839
 
              my ($fromext,$toext) = split(' ',$dep);
1840
 
              if ( -e "$path$base.$fromext" ) {
1841
 
                  # Source file for the missing file exists
1842
 
                  # So we have a real include file, and it will be made
1843
 
                  # next time by &make_dependents
1844
 
                  push @new_includes, "$path$base.$toext" ;
1845
 
#                  next MISSING_FILE;
1846
 
              }
1847
 
              if ( -e "$path$base.$toext" ) {
1848
 
                  # We've found the extensionfor the missing file,
1849
 
                  # and the file exists
1850
 
                  push @new_includes, "$path$base.$toext" ;
1851
 
#                  next MISSING_FILE;
1852
 
              }
1853
 
           }
1854
 
       }
1855
 
    } # end MISSING_FILES
1856
 
 
1857
 
    @new_includes = uniq( sort(@new_includes) );
1858
 
    @includes = uniq( sort(@includes, @new_includes) );
1859
 
    
1860
 
    my $found = $#new_includes + 1;
1861
 
    if ( $diagnostics && ( $found > 0 ) ) {
1862
 
        warn "Detected previously missing files:\n";
1863
 
        foreach (@new_includes) {
1864
 
            warn "   '$_'\n";
1865
 
        }
1866
 
    }
1867
 
    return $found;
1868
 
}
1869
 
 
1870
 
#************************************************************
1871
 
 
1872
 
sub make_dependents
1873
 
{
1874
 
# Usage: make_dependents(build)
1875
 
# First argument = 1 => rebuild unconditionally
1876
 
#                  0 => rebuild only if dest is out-of-date
1877
 
# Return 0 if nothing made, 1 if something made
1878
 
  my $build = shift;
1879
 
  my $makes = 0;     # Count of makes done
1880
 
FILE:
1881
 
  foreach my $file (@includes)
1882
 
  {
1883
 
     my ($base_name, $path, $toext) = fileparse ($file, '\.[^\.]*');
1884
 
     $base_name = $path.$base_name;
1885
 
     if ( $toext eq "" ) {next FILE;}
1886
 
     $toext =~ s/^\.//;
1887
 
DEP:
1888
 
     foreach my $dep ( @cus_dep_list )
1889
 
     {
1890
 
        my ($fromext,$proptoext,$must,$func_name) = split(' ',$dep);
1891
 
        if ( $toext eq $proptoext )
1892
 
        {
1893
 
           # Found match of rule
1894
 
           if ( -e "$base_name.$fromext" )
1895
 
           {
1896
 
              # From file exists, now check if it is newer
1897
 
              if (( ! (-e "$base_name.$toext" ))
1898
 
                  || $build
1899
 
                  || ( &get_mtime("$base_name.$toext")
1900
 
                        < &get_mtime("$base_name.$fromext") 
1901
 
                     )
1902
 
                 )
1903
 
              {
1904
 
                 warn "------------\nRunning $func_name [$base_name]\n------------\n"
1905
 
                    unless $silent;
1906
 
                 my $return = &$func_name($base_name);
1907
 
                 $updated = 1;
1908
 
                 if ( !$force_mode && $return )
1909
 
                 {
1910
 
                    $failure = $return;
1911
 
                    $failure_msg = "$func_name encountered an error";
1912
 
                    last FILE;
1913
 
                 }
1914
 
                 else {
1915
 
                    $makes++;
1916
 
                 }
1917
 
             }
1918
 
          }
1919
 
          else
1920
 
          {  # Source file does not exist
1921
 
             # Perhaps the rule is not to be applied.
1922
 
             if ( !$force_mode && ( $must != 0 ))
1923
 
             {
1924
 
                $failure = 1;
1925
 
                $failure_msg = "File '$base_name.$fromext' does not exist ".
1926
 
                               "to build '$base_name.$toext'";
1927
 
                last FILE;
1928
 
             }
1929
 
          } # 
1930
 
       } # End of Rule found
1931
 
     } # End DEP
1932
 
  } # End FILE
1933
 
  return ($makes>0 ? 1 : 0);
1934
 
} # End sub make_dependents
1935
 
 
1936
 
#************************************************************
1937
 
 
1938
 
sub make_dvi_filtered
1939
 
{
1940
 
  my $dvi_file = "$root_filename.dvi";
1941
 
  return if ( length($dvi_filter) == 0 );
1942
 
  if ( ! -e $dvi_file ) {
1943
 
       warn "Dvi file \"$dvi_file\" has not been made, so I cannot filter it\n";
1944
 
       return;
1945
 
  }
1946
 
  warn "------------\nRunning $dvi_filter [$root_filename]\n------------\n"
1947
 
     unless $silent;
1948
 
  &Run("$dvi_filter < $dvi_file > $root_filename.dviF");
1949
 
  $updated = 1;
1950
 
}
1951
 
 
1952
 
#************************************************************
1953
 
 
1954
 
sub make_pdf2
1955
 
{
1956
 
    my $ps_file;
1957
 
    my $pdf_file;
1958
 
 
1959
 
    if ( length($ps_filter) == 0 )
1960
 
        {$ps_file = "$root_filename.ps";}
1961
 
    else 
1962
 
        {$ps_file = "$root_filename.psF";}
1963
 
    $pdf_file = "$root_filename.pdf";
1964
 
 
1965
 
    my $ps_mtime = &get_mtime("$ps_file");
1966
 
    my $pdf_mtime = &get_mtime("$pdf_file");
1967
 
    if ( ! -e $ps_file ) {
1968
 
        warn "Postscript file \"$ps_file\" has not been made\n";
1969
 
        return;
1970
 
    }
1971
 
    if ((! -e "$pdf_file") 
1972
 
        ||( $pdf_mtime < $ps_mtime )
1973
 
       )
1974
 
    {
1975
 
        warn "------------\nRunning $ps2pdf [$root_filename]\n------------\n"
1976
 
          unless $silent;
1977
 
        &Run("$ps2pdf  $ps_file $pdf_file");
1978
 
        $updated = 1;
1979
 
    }
1980
 
    else
1981
 
    { 
1982
 
        warn "Latexmk: File '$pdf_file' is up to date\n" if !$quell_uptodate_msgs;
1983
 
    }
1984
 
}
1985
 
 
1986
 
#************************************************************
1987
 
 
1988
 
sub make_pdf3
1989
 
{
1990
 
    my $dvi_file;
1991
 
    my $pdf_file;
1992
 
 
1993
 
    if ( length($dvi_filter) == 0 )
1994
 
        {$dvi_file = "$root_filename.dvi";}
1995
 
    else 
1996
 
        {$dvi_file = "$root_filename.dviF";}
1997
 
    $pdf_file = "$root_filename.pdf";
1998
 
 
1999
 
    my $dvi_mtime = &get_mtime("$dvi_file");
2000
 
    my $pdf_mtime = &get_mtime("$pdf_file");
2001
 
    if ( ! -e $dvi_file ) {
2002
 
        warn "Dvi file \"$dvi_file\" has not been made, so I cannot convert it to pdf\n";
2003
 
        return;
2004
 
    }
2005
 
    if ((! -e "$pdf_file") 
2006
 
        ||( $pdf_mtime < $dvi_mtime )
2007
 
       )
2008
 
    {
2009
 
        warn "------------\nRunning $dvipdf [$root_filename]\n------------\n"
2010
 
           unless $silent;
2011
 
        &Run("$dvipdf  $dvi_file $pdf_file");
2012
 
        $updated = 1;
2013
 
    }
2014
 
    else
2015
 
    { 
2016
 
        warn "Latexmk: File '$pdf_file' is up to date\n" if !$quell_uptodate_msgs;
2017
 
    }
2018
 
}
2019
 
 
2020
 
#************************************************************
2021
 
 
2022
 
sub make_printout
2023
 
{
2024
 
  my $ext = '';      # extension of file to print
2025
 
  my $command = '';  # command to print it
2026
 
  if ( $print_type eq 'dvi' ) {
2027
 
      if ( length($dvi_filter) == 0 )
2028
 
      {
2029
 
        $ext = '.dvi';
2030
 
      }
2031
 
      else
2032
 
      {
2033
 
        $ext = '.dviF';
2034
 
      }
2035
 
      $command = $lpr_dvi;
2036
 
  }
2037
 
  elsif ( $print_type eq 'pdf' ) {
2038
 
      $ext = '.pdf';
2039
 
      $command = $lpr_pdf;
2040
 
  }
2041
 
  elsif ( $print_type eq 'ps' ) {
2042
 
      if ( length($ps_filter) == 0 )
2043
 
      {
2044
 
        $ext = '.ps';
2045
 
      }
2046
 
      else
2047
 
      {
2048
 
        $ext = '.psF';
2049
 
      }
2050
 
      $command = $lpr;
2051
 
  }
2052
 
  elsif ( $print_type eq 'none' ) {
2053
 
      warn "------------\nPrinting is configured off\n------------\n";
2054
 
      return;
2055
 
  }
2056
 
  else
2057
 
  {
2058
 
     die "Latexmk: incorrect value \"$print_type\" for type of file to print\n".
2059
 
         "Allowed values are \"dvi\", \"pdf\", \"ps\", \"none\"\n"
2060
 
  }
2061
 
  my $file = $root_filename.$ext;
2062
 
  if ( ! -e $file ) {
2063
 
      warn "File \"$file\" has not been made, so I cannot print it\n";
2064
 
      return;
2065
 
  }
2066
 
  warn "------------\nPrinting using $command $file\n------------\n"
2067
 
     unless $silent;
2068
 
  &Run("$command $file");
2069
 
}
2070
 
 
2071
 
#************************************************************
2072
 
 
2073
 
sub make_postscript
2074
 
{
2075
 
  my $tmpfile;
2076
 
  my $header;
2077
 
  my $dvi_file;
2078
 
 
2079
 
  # Figure out the dvi file name
2080
 
  if ( length($dvi_filter) == 0 )
2081
 
  {
2082
 
    $dvi_file = "$root_filename.dvi";
2083
 
  }
2084
 
  else
2085
 
  {
2086
 
    $dvi_file = "$root_filename.dviF";
2087
 
  }
2088
 
 
2089
 
  if ( ! -e $dvi_file ) {
2090
 
      warn "Dvi file \"$dvi_file\" has not been made, so I cannot convert it to postscript\n";
2091
 
      return;
2092
 
  }
2093
 
 
2094
 
  # Do banner stuff
2095
 
  if ( $banner )
2096
 
  {
2097
 
    ## Make temp banner file
2098
 
#    local(*INFILE,*OUTFILE,$count);
2099
 
    local(*OUTFILE,$count);
2100
 
 
2101
 
    $tmpfile = "$tmpdir/latexmk.$$";
2102
 
    $count = 0;
2103
 
    while ( -e $tmpfile )
2104
 
    {
2105
 
      $count = $count + 1;
2106
 
      $tmpfile = "$tmpdir/latexmk.$$.$count";
2107
 
    }
2108
 
    if ( ! open(OUTFILE, ">$tmpfile") ) {
2109
 
      die "Latexmk: Could not open temporary file [$tmpfile]\n"; }
2110
 
    print OUTFILE "userdict begin /bop-hook{gsave 200 30 translate\n";
2111
 
    print OUTFILE "65 rotate /Times-Roman findfont $banner_scale scalefont setfont\n";
2112
 
    print OUTFILE "0 0 moveto $banner_intensity setgray ($banner_message) show grestore}def end\n";
2113
 
    close(OUTFILE);
2114
 
    $header = "-h $tmpfile";
2115
 
  }
2116
 
  else
2117
 
  {
2118
 
    $header = '';
2119
 
  }
2120
 
 
2121
 
  my $ps_mtime = &get_mtime("$root_filename.ps");
2122
 
  my $dvi_mtime = &get_mtime("$dvi_file");
2123
 
  if ((! -e "$root_filename.ps") 
2124
 
      ||( $ps_mtime < $dvi_mtime )
2125
 
     )
2126
 
  {
2127
 
      warn "------------\nRunning $dvips [$root_filename]\n------------\n"
2128
 
         unless $silent;
2129
 
      &Run("$dvips $header $dvi_file -o $root_filename.ps");
2130
 
      ## Do we have postscript filtering?
2131
 
      if ( length($ps_filter) != 0 )
2132
 
      {
2133
 
         warn "------------\nRunning $ps_filter [$root_filename]\n------------\n"
2134
 
            unless $silent;
2135
 
         &Run("$ps_filter < $root_filename.ps > $root_filename.psF");
2136
 
      }
2137
 
      $updated = 1;
2138
 
  }
2139
 
  else
2140
 
  { 
2141
 
      warn "Latexmk: File '$root_filename.ps' is up to date\n" if !$quell_uptodate_msgs;
2142
 
  }
2143
 
 
2144
 
  if ( $banner )
2145
 
  {
2146
 
    unlink("$tmpfile");
2147
 
  }
2148
 
 
2149
 
}
2150
 
 
2151
 
#************************************************************
2152
 
# run appropriate previewer.
2153
 
 
2154
 
sub make_preview
2155
 
{
2156
 
  my $ext;
2157
 
  my $viewer;
2158
 
  if ( $view eq 'dvi' )
2159
 
  {
2160
 
     $viewer = $dvi_previewer;
2161
 
     $ext = '.dvi';
2162
 
     if ( length($dvi_filter) != 0 )
2163
 
     {
2164
 
       $ext = '.dviF';
2165
 
     }
2166
 
  } 
2167
 
  elsif ( $view eq 'ps' )
2168
 
  {
2169
 
    $viewer = $ps_previewer;
2170
 
    $ext = '.ps';
2171
 
    if ( length($ps_filter) != 0 )
2172
 
    {
2173
 
      $ext = '.psF';
2174
 
    }
2175
 
  }
2176
 
  elsif ( $view eq 'pdf' )
2177
 
  {
2178
 
    $viewer = $pdf_previewer;
2179
 
    $ext = '.pdf';
2180
 
  }
2181
 
  else
2182
 
  {
2183
 
      die "Latexmk: BUG: No preview method defined\n";
2184
 
  }
2185
 
 
2186
 
  my $view_file = "$root_filename$ext";  
2187
 
 
2188
 
  if ( ! -e $view_file ) {
2189
 
      warn "File \"$view_file\" has not been made, so I cannot view it\n";
2190
 
      return;
2191
 
  }
2192
 
  warn "------------\nStarting previewer: $viewer $view_file\n------------\n"
2193
 
     unless $silent;
2194
 
  my ($pid, $return) = &Run ("$viewer $view_file");
2195
 
  if ($return){
2196
 
    warn "Latexmk: Could not start previewer [$viewer $view_file]";
2197
 
  }
2198
 
#  exit;
2199
 
}
2200
 
 
2201
 
#************************************************************
2202
 
 
2203
 
sub make_preview_continous
2204
 
{
2205
 
 
2206
 
  # How do we persuade viewer to update.  Default is to do nothing.
2207
 
  my $viewer_update_method = 0;
2208
 
  # Extension of file:
2209
 
  my $ext;    
2210
 
  $quell_uptodate_msgs = 1;
2211
 
  if ( $view eq 'dvi' )
2212
 
  {
2213
 
     $viewer = $dvi_previewer;
2214
 
     $viewer_update_method = $dvi_update_method;
2215
 
     $ext = '.dvi';
2216
 
     if ( length($dvi_filter) != 0 )
2217
 
     {
2218
 
       $ext = '.dviF';
2219
 
     }
2220
 
  } 
2221
 
  elsif ( $view eq 'ps' )
2222
 
  {
2223
 
     $viewer = $ps_previewer;
2224
 
     $viewer_update_method = $ps_update_method;
2225
 
     $ext = '.ps';
2226
 
     if ( length($ps_filter) != 0 )
2227
 
     {
2228
 
        $ext = '.psF';
2229
 
     }
2230
 
  }
2231
 
  elsif ( $view eq 'pdf' )
2232
 
  {
2233
 
     $viewer_update_method = $pdf_update_method;
2234
 
     $viewer = $pdf_previewer;
2235
 
     $ext = '.pdf';
2236
 
  }
2237
 
  else
2238
 
  {
2239
 
      die "Latexmk: BUG: No preview method defined\n";
2240
 
  }
2241
 
 
2242
 
 
2243
 
  # Viewer information:
2244
 
  my $viewer_running = 0;    # No viewer running yet
2245
 
  my $view_file = "$root_filename$ext";  
2246
 
  my $viewer_process = 0;    # default: no viewer process number known
 
2280
} #END find_basename
 
2281
 
 
2282
#************************************************************
 
2283
 
 
2284
sub make_preview_continuousB {
 
2285
  # Version for use with makeB
 
2286
    local @changed = ();
 
2287
    local @disappeared = ();
 
2288
    local @no_dest = ();       # Non-existent destination files
 
2289
    local @rules_never_run = ();
 
2290
    local @rules_to_apply = ();
 
2291
 
 
2292
    local $failure = 0;
 
2293
    local $runs = 0;
 
2294
    local %rules_applied = ();
 
2295
    local $updated = 0;
 
2296
 
 
2297
    # What to make?
 
2298
    my @targets = keys %requested_filerules;
 
2299
 
 
2300
    $quell_uptodate_msgs = 1;
 
2301
 
 
2302
    local $view_file = '';
 
2303
    rdb_one_rule( 'view', sub{ $view_file = $$Psource; } );
2247
2304
  
2248
 
  $dest_condition_ignore = 1;   #make_latex_dvi-pdf will ignore destination 
2249
 
                                #in make rule. If the destination file does not
2250
 
                                #exists, it is because of an error.
2251
 
  # Loop forever, rebuilding .dvi and .ps as necessary.
2252
 
  my $first_time = 1;
2253
 
  while ( 1 ) {
2254
 
     # Wait to run a viewer until we know we have the view file
2255
 
     # If there are errors in the initial run, the 
2256
 
     if ( (!$viewer_running) && (-e $view_file) ) {
2257
 
        # note, we only launch a previewer if one isn't already running...
2258
 
        # But I only know how to do this under UNIX
2259
 
        $viewer_process = &find_process_id(  $view_file );
2260
 
        if ( $viewer_process ) {
2261
 
           warn "Previewer is already running\n" 
2262
 
              if $first_time && !$silent;
2263
 
        } else {
2264
 
           warn "I have not found a previewer that is already running. \n",
2265
 
                "So I will start it: $viewer $view_file\n------------\n"
2266
 
              unless $silent;
2267
 
           my $retcode;
2268
 
           ($viewer_process, $retcode) 
2269
 
              = &Run ("start $viewer $root_filename$ext");
2270
 
           if ( $retcode != 0 ) {
2271
 
              if ($force_mode) {
2272
 
                 warn "I could not run previewer\n";
2273
 
              }
2274
 
              else {
2275
 
                 &exit_msg1( "I could not run previewer", $retcode);
2276
 
              }
2277
 
           }
2278
 
           else {
2279
 
              $viewer_running = 1;
2280
 
           } # end analyze result of trying to run viewer
2281
 
       } # end if $viewer_process
2282
 
     } # end start viewer
2283
 
     if ( $first_time || $updated ) {
2284
 
        print "\n=== Watching for updated files. Use ctrl/C to stop ...\n";
2285
 
        $first_time = 0;
2286
 
     }
2287
 
     $updated = 0;
2288
 
     $failure = 0;
2289
 
     sleep($sleep_time);
2290
 
     &make_files;
2291
 
     if ( ($failure <= 0) 
2292
 
          && ($viewer_process != 0) 
2293
 
          && $updated 
2294
 
          && ($viewer_update_method == 2) 
2295
 
        )
2296
 
     {
2297
 
        if ( $diagnostics ) {
2298
 
            print "I am signalling viewer, process ID $viewer_process\n";
2299
 
        }
2300
 
        kill 'USR1', $viewer_process;
2301
 
     }
2302
 
  } #end infinite_loop
2303
 
} #end sub make_preview_continuous
2304
 
 
2305
 
#************************************************************
2306
 
 
2307
 
# cleanup_basic
2308
 
# - erases basic set of generated files, exits w/ no other processing.
2309
 
#   (all but aux, dep, dvi, pdf, and ps), 
2310
 
#   and also texput.log, and files with extensions in $clean_ext
2311
 
 
2312
 
sub cleanup_basic
2313
 
{
2314
 
# Basic set:
2315
 
  unlink("$root_filename.aux.bak");
2316
 
  unlink("$root_filename.bbl");
2317
 
  unlink("$root_filename.blg");
2318
 
  unlink("$root_filename.log");
2319
 
  unlink("$root_filename.ind");
2320
 
  unlink("$root_filename.idx");
2321
 
  unlink("$root_filename.idx.bak");
2322
 
  unlink("$root_filename.ilg");
2323
 
  unlink("$root_filename.toc");
2324
 
  unlink("$root_filename.toc.bak");
2325
 
  unlink("$root_filename.lof");
2326
 
  unlink("$root_filename.lot");
2327
 
  unlink("texput.log");
2328
 
 
2329
 
  # Do any other file extensions specified
2330
 
  foreach $ext (split(' ',$clean_ext))
2331
 
  {
2332
 
    unlink("$root_filename.$ext");
2333
 
  }
2334
 
}
2335
 
 
2336
 
 
2337
 
#************************************************************
2338
 
# cleanup_dvi_ps_pdf
2339
 
# - erases generated dvi, ps, and pdf files (and others specified in 
2340
 
#   $cleanup_full_ext),
2341
 
#   and also texput.dvi, and files with extensions in $clean_full_ext
2342
 
 
2343
 
sub cleanup_dvi_ps_pdf
2344
 
{
2345
 
  unlink("$root_filename.dvi");
2346
 
  unlink("$root_filename.pdf");
2347
 
  unlink("$root_filename.ps");
2348
 
  unlink("$root_filename.dviF");
2349
 
  unlink("$root_filename.psF");
2350
 
  unlink("texput.dvi");
2351
 
  # Do any other file extensions specified
2352
 
  foreach $ext (split(' ',$clean_full_ext))
2353
 
  {
2354
 
    unlink("$root_filename.$ext");
2355
 
  }
2356
 
}
2357
 
 
2358
 
 
2359
 
#************************************************************
2360
 
# cleanup_aux_dep
2361
 
# - erases generated aux and dep files, and also texput.aux
2362
 
 
2363
 
sub cleanup_aux_dep
2364
 
{
2365
 
  unlink("$root_filename.aux");
2366
 
  unlink("$root_filename.dep");
2367
 
  unlink("texput.aux");
2368
 
  # .aux files are also made for \include'd files
2369
 
  foreach my $include (@includes) { 
2370
 
     $include =~ s/\.[^\.]*$/.aux/;
2371
 
     unlink($include);
2372
 
  }
2373
 
}
2374
 
 
2375
 
 
2376
 
#************************************************************
2377
 
 
2378
 
sub aux_restore {
2379
 
   warn "Latexmk: restoring last $root_filename.aux file\n";
2380
 
   # But don't copy the time from the aux.bak file
2381
 
   # So the aux file will look up-to-date
2382
 
   copy_file_keep_time( "$root_filename.aux.bak", "$root_filename.aux" );
2383
 
}
 
2305
    if ( ($view eq 'dvi') || ($view eq 'pdf') || ($view eq 'ps') ) { 
 
2306
        warn "Viewing $view\n";
 
2307
    }
 
2308
    elsif ( $view eq 'none' ) {
 
2309
        warn "Not using a previewer\n";
 
2310
        $view_file = '';
 
2311
    }
 
2312
    else {
 
2313
        warn "$My_name:  BUG: Invalid preview method '$view'\n";
 
2314
        exit 20;
 
2315
    }
 
2316
 
 
2317
    my $viewer_running = 0;    # No viewer known to be running yet
 
2318
    # Get information from update_view rule
 
2319
    local $viewer_update_method = 0;
 
2320
    # Pointers so we can update the following:
 
2321
    local $Pviewer_process = undef;    
 
2322
    local $Pneed_to_get_viewer_process = undef;
 
2323
    rdb_one_rule( 'update_view', 
 
2324
                  sub{ $viewer_update_method = $$PAint_cmd[1]; 
 
2325
                       $Pviewer_process = \$$PAint_cmd[3]; 
 
2326
                       $Pneed_to_get_viewer_process = \$$PAint_cmd[4]; 
 
2327
                     } 
 
2328
                );
 
2329
    # Note that we don't get the previewer process number from the program
 
2330
    # that starts it; that might only be a script to get things set up and the 
 
2331
    # actual previewer could be (and sometimes IS) another process.
 
2332
 
 
2333
    if ( ($view_file ne '') && (-e $view_file) && !$new_viewer_always ) {
 
2334
        # Is a viewer already running?
 
2335
        #    (We'll save starting up another viewer.)
 
2336
        $$Pviewer_process = &find_process_id( $view_file );
 
2337
        if ( $$Pviewer_process ) {
 
2338
            warn "$My_name: Previewer is already running\n" 
 
2339
              if !$silent;
 
2340
            $viewer_running = 1;
 
2341
            $$Pneed_to_get_viewer_process = 0;
 
2342
        }
 
2343
    }
 
2344
 
 
2345
    # Loop forever, rebuilding .dvi and .ps as necessary.
 
2346
    # Set $first_time to flag first run (to save unnecessary diagnostics)
 
2347
CHANGE:
 
2348
    for (my $first_time = 1; 1; $first_time = 0 ) {
 
2349
        $updated = 0;
 
2350
        $failure = 0;
 
2351
        $failure_msg = '';
 
2352
        if ( $MSWin_fudge_break && ($^O eq "MSWin32") ) {
 
2353
            # Fudge under MSWin32 ONLY, to stop perl/latexmk from
 
2354
            #   catching ctrl/C and ctrl/break, and let it only reach
 
2355
            #   downstream programs. See comments at first definition of
 
2356
            #   $MSWin_fudge_break.
 
2357
            $SIG{BREAK} = $SIG{INT} = 'IGNORE';
 
2358
        }
 
2359
        $failure = rdb_makeB( @targets );
 
2360
 
 
2361
##     warn "=========Viewer PID = $$Pviewer_process; updated=$updated\n";
 
2362
 
 
2363
        if ( $MSWin_fudge_break && ($^O eq "MSWin32") ) {
 
2364
            $SIG{BREAK} = $SIG{INT} = 'DEFAULT';
 
2365
        }
 
2366
        if ( $failure > 0 ) {
 
2367
            if ( !$failure_msg ) {
 
2368
                $failure_msg = 'Failure to make the files correctly';
 
2369
            }
 
2370
            # There will be files changed during the run that are irrelevant.
 
2371
            # We need to wait for the user to change the files.
 
2372
            # So set the GENERATED files as up-to-date
 
2373
            rdb_for_some( [keys %current_primaries], \&rdb_update_gen_files );
 
2374
 
 
2375
            $failure_msg =~ s/\s*$//;  #Remove trailing space
 
2376
            warn "$My_name: $failure_msg\n",
 
2377
    "    ==> You will need to change a source file before I do another run <==\n";
 
2378
        }
 
2379
        elsif ( ($view_file ne '') && (-e $view_file) && $updated && $viewer_running ) {
 
2380
            # A viewer is running.  Explicitly get it to update screen if we have to do it:
 
2381
            rdb_one_rule( 'update_view', \&rdb_run1 );
 
2382
        }
 
2383
        elsif ( ($view_file ne '') && (-e $view_file) && !$viewer_running ) {
 
2384
            # Start the viewer
 
2385
            if ( !$silent ) {
 
2386
                if ($new_viewer_always) {
 
2387
                    warn "$My_name: starting previewer for '$view_file'\n",
 
2388
                         "------------\n";
 
2389
                }
 
2390
                else {
 
2391
                    warn "$My_name: I have not found a previewer that ",
 
2392
                         "is already running. \n",
 
2393
                         "   So I will start it for '$view_file'\n",
 
2394
                         "------------\n";
 
2395
               }
 
2396
            }
 
2397
            local $retcode = 0;
 
2398
            rdb_one_rule( 'view', sub { $retcode = &rdb_run1;} );
 
2399
# PREVIOUS            local $retcode = rdb_makeB ( 'view' );
 
2400
            if ( $retcode != 0 ) {
 
2401
                if ($force_mode) {
 
2402
                    warn "$My_name: I could not run previewer\n";
 
2403
                }
 
2404
                else {
 
2405
                    &exit_msg1( "I could not run previewer", $retcode);
 
2406
                }
 
2407
            }
 
2408
            else {
 
2409
                $viewer_running = 1;
 
2410
                $$Pneed_to_get_viewer_process = 1;
 
2411
            } # end analyze result of trying to run viewer
 
2412
       } # end start viewer
 
2413
       rdb_show_rule_errors();
 
2414
       if ( $first_time || $updated || $failure ) {
 
2415
          print "\n=== Watching for updated files. Use ctrl/C to stop ...\n";
 
2416
       }
 
2417
       $waiting = 1; if ($diagnostics) { warn "WAITING\n"; }
 
2418
       &catch_break;
 
2419
       $have_break = 0;
 
2420
  WAIT: while (1) {
 
2421
           sleep($sleep_time);
 
2422
           if ($have_break) { last WAIT; }
 
2423
           if ( rdb_new_changes(@targets) ) { 
 
2424
               if (!$silent) {
 
2425
                   warn "$My_name: Need to remake files.\n";
 
2426
                   &rdb_diagnose_changes( '  ' );
 
2427
               }
 
2428
               last WAIT;
 
2429
           }
 
2430
        # Does this do this job????
 
2431
           local $new_files = 0;
 
2432
           rdb_for_some( [keys %current_primaries], sub{ $new_files += &rdb_find_new_filesB } );
 
2433
           if ($new_files > 0) {
 
2434
               warn "$My_name: New file(s) found.\n";
 
2435
               last WAIT; 
 
2436
           }
 
2437
           if ($have_break) { last WAIT; }
 
2438
     } # end WAIT:
 
2439
     &default_break;
 
2440
     if ($have_break) { 
 
2441
          print "$My_name: User typed ctrl/C or ctrl/break.  I'll stop.\n";
 
2442
          exit;
 
2443
     }
 
2444
     $waiting = 0; if ($diagnostics) { warn "NOT       WAITING\n"; }
 
2445
  } #end infinite_loop CHANGE:
 
2446
} #END sub make_preview_continuousB
 
2447
 
 
2448
#************************************************************
 
2449
 
 
2450
sub process_rc_file {
 
2451
    # Usage process_rc_file( filename )
 
2452
    # Run rc_file whose name is given in first argument
 
2453
    #    Exit with code 11 if file could not be read.  
 
2454
    #      (In general this is not QUITE the right error)
 
2455
    #    Exit with code 13 if there is a syntax error or other problem.
 
2456
    # ???Should I leave the exiting to the caller (perhaps as an option)?
 
2457
    #     But I can always catch it with an eval if necessary.
 
2458
    #     That confuses ctrl/C and ctrl/break handling.
 
2459
    my $rc_file = $_[0];
 
2460
    warn "$My_name: Executing PERL code in file '$rc_file'...\n" 
 
2461
        if  $diagnostics;
 
2462
    do( $rc_file );
 
2463
    # The return value from the do is not useful, since it is the value of 
 
2464
    #    the last expression evaluated, which could be anything.
 
2465
    # The correct test of errors is on the values of $! and $@.
 
2466
 
 
2467
# This is not entirely correct.  On gluon2:
 
2468
#      rc_file does open of file, and $! has error, apparently innocuous
 
2469
#      See ~/proposal/06/latexmkrc-effect
 
2470
 
 
2471
    my $OK = 1;
 
2472
    if ( $! ) {
 
2473
        # Get both numeric error and its string, by forcing numeric and 
 
2474
        #   string contexts:
 
2475
        my $err_no = $!+0;
 
2476
        my $err_string = "$!";
 
2477
        warn "$My_name: Initialization file '$rc_file' could not be read,\n",
 
2478
             "   or it gave some other problem. Error code \$! = $err_no.\n",
 
2479
             "   Error string = '$err_string'\n";
 
2480
        $! = 256;
 
2481
        $OK = 0;
 
2482
    }
 
2483
    if ( $@ ) {
 
2484
        $! = 256;
 
2485
        # Indent the error message to make it easier to locate
 
2486
        my $indented = prefix( $@, "    " );
 
2487
        $@ = "";
 
2488
        warn "$My_name: Initialization file '$rc_file' gave an error:\n",
 
2489
            "$indented";
 
2490
        $OK = 0;
 
2491
    }
 
2492
    if ( ! $OK ) { 
 
2493
        die "$My_name: Stopping because of problem with rc file\n"; 
 
2494
    }
 
2495
} #END process_rc_file
 
2496
 
 
2497
#************************************************************
 
2498
 
 
2499
sub execute_code_string {
 
2500
    # Usage execute_code_string( string_of_code )
 
2501
    # Run the PERL code contained in first argument
 
2502
    #    Exit with code 13 if there is a syntax error or other problem.
 
2503
    # ???Should I leave the exiting to the caller (perhaps as an option)?
 
2504
    #     But I can always catch it with an eval if necessary.
 
2505
    #     That confuses ctrl/C and ctrl/break handling.
 
2506
    my $code = $_[0];
 
2507
    warn "$My_name: Executing initialization code specified by -e:\n",
 
2508
         "   '$code'...\n" 
 
2509
        if  $diagnostics;
 
2510
    eval $code;
 
2511
    # The return value from the eval is not useful, since it is the value of 
 
2512
    #    the last expression evaluated, which could be anything.
 
2513
    # The correct test of errors is on the values of $! and $@.
 
2514
 
 
2515
    if ( $@ ) {
 
2516
        $! = 256;
 
2517
        my $message = $@;
 
2518
        $@ = "";
 
2519
        $message =~ s/\s*$//;
 
2520
        die "$My_name: ",
 
2521
            "Stopping because executing following code from command line\n",
 
2522
            "    $code\n",
 
2523
            "gave an error:\n",
 
2524
            "    $message\n";
 
2525
    }
 
2526
} #END execute_code_string
 
2527
 
 
2528
#************************************************************
 
2529
 
 
2530
sub cleanup1 {
 
2531
    # Usage: cleanup1( exts_without_period, ... )
 
2532
    foreach (@_) { unlink("$root_filename.$_"); }
 
2533
} #END cleanup1
 
2534
 
 
2535
#************************************************************
 
2536
#************************************************************
 
2537
#************************************************************
 
2538
 
 
2539
#   Error handling routines, warning routines, help
 
2540
 
 
2541
#************************************************************
 
2542
 
 
2543
sub die_trace {
 
2544
    # Call: die_trace( message );
 
2545
    &traceback;   # argument(s) passed unchanged
 
2546
    die "\n";
 
2547
} #END die_trace
 
2548
 
 
2549
#************************************************************
 
2550
 
 
2551
sub traceback {
 
2552
    # Call: &traceback 
 
2553
    # or traceback( message,  )
 
2554
    my $msg = shift;
 
2555
    if ($msg) { warn "$msg\n"; }
 
2556
    warn "Traceback:\n";
 
2557
    my $i=0;     # Start with immediate caller
 
2558
    while ( my ($pack, $file, $line, $func) = caller($i++) ) {
 
2559
        if ($func eq 'die_trace') { next; }
 
2560
        warn "   $func called from line $line\n";
 
2561
    }
 
2562
} #END traceback
2384
2563
 
2385
2564
#************************************************************
2386
2565
 
2391
2570
  #    2. if action set, then restore aux file
2392
2571
  #    3. exit with retcode
2393
2572
  warn "\n------------\n";
2394
 
  warn "Latexmk: $_[0].\n";
 
2573
  warn "$My_name: $_[0].\n";
2395
2574
  warn "-- Use the -f option to force complete processing.\n";
2396
 
  if ($_[2])
2397
 
  {
2398
 
      &aux_restore;
2399
 
  }
 
2575
 
2400
2576
  my $retcode = $_[1];
2401
2577
  if ($retcode >= 256) {
2402
2578
     # Retcode is the kind returned by system from an external command
2404
2580
     $retcode /= 256;
2405
2581
  }
2406
2582
  exit $retcode;
2407
 
}
2408
 
 
2409
 
#************************************************************
2410
 
 
2411
 
sub die_help
2412
 
# Die giving diagnostic from arguments and how to get help.
 
2583
} #END exit_msg1
 
2584
 
 
2585
#************************************************************
 
2586
 
 
2587
sub warn_running {
 
2588
   # Message about running program:
 
2589
    if ( $silent ) {
 
2590
        warn "$My_name: @_\n";
 
2591
    }
 
2592
    else {
 
2593
        warn "------------\n@_\n------------\n";
 
2594
    }
 
2595
} #END warn_running
 
2596
 
 
2597
#************************************************************
 
2598
 
 
2599
sub exit_help
 
2600
# Exit giving diagnostic from arguments and how to get help.
2413
2601
{
2414
 
    die "\n@_\nUse\n    latexmk -help\nto get usage information\n";
2415
 
}
 
2602
    warn "\n$My_name: @_\n",
 
2603
         "Use\n",
 
2604
         "   $my_name -help\nto get usage information\n";
 
2605
    exit 10;
 
2606
} #END exit_help
2416
2607
 
2417
2608
 
2418
2609
#************************************************************
2420
2611
sub print_help
2421
2612
{
2422
2613
  print
2423
 
  "Latexmk $version_num: Automatic LaTeX document generation routine\n\n",
2424
 
  "Usage: latexmk [latexmk_options] [filename ...]\n\n",
 
2614
  "$My_name $version_num: Automatic LaTeX document generation routine\n\n",
 
2615
  "Usage: $my_name [latexmk_options] [filename ...]\n\n",
2425
2616
  "  Latexmk_options:\n",
 
2617
  "   -bibtex         - use bibtex when needed (default)\n",
 
2618
  "   -bibtex-        - never use bibtex\n",
 
2619
  "   -bibtex-cond    - use bibtex when needed, but only if the bib files exist\n",
2426
2620
  "   -bm <message> - Print message across the page when converting to postscript\n",
2427
2621
  "   -bi <intensity> - Set contrast or intensity of banner\n",
2428
2622
  "   -bs <scale> - Set scale for banner\n",
2429
 
  "   -commands  - list commands used by latexmk for processing files\n",
 
2623
  "   -commands  - list commands used by $my_name for processing files\n",
2430
2624
  "   -c     - clean up (remove) all nonessential files, except\n",
2431
 
  "            dvi, ps and pdf files\n",
 
2625
  "            dvi, ps and pdf files.\n",
 
2626
  "            This and the other clean-ups are instead of a regular make.\n",
2432
2627
  "   -C     - clean up (remove) all nonessential files\n",
2433
2628
  "            including aux, dep, dvi, postscript and pdf files\n",
2434
 
  "   -c1    - clean up (remove) all nonessential files,\n",
2435
 
  "            including dvi, pdf and ps files, but excluding aux and dep files \n",
2436
 
  "   -d     - Print `DRAFT' across the page when converting to postscript\n",
 
2629
  "            and file of database of file information\n",
 
2630
  "   -CA     - clean up (remove) absolutely ALL nonessential files.\n",
 
2631
  "            Now equivalent to -C option.\n",
 
2632
  "   -CF     - Remove file of database of file information before doing \n",
 
2633
  "            other actions\n",
 
2634
  "   -cd    - Change to directory of source file when processing it\n",
 
2635
  "   -cd-   - Do NOT change to directory of source file when processing it\n",
 
2636
  "   -dependents   - Show list of dependent files after processing\n",
 
2637
  "   -dependents-  - Do not show list of dependent files after processing\n",
2437
2638
  "   -dF <filter> - Filter to apply to dvi file\n",
2438
2639
  "   -dvi   - generate dvi\n",
2439
2640
  "   -dvi-  - turn off required dvi\n",
 
2641
  "   -e <code> - Execute specified PERL code\n",
2440
2642
  "   -f     - force continued processing past errors\n",
2441
2643
  "   -f-    - turn off forced continuing processing past errors\n",
2442
 
  "   -F     - Ignore non-existent files when making dependencies\n",
 
2644
  "   -F     - Ignore non-existent files when testing for dependencies\n",
2443
2645
  "   -F-    - Turn off -F\n",
 
2646
  "   -gg    - Super go mode: clean out generated files (-CA), and then\n",
 
2647
  "            process files regardless of file timestamps\n",
2444
2648
  "   -g     - process regardless of file timestamps\n",
2445
2649
  "   -g-    - Turn off -g\n",
2446
2650
  "   -h     - print help\n",
2447
2651
  "   -help - print help\n",
2448
 
  "   -i     - rescan for input if dependency file older than tex file\n",
2449
 
  "   -i-    - Turn off -i\n",
2450
 
  "   -il    - make list of input files by parsing log file\n",
2451
 
  "   -it    - make list of input files by parsing tex file\n",
2452
 
  "   -I     - force rescan for input files\n",
2453
 
  "   -I-    - Turn off -I\n",
 
2652
  "   -jobname=STRING - set basename of output file(s) to STRING.\n",
 
2653
  "            (Like --jobname=STRING on command line for many current\n",
 
2654
  "            implementations of latex/pdflatex.)\n",
2454
2655
  "   -l     - force landscape mode\n",
2455
2656
  "   -l-    - turn off -l\n",
 
2657
  "   -new-viewer    - in -pvc mode, always start a new viewer\n",
 
2658
  "   -new-viewer-   - in -pvc mode, start a new viewer only if needed\n",
 
2659
  "   -nobibtex      - never use bibtex\n",
 
2660
  "   -nodependents  - Do not show list of dependent files after processing\n",
2456
2661
  "   -pdf   - generate pdf by pdflatex\n",
2457
2662
  "   -pdfdvi - generate pdf by dvipdf\n",
2458
2663
  "   -pdfps - generate pdf by ps2pdf\n",
2461
2666
  "   -ps-   - turn off postscript\n",
2462
2667
  "   -pF <filter> - Filter to apply to postscript file\n",
2463
2668
  "   -p     - print document after generating postscript.\n",
2464
 
  "            (Can also print .dvi or .pdf files -- see documentation)\n",
2465
 
  "   -print=dvi - print dvi file\n",
2466
 
  "   -print=ps  - print ps file\n",
2467
 
  "   -print=pdf - print pdf file\n",
 
2669
  "            (Can also .dvi or .pdf files -- see documentation)\n",
 
2670
  "   -print=dvi     - when file is to be printed, print the dvi file\n",
 
2671
  "   -print=ps      - when file is to be printed, print the ps file (default)\n",
 
2672
  "   -print=pdf     - when file is to be printed, print the pdf file\n",
2468
2673
  "   -pv    - preview document.  (Side effect turn off continuous preview)\n",
2469
2674
  "   -pv-   - turn off preview mode\n",
2470
2675
  "   -pvc   - preview document and continuously update.  (This also turns\n",
2471
 
  "                on force mode, so errors do not cause latexmk to stop.)\n",
 
2676
  "                on force mode, so errors do not cause $my_name to stop.)\n",
2472
2677
  "            (Side effect: turn off ordinary preview mode.)\n",
2473
2678
  "   -pvc-  - turn off -pvc\n",
2474
2679
  "   -r <file> - Read custom RC file\n",
2478
2683
  "   -version      - display program version\n",
2479
2684
  "   -view=default - viewer is default (dvi, ps, pdf)\n",
2480
2685
  "   -view=dvi     - viewer is for dvi\n",
 
2686
  "   -view=none    - no viewer is used\n",
2481
2687
  "   -view=ps      - viewer is for ps\n",
2482
2688
  "   -view=pdf     - viewer is for pdf\n",
2483
2689
  "   filename = the root filename of LaTeX document\n",
2489
2695
  "Contents of RC file specified by -r overrides options specified\n",
2490
2696
  "  before the -r option on the command line\n";
2491
2697
 
2492
 
  exit;
2493
 
}
 
2698
} #END print_help
2494
2699
 
2495
2700
#************************************************************
2496
2701
sub print_commands
2497
2702
{
2498
 
  warn "Commands used by latexmk:\n",
 
2703
  warn "Commands used by $my_name:\n",
2499
2704
       "   To run latex, I use \"$latex\"\n",
2500
2705
       "   To run pdflatex, I use \"$pdflatex\"\n",
2501
2706
       "   To run bibtex, I use \"$bibtex\"\n",
2515
2720
       "   To print a ps file, I use \"$lpr\"\n",
2516
2721
       "   To print a dvi file, I use \"$lpr_dvi\"\n",
2517
2722
       "   To print a pdf file, I use \"$lpr_pdf\"\n",
2518
 
       "   To find running processes, I use \"$pscmd\", ",
2519
 
          "and the process number is at position $pid_position\n";
 
2723
       "   To find running processes, I use \"$pscmd\", \n",
 
2724
       "      and the process number is at position $pid_position\n";
2520
2725
   warn "Notes:\n",
2521
2726
        "  Command starting with \"start\" is run detached\n",
2522
2727
        "  Command that is just \"start\" without any other command, is\n",
2523
2728
        "     used under MS-Windows to run the command the operating system\n",
2524
2729
        "     has associated with the relevant file.\n",
2525
2730
        "  Command starting with \"NONE\" is not used at all\n";
2526
 
}
 
2731
} #END print_commands
 
2732
 
 
2733
#************************************************************
 
2734
 
 
2735
sub view_file_via_temporary {
 
2736
    return $always_view_file_via_temporary 
 
2737
           || ($pvc_view_file_via_temporary && $preview_continuous_mode);
 
2738
} #END view_file_via_temporary
2527
2739
 
2528
2740
#************************************************************
2529
2741
#### Tex-related utilities
2530
2742
 
2531
2743
 
2532
 
# check for citation which bibtex didnt find.
2533
 
 
2534
 
sub check_for_bibtex_errors
2535
 
# return 0: OK, 1: bibtex error, 2: could not open .blg file.
2536
 
{
2537
 
  my $log_name = "$root_filename.blg";
2538
 
  my $log_file = 0;
2539
 
  my $retcode = open( $log_file, "<$log_name" );
2540
 
  if ( $retcode == 0) {
2541
 
     if ( !$force_mode ) {
2542
 
        $failure = 1;
2543
 
        $failure_msg = "Could not open bibtex log file for error check";
2544
 
     }
2545
 
     warn "Could not open bibtex log file for error check\n";
2546
 
     return 2;
2547
 
  }
2548
 
  $retcode = 0;
2549
 
  while (<$log_file>)
2550
 
  {
2551
 
#    if (/Warning--/) { return 1; }
2552
 
    if (/error message/) 
2553
 
    { 
2554
 
       $retcode = 1; 
2555
 
       last;
2556
 
    }
2557
 
  }
2558
 
  close $log_file;
2559
 
  return $retcode;
2560
 
}
2561
 
 
2562
 
#************************************************************
2563
 
# check for bibtex warnings
2564
 
 
2565
 
sub check_for_bibtex_warnings
2566
 
# return 0: OK, 1: bibtex warnings, 2: could not open .blg file.
2567
 
{
2568
 
  my $log_name = "$root_filename.blg";
2569
 
  my $log_file = 0;
2570
 
  my $retcode = open( $log_file, "<$log_name" );
2571
 
  if ( $retcode == 0 ) 
2572
 
  {    
2573
 
      $failure = 1;
2574
 
      $failure_msg = "Could not open bibtex log file for warning check";
2575
 
      warn "Latexmk: $failure_msg\n";
2576
 
      return 2;
2577
 
  }
2578
 
  my $have_warning = 0;
2579
 
  while (<$log_file>)
2580
 
  {
2581
 
    if (/Warning--/) { print "Bibtex warning: $_"; $have_warning = 1}
2582
 
    if (/error message/) { print "Bibtex error: $_"; $have_warning = 1}
2583
 
  }
2584
 
  close $log_file;
2585
 
  return $have_warning;
2586
 
}
2587
 
 
2588
 
#************************************************************
2589
 
# - looks recursively for included & inputted and psfig'd files and puts
2590
 
#   them into @includes.
2591
 
# - note only primitive comment removal: cannot deal with escaped %s, but then,
2592
 
#       when would they occur in any line important to latexmk??
2593
 
 
2594
 
sub scan_for_includes
2595
 
{
2596
 
  my $texfile_name = $_[0];
2597
 
  warn "-----Scanning [$texfile_name] for input files etc ... -----\n";
2598
 
  &scan_for_includes_($texfile_name);
2599
 
  ## put root tex file into list of includes.
2600
 
  push @includes, $texfile_name;
2601
 
}
2602
 
 
2603
 
sub scan_for_includes_
2604
 
{
2605
 
  local(*FILE,$orig_filename);
2606
 
##JCC
2607
 
  local($ignoremode,$line);
2608
 
  $ignoremode = 0;
2609
 
  $line = 0;
2610
 
  if (!open(FILE,$_[0])) 
2611
 
  {
2612
 
    warn "Latexmk: could not open input file [$_[0]]\n";
2613
 
    return;
2614
 
  }
2615
 
LINE:
2616
 
  while(<FILE>)
2617
 
  {
2618
 
    $line = $line + 1;
2619
 
    
2620
 
    if ( /^\s*(%#.*)\s*$/ )
2621
 
    {
2622
 
       $_ = $1;
2623
 
       ##warn "======Metacommand \"$_\"\n";
2624
 
       if ( /%#{}end.raw/ || /%#{latexmk}end.ignore/ )
2625
 
       {
2626
 
           $ignoremode = 0;
2627
 
           warn "  Ignore mode off, at line $line in file $_[0].\n";
2628
 
       }
2629
 
       elsif ( $ignoremode == 1 )
2630
 
       {
2631
 
           # In ignore mode only end.raw, etc metacommands are recognized.
2632
 
           next LINE;
2633
 
       }
2634
 
       elsif ( /%#{}raw/ || /%#{}begin.raw/ || 
2635
 
            /%#{latexmk}ignore/ || /%#{latexmk}begin.ignore/ )
2636
 
       {
2637
 
           $ignoremode = 1;
2638
 
           warn "  Ignore mode on, at line $line in file $_[0].\n";
2639
 
       }
2640
 
       elsif ( /%#{latexmk}include.file[\040\011]+([^\040\011\n]*)/ 
2641
 
               || /%#{latexmk}input.file[\040\011]+([^\040\011\n]*)/ )
2642
 
       {
2643
 
          push @includes, $1;
2644
 
          warn "  Adding input file \"$1\" at line $line in file $_[0].\n";
2645
 
       }
2646
 
       else
2647
 
       { 
2648
 
         # Unrecognized metacommands are, by specification, to be ignored.
2649
 
           warn "Unrec. \"$_\"\n";
2650
 
       }
2651
 
       next LINE;
2652
 
    }
2653
 
    if ( $ignoremode == 1 )
2654
 
    {
2655
 
        ##warn "Skipping a line:\n  $_";
2656
 
        next LINE;
2657
 
    }
2658
 
 
2659
 
    ($_) = split('%',$_);               # primitive comment removal
2660
 
 
2661
 
    if (/\\def/ || /\\newcommand/ || /\\renewcommand/ || /\\providecommand/)
2662
 
    {
2663
 
        ##JCC Ignore definitions:
2664
 
        warn "Ignoring definition:\n  $_";
2665
 
    }
2666
 
    elsif (/\\include[{\s]+([^\001\040\011}]*)[\s}]/)
2667
 
    {
2668
 
      $full_filename = $1;
2669
 
      $orig_filename = $full_filename;
2670
 
      $full_filename = &find_file_ext($full_filename, 'tex', \@TEXINPUTS);
2671
 
      if ($full_filename)
2672
 
      {
2673
 
        push @includes,  $full_filename;
2674
 
        if ( -e $full_filename )
2675
 
        {
2676
 
          warn "        Found input file [$full_filename]\n";
2677
 
          &scan_for_includes_($full_filename);
2678
 
        }
2679
 
        else
2680
 
        {
2681
 
          if ( $orig_filename =~ /^\// )
2682
 
          {
2683
 
            warn "Latexmk: In \\include, ",
2684
 
                 "could not find file [$orig_filename]\n";
2685
 
          }
2686
 
          else
2687
 
          {
2688
 
            warn "Latexmk: In \\include, ",
2689
 
                 "could not find file [$orig_filename] in path [@TEXINPUTS]\n";
2690
 
            warn "         assuming in current directory ($full_filename)\n";
2691
 
          }
2692
 
        }
2693
 
      }
2694
 
      else
2695
 
      {
2696
 
        if ( ! $force_include_mode )
2697
 
        {
2698
 
          if ( $orig_filename =~ /^\// )
2699
 
          {
2700
 
            die "Latexmk: In \\include, ",
2701
 
                "could not find file [$orig_filename]\n";
2702
 
          }
2703
 
          else
2704
 
          {
2705
 
            die "Latexmk: In \\include, ",
2706
 
                "could not find file [$orig_filename] in path [@TEXINPUTS]\n";
2707
 
          }
2708
 
        }
2709
 
      }
2710
 
    }
2711
 
    elsif (/\\input[{\s]+([^\001\040\011}]*)[\s}]/)
2712
 
    {
2713
 
      $full_filename = $1;
2714
 
      $orig_filename = $full_filename;
2715
 
      $full_filename = &find_file_ext($full_filename, 'tex', \@TEXINPUTS);
2716
 
      if ($full_filename)
2717
 
      {
2718
 
        push @includes, $full_filename;
2719
 
#       warn "added '$full_filename'\n";
2720
 
        if ( -e $full_filename )
2721
 
        {
2722
 
          warn "        Found input for file [$full_filename]\n";
2723
 
          &scan_for_includes_($full_filename);
2724
 
        }
2725
 
        else
2726
 
        {
2727
 
          if ( $orig_filename =~ /^\// )
2728
 
          {
2729
 
            warn "Latexmk: In \\input, could not find file [$orig_filename]\n";
2730
 
          }
2731
 
          else
2732
 
          {
2733
 
            warn "Latexmk: In \\input, ",
2734
 
                 "could not find file [$orig_filename] in path [@TEXINPUTS]\n";
2735
 
            warn "         assuming in current directory ($full_filename)\n";
2736
 
          }
2737
 
        }
2738
 
      }
2739
 
      else
2740
 
      {
2741
 
        if ( ! $force_include_mode )
2742
 
        {
2743
 
          if ( $orig_filename =~ /^\// )
2744
 
          {
2745
 
            die "Latexmk: In \\input, could not find file [$orig_filename]\n";
2746
 
          }
2747
 
          else
2748
 
          {
2749
 
            die "Latexmk: In \\input, ",
2750
 
                "could not find file [$orig_filename] in path [@TEXINPUTS]\n";
2751
 
          }
2752
 
        }
2753
 
      }
2754
 
    }
2755
 
    elsif (/\\blackandwhite{([^\001\040\011}]*)}/ || /\\colorslides{([^\001}]*)}/)
2756
 
    {
2757
 
############      $slide_mode = 1;
2758
 
      $full_filename = &find_file_ext($1, 'tex', \@TEXINPUTS);
2759
 
      if ($full_filename)
2760
 
      {
2761
 
        push @includes, $full_filename;
2762
 
        if ( -e $full_filename )
2763
 
        {
2764
 
          warn "        Found slide input for file [$full_filename]\n";
2765
 
          &scan_for_includes_($full_filename);
2766
 
        }
2767
 
      }
2768
 
    }
2769
 
    elsif (/\\psfig{file=([^,}]+)/ || /\\psfig{figure=([^,}]+)/)
2770
 
    {
2771
 
      $orig_filename = $1;
2772
 
      $full_filename = &find_file($1, \@psfigsearchpath);
2773
 
      if ($full_filename)
2774
 
      {
2775
 
        push @includes, $full_filename;
2776
 
        if ( -e $full_filename )
2777
 
        {
2778
 
          warn "        Found psfig for file [$full_filename]\n";
2779
 
        }
2780
 
      }
2781
 
    }
2782
 
    elsif ( /\\epsfbox{([^}]+)}/ || /\\epsfbox\[[^\]]*\]{([^}]+)}/ ||
2783
 
            /\\epsffile{([^}]+)}/ || /\\epsffile\[[^\]]*\]{([^}]+)}/ ||
2784
 
            /\\epsfig{file=([^,}]+)/ || /\\epsfig{figure=([^,}]+)/ )
2785
 
    {
2786
 
      $orig_filename = $1;
2787
 
      $full_filename = &find_file($1, \@psfigsearchpath);
2788
 
      if ($full_filename)
2789
 
      {
2790
 
        push @includes, $full_filename;
2791
 
        if ( -e $full_filename )
2792
 
        {
2793
 
          warn "        Found epsf for file [$full_filename]\n";
2794
 
        }
2795
 
      }
2796
 
    }
2797
 
    elsif ( 
2798
 
        /\\includegraphics{([^}]+)}/ || /\\includegraphics\[[^\]]*\]{([^}]+)}/ 
2799
 
       )
2800
 
    {
2801
 
      $orig_filename = $1;
2802
 
      $full_filename = &find_file_ext($1,'eps', \@psfigsearchpath);
2803
 
      if ($full_filename)
2804
 
      {
2805
 
        push @includes, $full_filename;
2806
 
        if ( -e $full_filename )
2807
 
        {
2808
 
          warn "        Found epsf for file [$full_filename]\n";
2809
 
        }
2810
 
      }
2811
 
      else
2812
 
      {
2813
 
        warn "Latexmk: For \\includegraphics, ",
2814
 
             "could not find file [$orig_filename]\n",
2815
 
             "          in path [@psfigsearchpath]\n";
2816
 
        if ( ! $force_include_mode ) {die "\n";}        
2817
 
      }
2818
 
    }
2819
 
    elsif (/\\documentstyle[^\000]+landscape/)
2820
 
    {
2821
 
      warn "    Detected landscape mode\n";
2822
 
      $landscape_mode = 1;
2823
 
    }
2824
 
    elsif (/\\bibliography{([^}]+)}/)
2825
 
    {
2826
 
      @bib_files = split /,/, $1;
2827
 
      &find_file_list1( \@bib_files, \@bib_files, '.bib', \@BIBINPUTS );
2828
 
      warn "    Found bibliography files [@bib_files]\n" unless $silent;
2829
 
      $bibtex_mode = 1;
2830
 
    }
2831
 
    elsif (/\\psfigsearchpath{([^}]+)}/)
2832
 
    {
2833
 
      @psfigsearchpath = &split_search_path(':', '', $1);
2834
 
    }
2835
 
    elsif (/\\graphicspath{([^}]+)}/)
2836
 
    {
2837
 
      @psfigsearchpath = &split_search_path(':', '', $1);
2838
 
    }
2839
 
    elsif (/\\makeindex/)
2840
 
    {
2841
 
      $index_mode = 1;
2842
 
      warn "        Detected index mode\n";
2843
 
    }
2844
 
  }
2845
 
}
 
2744
sub check_bibtex_log {
 
2745
    # Check for bibtex warnings:
 
2746
    # Usage: check_bibtex_log( base_of_bibtex_run )
 
2747
    # return 0: OK, 1: bibtex warnings, 2: bibtex errors, 
 
2748
    #        3: could not open .blg file.
 
2749
 
 
2750
    my $base = $_[0];
 
2751
    my $log_name = "$base.blg";
 
2752
    my $log_file = new FileHandle;
 
2753
    open( $log_file, "<$log_name" )
 
2754
      or return 3;
 
2755
    my $have_warning = 0;
 
2756
    my $have_error = 0;
 
2757
    while (<$log_file>) {
 
2758
        if (/Warning--/) { 
 
2759
            #print "Bibtex warning: $_"; 
 
2760
            $have_warning = 1;
 
2761
        }
 
2762
        if (/error message/) { 
 
2763
            #print "Bibtex error: $_"; 
 
2764
            $have_error = 1;
 
2765
        }
 
2766
    }
 
2767
    close $log_file;
 
2768
    if ($have_error) {return 2;}
 
2769
    if ($have_warning) {return 1;}
 
2770
    return 0;
 
2771
} #END check_bibtex_log
2846
2772
 
2847
2773
#**************************************************
2848
 
sub parse_log
2849
 
{
2850
 
# Scan log file for: include files, bibtex mode, 
 
2774
 
 
2775
sub clean_file_name{
 
2776
    # Convert filename found in log file to true filename.
 
2777
    # Used normally only by parse_logB, below
 
2778
    # 1. For names of form 
 
2779
    #    `"string".ext', which arises e.g., from \jobname.bbl:
 
2780
    #    when the base filename contains spaces, \jobname has quotes.
 
2781
    #    and from \includegraphics with basename specified.
 
2782
    # 2. Or "string.ext" from \includegraphcs with basename and ext specified.
 
2783
    my $filename = $_[0];
 
2784
    $filename =~ s/^\"([^\"]*)\"(.*)$/$1$2/;
 
2785
    return $filename;
 
2786
}
 
2787
# ------------------------------
 
2788
 
 
2789
sub parse_logB {
 
2790
# Scan log file for: dependent files
2851
2791
#    reference_changed, bad_reference, bad_citation
2852
 
# In bibtex mode, scan aux file for bib files
2853
2792
# Return value: 1 if success, 0 if no log file.
2854
2793
# Set global variables:
2855
 
#   @includes to list of included files that exist or that appear to be 
2856
 
#       genuine files (as opposed to incorrectly parsed names).
2857
 
#   %includes_missing to list of files that latex appeared to search for 
2858
 
#        and didn't find, i.e., from error messages 
2859
 
#   @aux_files to list of .aux files.
2860
 
#   Leave these unchanged if there is no log file.
 
2794
#   %dependents: maps definite dependents to code:
 
2795
#      0 = from missing-file line
 
2796
#            May have no extension
 
2797
#            May be missing path
 
2798
#      1 = from 'File: ... Graphic file (type ...)' line
 
2799
#            no path.  Should exist, but may need a search, by kpsewhich.
 
2800
#      2 = from regular '(...' coding for input file, 
 
2801
#            Has NO path, which it would do if LaTeX file
 
2802
#            Highly likely to be mis-parsed line
 
2803
#      3 = ditto, but has a path character ('/').  
 
2804
#            Should be LaTeX file that exists.
 
2805
#            If it doesn't exist, we have probably a mis-parsed line.
 
2806
#            There's no need to do a search.
 
2807
#      4 = definitive, which in this subroutine is only done:
 
2808
#             for default dependents, 
 
2809
#             and for files that exist and are source of conversion
 
2810
#                reported by epstopdf et al.
 
2811
#      5 = Had a missing file line.  Now the file exists.
 
2812
#      6 = File was written during run.  (Overrides 5)
 
2813
#      7 = File was created during run to be read in.  (Overrides 5 and 6)
 
2814
#          (e.g., by epstopdf)
 
2815
# Treat the following specially, since they have special rules
 
2816
#   @bbl_files to list of .bbl files.
 
2817
#   %idx_files to map from .idx files to .ind files.
 
2818
# %generated_log: keys give set of files written by (pdf)latex (e.g., aux, idx)
 
2819
#   as determined by \openout = ... lines in log file.
 
2820
# Also set
2861
2821
#   $reference_changed, $bad_reference, $bad_citation
2862
 
 
2863
 
 
2864
 
    my $log_name = "$root_filename.log";
2865
 
    my $log_file = 0;
2866
 
    if ( ! open( $log_file, "<$log_name" ) )
2867
 
    {
2868
 
        return 0;
 
2822
# Trivial or default values if log file does not exist/cannot be opened
 
2823
 
 
2824
# Give a quick way of looking up custom-dependency extensions
 
2825
    my %cusdep_from = ();
 
2826
    my %cusdep_to = ();
 
2827
    foreach ( @cus_dep_list ) {
 
2828
        my ($fromext, $toext) = split;
 
2829
        $cusdep_from{$fromext} = $cusdep_from{".$fromext"} = $_;
 
2830
        $cusdep_to{$toext} = $cusdep_to{".$toext"} = $_;
2869
2831
    }
2870
 
    my $line_number = 0;
2871
 
    my $graphic_line = 0;
2872
 
    my @bbl_files = ();
2873
 
    my @ignored_input_files = ();
2874
 
    my @existent = ();
2875
 
    my @include_list = ($texfile_name);
2876
 
    my @include_graphics_list = ();
2877
 
    my %includes_from_errors = ();
2878
 
    @includes = ();
2879
 
    %includes_missing = ();
2880
 
    
 
2832
#    print "==== Cusdep from-exts:"; foreach (keys %cusdep_from) {print " '$_'";} print "\n";
 
2833
#    print "==== Cusdep to-exts:"; foreach (keys %cusdep_to) {print " '$_'";} print "\n";
 
2834
 
 
2835
    # Returned info:
 
2836
    %dependents = ();
 
2837
    foreach (@default_includes) { $dependents{$_} = 4; }
 
2838
    @bbl_files = ();
 
2839
    %idx_files = ();    # Maps idx_file to (ind_file, base)
 
2840
    %generated_log = ();
 
2841
    %conversions = ();
 
2842
    # $primary_out is actual output file (dvi or pdf)
 
2843
    # It is initialized before the call to this routine, to ensure
 
2844
    # a sensible default in case of misparsing
2881
2845
 
2882
2846
    $reference_changed = 0;
2883
2847
    $bad_reference = 0;
2884
2848
    $bad_citation = 0;
2885
2849
 
2886
 
##  ?? New.  We'll determine these modes from parsing the file
2887
 
    $bibtex_mode = 0;
2888
 
    $index_mode = 0;
 
2850
    my $log_name = "$root_filename.log";
 
2851
    my $log_file = new FileHandle;
 
2852
    if ( ! open( $log_file, "<$log_name" ) ) {
 
2853
        return 0;
 
2854
    }
 
2855
    if ($log_file_binary) { binmode $log_file; }
 
2856
# Collect lines of log file
 
2857
    my @lines = ();
 
2858
    while(<$log_file>) { 
 
2859
        # Could use chomp here, but that fails if there is a mismatch
 
2860
        #    between the end-of-line sequence used by latex and that
 
2861
        #    used by perl.  (Notably a problem with MSWin latex and
 
2862
        #    cygwin perl!)
 
2863
        s/[\n\r]*$//;
 
2864
        # Handle wrapped lines:
 
2865
        # They are lines brutally broken at exactly $log_wrap chars 
 
2866
        #    excluding line-end.  The TeX program adds an EXTRA 
 
2867
        #    end-of-line character whenever a line gets to $log_wrap
 
2868
        #    characters.  So we recover the unwrapped line(s) simply 
 
2869
        #    by deleting the end-of-line following a line of exactly 
 
2870
        #    $log_wrap characters.  
 
2871
        my $len = length($_);
 
2872
        while ( ($len == $log_wrap) && !eof($log_file) ) {
 
2873
            my $extra = <$log_file>;
 
2874
            $extra =~ s/[\n\r]*$//;
 
2875
            $len = length($extra);
 
2876
            $_ .= $extra;
 
2877
        }
 
2878
        push @lines, $_;
 
2879
    }
 
2880
    close $log_file;
2889
2881
 
 
2882
    push @lines, "";   # Blank line to terminate.  So multiline blocks 
 
2883
              # are always terminated by non-block line, rather than eof.
 
2884
    
 
2885
    my $line = 0;
 
2886
    # For parsing multiple line blocks of info
 
2887
    my $current_pkg = "";   # non-empty string for package name, if in 
 
2888
                            # middle of parsing multi-line block of form:
 
2889
                            #       Package name ....
 
2890
                            #       (name) ...
 
2891
                            #       ...
 
2892
    my $block_type = "";         # Specify information in such a block
 
2893
    my $delegated_source = "";   # If it is a file conversion, specify source
 
2894
    my $delegated_output = "";   #    and output file.  (Don't put in
 
2895
                                 #    data structure until block is ended.)
 
2896
    my %new_conversions = ();
2890
2897
LINE:
2891
 
   while(<$log_file>) { 
2892
 
      $line_number++;
2893
 
      chomp;
2894
 
      if ( $line_number == 1 ){
2895
 
          if ( /^This is / ) {
2896
 
              # First line OK\n";
2897
 
              next LINE;
2898
 
          } else {
2899
 
             die "Error on first line of \"$log_name\".  This is not a TeX log file.\n$_";
2900
 
          }
2901
 
      }
2902
 
      # Handle wrapped lines:
2903
 
      # They are lines brutally broken at exactly $log_wrap chars 
2904
 
      #    excluding line-end.
2905
 
      my $len = length($_);
2906
 
      while ($len == $log_wrap)
2907
 
      {
2908
 
        my $extra = <$log_file>;
2909
 
        chomp $extra;
2910
 
        $line_number++;
2911
 
        $len = length($extra);
2912
 
        $_ .= $extra;
2913
 
      }
2914
 
      # Check for changed references, bad references and bad citations:
2915
 
      if (/Rerun to get/) { 
2916
 
          warn "\n=== References changed.\n";
2917
 
          $reference_changed = 1;
2918
 
      } 
2919
 
      if (/LaTeX Warning: (Reference[^\001]*undefined)./) { 
2920
 
         warn "\n=== $1 \n";
2921
 
         $bad_reference = 1;
2922
 
      } 
2923
 
      if (/LaTeX Warning: (Citation[^\001]*undefined)./) {
2924
 
         warn "\n=== $1 \n";
2925
 
         $bad_citation = 1;
2926
 
      }
2927
 
      if ( /^Document Class: / ) {
2928
 
          # Latex message
2929
 
          next LINE;
2930
 
      }
2931
 
      if ( /^Output written on / ) {
2932
 
          # Latex message
2933
 
          next LINE;
2934
 
      }
2935
 
      if ( /^Underfull / ) {
2936
 
          # Latex error/warning
2937
 
          next LINE;
2938
 
      }
2939
 
      if ( /^Overfull / ) {
2940
 
          # Latex error/warning
2941
 
          next LINE;
2942
 
      }
2943
 
      if ( /^\(Font\)/ ) {
2944
 
          # Font info line
2945
 
          next LINE;
2946
 
      }
2947
 
      if ( /^Package: / ) {
2948
 
          # Package sign-on line
2949
 
          next LINE;
2950
 
      }
2951
 
      if ( /^Document Class: / ) {
2952
 
          # Class sign-on line
2953
 
          next LINE;
2954
 
      }
2955
 
      if ( /^Writing index file / ) {
2956
 
          $index_mode =1;
2957
 
          warn "Latexmk: Index file written, so turn on index_mode\n" 
2958
 
             unless $silent;
2959
 
          next LINE;
2960
 
      }
2961
 
      if ( /^No file .*?\.bbl./ ) {
2962
 
          warn "Non-existent bbl file, so turn on bibtex_mode\n $_"
2963
 
             unless $bibtex_mode == 1;
2964
 
          $bibtex_mode = 1;
2965
 
          next LINE;
2966
 
      }
2967
 
      if ( /^File: ([^\s\[]*) Graphic file \(type / ) {
2968
 
          # First line of message from includegraphics/x
2969
 
          push @include_graphics_list, $1;
2970
 
          next LINE;
2971
 
      }
2972
 
      if ( /^File: / ) {
2973
 
         # Package sign-on line. Includegraphics/x also produces a line 
2974
 
         # with this signature, but I've already handled it.
2975
 
         next LINE;
2976
 
      }
2977
 
      if (/^\! LaTeX Error: File \`([^\']*)\' not found\./ ) {
2978
 
          $includes_missing{$1} = [3];
2979
 
          next LINE;
2980
 
      }
2981
 
      if (/^\! LaTeX Error: / ) {
2982
 
          next LINE;
2983
 
      }
 
2898
    while( $line <= $#lines ) { 
 
2899
        $_ = $lines[$line];
 
2900
        $line ++;
 
2901
        if ( $line == 1 ){
 
2902
            if ( /^This is / ) {
 
2903
                # First line OK
 
2904
                next LINE;
 
2905
            } else {
 
2906
                warn "$My_name: Error on first line of '$log_name'.  ".
 
2907
                    "This is apparently not a TeX log file.\n";
 
2908
                $failure = 1;
 
2909
                $failure_msg = "Log file '$log_name' appears to have wrong format.";
 
2910
                return 0;
 
2911
            }
 
2912
        }
 
2913
        if ( $block_type ) {
 
2914
            # In middle of parsing block
 
2915
            if ( /^\($current_pkg\)/ ) {
 
2916
                # Block continues
 
2917
                if ( ($block_type eq 'conversion') 
 
2918
                     && /^\($current_pkg\)\s+Output file: <([^>]+)>/ ) 
 
2919
                {
 
2920
                    $delegated_output = $1;
 
2921
                }
 
2922
                next LINE;
 
2923
            }
 
2924
            # Block has ended.
 
2925
            if ($block_type eq 'conversion') {
 
2926
                 $new_conversions{$delegated_source} =  $delegated_output;
 
2927
            }
 
2928
            $current_pkg = $block_type 
 
2929
                 = $delegated_source = $delegated_output = "";
 
2930
            # Then process current line
 
2931
        }
 
2932
        # Check for changed references, bad references and bad citations:
 
2933
        if (/Rerun to get/) { 
 
2934
            warn "$My_name: References changed.\n";
 
2935
            $reference_changed = 1;
 
2936
        } 
 
2937
        if (/LaTeX Warning: (Reference[^\001]*undefined)./) { 
 
2938
            warn "$My_name: $1 \n";
 
2939
            $bad_reference = 1;
 
2940
        } 
 
2941
        if (/LaTeX Warning: (Citation[^\001]*undefined)./) {
 
2942
            warn "$My_name: $1 \n";
 
2943
            $bad_citation = 1;
 
2944
        }
 
2945
        if ( /^Document Class: / ) {
 
2946
            # Class sign-on line
 
2947
            next LINE;
 
2948
        }
 
2949
        if ( /^\(Font\)/ ) {
 
2950
            # Font info line
 
2951
            next LINE;
 
2952
        }
 
2953
        if (/^No pages of output\./) {
 
2954
            $primary_out = ''; 
 
2955
            warn "$My_name: Log file says no output from latex\n";
 
2956
            next LINE;
 
2957
        }
 
2958
        if ( /^Output written on\s+(.*)\s+\(\d+\s+page/ ) {
 
2959
            $primary_out = $1;
 
2960
            warn "$My_name: Log file says output to '$1'\n"
 
2961
               unless $silent;
 
2962
            next LINE;
 
2963
        }
 
2964
        if ( /^Overfull / 
 
2965
             || /^Underfull / 
 
2966
             || /^or enter new name\. \(Default extension: .*\)/ 
 
2967
             || /^\*\*\* \(cannot \\read from terminal in nonstop modes\)/
 
2968
           ) {
 
2969
            # Latex error/warning, etc.
 
2970
            next LINE;
 
2971
        }
 
2972
        if ( /^\\openout\d+\s*=\s*\`([^\']+)\'\.$/ ) {
 
2973
            $generated_log{$1} = 1;
 
2974
            next LINE;
 
2975
        }
 
2976
        # Test for conversion produced by package:
 
2977
        if ( /^Package (\S+) Info: Source file: <([^>]+)>/ ) {
 
2978
            # Info. produced by epstopdf (and possibly others) 
 
2979
            #    about file conversion
 
2980
            $current_pkg = $1;
 
2981
            $delegated_source = $2;
 
2982
            $block_type = 'conversion';
 
2983
            next LINE;
 
2984
        }
 
2985
#    Test for writing of index file.  The precise format of the message 
 
2986
#    depends on which package (makeidx.sty , multind.sty or index.sty) and 
 
2987
#    which version writes the message.
 
2988
        if ( /Writing index file (.*)$/ ) {
 
2989
            my $idx_file = '';
 
2990
            if ( /^Writing index file (.*)$/ ) {
 
2991
                # From makeidx.sty or multind.sty
 
2992
                $idx_file = $1;
 
2993
            }
 
2994
            elsif ( /^index\.sty> Writing index file (.*)$/ ) {
 
2995
                # From old versions of index.sty
 
2996
                $idx_file = $1;
 
2997
            }
 
2998
            elsif ( /^Package \S* Info: Writing index file (.*) on input line/ ) {
 
2999
                # From new versions of index.sty
 
3000
                $idx_file = $1;                
 
3001
            }
 
3002
            else {
 
3003
                warn "$My_name: Message indicates index file was written\n",
 
3004
                     "  ==> but I do not know how to understand it: <==\n",
 
3005
                     "  '$_'\n";
 
3006
                next LINE;
 
3007
            }
 
3008
            # Typically, there is trailing space, not part of filename:
 
3009
            $idx_file =~ s/\s*$//;
 
3010
            $idx_file = clean_file_name($idx_file);
 
3011
            my ($idx_base, $idx_path, $idx_ext) = fileparseA( $idx_file );
 
3012
            $idx_base = $idx_path.$idx_base;
 
3013
            $idx_file = $idx_base.$idx_ext;
 
3014
            if ( $idx_ext eq '.idx' ) {
 
3015
                warn "$My_name: Index file '$idx_file' was written\n"
 
3016
                  unless $silent;
 
3017
                $idx_files{$idx_file} = [ "$idx_base.ind", $idx_base ];
 
3018
            }
 
3019
            elsif ( exists $cusdep_from{$idx_ext} ) {
 
3020
                if ( !$silent ) {
 
3021
                    warn "$My_name: Index file '$idx_file' was written\n";
 
3022
                    warn "   Cusdep '$cusdep_from{$idx_ext}' should be used\n";
 
3023
                }
 
3024
                # No action needed here
 
3025
            }
 
3026
            else {
 
3027
                warn "$My_name: Index file '$idx_file' written\n",
 
3028
                     "  ==> but it has an extension I do not know how to handle <==\n";
 
3029
            }
 
3030
 
 
3031
            next LINE;
 
3032
        }
 
3033
        if ( /^No file (.*?\.bbl)./ ) {
 
3034
            # Notice that the
 
3035
            my $bbl_file = clean_file_name($1);
 
3036
            warn "$My_name: Non-existent bbl file '$bbl_file'\n $_\n";
 
3037
            $dependents{$bbl_file} = 0;
 
3038
            push @bbl_files, $bbl_file;
 
3039
            next LINE;
 
3040
        }
 
3041
        foreach my $pattern (@file_not_found) {
 
3042
            if ( /$pattern/ ) {
 
3043
                my $file = clean_file_name($1);
 
3044
                warn "$My_name: Missing input file: '$file' from line\n  '$_'\n"
 
3045
                    unless $silent;
 
3046
                $dependents{$file} = 0;
 
3047
                next LINE;
 
3048
            }
 
3049
        }
 
3050
        if ( /^File: ([^\s\[]*) Graphic file \(type / ) {
 
3051
            # First line of message from includegraphics/x
 
3052
            $dependents{$1} = 1;
 
3053
            next LINE;
 
3054
        }
 
3055
        # Now test for generic lines to ignore, only after special cases!
 
3056
        if ( /^File: / ) {
 
3057
           # Package sign-on line. Includegraphics/x also produces a line 
 
3058
           # with this signature, but I've already handled it.
 
3059
           next LINE;
 
3060
        }
 
3061
        if ( /^Package: / ) {
 
3062
            # Package sign-on line
 
3063
            next LINE;
 
3064
        }
 
3065
        if (/^\! LaTeX Error: / ) {
 
3066
            next LINE;
 
3067
        }
2984
3068
   INCLUDE_CANDIDATE:
2985
 
       while ( /\((.*$)/ ) {
2986
 
       # Filename found by
2987
 
       # '(', then filename, then terminator.
2988
 
       # Terminators: obvious candidates: ')':  end of reading file
2989
 
       #                                  '(':  beginning of next file
2990
 
       #                                  ' ':  space is an obvious separator
2991
 
       #                                  ' [': start of page: latex
2992
 
       #                                        and pdflatex put a
2993
 
       #                                        space before the '['
2994
 
       #                                  '[':  start of config file
2995
 
       #                                        in pdflatex, after
2996
 
       #                                        basefilename.
2997
 
       #                                  '{':  some kind of grouping
2998
 
       # Problem: 
2999
 
       #   All or almost all special characters are allowed in
3000
 
       #   filenames under some OS, notably UNIX.  Luckily most cases
3001
 
       #   are rare, if only because the special characters need
3002
 
       #   escaping.  BUT 2 important cases are characters that are
3003
 
       #   natural punctuation
3004
 
       #   Under MSWin, spaces are common (e.g., "C:\Program Files")
3005
 
       #   Under VAX/VMS, '[' delimits directory names.  This is
3006
 
       #   tricky to handle.  But I think few users use this OS
3007
 
       #   anymore.
3008
 
       #
3009
 
       # Solution: use ' [', but not '[' as first try at delimiter.
3010
 
       # Then if candidate filename is of form 'name1[name2]', then
3011
 
       #   try splitting it.  If 'name1' and/or 'name2' exists, put
3012
 
       #   it/them in list, else just put 'name1[name2]' in list.
3013
 
       # So form of filename is now:
3014
 
       #  '(', 
3015
 
       # then any number of characters that are NOT ')', '(', or '{'
3016
 
       #   (these form the filename);
3017
 
       # then ' [', or ' (', or ')', or end-of-string.
3018
 
       # That fails for pdflatex
3019
 
       # In log file:
3020
 
       #   '(' => start of reading of file, followed by filename
3021
 
       #   ')' => end of reading of file
3022
 
       #   '[' => start of page (normally preceeded by space)
3023
 
       # Remember: 
3024
 
       #    filename (on VAX/VMS) may include '[' and ']' (directory
3025
 
       #             separators) 
3026
 
       #    filenames (on MS-Win) commonly include space.
3027
 
 
3028
 
       # First step: replace $_ by whole of line after the '('
3029
 
       #             Thus $_ is putative filename followed by other stuff.
3030
 
          $_ = $1; 
3031
 
##          warn "==='$_'===\n";
3032
 
          if ( /^([^\(^\)^\{]*?)\s\[/ ) {
3033
 
              # Use *? in condition: to pick up first ' [' as terminator
3034
 
              # 'file [' should give good filename.
3035
 
          }
3036
 
          elsif ( /^([^\(^\)^\{]*)\s(?=\()/ ) {
3037
 
              # Terminator is ' (', but '(' isn't in matched string,
3038
 
              # so we keep the '(' ready for the next match
3039
 
          }
3040
 
          elsif  ( /^([^\(^\)^\{]*)(\))/ ) {
3041
 
              # Terminator is ')'
3042
 
          }
3043
 
          else {
3044
 
              #Terminator is end-of-string
3045
 
          }
3046
 
##          warn "   ---'$1'---'$''---\n";
3047
 
          $_ = $';       # Put $_ equal to the unmatched tail of string '
3048
 
          my $include_candidate = $1;
3049
 
          $include_candidate =~ s/\s*$//;   # Remove trailing space.
3050
 
          if ( "$include_candidate" eq "[]" ) {
3051
 
              # Part of overfull hbox message
3052
 
              next INCLUDE_CANDIDATE;
3053
 
          }
3054
 
          # Put on list of new include files
3055
 
          my @new_includes = ($include_candidate);
3056
 
          if ( $include_candidate =~ /^(.+)\[([^\]]+)\]$/ ) {
3057
 
             # Construct of form 'file1[file2]', as produced by pdflatex
3058
 
             if ( -e $1 ) {
3059
 
                 # If the first component exists, we probably have the
3060
 
                 #   pdflatex form
3061
 
                 @new_includes = ($1, $2);
3062
 
             }
3063
 
             else {
3064
 
                # We have something else.
3065
 
                # So leave the original candidate in the list
3066
 
             }
3067
 
          }
 
3069
        while ( /\((.*$)/ ) {
 
3070
        # Filename found by
 
3071
        # '(', then filename, then terminator.
 
3072
        # Terminators: obvious candidates: ')':  end of reading file
 
3073
        #                                  '(':  beginning of next file
 
3074
        #                                  ' ':  space is an obvious separator
 
3075
        #                                  ' [': start of page: latex
 
3076
        #                                        and pdflatex put a
 
3077
        #                                        space before the '['
 
3078
        #                                  '[':  start of config file
 
3079
        #                                        in pdflatex, after
 
3080
        #                                        basefilename.
 
3081
        #                                  '{':  some kind of grouping
 
3082
        # Problem: 
 
3083
        #   All or almost all special characters are allowed in
 
3084
        #   filenames under some OS, notably UNIX.  Luckily most cases
 
3085
        #   are rare, if only because the special characters need
 
3086
        #   escaping.  BUT 2 important cases are characters that are
 
3087
        #   natural punctuation
 
3088
        #   Under MSWin, spaces are common (e.g., "C:\Program Files")
 
3089
        #   Under VAX/VMS, '[' delimits directory names.  This is
 
3090
        #   tricky to handle.  But I think few users use this OS
 
3091
        #   anymore.
 
3092
        #
 
3093
        # Solution: use ' [', but not '[' as first try at delimiter.
 
3094
        # Then if candidate filename is of form 'name1[name2]', then
 
3095
        #   try splitting it.  If 'name1' and/or 'name2' exists, put
 
3096
        #   it/them in list, else just put 'name1[name2]' in list.
 
3097
        # So form of filename is now:
 
3098
        #  '(', 
 
3099
        # then any number of characters that are NOT ')', '(', or '{'
 
3100
        #   (these form the filename);
 
3101
        # then ' [', or ' (', or ')', or end-of-string.
 
3102
        # That fails for pdflatex
 
3103
        # In log file:
 
3104
        #   '(' => start of reading of file, followed by filename
 
3105
        #   ')' => end of reading of file
 
3106
        #   '[' => start of page (normally preceeded by space)
 
3107
        # Remember: 
 
3108
        #    filename (on VAX/VMS) may include '[' and ']' (directory
 
3109
        #             separators) 
 
3110
        #    filenames (on MS-Win) commonly include space.
 
3111
 
 
3112
        # First step: replace $_ by whole of line after the '('
 
3113
        #             Thus $_ is putative filename followed by other stuff.
 
3114
            $_ = $1; 
 
3115
            if ( /^\"([^\(^\)^\"]+)\"/ ) {
 
3116
               # Quoted file name, as from MikTeX
 
3117
            }
 
3118
            elsif ( /^([^\(^\)]*?)\s\[/ ) {
 
3119
                # Terminator: space then '['
 
3120
                # Use *? in condition: to pick up first ' [' as terminator
 
3121
                # 'file [' should give good filename.
 
3122
            }
 
3123
            elsif ( /^([^\(^\)]*)\s(?=\()/ ) {
 
3124
                # Terminator is ' (', but '(' isn't in matched string,
 
3125
                # so we keep the '(' ready for the next match
 
3126
            }
 
3127
            elsif  ( /^([^\(^\)]*)(\))/ ) {
 
3128
                # Terminator is ')'
 
3129
            }
 
3130
            elsif ( /^([^\(^\)]*?)\s*\{/ ) {
 
3131
                # Terminator: arbitrary space then '{'
 
3132
                # Use *? in condition: to pick up first ' [' as terminator
 
3133
                # 'file [' should give good filename.
 
3134
            }
 
3135
            else {
 
3136
                #Terminator is end-of-string
 
3137
            }
 
3138
            $_ = $';       # Put $_ equal to the unmatched tail of string '
 
3139
            my $include_candidate = $1;
 
3140
            $include_candidate =~ s/\s*$//;   # Remove trailing space.
 
3141
            if ( $include_candidate eq "[]" ) {
 
3142
                # Part of overfull hbox message
 
3143
                next INCLUDE_CANDIDATE;
 
3144
            }
 
3145
            if ( $include_candidate =~ /^\\/ ) {
 
3146
                # Part of font message
 
3147
                next INCLUDE_CANDIDATE;
 
3148
            }
 
3149
            # Remove quotes around filename, as for MikTeX.  I've already
 
3150
            # treated this as a special case.  For safety check here:
 
3151
            $include_candidate =~ s/^\"(.*)\"$/$1/;
 
3152
 
 
3153
            # Make list of new include files; sometimes more than one.
 
3154
            my @new_includes = ($include_candidate);
 
3155
            if ( $include_candidate =~ /^(.+)\[([^\]]+)\]$/ ) {
 
3156
                # Construct of form 'file1[file2]', as produced by pdflatex
 
3157
                if ( -e $1 ) {
 
3158
                    # If the first component exists, we probably have the
 
3159
                    #   pdflatex form
 
3160
                    @new_includes = ($1, $2);
 
3161
                }
 
3162
                else {
 
3163
                    # We have something else.
 
3164
                    # So leave the original candidate in the list
 
3165
                }
 
3166
            }
3068
3167
        INCLUDE_NAME:
3069
 
          foreach my $include_name (@new_includes) {
3070
 
              my ($base, $path, $ext) = fileparse ($include_name, '\.[^\.]*');
3071
 
              if ( $ext eq '.bbl' ) {
3072
 
                  warn "Input bbl file \"$include_name\", so turn on bibtex_mode\n"
3073
 
                     unless ($bibtex_mode == 1) || $silent;
3074
 
                  $bibtex_mode = 1;
3075
 
                  push @bbl_files, $include_name;
3076
 
              } elsif ( $ext eq ".aux" ) {
3077
 
                  push @aux_files, $include_name;
3078
 
                  push @ignored_input_files, $include_name;
3079
 
              } elsif ( $generated_exts{$ext} ) {
3080
 
                  #warn "Ignoring '$include_name'\n";
3081
 
                  push @ignored_input_files, $include_name;
3082
 
              } else {
3083
 
                  push @include_list, $include_name;
3084
 
              }
3085
 
          } # INCLUDE_NAME
3086
 
      } # INCLUDE_CANDIDATE
3087
 
  }  # LINE
3088
 
  close($log_file);
3089
 
  @aux_files = &uniq( sort(@aux_files) );
3090
 
  @ignored_input_files = &uniq( sort(@ignored_input_files) );
3091
 
 
3092
 
  if ( $bibtex_mode ) 
3093
 
  {  
3094
 
      &parse_aux; 
3095
 
      push @include_list, @bib_files;
3096
 
  }
3097
 
  @include_list = &uniq(sort @include_list);
3098
 
  @include_graphics_list = &uniq(sort @include_graphics_list);
3099
 
  foreach (@include_list) {
3100
 
      if ( -e $_ ) {
3101
 
         push @existent, $_;
3102
 
      } else {
3103
 
         $includes_missing{$_} = [1];
3104
 
      }
3105
 
  }
3106
 
  foreach (@include_graphics_list) {
3107
 
      if ( -e $_ ) {
3108
 
         push @existent, $_;
3109
 
      } else {
3110
 
         # I have to work harder finding the file
3111
 
         $includes_missing{$_} = [2];
3112
 
      }
3113
 
  }
3114
 
 
3115
 
  my $non_exist = 0;
3116
 
  my $not_found = 0;
3117
 
  my $missing = 0;
3118
 
  foreach (sort keys %includes_missing) {
3119
 
      $missing++;
3120
 
      my $code = ${$includes_missing{$_}}[0];
3121
 
      if ($code == 1) {$non_exist ++;}
3122
 
      if ($code == 2) {$not_found ++;}
3123
 
  }
3124
 
 
3125
 
 
3126
 
  @includes = @existent;
3127
 
 
3128
 
  if ( $diagnostics ) 
3129
 
  {
3130
 
     my $inc = $#include_list + 1;
3131
 
     my $exist = $#existent + 1;
3132
 
     my $non_exist = $#includes_missing + 1;
3133
 
     my $bbl = $#bbl_files + 1;
3134
 
     print "$inc included files detected, of which ";
3135
 
     print "$exist exist, and $non_exist do not exist.\n";
3136
 
     print "Input files that exist:\n";
3137
 
     foreach (@existent) { print "   $_\n";}
3138
 
 
3139
 
     if ( $#bbl_files >= 0 ) {
3140
 
        print "Input bbl files:\n";
3141
 
        foreach (@bbl_files) { print "   $_\n";  }
3142
 
     }
3143
 
     if ( $#ignored_input_files >= 0 ) {
3144
 
        print "Other input files that are generated via LaTeX run:\n";
3145
 
        foreach (@ignored_input_files) { print "   $_\n";  }
3146
 
     }
3147
 
     if ( $missing > 0 ) {
3148
 
        print "Apparent input files that appear NOT to exist:\n";
3149
 
        print "  Some correspond to misunderstood lines in the .log file\n";
3150
 
        print "  Some are files that latexmk failed to find\n";
3151
 
        print "  Some really don't exist\n";
3152
 
        foreach (sort keys %includes_missing) { print "   $_\n";  }
3153
 
     }
3154
 
  }
3155
 
  return 1;
3156
 
}
3157
 
 
3158
 
#************************************************************
3159
 
 
3160
 
sub parse_aux
3161
 
# Parse aux_file for bib files.  
3162
 
# Return 3 with @bib_files set if aux_file exists, but I couldn't find all the bib_files
3163
 
# Return 2 with @bib_files empty if aux_file exists, but there are no \bibdata
3164
 
#   lines. In that case turn off bibtex mode, as side effect.
3165
 
# Return 1 with @bib_files set if aux_file exists
3166
 
# Return 0 and leave @bib_files unchanged in aux_file does not exist (or 
3167
 
#      cannot be opened)
 
3168
            foreach my $include_name (@new_includes) {
 
3169
                my ($base, $path, $ext) = fileparseB( $include_name );
 
3170
                if ( ($path eq './') || ($path eq '.\\') ) {
 
3171
                    $include_name = $base.$ext;
 
3172
                }
 
3173
                if ( $include_name !~ m'[/|\\]' ) {
 
3174
                    # Filename does not include a path character
 
3175
                    # High potential for misparsed line
 
3176
                    $dependents{$include_name} = 2;
 
3177
                } else {
 
3178
                    $dependents{$include_name} = 3;
 
3179
                }
 
3180
                if ( $ext eq '.bbl' ) {
 
3181
                    warn "$My_name: Found input bbl file '$include_name'\n"
 
3182
                       unless $silent;
 
3183
                    push @bbl_files, $include_name;
 
3184
                }
 
3185
            } # INCLUDE_NAME
 
3186
        } # INCLUDE_CANDIDATE
 
3187
    } # LINE
 
3188
 
 
3189
    # Default includes are always definitive:
 
3190
    foreach (@default_includes) { $dependents{$_} = 4; }
 
3191
 
 
3192
    ###print "New parse: \n";
 
3193
    ###foreach (sort keys %dependents) { print "  '$_': $dependents{$_}\n"; }
 
3194
 
 
3195
    my @misparsed = ();
 
3196
    my @missing = ();
 
3197
    my @not_found = ();
 
3198
CANDIDATE:
 
3199
    foreach my $candidate (keys %dependents) {
 
3200
        my $code = $dependents{$candidate};
 
3201
        if ( -e $candidate ) {
 
3202
            if ( exists $generated_log{$candidate} ){
 
3203
                $dependents{$candidate} = 6;
 
3204
            }
 
3205
            elsif ($code == 0) {
 
3206
                $dependents{$candidate} = 5;
 
3207
            }
 
3208
            else {
 
3209
                $dependents{$candidate} = 4;
 
3210
            }
 
3211
        }
 
3212
        elsif ($code == 1) {
 
3213
            # Graphics file that is supposed to have been read.
 
3214
            # Candidate name is as given in source file, not as path
 
3215
            #   to actual file.
 
3216
            # We have already tested that file doesn't exist, as given.
 
3217
            #   so use kpsewhich.  
 
3218
            # If the file still is not found, assume non-existent;
 
3219
            my @kpse_result = kpsewhich( $candidate );
 
3220
            if ($#kpse_result > -1) {
 
3221
                $dependents{$kpse_result[0]} = 4;
 
3222
                delete $dependents{$candidate};
 
3223
                next CANDIDATE;
 
3224
            }
 
3225
            else {
 
3226
                push @not_found, $candidate;
 
3227
            }
 
3228
        }
 
3229
        elsif ($code == 2) {
 
3230
            # Candidate is from '(...' construct in log file, for input file
 
3231
            #    which should include pathname if valid input file.
 
3232
            # Name does not have pathname-characteristic character (hence
 
3233
            #    $code==2.
 
3234
            # We get here if candidate file does not exist with given name
 
3235
            # Almost surely result of a misparsed line in log file.
 
3236
            delete $dependents{$candidate};
 
3237
            push @misparse, $candidate;
 
3238
        }
 
3239
        elsif ($code == 3) {
 
3240
            # Candidate is from '(...' construct in log file, for input file
 
3241
            #    which should include pathname if valid input file.
 
3242
            # Name does have pathname-characteristic character (hence
 
3243
            #    $code==3.
 
3244
            # But we get here only if candidate file does not exist with 
 
3245
            # given name.  
 
3246
            # Almost surely result of a misparsed line in log file.
 
3247
            # But with lower probability than $code == 2
 
3248
            delete $dependents{$candidate};
 
3249
            push @misparse, $candidate;
 
3250
        }
 
3251
        elsif ($code == 0) {
 
3252
            my ($base, $path, $ext) = fileparseA($candidate);
 
3253
            $ext =~ s/^\.//;
 
3254
            if ( ($ext eq '') && (-e "$path$base.tex") ) {
 
3255
                # I don't think the old version was correct.
 
3256
                # If the missing-file report was of a bare
 
3257
                #    extensionless file, and a corresponding .tex file
 
3258
                #    exists, then the missing file does not correspond
 
3259
                #    to the missing file, unless the .tex file was
 
3260
                #    created during the run.  
 
3261
                # OLD $dependents{"$path$base.tex"} = 4;
 
3262
                # OLD delete $dependents{$candidate};
 
3263
                # NEW:
 
3264
                $dependents{"$path$base.tex"} = 4;
 
3265
            }
 
3266
            push @missing, $candidate;
 
3267
        }
 
3268
    }
 
3269
CANDIDATE_PAIR:
 
3270
    foreach my $delegated_source (keys %new_conversions) {
 
3271
        my $delegated_output = $new_conversions{$delegated_source};
 
3272
        my $rule = "Delegated $delegated_source, $delegated_output";
 
3273
        # N.B. $delegated_source eq '' means the output file
 
3274
        #      was created without a named input file.
 
3275
        foreach my $candidate ($delegated_source, $delegated_output) {
 
3276
            if (! -e $candidate ) {
 
3277
                # The file might be somewhere that can be found
 
3278
                #   in the search path of kpathsea:
 
3279
                my @kpse_result = kpsewhich( $candidate,);
 
3280
                if ($#kpse_result > -1) {
 
3281
                    $candidate = $kpse_result[0];
 
3282
                }
 
3283
            }
 
3284
        }
 
3285
        if ( ( (-e $delegated_source) || ($delegated_source eq '') )
 
3286
              && (-e $delegated_output) )
 
3287
        {
 
3288
            $conversions{$delegated_output} = $delegated_source;
 
3289
            $dependents{$delegated_output} = 7;
 
3290
            if ($delegated_source) {
 
3291
                $dependents{$delegated_source} = 4;
 
3292
            }
 
3293
        }
 
3294
        elsif (!$silent) {
 
3295
            print "Logfile claimed conversion from '$delegated_source' ",
 
3296
                  "to '$delegated_output'.  But:\n";
 
3297
            if (! -e $delegated_output) {
 
3298
                print  "   Output file does not exist\n";
 
3299
            }
 
3300
            if ( ($delegated_source ne '') && (! -e $delegated_source) ) {
 
3301
                print  "   Input file does not exist\n";
 
3302
            }
 
3303
        }
 
3304
    }
 
3305
 
 
3306
    
 
3307
    if ( $diagnostics ) {
 
3308
        @misparse = uniqs( @misparse );
 
3309
        @missing = uniqs( @missing );
 
3310
        @not_found = uniqs( @not_found );
 
3311
        my @dependents = sort( keys %dependents );
 
3312
 
 
3313
        my $dependents = $#dependents + 1;
 
3314
        my $misparse = $#misparse + 1;
 
3315
        my $missing = $#missing + 1;
 
3316
        my $not_found = $#not_found + 1;
 
3317
        my $exist = $dependents - $not_found - $missing;
 
3318
        my $bbl = $#bbl_files + 1;
 
3319
 
 
3320
        print "$dependents dependent files detected, of which ",
 
3321
              "$exist exist, $not_found were not found,\n",
 
3322
              "   and $missing appear not to exist.\n";
 
3323
        print "Dependents:\n";
 
3324
        foreach (@dependents) { 
 
3325
            print "   '$_' "; 
 
3326
            if ( $dependents{$_} == 6 ) { print " written by (pdf)latex";}
 
3327
            print "\n";
 
3328
            if ( $dependents{$_} == 7 ) { print " converted by (pdf)latex";}
 
3329
            print "\n";
 
3330
        }
 
3331
        if ($not_found > 0) {
 
3332
            print "Not found:\n";
 
3333
            foreach (@not_found) { print "   $_\n"; }
 
3334
        }
 
3335
        if ($missing > 0) {
 
3336
            print "Not existent:\n";
 
3337
            foreach (@missing) { print "   $_\n"; }
 
3338
        }
 
3339
        if ( $bbl > 0 ) {
 
3340
            print "Input bbl files:\n";
 
3341
            foreach (@bbl_files) { print "   $_\n"; }
 
3342
        }
 
3343
 
 
3344
        if ( $misparse > 0 ) {
 
3345
            print "$misparse\n";
 
3346
            print "Apparent input files apparently from misunderstood lines in .log file:\n";
 
3347
            foreach ( @misparse ) { print "   $_\n"; }
 
3348
        }
 
3349
    }
 
3350
    return 1;
 
3351
} #END parse_logB
 
3352
 
 
3353
#************************************************************
 
3354
 
 
3355
sub parse_aux {
 
3356
    #Usage: parse_aux( $aux_file, \@new_bib_files, \@new_aux_files )
 
3357
    # Parse aux_file (recursively) for bib files.  
 
3358
    # If can't open aux file, then
 
3359
    #    Return 0 and leave @new_bib_files empty
 
3360
    # Else set @new_bib_files from information in the aux files
 
3361
    #    And:
 
3362
    #    Return 1 if no problems
 
3363
    #    Return 2 with @new_bib_files empty if there are no \bibdata
 
3364
    #      lines. 
 
3365
    #    Return 3 if I couldn't locate all the bib_files
 
3366
    # Set @new_aux_files to aux files parsed
 
3367
 
 
3368
    my $aux_file = $_[0];
 
3369
    local $Pbib_files = $_[1];
 
3370
    local $Paux_files = $_[2];
 
3371
   
 
3372
    @$Pbib_files = ();
 
3373
    @$Paux_files = ();
 
3374
 
 
3375
    parse_aux1( $aux_file );
 
3376
    if ($#{$Paux_files} < 0) {
 
3377
       return 0;
 
3378
    }
 
3379
    @$Pbib_files = uniqs( @$Pbib_files );
 
3380
 
 
3381
    if ( $#{$Pbib_files} == -1 ) {
 
3382
        warn "$My_name: No .bib files listed in .aux file '$aux_file' \n",
 
3383
        return 2;
 
3384
    }
 
3385
    my $bibret = &find_file_list1( $Pbib_files, $Pbib_files,
 
3386
                                  '.bib', \@BIBINPUTS );
 
3387
    @$Pbib_files = uniqs( @$Pbib_files );
 
3388
    if ($bibret == 0) {
 
3389
        warn "$My_name: Found bibliography file(s) [@$Pbib_files]\n" 
 
3390
        unless $silent;
 
3391
    }
 
3392
    else {
 
3393
        warn "$My_name: Failed to find one or more bibliography files ",
 
3394
             "in [@$Pbib_files]\n";
 
3395
        if ($force_mode) {
 
3396
            warn "==== Force_mode is on, so I will continue.  ",
 
3397
                 "But there may be problems ===\n";
 
3398
        }
 
3399
        else {
 
3400
            #$failure = -1;
 
3401
            #$failure_msg = 'Failed to find one or more bib files';
 
3402
            #warn "$My_name: Failed to find one or more bib files\n";
 
3403
        }
 
3404
        return 3;
 
3405
    }
 
3406
    return 1;
 
3407
} #END parse_aux
 
3408
 
 
3409
#************************************************************
 
3410
 
 
3411
sub parse_aux1
 
3412
# Parse single aux file for bib files.  
 
3413
# Usage: &parse_aux1( aux_file_name )
 
3414
#   Append newly found bib_filenames in @$Pbib_files, already 
 
3415
#        initialized/in use.
 
3416
#   Append aux_file_name to @$Paux_files if aux file opened
 
3417
#   Recursively check \@input aux files
 
3418
#   Return 1 if success in opening $aux_file_name and parsing it
 
3419
#   Return 0 if fail to open it
3168
3420
{
3169
 
   local($aux_file) = "$root_filename.aux";
3170
 
   if (! open(aux_file) ) 
3171
 
      { return 0; }
3172
 
   @bib_files = ();
 
3421
   my $aux_file = $_[0];
 
3422
   my $aux_fh = new FileHandle;
 
3423
   if (! open($aux_fh, $aux_file) ) { 
 
3424
       warn "$My_name: Couldn't find aux file '$aux_file'\n";
 
3425
       return 0; 
 
3426
   }
 
3427
   push @$Paux_files, $aux_file;
3173
3428
AUX_LINE:
3174
 
   while (<aux_file>)
3175
 
   {
3176
 
      if ( /^\\bibdata\{(.*)\}/ )
3177
 
      { 
3178
 
         # \\bibdata{comma_separated_list_of_bib_file_names}
3179
 
         # (Without the '.bib' extension)
3180
 
         push( @bib_files, split /,/, $1 ); 
3181
 
      }
3182
 
   }
3183
 
   close(aux_file);
3184
 
   if ( $#bib_files eq -1 ) {
3185
 
       warn "No .bib files listed in .aux file, so turn off bibtex_mode\n";
3186
 
       $bibtex_mode = 0;
3187
 
       return 2;
3188
 
   }
3189
 
   my $bibret = &find_file_list1( \@bib_files, \@bib_files, '.bib', \@BIBINPUTS );
3190
 
   if ($bibret == 0) {
3191
 
      warn "Found bibliography files [@bib_files]\n" unless $silent;
3192
 
   }
3193
 
   else {
3194
 
       warn "Failed to find one or more bibliography files in [@bib_files]\n";
3195
 
       if ($force_mode) {
3196
 
          warn "==== Force_mode is on, so I will continue.  But there may be problems ===\n";
3197
 
       }
3198
 
       else {
3199
 
           $failure = -1;
3200
 
           $failure_msg = 'Failed to find one or more bib files';
3201
 
       }
3202
 
       return 3;
3203
 
   }
 
3429
   while (<$aux_fh>) {
 
3430
      if ( /^\\bibdata\{(.*)\}/ ) { 
 
3431
          # \\bibdata{comma_separated_list_of_bib_file_names}
 
3432
          # (Without the '.bib' extension)
 
3433
          push( @$Pbib_files, split /,/, $1 ); 
 
3434
      }
 
3435
      elsif ( /^\\\@input\{(.*)\}/ ) { 
 
3436
          # \\@input{next_aux_file_name}
 
3437
          &parse_aux1( $1 );
 
3438
      }
 
3439
   }
 
3440
   close($aux_fh);
3204
3441
   return 1;
3205
 
}
3206
 
 
3207
 
#************************************************************
3208
 
 
3209
 
sub update_depend_file
3210
 
{
3211
 
  warn "Writing dependency file [$root_filename.dep]\n";
3212
 
  $rc_file = ">$root_filename.dep";
3213
 
  open(rc_file) || die "Latexmk: Unable to open dependency file [$rc_file] for updating\n";
3214
 
  print rc_file '@includes = (\n';
3215
 
  my $first = 1;
3216
 
  foreach my $name (@includes) {
3217
 
      if (!$first) {print rc_file ",\n";}
3218
 
      print rc_file "\'$name\'";
3219
 
      $first = 0;
3220
 
  }
3221
 
  print rc_file "\n)\n";
3222
 
  print rc_file '@bib_files = (\n';
3223
 
  $first = 1;
3224
 
  foreach $name (@bib_files) {
3225
 
      if (!$first) {print rc_file ",\n";}
3226
 
      print rc_file "\'$name\'";
3227
 
      $first = 0;
3228
 
  }
3229
 
  print rc_file "\n)\n";
3230
 
  if ($bibtex_mode)
3231
 
  {
3232
 
    print rc_file '$bibtex_mode = 1;' . "\n";
3233
 
  }
3234
 
  if ($index_mode)
3235
 
  {
3236
 
    print rc_file '$index_mode = 1;' . "\n";
3237
 
  }
3238
 
  print rc_file "\$view = \"$view\";\n";
3239
 
  print rc_file "\$need_dvi = $need_dvi;\n";
3240
 
  print rc_file "\$need_ps = $need_ps;\n";
3241
 
  print rc_file "\$need_pdf = $need_pdf;\n";
3242
 
  print rc_file "\$pdf_mode = $pdf_mode;\n";
3243
 
  close rc_file;
3244
 
}
 
3442
} #END parse_aux1
 
3443
 
 
3444
#************************************************************
 
3445
 
 
3446
#************************************************************
 
3447
#************************************************************
 
3448
#************************************************************
 
3449
 
 
3450
#   Manipulations of main file database:
 
3451
 
 
3452
#************************************************************
 
3453
 
 
3454
sub fdb_get {
 
3455
    # Call: fdb_get(filename [, runtime])
 
3456
    # Returns an array (time, size, md5) for the current state of the
 
3457
    #    named file.
 
3458
    # The optional argument runtime is the runtime of some command
 
3459
    #    associated with the use of the file --- see below.
 
3460
    # For non-existent file, deletes its entry in fdb_current, 
 
3461
    #    and returns (0,-1,0)  
 
3462
    # As an optimization, the md5 value is taken from the cache in 
 
3463
    #    fdb_current, if the time and size stamp indicate that the 
 
3464
    #    file has not changed.
 
3465
    # The md5 value is recalculated if
 
3466
    #    the current filetime differs from the cached value: 
 
3467
    #               file has been written
 
3468
    #    the current filesize differs from the cached value: 
 
3469
    #               file has definitely changed
 
3470
    # But the file can also be rewritten without change in filetime when 
 
3471
    #    file processing happens within the 1-second granularity of the 
 
3472
    #    timestamp (notably for aux files from latex on a short source file).
 
3473
    # The only case that concerns us is when the file is an input to a program
 
3474
    #    at some runtime t, the file is rewritten later by the same or another
 
3475
    #    program, with timestamp t, and when the initial file also has 
 
3476
    #    timestamp t.
 
3477
    # A test is applied for this situation if the runtime argument is 
 
3478
    #    supplied and is nonzero.
 
3479
 
 
3480
    my ($file, $run_time) = @_;
 
3481
    if ( ! defined $run_time ) { $run_time = 0;}
 
3482
    my ($new_time, $new_size) = get_time_size($file);
 
3483
    my @nofile =  (0,-1,0);     # What we use for initializing
 
3484
                                # a new entry in fdb or flagging
 
3485
                                # non-existent file
 
3486
    if ( $new_size < 0 ) {
 
3487
        delete $fdb_current{$file};
 
3488
        return @nofile;
 
3489
    }
 
3490
    my $recalculate_md5 = 0;
 
3491
    if ( ! exists $fdb_current{$file} ) {
 
3492
        # Ensure we have a record.  
 
3493
        $fdb_current{$file} = [@nofile];
 
3494
        $recalculate_md5 = 1;
 
3495
    }
 
3496
    my $file_data = $fdb_current{$file};
 
3497
    my ( $time, $size, $md5 ) = @$file_data;
 
3498
#warn "--------- Getting MD5: $file: (N,O,R) = $new_time, $time, $run_time\n";
 
3499
#warn "--------- $file: (OT,OS,OM) = @$file_data\n";
 
3500
    if ( ($new_time != $time) || ($new_size != $size) 
 
3501
         || ( $run_time && ($run_time == $time ) )
 
3502
       ) {
 
3503
        # Only force recalculation of md5 if time or size changed
 
3504
        # Or if the time equals runtime, so that the file may
 
3505
        #   have changed within the 1-second granularity of the time
 
3506
        # Else we assume file is really unchanged.
 
3507
        $recalculate_md5 = 1;
 
3508
    }
 
3509
    if ($recalculate_md5) {
 
3510
#warn "--------- RECALC MD5: $rule $file: (N,O,R) = $new_time, $time, $run_time\n";
 
3511
#warn "  ------- $file: (OT,OS,OM) = @$file_data\n";
 
3512
#&traceback;
 
3513
        @$file_data = ( $new_time, $new_size, get_checksum_md5( $file ) );
 
3514
#warn "  ------- $file: (NT,NS,NM) = @$file_data\n";
 
3515
    }
 
3516
    return @$file_data;;
 
3517
} #END fdb_get
 
3518
 
 
3519
#************************************************************
 
3520
 
 
3521
sub fdb_set {
 
3522
    # Call: fdb_set(filename, $time, $size, $md5 )
 
3523
    # Set data in file data cache, i.e., %fdb_current
 
3524
    my ($file, $time, $size, $md5 ) = @_;
 
3525
    if ( ! exists $fdb_current{$file} ) {
 
3526
        $fdb_current{$file} = [0, -1, 0];
 
3527
    }
 
3528
    @{$fdb_current{$file}} = ( $time, $size, $md5 );
 
3529
} #END fdb_set
 
3530
 
 
3531
#************************************************************
 
3532
 
 
3533
sub fdb_show {
 
3534
    # Displays contents of fdb
 
3535
    foreach my $file ( sort keys %fdb_current ) {
 
3536
        print "'$file': @{$fdb_current{$file}}\n";
 
3537
    }
 
3538
} #END fdb_show
 
3539
 
 
3540
#************************************************************
 
3541
#************************************************************
 
3542
#************************************************************
 
3543
 
 
3544
# Routines for manipulating rule database
 
3545
 
 
3546
#************************************************************
 
3547
 
 
3548
sub rdb_read {
 
3549
    # Call: rdb_read( $in_name  )
 
3550
    # Sets rule database from saved file, in format written by rdb_write.
 
3551
    # Returns -1 if file could not be read else number of errors.
 
3552
    # Thus return value on success is 0
 
3553
    my $in_name = $_[0];
 
3554
    my $in_handle = new FileHandle;
 
3555
    $in_handle->open( $in_name, '<' )
 
3556
       or return ();
 
3557
    my $errors = 0;
 
3558
    my $state = 0;   # Outside a section 
 
3559
    my $rule = '';
 
3560
    my $run_time = 0;
 
3561
    my $source = '';
 
3562
    my $dest = '';
 
3563
    my $base = '';
 
3564
    local %new_sources = ();  # Hash: rule => { file=>[ time, size, md5, fromrule ] }
 
3565
    my $new_source = undef;   # Reference to hash of sources for current rule
 
3566
LINE:
 
3567
    while ( <$in_handle> ) {
 
3568
        # Remove leading and trailing white space.
 
3569
        s/^\s*//;
 
3570
        s/\s*$//;
 
3571
        # Ignore blank lines and comments
 
3572
        if ( /^$/ || /^#/ || /^%/ ) { next LINE;}
 
3573
        if ( /^\[\"([^\"]+)\"\]/ ) {
 
3574
            # Start of section
 
3575
            $rule = $1;
 
3576
#??             print "--- Starting rule '$rule'\n";
 
3577
            my $tail = $'; #'  Single quote in comment tricks the parser in
 
3578
                           # emacs from misparsing an isolated single quote
 
3579
            $run_time = 0;
 
3580
            $source = $dest = $base = '';
 
3581
            if ( $tail =~ /^\s*(\S+)\s*$/ ) {
 
3582
                $run_time = $1;
 
3583
            }
 
3584
            elsif ( $tail =~ /^\s*(\S+)\s+\"([^\"]*)\"\s+\"([^\"]*)\"\s+\"([^\"]*)\"\s*$/ ) {
 
3585
                $run_time = $1;
 
3586
                $source = $2;
 
3587
                $dest = $3;
 
3588
                $base = $4;
 
3589
            }
 
3590
            if ( rdb_rule_exists( $rule ) ) {
 
3591
                rdb_one_rule( $rule, 
 
3592
                              sub{ $$Ptest_kind = 1; 
 
3593
                                   $$Prun_time = $run_time;
 
3594
                                   #??if ($source) { $$Psource = $source; }
 
3595
                                   #??if ($dest) { $$Pdest = $dest; }
 
3596
                                   #??if ($base) { $$Pbase = $base; }
 
3597
                                 }                                      
 
3598
                             );
 
3599
            }
 
3600
            elsif ($rule =~ /^cusdep\s+(\S+)\s+(\S+)\s+(.+)$/ ) {
 
3601
                # Create custom dependency
 
3602
                my $fromext = $1;
 
3603
                my $toext = $2;
 
3604
                my $base = $3;
 
3605
                $source = "$base.$fromext";
 
3606
                $dest =   "$base.$toext";
 
3607
                my $PAnew_cmd = ['do_cusdep', ''];
 
3608
                foreach my $dep ( @cus_dep_list ) {
 
3609
                    my ($tryfromext,$trytoext,$must,$func_name) = split(' ',$dep);
 
3610
                    if ( ($tryfromext eq $fromext) && ($trytoext eq $toext) ) {
 
3611
                       $$PAnew_cmd[1] = $func_name;
 
3612
                    }
 
3613
                }
 
3614
                # Set source file as non-existent.  
 
3615
                # If it existed on last run, it will be in later 
 
3616
                #    lines of the fdb file
 
3617
                rdb_create_rule( $rule, 'cusdep', '', $PAnew_cmd, 1, 
 
3618
                                 $source, $dest, $base, 0, $run_time, 1 );
 
3619
            }
 
3620
            elsif ( $rule =~ /^(makeindex|bibtex)\s*(.*)$/ ) {
 
3621
                my $rule_generic = $1;
 
3622
                if ( ! $source ) {
 
3623
                    # If fdb_file was old-style (v. 1)
 
3624
                    $source = $2;
 
3625
                    my $path = '';
 
3626
                    my $ext = '';
 
3627
                    ($base, $path, $ext) = fileparseA( $source );
 
3628
                    $base = $path.$base;
 
3629
                    if ($rule_generic eq 'makeindex') {
 
3630
                        $dest = "$base.ind";
 
3631
                    }
 
3632
                    elsif ($rule_generic eq 'bibtex') {
 
3633
                        $dest = "$base.bbl";
 
3634
                        $source = "$base.aux";
 
3635
                    }
 
3636
                }
 
3637
                warn "$My_name: File-database '$in_name': setting rule '$rule'\n"
 
3638
                   if $diagnostics;
 
3639
                my $cmd_type = 'external';
 
3640
                my $ext_cmd = ${$rule_generic};
 
3641
                warn "  Rule kind = '$rule_generic'; ext_cmd = '$ext_cmd';\n",
 
3642
                     "  source = '$source'; dest = '$dest'; base = '$base';\n"
 
3643
                   if $diagnostics;
 
3644
                # Set source file as non-existent.  
 
3645
                # If it existed on last run, it will be in later 
 
3646
                #    lines of the fdb file
 
3647
                rdb_create_rule( $rule, $cmd_type, $ext_cmd, '', 1, 
 
3648
                                 $source, $dest, $base, 0, $run_time, 1);
 
3649
            }
 
3650
            else {
 
3651
                warn "$My_name: In file-database '$in_name' rule '$rule'\n",
 
3652
                     "   is not in use in this session\n"
 
3653
                if $diagnostics;
 
3654
                $new_source = undef;
 
3655
                $state = 3;
 
3656
                next LINE;
 
3657
            }
 
3658
            $new_source = $new_sources{$rule} = {};
 
3659
            $state = 1;  #Reading a section
 
3660
        }
 
3661
        elsif ( /^\"([^\"]*)\"\s+(\S+)\s+(\S+)\s+(\S+)\s+\"([^\"]*)\"/ ) {
 
3662
            # Source file line
 
3663
            if ($state == 3) {
 
3664
                # The rule is not being currently used.
 
3665
                next LINE;
 
3666
            }
 
3667
            my $file = $1;
 
3668
            my $time = $2;
 
3669
            my $size = $3;
 
3670
            my $md5 = $4;
 
3671
            my $from_rule = $5;
 
3672
#??            print "  --- File '$file'\n";
 
3673
            if ($state != 1) {
 
3674
                warn "$My_name: In file-database '$in_name' ",
 
3675
                     "line $. is outside a section:\n   '$_'\n";
 
3676
                $errors++;
 
3677
                next LINE;
 
3678
            }
 
3679
            # Set file in database.  But ensure we don't do an unnecessary 
 
3680
            #    fdb_get, which can trigger a new MD5 calculation, which is
 
3681
            #    lengthy for a big file.  Ininitially flagging the file
 
3682
            #    as non-existent solves the problem:
 
3683
            rdb_ensure_file( $rule, $file, undef, 1 ); 
 
3684
            rdb_set_file1( $rule, $file, $time, $size, $md5 );
 
3685
            fdb_set( $file, $time, $size, $md5 );
 
3686
            # Save the rest of the data, especially the from_fule until we know all 
 
3687
            #   the rules, otherwise the from_rule may not exist.
 
3688
            # Also we'll have a better chance of looping through files.
 
3689
            ${$new_source}{$file} = [ $time, $size, $md5, $from_rule ];
 
3690
        }
 
3691
        elsif ($state == 0) {
 
3692
            # Outside a section.  Nothing to do.
 
3693
        }
 
3694
        else {
 
3695
            warn "$My_name: In file-database '$in_name' ",
 
3696
                 "line $. is of wrong format:\n   '$_'\n";
 
3697
            $errors++;
 
3698
            next LINE;
 
3699
        }
 
3700
    }
 
3701
    undef $in_handle;
 
3702
    # Set cus dependencies.
 
3703
    &rdb_set_dependentsA( keys %rule_db );
 
3704
 
 
3705
#?? Check from_rules exist.
 
3706
 
 
3707
    return $errors;
 
3708
}  # END rdb_read
 
3709
 
 
3710
#************************************************************
 
3711
 
 
3712
sub rdb_read_generatedB {
 
3713
    # Call: rdb_read_generatedB( $in_name, \@generated1, \@aux_files.
 
3714
    #                            \%other_generated )
 
3715
    # From rule database in saved file, in format written by rdb_write,
 
3716
    # finds the non-trivial generated files that are to be deleted by a cleanup. 
 
3717
    # On entry:
 
3718
    #     Keys of %other_generated: any detected generated files, from \openout 
 
3719
    #       lines log file, usually.
 
3720
    # At exit:
 
3721
    #    Array @generated1: files associated with makeindex and bibtex
 
3722
    #    Array @aux_files: aux files
 
3723
    #    Added to keys of %other_generated: any files that are destinations of rules
 
3724
    #       whose source is in %other_generated.  (One stage only.)
 
3725
    my ($in_name, $Pgenerated1, $Paux_files, $Pother_generated) = @_;
 
3726
    @$Pgenerated1 = ();
 
3727
    @$Paux_files = ();
 
3728
 
 
3729
    my $in_handle = new FileHandle;
 
3730
    $in_handle->open( $in_name, '<' )
 
3731
       or return ();
 
3732
    my $rule = '';
 
3733
    my $run_time = 0;
 
3734
    my $source = '';
 
3735
    my $dest = '';
 
3736
    my $base = '';
 
3737
    my $ext = '';
 
3738
    my $path = '';
 
3739
    my $state = 0;   # Outside a section 
 
3740
    my @other_additions = ();
 
3741
LINE:
 
3742
    while ( <$in_handle> ) {
 
3743
        # Remove leading and trailing white space.
 
3744
        s/^\s*//;
 
3745
        s/\s*$//;
 
3746
        # Ignore blank lines and comments
 
3747
        if ( /^$/ || /^#/ || /^%/ ) { next LINE;}
 
3748
        if ( /^\[\"([^\"]+)\"\]/ ) {
 
3749
            # Start of section
 
3750
            $rule = $1;
 
3751
            my $tail = $'; #'  Single quote in comment tricks the parser in
 
3752
                           # emacs from misparsing an isolated single quote
 
3753
            $run_time = 0;
 
3754
            $source = $dest = $base = '';
 
3755
            if ( $tail =~ /^\s*(\S+)\s+\"([^\"]*)\"\s+\"([^\"]*)\"\s+\"([^\"]*)\"\s*$/ ) {
 
3756
                $source = $2;
 
3757
                $dest = $3;
 
3758
                $base = $4;
 
3759
            }
 
3760
            else { next LINE; }
 
3761
            if ( $rule =~ /^makeindex/ ) {
 
3762
                push @$Pgenerated1, $source, $dest, "$base.ilg";
 
3763
            }
 
3764
            elsif ( $rule =~ /^bibtex/ ) {
 
3765
                push @$Pgenerated1, $dest, "$base.blg";
 
3766
                push @$Paux_files, $source;
 
3767
            }
 
3768
            elsif ( exists ${$Pother_generated}{$source} ) {
 
3769
                push @other_additions, $dest;
 
3770
            }
 
3771
            $state = 1;  #Reading a section
 
3772
        }
 
3773
        elsif ( /^\"([^\"]*)\"\s+(\S+)\s+(\S+)\s+(\S+)\s+\"([^\"]*)\"/ ) {
 
3774
            # Source file line
 
3775
            if ($state == 3) {
 
3776
                # The rule is not being currently used.
 
3777
                next LINE;
 
3778
            }
 
3779
            my $file = $1;
 
3780
            ($base, $path, $ext) = fileparseA( $file );
 
3781
            if ( $ext eq '.aux' ) { push @$Paux_files, $file; }
 
3782
        }
 
3783
        elsif ($state == 0) {
 
3784
            # Outside a section.  Nothing to do.
 
3785
        }
 
3786
        else {
 
3787
            warn "$My_name: In file-database '$in_name' ",
 
3788
                 "line $. is of wrong format:\n   '$_'\n";
 
3789
            next LINE;
 
3790
        }
 
3791
    } # LINE
 
3792
    undef $in_handle;
 
3793
    foreach (@other_additions) {
 
3794
        ${$Pother_generated}{$_} = 1;
 
3795
    }
 
3796
}  # END rdb_read_generatedB
 
3797
 
 
3798
#************************************************************
 
3799
 
 
3800
sub rdb_write {
 
3801
    # Call: rdb_write( $out_name )
 
3802
    # Writes to the given file name the database of file and rule data
 
3803
    #   for all rules needed to make final output
 
3804
    # !!?? Previously was:
 
3805
    # OLD Writes to the given file name the database of file and rule data
 
3806
    # OLD   accessible from the primary rules.
 
3807
    # Returns 1 on success, 0 if file couldn't be opened.
 
3808
    local $out_name = $_[0];
 
3809
    local $out_handle = new FileHandle;
 
3810
    if ( ($out_name eq "") || ($out_name eq "-") ) {
 
3811
        # Open STDOUT
 
3812
        $out_handle->open( '>-' );
 
3813
    }
 
3814
    else {
 
3815
       $out_handle->open( $out_name, '>' );
 
3816
    }
 
3817
    if (!$out_handle) { return 0; }
 
3818
 
 
3819
    local %current_primaries = ();   # Hash whose keys are primary rules 
 
3820
                # needed, i.e., known latex-like rules which trigger
 
3821
                # circular dependencies
 
3822
    local @pre_primary = ();   # Array of rules
 
3823
    local @post_primary = ();  # Array of rules
 
3824
    local @one_time = ();      # Array of rules
 
3825
    &rdb_classify_rules( \%possible_primaries, keys %requested_filerules );
 
3826
 
 
3827
    print $out_handle "# Fdb version $fdb_ver\n";
 
3828
# !!??   Rules or rules accessible from primary
 
3829
#    my @rules = rdb_accessible( uniq1( keys %possible_primaries )  ) ;
 
3830
    my @rules = rdb_accessible( uniq1( keys %possible_primaries, keys %requested_filerules  )  ) ;
 
3831
    # Separate call to sort.  Otherwise rdb_accessible seems to get wrong argument.
 
3832
    @rules = sort( @rules );
 
3833
    rdb_for_some(
 
3834
       \@rules,
 
3835
       sub { 
 
3836
           # Omit data on a unused and never-run primary rule:
 
3837
           if ( ($$Prun_time == 0) 
 
3838
                && exists( $possible_primaries{$rule} )
 
3839
                && ! exists( $current_primaries{$rule} )
 
3840
              )
 
3841
           { 
 
3842
               return; 
 
3843
           }
 
3844
           print $out_handle "[\"$rule\"] $$Prun_time \"$$Psource\" \"$$Pdest\" \"$$Pbase\" \n"; 
 
3845
           rdb_do_files(
 
3846
             sub { print $out_handle "  \"$file\" $$Ptime $$Psize $$Pmd5 \"$$Pfrom_rule\"\n"; }
 
3847
           );
 
3848
       }
 
3849
    );
 
3850
    undef $out_handle;
 
3851
    return 1;
 
3852
} #END rdb_write
 
3853
 
 
3854
#************************************************************
 
3855
 
 
3856
sub rdb_set_from_logB {
 
3857
    # Assume rule context.  
 
3858
    # This is intended to be applied only for a primary (LaTeX-like) rule
 
3859
    # Starting from the log_file, set current details for the current rule.
 
3860
 
 
3861
    # Rules should only be primary
 
3862
    if ( $$Pcmd_type ne 'primary' ) {
 
3863
        warn "\n$My_name: ==========$My_name: Probable BUG======= \n   ",
 
3864
             "   rdb_set_from_logB called to set files ",
 
3865
             "for non-primary rule '$rule'\n\n";
 
3866
        return;
 
3867
    }
 
3868
 
 
3869
 
 
3870
#??    # We'll prune this by all files determined to be needed for source files.
 
3871
#??    my %unneeded_source = %$PHsource;
 
3872
 
 
3873
    # Parse log file to find relevant filenames
 
3874
    # Result in the following variables:
 
3875
    local %dependents = ();    # Maps files to status
 
3876
    local @bbl_files = ();
 
3877
    local %idx_files = ();     # Maps idx_file to (ind_file, base)
 
3878
    local %generated_log = (); # Lists generated files found in log file
 
3879
    local $primary_out = $$Pdest;  # output file (dvi or pdf)
 
3880
    local %conversions = ();   # (pdf)latex-performed conversions.
 
3881
                     # Maps output file created and read by (pdf)latex
 
3882
                     #    to source file of conversion.
 
3883
    # The following are also returned, but are global, to be used by caller
 
3884
    # $reference_changed, $bad_reference $bad_citation
 
3885
 
 
3886
    &parse_logB;
 
3887
 
 
3888
    # Handle result on output file:
 
3889
    #   1.  Non-existent output file, which is because of no content.
 
3890
    #         This could either be because the source file has genuinely
 
3891
    #         no content, or because of a missing input file.  Since a
 
3892
    #         missing input file might be correctable by a run of some
 
3893
    #         other program whose running is provoked AFTER a run of
 
3894
    #         (pdf)latex, we'll set a diagnostic and leave it to the
 
3895
    #         rdb_makeB to handle after all circular dependencies are
 
3896
    #         resolved. 
 
3897
    #   2.  The output file might be of a different kind than expected
 
3898
    #         (i.e., dvi instead of pdf, or vv).  This could
 
3899
    #         legitimately occur when the source file (or an invoked
 
3900
    #         package or class) sets \pdfoutput. 
 
3901
    $missing_dvi_pdf = ''; 
 
3902
    if ($primary_out eq '')  {
 
3903
        warn "$My_name: For rule '$rule', no output was made\n";
 
3904
        $missing_dvi_pdf = $$Pdest;
 
3905
    }
 
3906
    elsif ($primary_out ne $$Pdest) {
 
3907
        warn "$My_name: ===For rule '$rule', actual output '$primary_out'\n",
 
3908
             "       ======appears not to match expected output '$$Pdest'\n";
 
3909
    }
 
3910
 
 
3911
  IDX_FILE:
 
3912
    foreach my $idx_file ( keys %idx_files ) {
 
3913
        my ($ind_file, $ind_base) = @{$idx_files{$idx_file}};
 
3914
        my $from_rule = "makeindex $idx_file";
 
3915
        if ( ! rdb_rule_exists( $from_rule ) ){
 
3916
            print "!!!===Creating rule '$from_rule': '$ind_file' from '$idx_file'\n"
 
3917
                  if ($diagnostics);
 
3918
            rdb_create_rule( $from_rule, 'external', $makeindex, '', 1, 
 
3919
                             $idx_file, $ind_file, $ind_base, 1, 0);
 
3920
            print "  ===Source file '$ind_file' for '$rule'\n"
 
3921
                  if ($diagnostics > -1);
 
3922
            rdb_ensure_file( $rule, $ind_file, $from_rule );
 
3923
        }
 
3924
        if ( ! -e $ind_file ) { 
 
3925
            # Failure was non-existence of makable file
 
3926
            # Leave failure issue to other rules.
 
3927
            $failure = 0;
 
3928
        }
 
3929
    }
 
3930
 
 
3931
  BBL_FILE:
 
3932
    foreach my $bbl_file ( uniqs( @bbl_files ) ) {
 
3933
        my ($bbl_base, $bbl_path, $bbl_ext) = fileparseA( $bbl_file );
 
3934
        $bbl_base = $bbl_path.$bbl_base;
 
3935
        my @new_bib_files;
 
3936
        my @new_aux_files;
 
3937
        &parse_aux( "$bbl_base.aux", \@new_bib_files, \@new_aux_files );
 
3938
        my $from_rule = "bibtex $bbl_base";
 
3939
        print "!!!===Dealing with rule '$from_rule'\n"
 
3940
            if ($diagnostics);
 
3941
        if ( ! rdb_rule_exists( $from_rule ) ){
 
3942
            print "   ===Creating rule '$from_rule'\n"
 
3943
              if ($diagnostics);
 
3944
            rdb_create_rule( $from_rule, 'external', $bibtex, '', 1, 
 
3945
                             "$bbl_base.aux", $bbl_file, $bbl_base, 1, 0);
 
3946
        }
 
3947
        local %old_sources = ();
 
3948
        rdb_one_rule( $from_rule, sub { %old_sources = %$PHsource; } );
 
3949
        foreach my $source ( @new_bib_files, @new_aux_files ) {
 
3950
            print "  === Source file '$source' for '$from_rule'\n"
 
3951
               if ($diagnostics);
 
3952
            rdb_ensure_file( $from_rule, $source );
 
3953
            delete $old_sources{$source};
 
3954
        }
 
3955
        if ($diagnostics>-1 ) {
 
3956
            foreach ( keys %old_sources ) {
 
3957
                print "Removing no-longer-needed dependent '$_' from rule '$from_rule'\n";
 
3958
            }
 
3959
        }        
 
3960
        rdb_remove_files( $from_rule, keys %old_sources );
 
3961
        print "  ===Source file '$bbl_file' for '$rule'\n"
 
3962
            if ($diagnostics);
 
3963
        rdb_ensure_file( $rule, $bbl_file, $from_rule );
 
3964
        if ( ! -e $bbl_file ) { 
 
3965
            # Failure was non-existence of makable file
 
3966
            # Leave failure issue to other rules.
 
3967
            $failure = 0;
 
3968
        }
 
3969
    }
 
3970
 
 
3971
NEW_SOURCE:
 
3972
    foreach my $new_source (keys %dependents, keys %conversions) {
 
3973
        print "  ===Source file for rule '$rule': '$new_source'\n"
 
3974
            if ($diagnostics);
 
3975
        if ( ($dependents{$new_source} == 5) 
 
3976
             || ($dependents{$new_source} == 6) ) {
 
3977
            # (a) File was detected in "No file..." line in log file. 
 
3978
            #     Typically file was searched for early in run of 
 
3979
            #     latex/pdflatex, was not found, and then was written 
 
3980
            #     later in run.
 
3981
            # or (b) File was written during run. 
 
3982
            # In both cases, if file doesn't already exist in database, we 
 
3983
            #    don't know its previous status.  Therefore we tell 
 
3984
            #    rdb_ensure_file that if it needs to add the file to its 
 
3985
            #    database, then the previous version of the file should be 
 
3986
            #    treated as non-existent, to ensure another run is forced.
 
3987
            rdb_ensure_file( $rule, $new_source, undef, 1 );
 
3988
        }
 
3989
        elsif ( $dependents{$new_source} == 7 )  {
 
3990
            # File was result of conversion by (pdf)latex.
 
3991
            my $cnv_source = $conversions{$new_source};
 
3992
            rdb_ensure_file( $rule, $new_source );
 
3993
            if ($cnv_source) {
 
3994
                # Conversion from $cnv_source to $new_source
 
3995
                #   implies that effectively $cnv_source is a source
 
3996
                #   of the (pdf)latex run.
 
3997
                rdb_ensure_file( $rule, $cnv_source );
 
3998
            }
 
3999
            # Flag that changes of the generated file during a run 
 
4000
            #    do not require a rerun:
 
4001
            rdb_one_file( $new_source, sub{ $$Pcorrect_after_primary = 1; } );
 
4002
        }
 
4003
        else {
 
4004
            # But we don't need special precautions for ordinary user files 
 
4005
            #    (or for files that are generated outside of latex/pdflatex). 
 
4006
            rdb_ensure_file( $rule, $new_source );
 
4007
        }
 
4008
    }
 
4009
 
 
4010
    my @more_sources = &rdb_set_dependentsA( $rule );
 
4011
    my $num_new = $#more_sources + 1;
 
4012
    foreach (@more_sources) { 
 
4013
        $dependents{$_} = 4;
 
4014
        if ( ! -e $_ ) { 
 
4015
            # Failure was non-existence of makable file
 
4016
            # Leave failure issue to other rules.
 
4017
            $failure = 0; 
 
4018
            $$Pchanged = 1; # New files can be made.  Ignore error.
 
4019
        }
 
4020
    }
 
4021
    if ($diagnostics) {
 
4022
        if ($num_new > 0 ) {
 
4023
            print "$num_new new source files for rule '$rule':\n";
 
4024
            foreach (@more_sources) { print "   '$_'\n"; }
 
4025
        }
 
4026
        else {
 
4027
            print "No new source files for rule '$rule':\n";
 
4028
        }
 
4029
    }
 
4030
 
 
4031
    my @files_not_needed = ();
 
4032
    foreach (keys %$PHsource) { 
 
4033
        if ( ! exists $dependents{$_} ) {
 
4034
            print "Removing no-longer-needed dependent '$_' from rule '$rule'\n"
 
4035
              if $diagnostics>-1;
 
4036
            push @files_not_needed, $_;
 
4037
        }
 
4038
    }
 
4039
    rdb_remove_files( $rule, @files_not_needed );
 
4040
 
 
4041
} # END rdb_set_from_logB
 
4042
 
 
4043
#************************************************************
 
4044
 
 
4045
sub rdb_find_new_filesB {
 
4046
    # Call: rdb_find_new_filesB
 
4047
    # Assumes rule context for primary rule.
 
4048
    # Deal with files which were missing and for which a method
 
4049
    # of finding them has become available:
 
4050
    #   (a) A newly available source file for a custom dependency.
 
4051
    #   (b) When there was no extension, a file with appropriate
 
4052
    #       extension
 
4053
    #   (c) When there was no extension, and a newly available source 
 
4054
    #       file for a custom dependency can make it.
 
4055
 
 
4056
    my %new_includes = ();
 
4057
 
 
4058
MISSING_FILE:
 
4059
    foreach my $missing ( keys %$PHsource ) {
 
4060
        next if ( $$PHsource{$missing} != 0 ); 
 
4061
        my ($base, $path, $ext) = fileparseA( $missing );
 
4062
        $ext =~ s/^\.//;
 
4063
        if ( -e "$missing.tex" ) { 
 
4064
            $new_includes{"$missing.tex"} = 1;
 
4065
        }
 
4066
        if ( -e $missing ) { 
 
4067
            $new_includes{$missing} = 1;
 
4068
        }
 
4069
        if ( $ext ne "" ) {
 
4070
            foreach my $dep (@cus_dep_list){
 
4071
               my ($fromext,$toext) = split(' ',$dep);
 
4072
               if ( ( "$ext" eq "$toext" )
 
4073
                    && ( -e "$path$base.$fromext" )
 
4074
                  )  {
 
4075
                  # Source file for the missing file exists
 
4076
                  # So we have a real include file, and it will be made
 
4077
                  # next time by rdb_set_dependents
 
4078
                  $new_includes{$missing} = 1;
 
4079
               }
 
4080
               else {
 
4081
                   # no point testing the $toext if the file doesn't exist.
 
4082
               }
 
4083
               next MISSING_FILE;
 
4084
            }
 
4085
       }
 
4086
       else {
 
4087
           # $_ doesn't exist, $_.tex doesn't exist,
 
4088
           # and $_ doesn't have an extension
 
4089
           foreach my $dep (@cus_dep_list){
 
4090
              my ($fromext,$toext) = split(' ',$dep);
 
4091
              if ( -e "$path$base.$fromext" ) {
 
4092
                  # Source file for the missing file exists
 
4093
                  # So we have a real include file, and it will be made
 
4094
                  # next time by &rdb__dependents
 
4095
                  $new_includes{"$path$base.$toext"} = 1;
 
4096
#                  next MISSING_FILE;
 
4097
              }
 
4098
              if ( -e "$path$base.$toext" ) {
 
4099
                  # We've found the extension for the missing file,
 
4100
                  # and the file exists
 
4101
                  $new_includes{"$path$base.$toext"} = 1;
 
4102
#                  next MISSING_FILE;
 
4103
              }
 
4104
           }
 
4105
       }
 
4106
    } # end MISSING_FILES
 
4107
 
 
4108
    # Sometimes bad line-breaks in log file (etc) create the
 
4109
    # impression of a missing file e.g., ./file, but with an incorrect
 
4110
    # extension.  The above tests find the file with an extension,
 
4111
    # e.g., ./file.tex, but it is already in the list.  So now I will
 
4112
    # remove files in the new_include list that are already in the
 
4113
    # include list.  Also handle aliasing of file.tex and ./file.tex.
 
4114
    # For example, I once found:
 
4115
# (./qcdbook.aux (./to-do.aux) (./ideas.aux) (./intro.aux) (./why.aux) (./basics
 
4116
#.aux) (./classics.aux)
 
4117
 
 
4118
    my $found = 0;
 
4119
    foreach my $file (keys %new_includes) {
 
4120
        my $stripped = $file;
 
4121
        $stripped =~ s{^\./}{};
 
4122
        if ( exists $PHsource{$file} ) {
 
4123
            delete $new_includes{$file};
 
4124
        }
 
4125
        else {
 
4126
            $found ++;
 
4127
            rdb_ensure_file( $rule, $file );
 
4128
        }
 
4129
    }
 
4130
 
 
4131
    if ( $diagnostics && ( $found > 0 ) ) {
 
4132
        warn "$My_name: Detected previously missing files:\n";
 
4133
        foreach ( sort keys %new_includes ) {
 
4134
            warn "   '$_'\n";
 
4135
        }
 
4136
    }
 
4137
    return $found;
 
4138
} # END rdb_find_new_filesB
 
4139
 
 
4140
#************************************************************
 
4141
 
 
4142
sub rdb_set_dependentsA {
 
4143
    # Call rdb_set_dependentsA( rules ...)
 
4144
    # Returns array (sorted), of new source files.
 
4145
    local @new_sources = ();
 
4146
    local @deletions = ();
 
4147
 
 
4148
# Shouldn't recurse.  The definite rules to be examined are given.
 
4149
    rdb_for_some( [@_],  0, \&rdb_one_depA );
 
4150
# OLD    rdb_recurseA( [@_],  0, \&rdb_one_depA );
 
4151
    foreach (@deletions) {
 
4152
        my ($rule, $file) = @$_;
 
4153
        rdb_remove_files( $rule, $file );
 
4154
    }
 
4155
    &rdb_make_links;
 
4156
    return uniqs( @new_sources );
 
4157
} #END rdb_set_dependentsA
 
4158
 
 
4159
#************************************************************
 
4160
 
 
4161
sub rdb_one_depA {
 
4162
    # Helper for finding dependencies.  One case, $rule and $file given
 
4163
    # Assume file (and rule) context for DESTINATION file.
 
4164
    local $new_dest = $file;
 
4165
    my ($base_name, $path, $toext) = fileparseA( $new_dest );
 
4166
    $base_name = $path.$base_name;
 
4167
    $toext =~ s/^\.//;
 
4168
    my $Pinput_extensions = $input_extensions{$rule};
 
4169
DEP:
 
4170
    foreach my $dep ( @cus_dep_list ) {
 
4171
        my ($fromext,$proptoext,$must,$func_name) = split(' ',$dep);
 
4172
        if ( $toext eq $proptoext ) {
 
4173
            my $source = "$base_name.$fromext";
 
4174
            # Found match of rule
 
4175
            if ($diagnostics) {
 
4176
                print "Found cusdep:  $source to make $rule:$new_dest ====\n";
 
4177
            }
 
4178
            if ( -e $source ) {
 
4179
                $$Pfrom_rule = "cusdep $fromext $toext $base_name";
 
4180
#??             print "?? Ensuring rule for '$$Pfrom_rule'\n";
 
4181
                local @PAnew_cmd = ( 'do_cusdep', $func_name );
 
4182
                if ( !-e $new_dest ) {
 
4183
                    push @new_sources, $new_dest;
 
4184
                }
 
4185
                if (! rdb_rule_exists( $$Pfrom_rule ) ) {
 
4186
                    print "=== Creating rule for '$$Pfrom_rule'\n";
 
4187
                    rdb_create_rule( $$Pfrom_rule, 'cusdep', '', \@PAnew_cmd, 3, 
 
4188
                                     $source, $new_dest, $base_name, 0 );
 
4189
                }
 
4190
                else {
 
4191
                    rdb_one_rule( 
 
4192
                       $$Pfrom_rule, 
 
4193
                       sub{ @$PAint_cmd = @PAnew_cmd; $$Pdest = $new_dest;}
 
4194
                    );
 
4195
                }
 
4196
                return;
 
4197
            }
 
4198
            else {
 
4199
                # Source file does not exist
 
4200
                if ( !$force_mode && ( $must != 0 ) ) {
 
4201
                    # But it is required that the source exist ($must !=0)
 
4202
                    $failure = 1;
 
4203
                    $failure_msg = "File '$base_name.$fromext' does not exist ".
 
4204
                                   "to build '$base_name.$toext'";
 
4205
                    return;
 
4206
                }
 
4207
                elsif ( $$Pfrom_rule =~ /^cusdep $fromext $toext / )  {
 
4208
                    # Source file does not exist, destination has the rule set.
 
4209
                    # So turn the from_rule off
 
4210
                    $$Pfrom_rule = '';
 
4211
                }
 
4212
                else {
 
4213
                }
 
4214
            }
 
4215
        }
 
4216
        elsif ( ($toext eq '') 
 
4217
                && (! -e $file ) 
 
4218
                && (! -e "$base_name.$proptoext" ) 
 
4219
                && exists $$Pinput_extensions{$proptoext}
 
4220
              ) {
 
4221
            # Empty extension and non-existent destination
 
4222
            #   This normally results from  \includegraphics{A}
 
4223
            #    without graphics extension for file, when file does
 
4224
            #    not exist.  So we will try to find something to make it.
 
4225
            my $source = "$base_name.$fromext";
 
4226
            if ( -e $source ) {
 
4227
                $new_dest = "$base_name.$proptoext";
 
4228
                my $from_rule = "cusdep $fromext $proptoext $base_name";
 
4229
                push @new_sources, $new_dest;
 
4230
                print "Ensuring rule for '$from_rule', to make '$new_dest'\n"
 
4231
                    if $diagnostics > -1;
 
4232
                local @PAnew_cmd = ( 'do_cusdep', $func_name );
 
4233
                if (! rdb_rule_exists( $from_rule ) ) {
 
4234
                    rdb_create_rule( $from_rule, 'cusdep', '', \@PAnew_cmd, 3, 
 
4235
                                     $source, $new_dest, $base_name, 0);
 
4236
                }
 
4237
                else {
 
4238
                    rdb_one_rule( 
 
4239
                       $$Pfrom_rule, 
 
4240
                       sub{ @$PAint_cmd = @PAnew_cmd; $$Pdest = $new_dest;}
 
4241
                    );
 
4242
                }
 
4243
                rdb_ensure_file( $rule, $new_dest, $from_rule );
 
4244
                # We've now got a spurious file in our rule.  But don't mess
 
4245
                # with deleting an item we are in the middle of!
 
4246
                push @deletions, [$rule, $file];
 
4247
                return;
 
4248
            }
 
4249
        } # End of Rule found
 
4250
    } # End DEP
 
4251
} #END rdb_one_depA
 
4252
 
 
4253
#************************************************************
 
4254
 
 
4255
sub rdb_list {
 
4256
    # Call: rdb_list()
 
4257
    # List rules and their source files
 
4258
    print "===Rules:\n";
 
4259
    local $count_rules = 0;
 
4260
    my @accessible_all = rdb_accessible( keys %requested_filerules ); 
 
4261
    rdb_for_some( 
 
4262
        \@accessible_all,
 
4263
        sub{ $count_rules++; 
 
4264
             print "Rule '$rule' depends on:\n"; 
 
4265
           },
 
4266
        sub{ print "    '$file'\n"; }
 
4267
    );
 
4268
    if ($count_rules <= 0) {
 
4269
        print "   ---No rules defined\n";
 
4270
    }
 
4271
} #END rdb_list
 
4272
 
 
4273
#************************************************************
 
4274
 
 
4275
sub rdb_show {
 
4276
    # Call: rdb_show()
 
4277
    # Displays contents of rule data base.
 
4278
    # Side effect: Exercises access routines!
 
4279
    print "===Rules:\n";
 
4280
    local $count_rules = 0;
 
4281
    rdb_for_all( 
 
4282
        sub{ $count_rules++; 
 
4283
             my @int_cmd = @$PAint_cmd;
 
4284
             foreach (@int_cmd) {
 
4285
                 if ( !defined($_) ) { $_='undef';}
 
4286
             }
 
4287
             print "  [$rule]: '$$Pcmd_type' '$$Pext_cmd' '@int_cmd' $$Ptest_kind ",
 
4288
                   "'$$Psource' '$$Pdest' '$$Pbase' $$Pout_of_date $$Pout_of_date_user\n"; },
 
4289
        sub{ print "    '$file': $$Ptime $$Psize $$Pmd5 '$$Pfrom_rule'\n"; }
 
4290
    );
 
4291
    if ($count_rules <= 0) {
 
4292
        print "   ---No rules defined\n";
 
4293
    }
 
4294
} #END rdb_show
 
4295
 
 
4296
#************************************************************
 
4297
 
 
4298
sub rdb_accessible {
 
4299
    # Call: rdb_accessible( rule, ...)
 
4300
    # Returns array of rules accessible from the given rules
 
4301
    local @accessible = ();
 
4302
    rdb_recurseA( [@_], sub{ push @accessible, $rule; } );
 
4303
    return @accessible;
 
4304
} #END rdb_accessible
 
4305
 
 
4306
#************************************************************
 
4307
#************************************************************
 
4308
#************************************************************
 
4309
 
 
4310
sub rdb_makeB {
 
4311
    # Call: rdb_makeB( target, ... )
 
4312
    # Makes the targets and prerequisites.  
 
4313
    # Leaves one-time rules to last.
 
4314
    # Does appropriate repeated makes to resolve dependency loops
 
4315
 
 
4316
    # Returns 0 on success, nonzero on failure.
 
4317
 
 
4318
    # General method: Find all accessible rules, then repeatedly make
 
4319
    # them until all accessible rules are up-to-date and the source
 
4320
    # files are unchanged between runs.  On termination, all
 
4321
    # accessible rules have stable source files.
 
4322
    #
 
4323
    # One-time rules are view and print rules that should not be
 
4324
    # repeated in an algorithm that repeats rules until the source
 
4325
    # files are stable.  It is the calling routine's responsibility to
 
4326
    # arrange to call them, or to use them here with caution.
 
4327
    #
 
4328
    # Note that an update-viewer rule need not be considered
 
4329
    # one-time.  It can be legitimately applied everytime the viewed
 
4330
    # file changes.
 
4331
    #
 
4332
    # Note also that the criterion of stability is to be applied to
 
4333
    # source files, not to output files.  Repeated application of a
 
4334
    # rule to IDENTICALLY CONSTANT source files may produce different
 
4335
    # output files.  This may be for a trivial reason (e.g., the
 
4336
    # output file contains a time stamp, as in the header comments for
 
4337
    # a typical postscript file), or for a non-trivial reason (e.g., a
 
4338
    # stochastic algorithm, as in abcm2ps).   
 
4339
    #
 
4340
    # This caused me some actual trouble.  In general, circular
 
4341
    # dependencies produce non-termination, and the the following
 
4342
    # situation is an example of a generic situation where certain
 
4343
    # rules must be obeyed in order to obtain proper results:
 
4344
    #    1.  A/the latex source file contains specifications for
 
4345
    #        certain postprocessing operations.  Standard (pdf)latex 
 
4346
    #        already has this, for indexing and bibliography.
 
4347
    #    2.  In the case in point that caused me trouble, the
 
4348
    #        specification was for musical tunes that were contained
 
4349
    #        in external source files not directly input to
 
4350
    #        (pdf)latex.  But in the original version, there was a
 
4351
    #        style file (abc.sty) that caused latex itself to call
 
4352
    #        abcm2ps to make .eps files for each tune that were to be
 
4353
    #        read in on the next run of latex. 
 
4354
    #    3.  Thus the specification can cause a non-terminating loop
 
4355
    #        for latexmk, because the output files of abcm2ps changed
 
4356
    #        even with identical input.  
 
4357
    #    4.  The solution was to 
 
4358
    #        a. Use a style file abc_get.sty that simply wrote the
 
4359
    #           specification on the tunes to the .aux file in a
 
4360
    #           completely deterministic fashion.
 
4361
    #        b. Instead of latex, use a script abclatex.pl that runs
 
4362
    #           latex and then extracts the abc contents for each tune
 
4363
    #           from the source abc file.  This is also
 
4364
    #           deterministic. 
 
4365
    #        c. Use a cusdep rule in latexmk to convert the tune abc
 
4366
    #           files to eps.  This is non-deterministic, but only
 
4367
    #           gets called when the (deterministic) source file
 
4368
    #           changes.
 
4369
    #        This solves the problem.  Latexmk works.  Also, it is no
 
4370
    #        longer necessary to enable write18 in latex, and multiple
 
4371
    #        unnecessary runs of abcm2ps are no longer used. 
 
4372
    #
 
4373
    # The order of testing and applying rules is chosen by the
 
4374
    # following heuristics: 
 
4375
    #    1.  Both latex and pdflatex may be used, but the resulting
 
4376
    #        aux files etc may not be completely identical.  Define
 
4377
    #        latex and pdflatex as primary rules.  Apply the general
 
4378
    #        method of repeated circulating through all rules until
 
4379
    #        the source files are stable for each primary rule
 
4380
    #        separately.  Naturally the rules are all accessible
 
4381
    #        rules, but excluding primary rules except for the current
 
4382
    #        primary.
 
4383
    #    2.  Assume that the primary rules are relatively
 
4384
    #        time-consuming, so that unnecessary passes through them
 
4385
    #        to check stability of the source files should be avoided.
 
4386
    #    3.  Assume that although circular dependencies exist, the
 
4387
    #        rules can nevertheless be thought of as basically
 
4388
    #        non-circular, and that many rules are strictly or
 
4389
    #        normally non-circular.  In particular cusdep rules are
 
4390
    #        typically non-circular (e.g., fig2eps), as are normal
 
4391
    #        output processing rules like dvi2ps.  
 
4392
    #    4.  The order for the non-circular approximation is
 
4393
    #        determined by applying the assumption that an output file
 
4394
    #        from one rule that is read in for an earlier stage is
 
4395
    #        unchanged. 
 
4396
    #    HOWEVER, at a first attempt, the ordering is not needed.  It
 
4397
    #    only gives an optimization
 
4398
    #    5.  (Note that these assumptions could be violated, e.g., if
 
4399
    #        $dvips is arranged not only to do the basic dvips
 
4400
    #        command, but also to extract information from the ps file
 
4401
    #        and feed it back to an input file for (pdf)latex.)
 
4402
    #    6.  Nevertheless, the overall algorithm should allow
 
4403
    #        circularities.  Then the general criterion of stability
 
4404
    #        of source files covers the general case, and also
 
4405
    #        robustly handles the case that the USER changes source
 
4406
    #        files during a run.  This is particularly important in
 
4407
    #        -pvc mode, given that a full make on a large document can
 
4408
    #        be quite lengthy in time, and moreover that a user
 
4409
    #        naturally wishes to make corrections in response to
 
4410
    #        errors, particularly latex errors, and have them apply
 
4411
    #        right away.
 
4412
    # This leads to the following approach:
 
4413
    #    1.  Classify accessible rules as: primary, pre-primary
 
4414
    #        (typically cusdep, bibtex, makeindex, etc), post-primary
 
4415
    #        (typically dvips, etc), and one-time
 
4416
    #    2.  Then stratify the rules into an order of application that
 
4417
    #        corresponds to the basic feedforward structure, with the
 
4418
    #        exclusion of one-time rules.
 
4419
    #    3.  Always require that one-time rules are among the
 
4420
    #        explicitly requested rules, i.e., the last to be applied,
 
4421
    #        were we to apply them.  Anything else would not match the
 
4422
    #        idea of a one-time rule.  
 
4423
    #    4.  Then work as follows:
 
4424
    #        a. Loop over primaries
 
4425
    #        b. For each primary, examine each pre-primary rule and
 
4426
    #           apply if needed, then the primary rule and then each
 
4427
    #           post-primary rule.  The ordering of the pre-primary
 
4428
    #           and post-primary rules was found in step 2.
 
4429
    #      BUT applying the ordering is not essential
 
4430
    #        c. Any time that a pre-primary or primary rule is
 
4431
    #           applied, loop back to the beginning of step b.  This
 
4432
    #           ensures that bibtex etc are applied before rerunning
 
4433
    #           (pdf)latex, and also covers changing source files, and
 
4434
    #           gives priority to quick pre-primary rules for changing
 
4435
    #           source files against slow reruns of latex.
 
4436
    #        d. Then apply post-primary rules in order, but not
 
4437
    #           looping back after each rule.  This non-looping back
 
4438
    #           is because the rules are normally feed-forward only.
 
4439
    #      BUT applying the ordering is not essential
 
4440
    #        e. But after completing post-primary rules do loop back
 
4441
    #           to b if any rules were applied.  This covers exotic
 
4442
    #           circular dependence (and as a byproduct, changing
 
4443
    #           source files).
 
4444
    #        f. On each case of looping back to b, re-evaluate the
 
4445
    #           dependence setup to allow for the effect of changing
 
4446
    #           source files.  
 
4447
    #    
 
4448
 
 
4449
    local @requested_targets = @_;
 
4450
    local %current_primaries = ();   # Hash whose keys are primary rules 
 
4451
                # needed, i.e., known latex-like rules which trigger
 
4452
                # circular dependencies
 
4453
    local @pre_primary = ();   # Array of rules
 
4454
    local @post_primary = ();  # Array of rules
 
4455
    local @one_time = ();      # Array of rules
 
4456
 
 
4457
 
 
4458
    # For diagnostics on changed files, etc:
 
4459
    local @changed = ();
 
4460
    local @disappeared = ();
 
4461
    local @no_dest = ();       # Non-existent destination files
 
4462
    local @rules_never_run = ();
 
4463
    local @rules_to_apply = ();
 
4464
 
 
4465
    &rdb_classify_rules( \%possible_primaries, @requested_targets );
 
4466
 
 
4467
    local %pass = ();
 
4468
    local $failure = 0;        # General accumulated error flag
 
4469
    local $missing_dvi_pdf = ''; # Did primary run fail to make its output file? 
 
4470
    local $runs = 0;
 
4471
    local $too_many_runs = 0;
 
4472
    local %rules_applied = ();
 
4473
    my $retry_msg = 0;         # Did I earlier say I was going to attempt 
 
4474
                               # another pass after a failure?
 
4475
  PRIMARY:
 
4476
    foreach my $primary (keys %current_primaries ) {
 
4477
        foreach my $rule (keys %rule_db) { 
 
4478
            $pass{$rule} = 0; 
 
4479
        }
 
4480
      PASS:
 
4481
        while (1==1) {
 
4482
            $runs = 0;
 
4483
            my $previous_failure = $failure;
 
4484
            $failure = 0;
 
4485
            local $newrule_nofile = 0;  # Flags whether rule created for
 
4486
                           # making currently non-existent file, which
 
4487
                           # could become a needed source file for a run
 
4488
                           # and therefore undo an error condition
 
4489
            if ($diagnostics) {
 
4490
                print "MakeB: doing pre_primary and primary...\n";
 
4491
            }
 
4492
            rdb_for_some( [@pre_primary, $primary], \&rdb_makeB1 );
 
4493
            if ( ($runs > 0) && ! $too_many_runs ) {
 
4494
                $retry_msg = 0;
 
4495
                if ( $failure && $newrule_nofile ) { 
 
4496
                    $retry_msg = 1;
 
4497
                    print "$My_name: Error on run, but found possibility to ",
 
4498
                          "make new source files\n";
 
4499
                    next PASS;
 
4500
                }
 
4501
                elsif ( ! $failure ) {
 
4502
                    next PASS;
 
4503
                }
 
4504
            }
 
4505
            elsif ($runs == 0) {
 
4506
                # $failure not set on this pass, so use value from previous pass:
 
4507
                $failure = $previous_failure;
 
4508
                if ($retry_msg) {
 
4509
                    print "But in fact no new files made\n";
 
4510
                }
 
4511
            }
 
4512
            if ( $missing_dvi_pdf ) { 
 
4513
               # No output from primary, after completing circular dependence
 
4514
               warn "Failure to make '$missing_dvi_pdf'\n";
 
4515
               $failure = 1; 
 
4516
               last PASS;
 
4517
            }    
 
4518
            if ($failure && !$force_mode ) { last PASS; }
 
4519
            if ($diagnostics) {
 
4520
                print "MakeB: doing post_primary...\n";
 
4521
            }
 
4522
            rdb_for_some( [@post_primary], \&rdb_makeB1 );
 
4523
            if ($failure) { last PASS; }
 
4524
            if ($runs > 0) { next PASS; }
 
4525
            # Get here if nothing was run.
 
4526
            last PASS;
 
4527
        }
 
4528
        continue {
 
4529
            # Re-evaluate rule classification and accessibility,
 
4530
            # but do not change primaries.
 
4531
            # Problem is that %current_primaries gets altered
 
4532
            my %old_curr_prim = %current_primaries;
 
4533
            &rdb_classify_rules( \%possible_primaries, @requested_targets );
 
4534
            %current_primaries = %old_curr_prim;
 
4535
            &rdb_make_links;
 
4536
        }
 
4537
    }
 
4538
    rdb_for_some( [@one_time], \&rdb_makeB1 );
 
4539
    rdb_write( $fdb_file );
 
4540
 
 
4541
    if (! $silent) { 
 
4542
        # Diagnose of the runs
 
4543
        if ( $#{keys %rules_applied }  > -1 ) {
 
4544
            print "$My_name: $runs runs.  Rules applied:\n";
 
4545
            foreach (sort keys %rules_applied) {
 
4546
                print "    '$_'\n";
 
4547
            }
 
4548
        }
 
4549
        elsif ($failure && $force_mode) {
 
4550
            print "$My_name: Errors, in force_mode: so I tried finishing targets\n";
 
4551
        }
 
4552
        elsif ($failure) {
 
4553
            print "$My_name: Errors, so I did not complete making targets\n";
 
4554
        }
 
4555
        else {
 
4556
            local @dests = ();
 
4557
            rdb_for_some( [@_], sub{ push @dests, $$Pdest if ($$Pdest); } );
 
4558
            print "$My_name: All targets (@dests) are up-to-date\n";
 
4559
        }
 
4560
    }
 
4561
    return $failure;
 
4562
} #END rdb_makeB
 
4563
 
 
4564
#-------------------
 
4565
 
 
4566
sub rdb_show_rule_errors {
 
4567
    local @messages = ();
 
4568
    rdb_for_all( 
 
4569
               sub{
 
4570
                   if ($$Plast_message ne '') {
 
4571
                       push @messages, "$rule: $$Plast_message";
 
4572
                   }
 
4573
                   elsif ($$Plast_result == 1) {
 
4574
                       push @messages, "$rule: failed to create output file";
 
4575
                   }
 
4576
                   elsif ($$Plast_result == 2) {
 
4577
                       push @messages, "$rule: gave an error";
 
4578
                   }
 
4579
                   elsif ($$Prun_time == 0) {
 
4580
#    This can have innocuous causes.  So don't report
 
4581
#                      push @messages, "$rule: never run";
 
4582
                   }
 
4583
               }
 
4584
              );
 
4585
    if ($#messages > -1) { 
 
4586
        warn "Collected error summary (may duplicate other messages):\n";
 
4587
        foreach (@messages){
 
4588
            warn "  $_\n";
 
4589
        }
 
4590
    }
 
4591
    return $#messages+1;
 
4592
}
 
4593
 
 
4594
#-------------------
 
4595
 
 
4596
sub rdb_makeB1 {
 
4597
    # Call: rdb_makeB1
 
4598
    # Helper routine for rdb_makeB.
 
4599
    # Carries out make at level of given rule (all data available).
 
4600
    # Assumes contexts for recursion, make, and rule, and
 
4601
    # assumes that source files for the rule are to be considered
 
4602
    # up-to-date. 
 
4603
    if ($diagnostics) { print "  MakeB1 $rule\n"; }
 
4604
    if ($failure & ! $force_mode) {return;}
 
4605
    if ( ! defined $pass{$rule} ) {$pass{$rule} = 0; } 
 
4606
    &rdb_clear_change_record;
 
4607
 
 
4608
    # Special fix up for bibtex:
 
4609
    my $bibtex_not_run = -1;   # Flags status as to whether this is a
 
4610
        # bibtex rule and if it is, whether out-of-date condition is to
 
4611
        # be ignored.
 
4612
        #  -1 => not a bibtex rule
 
4613
        #   0 => no special treatment
 
4614
        #   1 => don't run bibtex because of non-existent bibfiles
 
4615
        #           (and setting to do this test)
 
4616
        #   2 => don't run bibtex because of setting
 
4617
    my @missing_bib_files = ();
 
4618
    if ( $rule =~ /^bibtex/ ) {
 
4619
        $bibtex_not_run = 0;
 
4620
        if ($bibtex_use == 0) {
 
4621
           $bibtex_not_run = 2;
 
4622
        }
 
4623
        elsif ($bibtex_use == 1) {
 
4624
            foreach ( keys %$PHsource ) {
 
4625
                if ( ( /\.bib$/ ) && (! -e $_) ) {
 
4626
                    push @missing_bib_files, $_;
 
4627
                    $bibtex_not_run = 1;
 
4628
                }
 
4629
            }
 
4630
        }
 
4631
    }
 
4632
 
 
4633
    if ( ($$Prun_time == 0) && exists($possible_primaries{$rule}) ) {
 
4634
        push @rules_never_run, $rule;
 
4635
        $$Pout_of_date = 1;
 
4636
        $$Plast_result = -1;
 
4637
    }
 
4638
    else {
 
4639
        if ( $$Pdest && (! -e $$Pdest) ) {
 
4640
            # With a non-existent destination, if we haven't made any passes
 
4641
            #   through a rule, rerunning the rule is good, because the file
 
4642
            #   may fail to exist because of being deleted by the user (for ex.)
 
4643
            #   rather than because of a failure on a previous run. 
 
4644
            # (We could do better with a flag in fdb file.)
 
4645
            # But after the first pass, the situation is different.  
 
4646
            #   For a primary rule (pdf)latex, the lack of a destination file 
 
4647
            #      could result from there being zero content due to a missing
 
4648
            #      essential input file.  The input file could be generated 
 
4649
            #      by a program to be run later (e.g., a cusdep or bibtex), 
 
4650
            #      so we should wait until all passes are completed before 
 
4651
            #      deciding a non-existent destination file is an error.
 
4652
            #   For a custom dependency, the rule may be obsolete, and
 
4653
            #      if the source file does not exist also, we should simply
 
4654
            #      not run the rule, but not set an error condition.
 
4655
            #      Any error will arise at the (pdf)latex level due to a 
 
4656
            #      missing source file at that level.
 
4657
            if ( ( $$Pcmd_type eq 'cusdep') && $$Psource && (! -e $$Psource) ) {
 
4658
                # No action
 
4659
            }
 
4660
            elsif ( $$Pcmd_type eq 'delegated' ) {
 
4661
                # Delegate to destination rule
 
4662
            }
 
4663
            elsif ( $pass{$rule}==0) {
 
4664
                push @no_dest, $$Pdest;
 
4665
                $$Pout_of_date = 1;
 
4666
            }
 
4667
            if ( $$Pcmd_type eq 'primary' ) {
 
4668
                $missing_dvi_pdf = $$Pdest;
 
4669
            }
 
4670
        }
 
4671
    }
 
4672
 
 
4673
    &rdb_flag_changes_here;
 
4674
 
 
4675
    if (!$$Pout_of_date) {
 
4676
#??     if ( ($$Pcmd_type eq 'primary') && (! $silent) ) {
 
4677
#            print "Rule '$rule' up to date\n";
 
4678
#        }
 
4679
        return;
 
4680
    }
 
4681
    if ($diagnostics) { print "     remake\n"; }
 
4682
    if (!$silent) { 
 
4683
        print "$My_name: applying rule '$rule'...\n"; 
 
4684
        &rdb_diagnose_changes( "Rule '$rule': " );
 
4685
    }
 
4686
 
 
4687
    $rules_applied{$rule} = 1;
 
4688
    $runs++;
 
4689
 
 
4690
    # We are applying the rule, so its source file state for when it
 
4691
    # was last made is as of now:
 
4692
    # ??IS IT CORRECT TO DO NOTHING IN CURRENT VERSION?
 
4693
 
 
4694
    # The actual run
 
4695
    my $return = 0;   # Return code from called routine
 
4696
    # Rule may have been created since last run:
 
4697
    if ( ! defined $pass{$rule} ) {$pass{$rule} = 0; }
 
4698
    if ( $pass{$rule} ge $max_repeat ) {
 
4699
        # Avoid infinite loop by having a maximum repeat count
 
4700
        # Getting here represents some kind of weird error.
 
4701
        warn "$My_name: Maximum runs of $rule reached ",
 
4702
             "without getting stable files\n";
 
4703
        $too_many_runs = 1;
 
4704
        $failure = 1;
 
4705
        $failure_msg = "'$rule' needed too many passes";
 
4706
        return;
 
4707
    }
 
4708
    $pass{$rule}++; 
 
4709
    if ($bibtex_not_run > 0) {
 
4710
        if ($bibtex_not_run == 1 ) {
 
4711
            show_array ("$My_name: I WON'T RUN '$rule' because I don't find the following files:",
 
4712
                        @missing_bib_files);
 
4713
        }
 
4714
        elsif ($bibtex_not_run == 2 ) {
 
4715
            warn "$My_name: I AM CONFIGURED/INVOKED NOT TO RUN '$rule'\n"; 
 
4716
        }
 
4717
        $return = &rdb_dummy_run1;
 
4718
    }
 
4719
    else {
 
4720
        warn_running( "Run number $pass{$rule} of rule '$rule'" );
 
4721
        if ($$Pcmd_type eq 'primary' ) { 
 
4722
            $return = &rdb_primary_run; 
 
4723
        }
 
4724
        else { $return = &rdb_run1; }
 
4725
    }
 
4726
    if ($$Pchanged) {
 
4727
        $newrule_nofile = 1;
 
4728
        $return = 0;
 
4729
    }
 
4730
    elsif ( $$Pdest && ( !-e $$Pdest ) && (! $failure) ){
 
4731
        # If there is a destination to make, but for some reason
 
4732
        #    it did not get made, and no other error was reported, 
 
4733
        #    then a priori there appears to be an error condition:
 
4734
        #    the run failed.   But there are two important cases in
 
4735
        #    which this is a wrong diagnosis.
 
4736
        if ( ( $$Pcmd_type eq 'cusdep') && $$Psource && (! -e $$Psource) ) {
 
4737
            # However, if the rule is a custom dependency, this is not by
 
4738
            #  itself an error, if also the source file does not exist.  In 
 
4739
            #  that case, we may have the situation that (1) the dest file is no
 
4740
            #  longer needed by the tex file, and (2) therefore the user
 
4741
            #  has deleted the source and dest files.  After the next
 
4742
            #  latex run and the consequent analysis of the log file, the
 
4743
            #  cusdep rule will no longer be needed, and will be removed.
 
4744
 
 
4745
            # So in this case, do NOT report an error          
 
4746
            $$Pout_of_date = 0;
 
4747
        }
 
4748
        elsif ($$Pcmd_type eq 'primary' ) { 
 
4749
            # For a primary rule, i.e., (pdf)latex, not to produce the 
 
4750
            #    expected output file may not be an error condition.  
 
4751
            # Diagnostics were handled in parsing the log file.
 
4752
            # Special action in main loop inrdb_makeB1
 
4753
            $missing_dvi_pdf = $$Pdest;
 
4754
        }
 
4755
        else {
 
4756
            $failure = 1;
 
4757
        }
 
4758
    }
 
4759
    if ($return != 0) {
 
4760
        $failure = 1; 
 
4761
        $$Plast_result = 2;
 
4762
        if ( !$$Plast_message ) {
 
4763
            $$Plast_message = "Run of rule '$rule' gave a non-zero error code";
 
4764
        }
 
4765
# !!??        $failure_msg = $$Plast_message;
 
4766
        
 
4767
    }
 
4768
}  #END rdb_makeB1
 
4769
 
 
4770
#************************************************************
 
4771
 
 
4772
sub rdb_submakeB {
 
4773
    # Call: rdb_submakeB
 
4774
    # Makes all the source files for a given rule.
 
4775
    # Assumes contexts for recursion, for make, and rule.
 
4776
    %visited = %visited_at_rule_start;
 
4777
    local $failure = 0;  # Error flag
 
4778
    my @v = keys %visited;
 
4779
#??    print "---submakeB $rule.  @v \n";
 
4780
    rdb_do_files( sub{ rdb_recurse_rule( $$Pfrom_rule, 0,0,0, \&rdb_makeB1 ) } );
 
4781
    return $failure;
 
4782
}  #END rdb_submakeB
 
4783
 
 
4784
#************************************************************
 
4785
 
 
4786
 
 
4787
sub rdb_classify_rules {
 
4788
    # Usage: rdb_classify_rules( \%allowed_primaries, requested targets )
 
4789
    # Assume the following variables are available (global or local):
 
4790
    # Input:
 
4791
    #    @requested_targets    # Set to target rules
 
4792
    
 
4793
    # Output:
 
4794
    #    %current_primaries    # Keys are actual primaries
 
4795
    #    @pre_primary          # Array of rules
 
4796
    #    @post_primary         # Array of rules
 
4797
    #    @one_time             # Array of rules
 
4798
    # @pre_primary and @post_primary are in natural order of application.
 
4799
 
 
4800
    local $P_allowed_primaries = shift;
 
4801
    local @requested_targets = @_;
 
4802
    local $state = 0;       # Post-primary
 
4803
    local @classify_stack = ();
 
4804
 
 
4805
    %current_primaries = ();
 
4806
    @pre_primary = ();
 
4807
    @post_primary = ();
 
4808
    @one_time = ();
 
4809
 
 
4810
    rdb_recurseA( \@requested_targets, \&rdb_classify1, 0,0, \&rdb_classify2 );
 
4811
 
 
4812
    # Reverse, as tendency is to find last rules first.
 
4813
    @pre_primary = reverse @pre_primary;
 
4814
    @post_primary = reverse @post_primary;
 
4815
 
 
4816
    if ($diagnostics) {
 
4817
        print "Rule classification: \n";
 
4818
        if ($#requested_targets < 0) {
 
4819
            print "  No requested rules\n";
 
4820
        }
 
4821
        else {
 
4822
            print "  Requested rules:\n";
 
4823
            foreach ( @requested_targets ) { print "    $_\n"; }
 
4824
        }
 
4825
        if ($#pre_primary < 0) {
 
4826
            print "  No pre-primaries\n";
 
4827
        }
 
4828
        else {
 
4829
            print "  Pre-primaries:\n";
 
4830
            foreach (@pre_primary) { print "    $_\n"; }
 
4831
        }
 
4832
        print "  Primaries:\n";
 
4833
        foreach (keys %current_primaries) { print "    $_\n"; }
 
4834
        if ($#post_primary < 0) {
 
4835
            print "  No post-primaries\n";
 
4836
        }
 
4837
        else {
 
4838
            print "  Post-primaries:\n";
 
4839
            foreach (@post_primary) { print "    $_\n"; }
 
4840
        }
 
4841
        if ($#one_time < 0) {
 
4842
            print "  No one_time rules\n";
 
4843
        }
 
4844
        else {
 
4845
            print "  One_time rules:\n";
 
4846
            foreach ( @one_time ) { print "    $_\n"; }
 
4847
        }
 
4848
    } #end diagnostics
 
4849
 
 
4850
} #END rdb_classify_rules
 
4851
 
 
4852
#-------------------
 
4853
 
 
4854
sub rdb_classify1 {
 
4855
    # Helper routine for rdb_classify_rules
 
4856
    # Applied as rule_act1 in recursion over rules
 
4857
    # Assumes rule context, and local variables from rdb_classify_rules
 
4858
    #print "??======= '$rule' $depth $state ========== \n";
 
4859
    push @classify_stack, [$state];
 
4860
    if ( exists $possible_one_time{$rule} ) {
 
4861
        # Normally, we will have already extracted the one_time rules,
 
4862
        # and they will never be accessed here.  But just in case of
 
4863
        # problems or generalizations, we will cover all possibilities:
 
4864
        if ($depth > 1) {
 
4865
           warn "ONE TIME rule not at outer level '$rule'\n";
 
4866
        }
 
4867
        push @one_time, $rule;
 
4868
    }
 
4869
    elsif ($state == 0) {
 
4870
       if ( exists ${$P_allowed_primaries}{$rule} ) {
 
4871
           $state = 1;   # In primary rule
 
4872
           $current_primaries{ $rule } = 1;
 
4873
       }
 
4874
       else {
 
4875
           push @post_primary, $rule;
 
4876
       }
 
4877
    }
 
4878
    else {
 
4879
        $state = 2;     # in post-primary rule
 
4880
        push @pre_primary, $rule;
 
4881
    }
 
4882
} #END rdb_classify1
 
4883
 
 
4884
#-------------------
 
4885
 
 
4886
sub rdb_classify2 {
 
4887
    # Helper routine for rdb_classify_rules
 
4888
    # Applied as rule_act2 in recursion over rules
 
4889
    # Assumes rule context
 
4890
    ($state) = @{ pop @classify_stack };
 
4891
} #END rdb_classify2
 
4892
 
 
4893
#************************************************************
 
4894
 
 
4895
 
 
4896
sub rdb_run1 {
 
4897
    # Assumes contexts for: rule.
 
4898
    # Unconditionally apply the rule
 
4899
    # Returns return code from applying the rule.
 
4900
    # Otherwise: 0 on other kind of success, -1 on error.
 
4901
 
 
4902
    # Source file data, by definition, correspond to the file state just before 
 
4903
    # the latest run, and the run_time to the time just before the run:
 
4904
    &rdb_update_filesA;
 
4905
    $$Prun_time = time;
 
4906
    $$Pchanged = 0;       # No special changes in files
 
4907
    $$Plast_result = 0;
 
4908
    $$Plast_message = '';
 
4909
 
 
4910
    # Return values for external command:
 
4911
    my $return = 0;
 
4912
 
 
4913
    # Find any internal command
 
4914
    my @int_args = @$PAint_cmd;
 
4915
    my $int_cmd = shift @int_args;
 
4916
    my @int_args_for_printing = @int_args;
 
4917
    foreach (@int_args_for_printing) {
 
4918
        if ( ! defined $_ ) { $_ = 'undef'; }
 
4919
    }
 
4920
    if ($int_cmd) {
 
4921
        print "For rule '$rule', running '\&$int_cmd( @int_args_for_printing )' ...\n";
 
4922
        $return = &$int_cmd( @int_args ); 
 
4923
    }
 
4924
    elsif ($$Pext_cmd) {
 
4925
        $return = &rdb_ext_cmd;
 
4926
    }
 
4927
    else {
 
4928
        warn "$My_name: Either a bug OR a configuration error:\n",
 
4929
             "    Need to implement the command for '$rule'\n";
 
4930
        &traceback();
 
4931
        $return = -1;
 
4932
        $$Plast_result = 2;
 
4933
        $$Plast_message = "Bug or configuration error; incorrect command type";
 
4934
    }
 
4935
    if ( $rule =~ /^bibtex/ ) {
 
4936
        my $retcode = check_bibtex_log($$Pbase);
 
4937
        if ($retcode == 3) {
 
4938
            $$Plast_result = 2;
 
4939
            $$Plast_message = "Could not open bibtex log file for '$$Pbase'";
 
4940
            push @warnings, $$Plast_message;
 
4941
        }
 
4942
        elsif ($retcode == 2) {
 
4943
            $$Plast_message = "Bibtex errors: See file '$$Pbase.blg'";
 
4944
            push @warnings, $$Plast_message;
 
4945
        }
 
4946
        elsif ($retcode == 1) {
 
4947
            push @warnings, "Bibtex warnings for '$$Pbase'";
 
4948
        }
 
4949
    }
 
4950
 
 
4951
    $updated = 1;
 
4952
    if ($$Ptest_kind == 3) { 
 
4953
        # We are time-criterion first time only.  Now switch to
 
4954
        # file-change criterion
 
4955
        $$Ptest_kind = 1; 
 
4956
    }
 
4957
    $$Pout_of_date = $$Pout_of_date_user = 0;
 
4958
 
 
4959
    if ( ($$Plast_result == 0) && ($return != 0) ) {
 
4960
        $$Plast_result = 2;
 
4961
        if ($$Plast_message eq '') {
 
4962
            $$Plast_message = "Command for '$rule' gave return code $return";
 
4963
        }
 
4964
    }
 
4965
    elsif ( $$Pdest && (! -e $$Pdest) ) {
 
4966
        $$Plast_result = 1;
 
4967
    }
 
4968
 
 
4969
    return $return;
 
4970
}  # END rdb_run1
 
4971
 
 
4972
#-----------------
 
4973
 
 
4974
sub rdb_dummy_run1 {
 
4975
    # Assumes contexts for: rule.
 
4976
    # Update rule state as if the rule ran successfully,
 
4977
    #    but don't run the rule.
 
4978
    # Returns 0 (success code)
 
4979
 
 
4980
    # Source file data, by definition, correspond to the file state just before 
 
4981
    # the latest run, and the run_time to the time just before the run:
 
4982
    &rdb_update_filesA;
 
4983
    $$Prun_time = time;
 
4984
    $$Pchanged = 0;       # No special changes in files
 
4985
    $$Plast_result = 0;
 
4986
    $$Plast_message = '';
 
4987
 
 
4988
    if ($$Ptest_kind == 3) { 
 
4989
        # We are time-criterion first time only.  Now switch to
 
4990
        # file-change criterion
 
4991
        $$Ptest_kind = 1; 
 
4992
    }
 
4993
    $$Pout_of_date = $$Pout_of_date_user = 0;
 
4994
 
 
4995
    return 0;
 
4996
}  # END rdb_dummy_run1
 
4997
 
 
4998
#-----------------
 
4999
 
 
5000
sub rdb_ext_cmd {
 
5001
    # Call: rdb_ext_cmd
 
5002
    # Assumes rule context.  Runs external command with substitutions.
 
5003
    # Uses defaults for the substitutions.  See rdb_ext_cmd1.
 
5004
    return rdb_ext_cmd1();
 
5005
} #END rdb_ext_cmd
 
5006
 
 
5007
#-----------------
 
5008
 
 
5009
sub rdb_ext_cmd1 {
 
5010
    # Call: rdb_ext_cmd1( options, source, dest, base ) or rdb_ext_cmd1() or ...
 
5011
    # Assumes rule context.  Returns command with substitutions.
 
5012
    # Null arguments or unprovided arguments => use defaults.
 
5013
    # for %S=source, %D=dest, %B=base, %R=root=base for latex, %O='', %T=texfile
 
5014
    my ($options, $source, $dest, $base ) = @_;
 
5015
    # Apply defaults
 
5016
    $options ||= '';
 
5017
    $source  ||= $$Psource;
 
5018
    $dest    ||= $$Pdest;
 
5019
    $base    ||= $$Pbase;
 
5020
    
 
5021
    my $ext_cmd = $$Pext_cmd;
 
5022
    
 
5023
    #Set character to surround filenames:
 
5024
    my $q = $quote_filenames ? '"' : '';
 
5025
 
 
5026
    %subst = ( 
 
5027
       '%O' => $options,
 
5028
       '%R' => $q.$root_filename.$q,
 
5029
       '%B' => $q.$base.$q,
 
5030
       '%T' => $q.$texfile_name.$q,
 
5031
       '%S' => $q.$source.$q,
 
5032
       '%D' => $q.$dest.$q,
 
5033
       '%%' => '%'         # To allow literal %B, %R, etc, by %%B.
 
5034
    );
 
5035
 
 
5036
    my @tokens = split /(%.)/, $ext_cmd;
 
5037
    foreach (@tokens) {
 
5038
        if (exists($subst{$_})) { $_ = $subst{$_}; }
 
5039
    }
 
5040
    $ext_cmd = join '', @tokens;
 
5041
 
 
5042
    # print "quote is '$q'; ext_cmd = '$ext_cmd'\n";
 
5043
    my ($pid, $return) = &Run_msg($ext_cmd);
 
5044
    return $return;
 
5045
} #END rdb_ext_cmd1
 
5046
 
 
5047
#-----------------
 
5048
 
 
5049
sub rdb_primary_run {
 
5050
#?? See multipass_run in previous version Aug 2007 for issues
 
5051
    # Call: rdb_primary_run
 
5052
    # Assumes contexts for: recursion, make, & rule.
 
5053
    # Assumes (a) the rule is a primary, 
 
5054
    #         (b) a run has to be made,
 
5055
    #         (c) source files have been made.
 
5056
    # This routine carries out the run of the rule unconditionally,
 
5057
    # and then parses log file etc.
 
5058
    my $return = 0;
 
5059
 
 
5060
    my $return_latex = &rdb_run1;
 
5061
    if (-e $$Pdest) { $missing_dvi_pdf = '';}
 
5062
 
 
5063
    ######### Analyze results of run:
 
5064
    if ( ! -e "$root_filename.log" ) {
 
5065
        $failure = 1;
 
5066
        $$Plast_result = 2;
 
5067
        $$Plast_message = $failure_msg = "(Pdf)LaTeX failed to generate a log file";
 
5068
        return -1;
 
5069
    }
 
5070
    ####### NOT ANY MORE! Capture any changes in source file status before we
 
5071
    #         check for errors in the latex run
 
5072
 
 
5073
    # Find current set of source files:
 
5074
    &rdb_set_from_logB;
 
5075
 
 
5076
    # For each file of the kind made by epstopdf.sty during a run, 
 
5077
    #   if the file has changed during a run, then the new version of
 
5078
    #   the file will have been read during the run.  Unlike the usual
 
5079
    #   case, we will NOT need to redo the primary run because of the
 
5080
    #   change of this file during the run.  Therefore set the file as
 
5081
    #   up-to-date:
 
5082
    rdb_do_files( sub { if ($$Pcorrect_after_primary) {&rdb_update1;} } );
 
5083
 
 
5084
    # There may be new source files, and the run may have caused
 
5085
    # circular-dependency files to be changed.  And the regular
 
5086
    # source files may have been updated during a lengthy run of
 
5087
    # latex.  So redo the makes for sources of the current rule:
 
5088
    my $submake_return = &rdb_submakeB;
 
5089
    &rdb_clear_change_record;
 
5090
    &rdb_flag_changes_here;
 
5091
    if ($$Pout_of_date && !$silent) { 
 
5092
        &rdb_diagnose_changes( "Rule '$rule': " );
 
5093
    }
 
5094
    $updated = 1;    # Flag that some dependent file has been remade
 
5095
    # Fix the state of the files as of now: this will solve the
 
5096
    # problem of latex and pdflatex interfering with each other,
 
5097
    # at the expense of some non-optimality
 
5098
    #??  Check this is correct:
 
5099
    &rdb_update_filesA;
 
5100
    if ( $diagnostics ) {
 
5101
        print "$My_name: Rules after run: \n";
 
5102
        rdb_show();
 
5103
    }
 
5104
 
 
5105
    $return = $return_latex;
 
5106
    if ($return_latex && $$Pout_of_date_user) {
 
5107
       print "Error in (pdf)LaTeX, but change of user file(s), ",
 
5108
             "so ignore error & provoke rerun\n"
 
5109
          if (! $silent);
 
5110
       $return = 0;
 
5111
    }
 
5112
 
 
5113
    # Summarize issues that may have escaped notice:
 
5114
    my @warnings = ();
 
5115
    if ($bad_reference) {
 
5116
        push @warnings, "Latex could not resolve all references";
 
5117
    }
 
5118
    if ($bad_citation) {
 
5119
        push @warnings, "Latex could not resolve all citations";
 
5120
    }
 
5121
    if ($#warnings > 0) {
 
5122
        show_array( "$My_name: Summary of warnings:", @warnings );
 
5123
    }
 
5124
    return $return;
 
5125
} #END rdb_primary_run
 
5126
 
 
5127
#************************************************************
 
5128
 
 
5129
sub rdb_clear_change_record {
 
5130
    # Initialize diagnostics for reasons for running rule.
 
5131
    @changed = ();
 
5132
    @disappeared = ();
 
5133
    @no_dest = ();          # We are not now using this
 
5134
    @rules_never_run = ();
 
5135
    @rules_to_apply = ();   # This is used in recursive application
 
5136
                            # of rdb_flag_changes_here, to list
 
5137
                            # rules that were out-of-date for some reason.
 
5138
} #END rdb_clear_change_record 
 
5139
 
 
5140
#************************************************************
 
5141
 
 
5142
sub rdb_flag_changes_here {
 
5143
    # Flag changes in current rule.  
 
5144
    # Assumes rule context.
 
5145
    # Optional argument: if true then fdb_get shouldn't do runtime test
 
5146
    #                    for recalculation of md5
 
5147
    local $ignore_run_time = $_[0];
 
5148
    if ( ! defined $ignore_run_time ) { $ignore_run_time = 0; }
 
5149
    local $dest_mtime = 0;
 
5150
    $dest_mtime = get_mtime($$Pdest) if ($$Pdest);
 
5151
    rdb_do_files( \&rdb_file_change1);
 
5152
    if ($$Pout_of_date) {
 
5153
        push @rules_to_apply, $rule;
 
5154
    }
 
5155
#??     print "======== flag: $rule $$Pout_of_date ==========\n";
 
5156
} #END rdb_flag_changes_here
 
5157
 
 
5158
#************************************************************
 
5159
 
 
5160
sub rdb_file_change1 {
 
5161
    # Call: &rdb_file_change1
 
5162
    # Assumes rule and file context.  Assumes $dest_mtime set.
 
5163
    # Flag whether $file in $rule has changed or disappeared.
 
5164
    # Set rule's make flag if there's a change.
 
5165
    my $run_time_argument = $ignore_run_time ? 0 : $$Prun_time;
 
5166
    my ($new_time, $new_size, $new_md5) = fdb_get($file, $run_time_argument);
 
5167
#??    print "FC1 '$rule':$file $$Pout_of_date TK=$$Ptest_kind\n"; 
 
5168
#??    print "    OLD $$Ptime, $$Psize, $$Pmd5\n",
 
5169
#??          "    New $new_time, $new_size, $new_md5\n";
 
5170
    my $ext_no_period = ext_no_period( $file );
 
5171
    if ( ($new_size < 0) && ($$Psize >= 0) ) {
 
5172
        # print "Disappeared '$file' in '$rule'\n";
 
5173
        push @disappeared, $file;
 
5174
        # No reaction is good.  
 
5175
        #$$Pout_of_date = 1;
 
5176
        # ??? 1 Sep. 2008: I do NOT think so, for cusdep no-file-exists issue
 
5177
        # ??? 30 Sep 2008: I think I have this fixed.  There were other changes
 
5178
        #  needed.  No-change-flagged is correct.  The array @disappeared flags 
 
5179
        #  files that have disappeared, if I need to know.  But having a source
 
5180
        #  file disappear is not a reason for a remake unless I know how to 
 
5181
        #  make the file.  If the file is a destination of a rule, that rule
 
5182
        #  will be rerun.  It may be that the user is changing another source 
 
5183
        #  in such a way that the disappeared file won't be needed.  Before the
 
5184
        #  change is applied we get a superfluous infinite loop.
 
5185
        return;
 
5186
    }
 
5187
    if ( ($new_size < 0) && ($$Psize < 0) ) {
 
5188
        return;
 
5189
    }
 
5190
    if ( ($new_size != $$Psize) || ($new_md5 ne $$Pmd5) ) {
 
5191
#??        print "FC1: changed $file: ($new_size != $$Psize) $new_md5 ne $$Pmd5)\n";
 
5192
        push @changed, $file;
 
5193
        $$Pout_of_date = 1;
 
5194
        if ( ! exists $generated_exts_all{$ext_no_period} ) {
 
5195
            $$Pout_of_date_user = 1;
 
5196
        }
 
5197
    }
 
5198
    elsif ( $new_time != $$Ptime ) {
 
5199
#warn "--==-- Unchanged $file, changed time, update filetime in $rule\n";
 
5200
        $$Ptime = $new_time;
 
5201
    }
 
5202
    if ( ( ($$Ptest_kind == 2) || ($$Ptest_kind == 3) )
 
5203
         && (! exists $generated_exts_all{$ext_no_period} )
 
5204
         && ( $new_time > $dest_mtime )
 
5205
        ) {
 
5206
#??        print "FC1: changed $file: ($new_time > $dest_mtime)\n";
 
5207
            push @changed, $file;
 
5208
            $$Pout_of_date = $$Pout_of_date_user = 1;
 
5209
    }
 
5210
} #END rdb_file_change1
 
5211
 
 
5212
#************************************************************
 
5213
 
 
5214
sub rdb_new_changes {
 
5215
    &rdb_clear_change_record;
 
5216
    rdb_recurseA( [@_], sub{ &rdb_flag_changes_here(1); } );
 
5217
    return ($#changed >= 0) || ($#no_dest >= 0) || ($#rules_to_apply >= 0);
 
5218
} #END rdb_new_changes
 
5219
 
 
5220
#************************************************************
 
5221
 
 
5222
sub rdb_diagnose_changes {
 
5223
    # Call: rdb_diagnose_changes or rdb_diagnose_changes( heading )
 
5224
    # List changes on STDERR
 
5225
    # Precede the message by the optional heading, else by "$My_name: " 
 
5226
    my $heading = defined($_[0]) ?   $_[0]  :  "$My_name: "; 
 
5227
 
 
5228
    if ($#rules_never_run >= 0) {
 
5229
        warn "${heading}Rules & subrules not known to be previously run:\n";
 
5230
        foreach (@rules_never_run) { warn "   $_\n"; }
 
5231
    }
 
5232
    if ( ($#changed >= 0) || ($#disappeared >= 0) || ($#no_dest >= 0) ) {
 
5233
        warn "${heading}File changes, etc:\n";
 
5234
        if ( $#changed >= 0 ) {
 
5235
            warn "   Changed files, or newly in use since previous run(s):\n";
 
5236
            foreach (uniqs(@changed)) { warn "      '$_'\n"; }
 
5237
        }
 
5238
        if ( $#disappeared >= 0 ) {
 
5239
            warn "   No-longer-existing files:\n";
 
5240
            foreach (uniqs(@disappeared)) { warn "      '$_'\n"; }
 
5241
        }
 
5242
        if ( $#no_dest >= 0 ) {
 
5243
            warn "   Non-existent destination files:\n";
 
5244
            foreach (uniqs(@no_dest)) { warn "      '$_'\n"; }
 
5245
        }
 
5246
    }
 
5247
    elsif ($#rules_to_apply >=0) {
 
5248
         warn "${heading}The following rules & subrules became out-of-date:\n";
 
5249
         foreach (@rules_to_apply) { warn "      '$_'\n"; }
 
5250
    }
 
5251
    else {
 
5252
        warn "${heading}No file changes\n";
 
5253
    }
 
5254
}     #END rdb_diagnose_changes
 
5255
 
 
5256
 
 
5257
#************************************************************
 
5258
#************************************************************
 
5259
#************************************************************
 
5260
#************************************************************
 
5261
 
 
5262
#************************************************************
 
5263
#************************************************************
 
5264
#************************************************************
 
5265
#************************************************************
 
5266
 
 
5267
# Routines for convenient looping and recursion through rule database
 
5268
# ================= NEW VERSION ================
 
5269
 
 
5270
# There are several places where we need to loop through or recurse
 
5271
# through rules and files.  This tends to involve repeated, tedious
 
5272
# and error-prone coding of much book-keeping detail.  In particular,
 
5273
# working on files and rules needs access to the variables involved,
 
5274
# which either involves direct access to the elements of the database,
 
5275
# and consequent fragility against changes and upgrades in the
 
5276
# database structure, or involves lots of routines for reading and
 
5277
# writing data in the database, then with lots of repetitious
 
5278
# house-keeping code.
 
5279
#
 
5280
# The routines below provide a solution.  Looping and recursion
 
5281
# through the database are provided by a set of basic routines where
 
5282
# each necessary kind of looping and iteration is coded once.  The
 
5283
# actual actions are provided as references to action subroutines.
 
5284
# (These can be either actual references, as in \&routine, or
 
5285
# anonymous subroutines, as in sub{...}, or aas a zero value 0 or an
 
5286
# omitted argument, to indicate that no action is to be performed.)
 
5287
#
 
5288
# When the action subroutine(s) are actually called, a context for the
 
5289
# rule and/or file (as appropriate) is given by setting named
 
5290
## NEW ??
 
5291
# variables to REFERENCES to the relevant data values.  These can be
 
5292
# used to retrieve and set the data values.  As a convention,
 
5293
# references to scalars are given by variables named start with "$P",
 
5294
# as in "$Pdest", while references to arrays start with "$PA", as in 
 
5295
# "$PAint_cmd", and references to hashes with "$PH", as in "$PHsource".
 
5296
# After the action subroutine has finished, checks for data
 
5297
# consistency may be made. 
 
5298
## ??? OLD
 
5299
# variables to the relevant data values.  After the action subroutine
 
5300
# has finished, the database is updated with the values of these named
 
5301
# variables, with any necessary consistency checks.  Thus the action
 
5302
# subroutines can act on sensibly named variables without needed to
 
5303
# know the database structure.  
 
5304
#
 
5305
# The only routines that actually use the database structure and need
 
5306
# to be changed if that is changed are:  (a) the routines rdb_one_rule
 
5307
# and rdb_one_file that implement the calling of the action subroutines,
 
5308
# (b) routines for creation of single rules and file items, and (c) to
 
5309
# a lesser extent, the routine for destroying a file item.  
 
5310
#
 
5311
# Note that no routine is provided for destroying a rule.  During a
 
5312
# run, a rule, with its source files, may become inaccessible or
 
5313
# unused.  This happens dynamically, depending on the dependencies
 
5314
# caused by changes in the source file or by error conditions that
 
5315
# cause the computation of dependencies, particular of latex files, to
 
5316
# become wrong.  In that situation the files certainly come and go in
 
5317
# the database, but subsidiary rules, with their content information
 
5318
# on their source files, need to be retained so that their use can be
 
5319
# reinstated later depending on dynamic changes in other files.
 
5320
#
 
5321
# However, there is a potential memory leak unless some pruning is
 
5322
# done in what is written to the fdb file.  (Probably only accessible
 
5323
# rules and those for which source files exist.  Other cases have no
 
5324
# relevant information that needs to be preserved between runs.)
 
5325
 
 
5326
#
 
5327
#
 
5328
 
 
5329
 
 
5330
#************************************************************
 
5331
 
 
5332
# First the top level routines for recursion and iteration
 
5333
 
 
5334
#************************************************************
 
5335
 
 
5336
sub rdb_recurseA {
 
5337
    # Call: rdb_recurseA( rule | [ rules],
 
5338
    #                    \&rule_act1, \&file_act1, \&file_act2, 
 
5339
    #                    \&rule_act2 )
 
5340
    # The actions are pointers to subroutines, and may be null (0, or
 
5341
    # undefined) to indicate no action to be applied.
 
5342
    # Recursively acts on the given rules and all ancestors:
 
5343
    #   foreach rule found:
 
5344
    #       apply rule_act1
 
5345
    #       loop through its files:
 
5346
    #          apply file_act1
 
5347
    #          act on its ancestor rule, if any
 
5348
    #          apply file_act2
 
5349
    #       apply rule_act2
 
5350
    # Guards against loops.  
 
5351
    # Access to the rule and file data by local variables, only
 
5352
    #   for getting and setting.
 
5353
 
 
5354
    # This routine sets a context for anything recursive, with @heads,
 
5355
    # %visited  and $depth being set as local variables.
 
5356
 
 
5357
    local @heads = ();
 
5358
    my $rules = shift;
 
5359
 
 
5360
    # Distinguish between single rule (a string) and a reference to an
 
5361
    # array of rules:
 
5362
    if ( ref $rules eq 'ARRAY' ) { @heads = @$rules; }
 
5363
    else { @heads = ( $rules ); }
 
5364
 
 
5365
    # Keep a list of visited rules, used to block loops in recursion:
 
5366
    local %visited = (); 
 
5367
    local $depth = 0;
 
5368
 
 
5369
    foreach $rule ( @heads ) { rdb_recurse_rule( $rule, @_ ); }
 
5370
 
 
5371
} #END rdb_recurseA
 
5372
 
 
5373
#************************************************************
 
5374
 
 
5375
sub rdb_for_all {
 
5376
    # Call: rdb_for_all( \&rule_act1, \&file_act, \&rule_act2 )
 
5377
    # Loops through all rules and their source files, using the 
 
5378
    #   specified set of actions, which are pointers to subroutines.
 
5379
    # Sorts rules alphabetically.
 
5380
    # See rdb_for_some for details.
 
5381
    rdb_for_some( [ sort keys %rule_db ], @_);
 
5382
} #END rdb_for_all
 
5383
 
 
5384
#************************************************************
 
5385
 
 
5386
sub rdb_for_some {
 
5387
    # Call: rdb_for_some( rule | [ rules],
 
5388
    #                    \&rule_act1, \&file_act, \&rule_act2)
 
5389
    # Actions can be zero, and rules at tail of argument list can be
 
5390
    # omitted.  E.g. rdb_for_some( rule, 0, \&file_act ).  
 
5391
    # Anonymous subroutines can be used, e.g., rdb_for_some( rule, sub{...} ).  
 
5392
    #
 
5393
    # Loops through rules and their source files, using the 
 
5394
    # specified set of rules:
 
5395
    #   foreach rule:
 
5396
    #       apply rule_act1
 
5397
    #       loop through its files:
 
5398
    #          apply file_act
 
5399
    #       apply rule_act2
 
5400
    #
 
5401
    # Rule data and file data are made available in local variables 
 
5402
    # for access by the subroutines.
 
5403
 
 
5404
    local @heads = ();
 
5405
    my $rules = shift;
 
5406
    # Distinguish between single rule (a string) and a reference to an
 
5407
    # array of rules:
 
5408
    if ( ref $rules eq 'ARRAY' ) { @heads = @$rules; }
 
5409
    else { @heads = ( $rules ); }
 
5410
 
 
5411
    foreach $rule ( @heads ) {
 
5412
        # $rule is implicitly local
 
5413
        &rdb_one_rule( $rule, @_ );
 
5414
    }
 
5415
}  #END rdb_for_some
 
5416
 
 
5417
#************************************************************
 
5418
 
 
5419
sub rdb_for_one_file {
 
5420
    my $rule = shift;
 
5421
    # Avoid name collisions with general recursion and iteraction routines:
 
5422
    local $file1 = shift;
 
5423
    local $action1 = shift;
 
5424
    rdb_for_some( $rule, sub{rdb_one_file($file1,$action1)} );
 
5425
} #END rdb_for_one_file
 
5426
 
 
5427
 
 
5428
#************************************************************
 
5429
 
 
5430
#   Routines for inner part of recursion and iterations
 
5431
 
 
5432
#************************************************************
 
5433
 
 
5434
sub rdb_recurse_rule {
 
5435
    # Call: rdb_recurse_rule($rule, \&rule_act1, \&file_act1, \&file_act2, 
 
5436
    #                    \&rule_act2 )
 
5437
    # to do the work for one rule, recurisvely called from_rules for
 
5438
    # the sources of the rules.
 
5439
    # Assumes recursion context, i.e. that %visited, @heads, $depth.
 
5440
    # We are overriding actions:
 
5441
    my ($rule, $rule_act1, $new_file_act1, $new_file_act2, $rule_act2)
 
5442
        = @_;
 
5443
    # and must propagate the file actions:
 
5444
    local $file_act1 = $new_file_act1;
 
5445
    local $file_act2 = $new_file_act2;
 
5446
    # Prevent loops:
 
5447
    if ( (! $rule) || exists $visited{$rule} ) { return; }
 
5448
    $visited{$rule} = 1;
 
5449
    # Recursion depth
 
5450
    $depth++;
 
5451
    # We may need to repeat actions on dependent rules, without being
 
5452
    # blocked by the test on visited files.  So save %visited:
 
5453
    local %visited_at_rule_start = %visited;
 
5454
    # At end, the last value set for %visited wins.
 
5455
    rdb_one_rule( $rule, $rule_act1, \&rdb_recurse_file, $rule_act2 );
 
5456
    $depth--;
 
5457
 } #END rdb_recurse_rule 
 
5458
 
 
5459
#************************************************************
 
5460
 
 
5461
sub rdb_recurse_file {
 
5462
    # Call: rdb_recurse_file to do the work for one file.
 
5463
    # This has no arguments, since it is used as an action subroutine,
 
5464
    # passed as a reference in calls in higher-level subroutine.
 
5465
    # Assumes contexts set for: Recursion, rule, and file
 
5466
    &$file_act1 if $file_act1;
 
5467
    rdb_recurse_rule( $$Pfrom_rule, $rule_act1, $file_act1, $file_act2,
 
5468
                      $rule_act2 )
 
5469
        if $$Pfrom_rule;
 
5470
    &$file_act2 if $file_act2;
 
5471
} #END rdb_recurse_file
 
5472
 
 
5473
#************************************************************
 
5474
 
 
5475
sub rdb_do_files {
 
5476
    # Assumes rule context, including $PHsource.
 
5477
    # Applies an action to all the source files of the rule.
 
5478
    local $file_act = shift;
 
5479
    my @file_list = sort keys %$PHsource;
 
5480
    foreach my $file ( @file_list ){
 
5481
        rdb_one_file( $file, $file_act );
 
5482
    }
 
5483
} #END rdb_do_files
 
5484
 
 
5485
#************************************************************
 
5486
 
 
5487
# Routines for action on one rule and one file.  These are the main
 
5488
# places (in addition to creation and destruction routines for rules
 
5489
# and files) where the database structure is accessed.
 
5490
 
 
5491
#************************************************************
 
5492
 
 
5493
sub rdb_one_rule {
 
5494
    # Call: rdb_one_rule( $rule, $rule_act1, $file_act, $rule_act2 )
 
5495
    # Sets context for rule and carries out the actions.
 
5496
#===== Accesses rule part of database structure =======
 
5497
 
 
5498
    local ( $rule, $rule_act1, $file_act, $rule_act2 ) = @_;
 
5499
#??    &R1;
 
5500
    if ( (! $rule) || ! rdb_rule_exists($rule) ) { return; }
 
5501
 
 
5502
    local ( $PArule_data, $PHsource ) = @{$rule_db{$rule}};
 
5503
    local ($Pcmd_type, $Pext_cmd, $PAint_cmd, $Ptest_kind, 
 
5504
           $Psource, $Pdest, $Pbase,
 
5505
           $Pout_of_date, $Pout_of_date_user, $Prun_time, $Pchanged,
 
5506
           $Plast_result, $Plast_message )
 
5507
        = Parray( $PArule_data );
 
5508
    # Correct array ref:
 
5509
    $PAint_cmd = $$PArule_data[2];
 
5510
 
 
5511
    &$rule_act1 if $rule_act1;
 
5512
    &rdb_do_files( $file_act ) if $file_act;
 
5513
    &$rule_act2 if $rule_act2;
 
5514
 
 
5515
#??    &R2;
 
5516
} #END rdb_one_rule
 
5517
 
 
5518
#************************************************************
 
5519
 
 
5520
sub rdb_one_file {
 
5521
    # Call: rdb_one_file($file, $file_act)
 
5522
    # Sets context for file and carries out the action.
 
5523
    # Assumes $rule context set.
 
5524
#===== Accesses file part of database structure =======
 
5525
    local ($file, $file_act) = @_;
 
5526
#??    &F1;
 
5527
    if ( (!$file) ||(!exists ${$PHsource}{$file}) ) { return; }
 
5528
    local $PAfile_data = ${$PHsource}{$file};
 
5529
    local ($Ptime, $Psize, $Pmd5, $Pfrom_rule, $Pcorrect_after_primary ) 
 
5530
          = Parray( $PAfile_data );
 
5531
    &$file_act if $file_act;
 
5532
    if ( ! rdb_rule_exists( $$Pfrom_rule ) ) {
 
5533
        $$Pfrom_rule = '';
 
5534
    }
 
5535
#??    &F2;
 
5536
} #END rdb_one_file
 
5537
 
 
5538
#************************************************************
 
5539
 
 
5540
# Routines for creation of rules and file items, and for removing file
 
5541
# items. 
 
5542
 
 
5543
#************************************************************
 
5544
 
 
5545
sub rdb_create_rule {
 
5546
    # rdb_create_rule( rule, command_type, ext_cmd, int_cmd, test_kind,
 
5547
    #                  source, dest, base, 
 
5548
    #                  needs_making, run_time, set_file_not_exists )
 
5549
    # int_cmd is either a string naming a perl subroutine or it is a
 
5550
    # reference to an array containing the subroutine name and its
 
5551
    # arguments. 
 
5552
    # Makes rule.  Error if it already exists.
 
5553
    # Omitted arguments: replaced by 0 or '' as needed.    
 
5554
# ==== Sets rule data ====
 
5555
    my ( $rule, $cmd_type, $int_cmd, $PAext_cmd, $test_kind, 
 
5556
         $source, $dest, $base, 
 
5557
         $needs_making, $run_time, $set_file_not_exists ) = @_;
 
5558
    my $changed = 0;
 
5559
    # Set defaults, and normalize parameters:
 
5560
    foreach ( $cmd_type, $int_cmd, $PAext_cmd, $source, $dest, $base, 
 
5561
              $set_file_not_exists ) {
 
5562
        if (! defined $_) { $_ = ''; }
 
5563
    }
 
5564
    foreach ( $needs_making, $run_time, $test_kind ) {
 
5565
        if (! defined $_) { $_ = 0; }
 
5566
    }
 
5567
    if (!defined $test_kind) {
 
5568
        # Default to test on file change
 
5569
        $test_kind = 1; 
 
5570
    }
 
5571
    if ( ref( $PAext_cmd ) eq '' ) {
 
5572
        #  It is a single command.  Convert to array reference:
 
5573
        $PAext_cmd = [ $PAext_cmd ];
 
5574
    }
 
5575
    else {
 
5576
        # COPY the referenced array:
 
5577
        $PAext_cmd = [ @$PAext_cmd ];
 
5578
    }
 
5579
 
 
5580
    $rule_db{$rule} = 
 
5581
        [  [$cmd_type, $int_cmd, $PAext_cmd, $test_kind, 
 
5582
            $source, $dest, $base, $needs_making, 0, $run_time,
 
5583
            $changed, -1, '' ],
 
5584
           {}
 
5585
        ];
 
5586
    if ($source) { 
 
5587
       rdb_ensure_file( $rule, $source, undef, $set_file_not_exists );  
 
5588
    }
 
5589
} #END rdb_create_rule
 
5590
 
 
5591
#************************************************************
 
5592
 
 
5593
sub rdb_ensure_file {
 
5594
    # rdb_ensure_file( rule, file[, fromrule[, set_not_exists]] )
 
5595
    # Ensures the source file item exists in the given rule.
 
5596
    # Then if the fromrule is specified, set it for the file item.
 
5597
    # If the item is created, then:
 
5598
    #    (a) by default initialize it to current file state.
 
5599
    #    (b) but if the fourth argument, set_not_exists, is true, 
 
5600
    #        initialize the item as if the file does not exist.
 
5601
    #        This case is typically used when the log file for a run
 
5602
    #        of latex/pdflatex claims that the file was non-existent
 
5603
    #        at the beginning of a run. 
 
5604
#============ rule and file data set here ======================================
 
5605
    my $rule = shift;
 
5606
    local ( $new_file, $new_from_rule, $set_not_exists ) = @_;
 
5607
    if ( ! rdb_rule_exists( $rule ) ) {
 
5608
        die_trace( "$My_name: BUG in rdb_ensure_file: non-existent rule '$rule'" );
 
5609
    }
 
5610
    if ( ! defined $new_file ) {
 
5611
        die_trace( "$My_name: BUG in rdb_ensure_file: undefined file for '$rule'" );
 
5612
    }
 
5613
    if ( ! defined $set_not_exists ) { $set_not_exists = 0; }
 
5614
    rdb_one_rule( $rule, 
 
5615
                  sub{
 
5616
                      if (! exists ${$PHsource}{$new_file} ) {
 
5617
                          if ( $set_not_exists ) {
 
5618
                              ${$PHsource}{$new_file} = [0, -1, 0, '', 0];
 
5619
                          }
 
5620
                          else {
 
5621
                              ${$PHsource}{$new_file} 
 
5622
                              = [fdb_get($new_file, $$Prun_time), '', 0];
 
5623
                          }
 
5624
                      }
 
5625
                  }
 
5626
    );
 
5627
    if (defined $new_from_rule ) {
 
5628
        rdb_for_one_file( $rule, $new_file, sub{ $$Pfrom_rule = $new_from_rule; });
 
5629
    }
 
5630
} #END rdb_ensure_file 
 
5631
 
 
5632
#************************************************************
 
5633
 
 
5634
sub rdb_remove_files {
 
5635
    # rdb_remove_file( rule, file,... )
 
5636
    # Removes file(s) for the rule.  
 
5637
    my $rule = shift;
 
5638
    if (!$rule) { return; }
 
5639
    local @files = @_;
 
5640
    rdb_one_rule( $rule, 
 
5641
                  sub{ foreach (@files) { delete ${$PHsource}{$_}; }  }
 
5642
    );
 
5643
} #END rdb_remove_files
 
5644
 
 
5645
#************************************************************
 
5646
 
 
5647
sub rdb_rule_exists { 
 
5648
    # Call rdb_rule_exists($rule): Returns whether rule exists.
 
5649
    my $rule = shift;
 
5650
    if (! $rule ) { return 0; }
 
5651
    return exists $rule_db{$rule}; 
 
5652
} #END rdb_rule_exists
 
5653
 
 
5654
#************************************************************
 
5655
 
 
5656
sub rdb_file_exists { 
 
5657
    # Call rdb_file_exists($rule, $file): 
 
5658
    # Returns whether source file item in rule exists.
 
5659
    local ( $rule, $file ) = @_;
 
5660
    local $exists = 0;
 
5661
    rdb_one_rule( $rule, 
 
5662
                  sub{ $exists =  exists( ${$PHsource}{$file} ) ? 1:0; } 
 
5663
                );
 
5664
    return $exists; 
 
5665
} #END rdb_file_exists
 
5666
 
 
5667
#************************************************************
 
5668
 
 
5669
sub rdb_update_gen_files {
 
5670
    # Call: fdb_updateA
 
5671
    # Assumes rule context.  Update source files of rule to current state.
 
5672
    rdb_do_files( 
 
5673
        sub{
 
5674
            if ( exists $generated_exts_all{ ext_no_period($file) } ) {&rdb_update1;} 
 
5675
        }
 
5676
    );
 
5677
} #END rdb_update_gen_files
 
5678
 
 
5679
#************************************************************
 
5680
 
 
5681
sub rdb_update_filesA {
 
5682
    # Call: fdb_updateA
 
5683
    # Assumes rule context.  Update source files of rule to current state.
 
5684
    rdb_do_files( \&rdb_update1 );
 
5685
}
 
5686
 
 
5687
#************************************************************
 
5688
 
 
5689
sub rdb_update1 {
 
5690
    # Call: rdb_update1.  
 
5691
    # Assumes file context.  Updates file data to correspond to
 
5692
    # current file state on disk
 
5693
    ($$Ptime, $$Psize, $$Pmd5) = fdb_get($file);
 
5694
}
 
5695
 
 
5696
#************************************************************
 
5697
 
 
5698
sub rdb_set_file1 {
 
5699
    # Call: fdb_file1(rule, file, new_time, new_size, new_md5)
 
5700
    # Sets file time, size and md5.
 
5701
    my $rule = shift;
 
5702
    my $file = shift;
 
5703
    local @new_file_data = @_;
 
5704
    rdb_for_one_file( $rule, $file, sub{ ($$Ptime,$$Psize,$$Pmd5)=@new_file_data; } );
 
5705
}
 
5706
 
 
5707
#************************************************************
 
5708
 
 
5709
sub rdb_dummy_file {
 
5710
    # Returns file data for non-existent file
 
5711
# ==== Uses rule_db structure ====
 
5712
    return (0, -1, 0, '');
 
5713
}
 
5714
 
 
5715
#************************************************************
 
5716
#************************************************************
 
5717
 
 
5718
# Predefined subroutines for custom dependency
 
5719
 
 
5720
sub cus_dep_delete_dest {
 
5721
    # This subroutine is used for situations like epstopdf.sty, when
 
5722
    #   the destination (target) of the custom dependency invoking
 
5723
    #   this subroutine will be made by the primary run provided the
 
5724
    #   file (destination of the custom dependency, source of the
 
5725
    #   primary run) doesn't exist.
 
5726
    # It is assumed that the resulting file will be read by the
 
5727
    #   primary run.
 
5728
 
 
5729
    # Remove the destination file, to indicate it needs to be remade:
 
5730
    unlink $$Pdest;
 
5731
    # Arrange that the non-existent destination file is not treated as
 
5732
    #   an error.  The variable changed here is a bit misnamed.
 
5733
    $$Pchanged = 1;
 
5734
    # Ensure a primary run is done
 
5735
    &cus_dep_require_primary_run;
 
5736
    # Return success:
 
5737
    return 0;
 
5738
}
 
5739
 
 
5740
#************************************************************
 
5741
 
 
5742
sub cus_dep_require_primary_run {
 
5743
    # This subroutine is used for situations like epstopdf.sty, when
 
5744
    #   the destination (target) of the custom dependency invoking
 
5745
    #   this subroutine will be made by the primary run provided the
 
5746
    #   file (destination of the custom dependency, source of the
 
5747
    #   primary run) doesn't exist.
 
5748
    # It is assumed that the resulting file will be read by the
 
5749
    #   primary run.
 
5750
 
 
5751
    local $cus_dep_target = $$Pdest;
 
5752
    # Loop over all rules and source files:
 
5753
    rdb_for_all( 0, 
 
5754
                 sub { if ($file eq $cus_dep_target) {
 
5755
                            $$Pout_of_date = 1;
 
5756
                            $$Pcorrect_after_primary = 1;
 
5757
                       }
 
5758
                     }
 
5759
               );
 
5760
    # Return success:
 
5761
    return 0;
 
5762
}
 
5763
 
3245
5764
 
3246
5765
#************************************************************
3247
5766
#************************************************************
3254
5773
# Miscellaneous
3255
5774
 
3256
5775
sub show_array {
3257
 
# For use in debugging. $_[0] = label.  Rest of @_ is list of items
3258
 
    print "$_[0]\n";
 
5776
# For use in diagnostics and debugging. 
 
5777
#  On stderr, print line with $_[0] = label.  
 
5778
#  Then print rest of @_, one item per line preceeded by some space
 
5779
    warn "$_[0]\n";
3259
5780
    shift;
3260
 
    foreach (@_){ print "  $_\n";}
 
5781
    if ($#_ >= 0) {  foreach (@_){ warn "  '$_'\n";} }
 
5782
    else { warn "  NONE\n"; }
 
5783
}
 
5784
 
 
5785
#************************************************************
 
5786
 
 
5787
sub Parray {
 
5788
    # Call: Parray( \@A )
 
5789
    # Returns array of references to the elements of @A
 
5790
    my $PA = shift;
 
5791
    my @P = (undef) x (1+$#$PA);
 
5792
    foreach my $i (0..$#$PA) { $P[$i] = \$$PA[$i]; }
 
5793
    return @P;
3261
5794
}
3262
5795
 
3263
5796
#************************************************************
3269
5802
    foreach (@_) {
3270
5803
        push @globbed, glob;
3271
5804
    }
3272
 
    return uniq( sort( @globbed ) );
3273
 
}
3274
 
 
3275
 
#************************************************************
3276
 
#      File handling routines:
 
5805
    return uniqs( @globbed );
 
5806
}
 
5807
 
 
5808
#==================================================
 
5809
 
 
5810
sub glob_list1 {
 
5811
    # Glob a collection of filenames.  
 
5812
    # But no sorting or elimination of duplicates
 
5813
    # Usage: e.g., @globbed = glob_list1(string, ...);
 
5814
    # Since perl's glob appears to use space as separator, I'll do a special check
 
5815
    # for existence of non-globbed file (assumed to be tex like)
 
5816
 
 
5817
    my @globbed = ();
 
5818
    foreach my $file_spec (@_) {
 
5819
        # Problem, when the PATTERN contains spaces, the space(s) are
 
5820
        # treated as pattern separaters (in MSWin at least).
 
5821
        # MSWin: I can quote the pattern (is that MSWin native, or also 
 
5822
        #        cygwin?)
 
5823
        # Linux: Quotes in a pattern are treated as part of the filename!
 
5824
        #        So quoting a pattern is definitively wrong.
 
5825
        # The following hack solves this partly, for the cases that there is no wildcarding 
 
5826
        #    and the specified file exists possibly space-containing, and that there is wildcarding,
 
5827
        #    but spaces are prohibited.
 
5828
        if ( -e $file_spec || -e "$file_spec.tex" ) { 
 
5829
           # Non-globbed file exists, return the file_spec.
 
5830
           # Return $file_spec only because this is not a file-finding subroutine, but
 
5831
           #   only a globber
 
5832
           push @globbed, $file_spec; 
 
5833
        }
 
5834
        else { 
 
5835
            # This glob fails to work as desired, if the pattern contains spaces.
 
5836
            push @globbed, glob( "$file_spec" );
 
5837
        }
 
5838
    }
 
5839
    return @globbed;
 
5840
}
 
5841
 
 
5842
#************************************************************
 
5843
# Miscellaneous
 
5844
 
 
5845
sub prefix {
 
5846
   #Usage: prefix( string, prefix );
 
5847
   #Return string with prefix inserted at the front of each line
 
5848
   my @line = split( /\n/, $_[0] );
 
5849
   my $prefix = $_[1];
 
5850
   for (my $i = 0; $i <= $#line; $i++ ) {
 
5851
       $line[$i] = $prefix.$line[$i]."\n";
 
5852
   }
 
5853
   return join( "", @line );
 
5854
}
 
5855
 
 
5856
 
 
5857
#************************************************************
 
5858
#************************************************************
 
5859
#      File handling utilities:
3277
5860
 
3278
5861
 
3279
5862
#************************************************************
3297
5880
}
3298
5881
 
3299
5882
#************************************************************
3300
 
sub get_mtime
 
5883
 
 
5884
sub get_mtime_raw
3301
5885
3302
5886
  my $mtime = (stat($_[0]))[9];
3303
5887
  return $mtime;
3305
5889
 
3306
5890
#************************************************************
3307
5891
 
3308
 
 
3309
 
 
3310
 
# Find file with default extension
3311
 
# Usage: find_file_ext( name, default_ext, ref_to_array_search_path)
3312
 
sub find_file_ext
3313
 
{
3314
 
    my $full_filename = shift;
3315
 
    my $ext = shift;
3316
 
    my $ref_search_path = shift;
3317
 
    my $full_filename1 = &find_file($full_filename, $ref_search_path, '1');
3318
 
#print "Finding \"$full_filename\" with ext \"$ext\" ... ";
3319
 
    if (( $full_filename1 eq '' ) || ( ! -e $full_filename1 ))
3320
 
    {
3321
 
      my $full_filename2 = 
3322
 
          &find_file("$full_filename.$ext",$ref_search_path,'1');
3323
 
      if (( $full_filename2 ne '' ) && ( -e $full_filename2 ))
3324
 
      {
3325
 
        $full_filename = $full_filename2;
3326
 
      }
3327
 
      else
3328
 
      {
3329
 
        $full_filename = $full_filename1;
3330
 
      }
3331
 
    }
3332
 
    else
3333
 
    {
3334
 
      $full_filename = $full_filename1;
3335
 
    }
3336
 
#print "Found \"$full_filename\".\n";
3337
 
    return $full_filename;
3338
 
}
3339
 
 
3340
 
#************************************************************
3341
 
# given filename and path, return full name of file, or die if none found.
3342
 
# when force_include_mode=1, only warn if an include file was not
3343
 
# found, and return 0 (PvdS).
3344
 
# Usage: find_file(name, ref_to_array_search_path, param)
3345
 
sub find_file
3346
 
{
3347
 
  my $name = $_[0];
3348
 
  my $ref_path = $_[1];
3349
 
  my $dir;
3350
 
  if ( $name =~ /^\// )
3351
 
  {
3352
 
    if ($force_include_mode)
3353
 
    {
3354
 
        if ( $_[2] eq '' )
3355
 
        {
3356
 
          warn "Latexmk: Could not find file [$name]\n";
3357
 
        }
3358
 
        return("$name");
3359
 
    }
3360
 
    else
3361
 
    {
3362
 
        if (-e $name)
3363
 
        {
3364
 
          return("$name");
3365
 
        }
3366
 
        die "Latexmk: Could not find file [$name]\n";
3367
 
    }
3368
 
  }
3369
 
  foreach $dir ( @{$ref_path} )
3370
 
  {
3371
 
#warn "\"$dir\", \"$name\"\n";
3372
 
    if (-e "$dir/$name")
3373
 
    {
3374
 
      return("$dir/$name");
3375
 
    }
3376
 
  }
3377
 
  if ($force_include_mode)
3378
 
  {
3379
 
        if ( $_[2] eq '' )
3380
 
        {
3381
 
          warn "Latexmk: Could not find file [$name] in path [@{$ref_path}]\n";
3382
 
          warn "         assuming in current directory (./$name)\n";
3383
 
        }
3384
 
        return("./$name");
3385
 
  }
3386
 
  else
3387
 
  {
3388
 
        if ( $_[2] ne '' )
3389
 
        {
3390
 
          return('');
3391
 
        }
3392
 
# warn "\"$name\", \"$ref_path\", \"$dir\"\n";
3393
 
        die "Latexmk: Could not find file [$name] in path [@{$ref_path}]\n";
3394
 
  }
3395
 
}
3396
 
 
3397
 
#************************************************************
3398
 
# Usage: find_file1(name, ref_to_array_search_path, param)
3399
 
# Modified find_file, which doesn't die.
3400
 
# Given filename and path, return array of:
3401
 
#             full name 
3402
 
#             retcode
3403
 
# On success: full_name = full name with path, retcode = 0
3404
 
# On failure: full_name = given name, retcode = 1
3405
 
# If second argument is absent, give warning
3406
 
sub find_file1
3407
 
{
3408
 
  my $name = $_[0];
3409
 
  my $ref_path = $_[1];
3410
 
  my $action = $_[2];
3411
 
  my $dir;
3412
 
  if ( $name =~ /^\// )
3413
 
  {
3414
 
     # Absolute path
3415
 
     if (-e $name)
3416
 
        { return( $name, 0 );}
3417
 
     else
3418
 
        { return( $name, 1 );}
3419
 
  }
3420
 
  foreach $dir ( @{$ref_path} )
3421
 
  {
3422
 
#warn "\"$dir\", \"$name\"\n";
3423
 
    if (-e "$dir/$name")
3424
 
    {
3425
 
      return("$dir/$name", 0);
3426
 
    }
3427
 
  }
3428
 
  if ( $_[2] eq '' ) {
3429
 
     warn "Latexmk: Could not find file [$name] in path [@{$ref_path}]\n";
 
5892
sub get_mtime { 
 
5893
    return get_mtime0($_[0]);
 
5894
}
 
5895
 
 
5896
#************************************************************
 
5897
 
 
5898
sub get_mtime0 {
 
5899
   # Return time of file named in argument
 
5900
   # If file does not exist, return 0;
 
5901
   if ( -e $_[0] ) {
 
5902
       return get_mtime_raw($_[0]);
 
5903
   }
 
5904
   else {
 
5905
       return 0;
 
5906
   }
 
5907
}
 
5908
 
 
5909
#************************************************************
 
5910
 
 
5911
sub get_size {
 
5912
   # Return time of file named in argument
 
5913
   # If file does not exist, return 0;
 
5914
   if ( -e $_[0] ) {
 
5915
       return get_size_raw($_[0]);
 
5916
   }
 
5917
   else {
 
5918
       return 0;
 
5919
   }
 
5920
}
 
5921
 
 
5922
#************************************************************
 
5923
 
 
5924
sub get_size_raw
 
5925
 
5926
  my $size = (stat($_[0]))[7];
 
5927
  return $size;
 
5928
}
 
5929
 
 
5930
#************************************************************
 
5931
 
 
5932
sub get_time_size {
 
5933
   # Return time and size of file named in argument
 
5934
   # If file does not exist, return (0,-1);
 
5935
   if ( -e $_[0] ) {
 
5936
       return get_time_size_raw($_[0]);
 
5937
   }
 
5938
   else {
 
5939
       return (0,-1);
 
5940
   }
 
5941
}
 
5942
 
 
5943
#************************************************************
 
5944
 
 
5945
sub get_time_size_raw
 
5946
 
5947
  my $mtime = (stat($_[0]))[9];
 
5948
  my $size = (stat($_[0]))[7];
 
5949
  return ($mtime, $size);
 
5950
}
 
5951
 
 
5952
#************************************************************
 
5953
 
 
5954
sub get_checksum_md5 {
 
5955
    my $source = shift;
 
5956
    my $input = new FileHandle;
 
5957
    my $md5 = Digest->MD5;
 
5958
    my $ignore_pattern = '';
 
5959
 
 
5960
#warn "======= GETTING MD5: $source\n";
 
5961
    if ( $source eq "" ) { 
 
5962
       # STDIN:
 
5963
       open( $input, '-' );
 
5964
    }
 
5965
    else {
 
5966
        open( $input, '<', $source )
 
5967
        or return 0;
 
5968
        my ($base, $path, $ext) = fileparseA( $source );
 
5969
        $ext =~ s/^\.//;
 
5970
        if ( exists $hash_calc_ignore_pattern{$ext} ) {
 
5971
            $ignore_pattern = $hash_calc_ignore_pattern{$ext};
 
5972
        }
 
5973
    }
 
5974
 
 
5975
    if ( $ignore_pattern ) {
 
5976
        while (<$input>) {
 
5977
            if ( /$ignore_pattern/ ){
 
5978
                $_= '';
 
5979
            }
 
5980
            $md5->add($_);
 
5981
        }
 
5982
    }
 
5983
    else {
 
5984
        $md5->addfile($input);
 
5985
    }
 
5986
    close $input;
 
5987
    return $md5->hexdigest();
 
5988
}
 
5989
 
 
5990
#************************************************************
 
5991
#************************************************************
 
5992
 
 
5993
sub find_file1 {
 
5994
#?? Need to use kpsewhich, if possible
 
5995
 
 
5996
    # Usage: find_file1(name, ref_to_array_search_path)
 
5997
    # Modified find_file, which doesn't die.
 
5998
    # Given filename and path, return array of:
 
5999
    #             full name 
 
6000
    #             retcode
 
6001
    # On success: full_name = full name with path, retcode = 0
 
6002
    # On failure: full_name = given name, retcode = 1
 
6003
 
 
6004
  my $name = $_[0];
 
6005
  # Make local copy of path, since we may rewrite it!
 
6006
  my @path = @{$_[1]};
 
6007
  if ( $name =~ /^\// ) {
 
6008
     # Absolute path (if under UNIX)
 
6009
     # This needs fixing, in general
 
6010
     if (-e $name) { return( $name, 0 );}
 
6011
     else { return( $name, 1 );}
 
6012
  }
 
6013
  foreach my $dir ( @path ) {
 
6014
      #??print "-------------dir='$dir',  ";
 
6015
      # Make $dir concatenatable, and empty for current dir:
 
6016
      if ( $dir eq '.' ) { 
 
6017
          $dir = ''; 
 
6018
      }
 
6019
      elsif ( $dir =~ /[\/\\:]$/ ) { 
 
6020
          #OK if dir ends in / or \ or :
 
6021
      }
 
6022
      elsif ( $dir ne '' ) { 
 
6023
          #Append directory separator only to non-empty dir
 
6024
          $dir = "$dir/"; 
 
6025
      }
 
6026
      #?? print " newdir='$dir'\n";
 
6027
      if (-e "$dir$name") {
 
6028
          return("$dir$name", 0);
 
6029
      }
 
6030
  }
 
6031
  my @kpse_result = kpsewhich( $name );
 
6032
  if ($#kpse_result > -1) {
 
6033
      return( $kpse_result[0], 0);
3430
6034
  }
3431
6035
  return("$name" , 1);
3432
 
}
 
6036
} #END find_file1
3433
6037
 
3434
6038
#************************************************************
3435
6039
 
3436
 
sub find_file_list1
3437
 
# Modified version of find_file_list that doesn't die.
3438
 
# Given output and input arrays of filenames, a file suffix, and a path, 
3439
 
# fill the output array with full filenames
3440
 
# Return a status code:
3441
 
# Retcode = 0 on success
3442
 
# Retocde = 1 if at least one file was not found
3443
 
# Usage: find_file_list1( ref_to_output_file_array, 
3444
 
#                         ref_to_input_file_array, 
3445
 
#                         suffix,
3446
 
#                         ref_to_array_search_path
3447
 
#                       )
3448
 
{
 
6040
sub find_file_list1 {
 
6041
    # Modified version of find_file_list that doesn't die.
 
6042
    # Given output and input arrays of filenames, a file suffix, and a path, 
 
6043
    # fill the output array with full filenames
 
6044
    # Return a status code:
 
6045
    # Retcode = 0 on success
 
6046
    # Retocde = 1 if at least one file was not found
 
6047
    # Usage: find_file_list1( ref_to_output_file_array, 
 
6048
    #                         ref_to_input_file_array, 
 
6049
    #                         suffix,
 
6050
    #                         ref_to_array_search_path
 
6051
    #                       )
 
6052
 
3449
6053
  my $ref_output = $_[0];
3450
6054
  my $ref_input  = $_[1];
3451
6055
  my $suffix     = $_[2];
3452
6056
  my $ref_search = $_[3];
3453
6057
 
 
6058
#??  show_array( "=====find_file_list1.  Suffix: '$suffix'\n Source:",  @$ref_input );
 
6059
#??  show_array( " Bibinputs:",  @$ref_search );
 
6060
 
3454
6061
  my @return_list = ();    # Generate list in local array, since input 
3455
6062
                           # and output arrays may be same
3456
6063
  my $retcode = 0;
3457
 
  foreach my $file (@$ref_input)
3458
 
  {
 
6064
  foreach my $file (@$ref_input) {
3459
6065
    my ($tmp_file, $find_retcode) = &find_file1( "$file$suffix", $ref_search );
3460
 
    if ($tmp_file)
3461
 
    {
 
6066
    if ($tmp_file)  {
3462
6067
        push @return_list, $tmp_file;
3463
6068
    }
3464
6069
    if ( $find_retcode != 0 ) {
3466
6071
    }
3467
6072
  }
3468
6073
  @$ref_output = @return_list;
 
6074
#??  show_array( " Output", @$ref_output );
 
6075
#??  foreach (@$ref_output) { if ( /\/\// ) {  print " ====== double slash in  '$_'\n"; }  }
3469
6076
  return $retcode;
3470
 
}
 
6077
} #END find_file_list1
3471
6078
 
3472
6079
#************************************************************
3473
6080
 
 
6081
sub kpsewhich {
 
6082
# Usage: kpsewhich( filespec, ...)
 
6083
# Returns array of files with paths as found by kpsewhich
 
6084
#    kpsewhich( 'try.sty', 'jcc.bib' );
 
6085
# Can also do, e.g.,
 
6086
#    kpsewhich( '-format=bib', 'trial.bib', 'file with spaces');
 
6087
    my $cmd = $kpsewhich;
 
6088
    my @args = @_;
 
6089
    foreach (@args) {
 
6090
        if ( ! /^-/ ) {
 
6091
            $_ = "\"$_\"";
 
6092
        }
 
6093
    }
 
6094
    foreach ($cmd) {
 
6095
        s/%[RBTDO]//g;
 
6096
    }
 
6097
    $cmd =~ s/%S/@args/g;
 
6098
    my @found = ();
 
6099
    local $fh;
 
6100
    open $fh, "$cmd|"
 
6101
        or die "Cannot open pipe for \"$cmd\"\n";
 
6102
    while ( <$fh> ) {
 
6103
        s/^\s*//;
 
6104
        s/\s*$//;
 
6105
        push @found, $_;
 
6106
    }
 
6107
    close $fh;
 
6108
#    show_array( "Kpsewhich: '$cmd', '$file_list' ==>", @found );
 
6109
    return @found;
 
6110
}
 
6111
 
 
6112
####################################################
 
6113
 
 
6114
sub add_cus_dep {
 
6115
    # Usage: add_cus_dep( from_ext, to_ext, flag, sub_name )
 
6116
    # Add cus_dep after removing old versions
 
6117
    my ($from_ext, $to_ext, $must, $sub_name) = @_;
 
6118
    remove_cus_dep( $from_ext, $to_ext );
 
6119
    push @cus_dep_list, "$from_ext $to_ext $must $sub_name";
 
6120
}
 
6121
 
 
6122
####################################################
 
6123
 
 
6124
sub remove_cus_dep {
 
6125
    # Usage: remove_cus_dep( from_ext, to_ext )
 
6126
    my ($from_ext, $to_ext) = @_;
 
6127
    my $i = 0;
 
6128
    while ($i <= $#cus_dep_list) {
 
6129
        if ( $cus_dep_list[$i] =~ /^$from_ext $to_ext / ) {
 
6130
            splice @cus_dep_list, $i, 1;
 
6131
        }
 
6132
        else {
 
6133
            $i++;
 
6134
        }
 
6135
    }
 
6136
}
 
6137
 
 
6138
####################################################
 
6139
 
 
6140
sub show_cus_dep {
 
6141
    show_array( "Custom dependency list:", @cus_dep_list );
 
6142
}
 
6143
 
 
6144
####################################################
 
6145
 
 
6146
sub add_input_ext {
 
6147
    # Usage: add_input_ext( rule, ext, ... )
 
6148
    # Add extension(s) (specified without a leading period) to the 
 
6149
    # list of input extensions for the given rule.  The rule should be
 
6150
    # 'latex' or 'pdflatex'.  These extensions are used when an input
 
6151
    # file without an extension is found by (pdf)latex, as in
 
6152
    # \input{file} or \includegraphics{figure}.  When latexmk searches
 
6153
    # custom dependencies to make the missing file, it will assume that
 
6154
    # the file has one of the specified extensions.
 
6155
    my $rule = shift;
 
6156
    if ( ! exists $input_extensions{$rule} ) {
 
6157
       $input_extensions{$rule} = {};
 
6158
    }
 
6159
    my $Prule = $input_extensions{$rule};
 
6160
    foreach (@_) { $$Prule{$_} = 1; }
 
6161
}
 
6162
 
 
6163
####################################################
 
6164
 
 
6165
sub remove_input_ext {
 
6166
    # Usage: remove_input_ext( rule, ext, ... )
 
6167
    # Remove extension(s) (specified without a leading period) to the 
 
6168
    # list of input extensions for the given rule.  The rule should be
 
6169
    # 'latex' or 'pdflatex'.  See sub add_input_ext for the use.
 
6170
    my $rule = shift;
 
6171
    if ( ! exists $input_extensions{$rule} ) { return; }
 
6172
    my $Prule = $input_extensions{$rule};
 
6173
    foreach (@_) { delete $$Prule{$_}; }
 
6174
}
 
6175
 
 
6176
####################################################
 
6177
 
 
6178
sub show_input_ext {
 
6179
    # Usage: show_input_ext( rule )
 
6180
    my $rule = shift;
 
6181
    show_array ("Input extensions for rule '$rule': ", 
 
6182
                keys %{$input_extensions{$rule}} );
 
6183
}
 
6184
 
 
6185
####################################################
 
6186
 
3474
6187
sub find_dirs1 {
3475
6188
   # Same as find_dirs, but argument is single string with directories
3476
6189
   # separated by $search_path_separator
3486
6199
#         name ending in //, a list of all subdirectories (recursive)
3487
6200
#         is added to the list.
3488
6201
#   Non-existent directories and non-directories are removed from the list
3489
 
#   Trailing "/"s are removed, and multiple "/" are collapsed to single "/".
 
6202
#   Trailing "/"s and "\"s are removed
3490
6203
    local @result = ();
3491
6204
    my $find_action 
3492
6205
        = sub 
3499
6212
        # Remove all trailing /s, since directory name with trailing /
3500
6213
        #   is not always allowed:
3501
6214
        $directory =~ s[/+$][];
3502
 
        # Collapse multiple / to single /, since filenames with
3503
 
        #   multiple slashes are not necessarily valid.
3504
 
        $directory =~ s[/+][/];
 
6215
        # Similarly for MSWin reverse slash
 
6216
        $directory =~ s[\\+$][];
3505
6217
        if ( ! -e $directory ){
3506
6218
            next;
3507
6219
        }
3538
6250
    return @sort;
3539
6251
}
3540
6252
 
3541
 
#************************************************************
3542
 
 
3543
 
sub copy_file_and_time {
3544
 
    # Copy file1 to file2, copying time
3545
 
    # I think copy() already does this, but it may depend on version.
3546
 
    my $source = shift;
3547
 
    my $dest   = shift;
3548
 
    my $retcode = copy ($source, $dest)
3549
 
        and do {
3550
 
              my $mtime = get_mtime($dest);
3551
 
              utime $mtime, $mtime, $dest;
3552
 
          };
3553
 
    return $retcode;    
3554
 
}
3555
 
 
3556
 
#************************************************************
3557
 
 
3558
 
sub copy_file_keep_time {
3559
 
    # Copy file1 to file2, preserving time of file 2
3560
 
    my $source = shift;
3561
 
    my $dest   = shift;
3562
 
    if (-e $dest) { return 1; }
3563
 
    my $mtime = get_mtime($dest);
3564
 
    my $retcode = copy ($source, $dest)
3565
 
        and do {
3566
 
              utime $mtime, $mtime, $dest;
3567
 
          };
3568
 
    return $retcode;    
3569
 
}
3570
 
 
3571
 
#************************************************************
3572
 
 
3573
 
sub diff {
3574
 
   # diff(filename1, filename2): 
3575
 
   #         Return 2 if either or both files cannot be opened.
3576
 
   #                1 if the files are different
3577
 
   #                0 if the files are the same
3578
 
    my $file1 = new FileHandle;
3579
 
    my $file2 = new FileHandle;
3580
 
   # Note automatic close of files when they go out of scope.
3581
 
    open ($file1, $_[0]) or return 2;
3582
 
    open ($file2, $_[1]) or return 2;
3583
 
    my $retcode = 0;
3584
 
    while ( ( not eof($file1)) || ( not eof($file2) ) ){
3585
 
        if ( <$file1> ne <$file2> ) {
3586
 
            $retcode = 1;
3587
 
            last;
3588
 
        }
3589
 
    }
3590
 
    return $retcode;
3591
 
}
3592
 
 
3593
 
#************************************************************
3594
 
 
3595
 
sub diff_OLDVERSION {
3596
 
   # diff(filename1, filename2): 
3597
 
   #         Return 2 if either or both files cannot be opened.
3598
 
   #                1 if the files are different
3599
 
   #                0 if the files are the same
3600
 
    local (*file1, *file2);
3601
 
    unless(  open (file1, $_[0]) ) {
3602
 
        return 2;
3603
 
    }
3604
 
    unless ( open (file2, $_[1])) {
3605
 
        close (file1);
3606
 
        return 2;
3607
 
    }
3608
 
    my $retcode = 0;
3609
 
    while ( ( not eof(file1)) && ( not eof(file2) ) ){
3610
 
        if ( <file1> ne <file2> ) {
3611
 
            $retcode = 1;
3612
 
            last;
3613
 
        }
3614
 
    }
3615
 
    close (file1);
3616
 
    close (file2);
3617
 
    return $retcode;
3618
 
}
 
6253
#==================================================
 
6254
 
 
6255
sub uniq1 {
 
6256
   # Usage: uniq1( strings )
 
6257
   # Returns array of strings with duplicates later in list than
 
6258
   # first occurence deleted.  Otherwise preserves order.
 
6259
 
 
6260
    my @strings = ();
 
6261
    my %string_hash = ();
 
6262
 
 
6263
    foreach my $string (@_) {
 
6264
        if (!exists( $string_hash{$string} )) { 
 
6265
            $string_hash{$string} = 1;
 
6266
            push @strings, $string; 
 
6267
        }
 
6268
    }
 
6269
    return @strings;
 
6270
}
 
6271
 
 
6272
#************************************************************
 
6273
 
 
6274
sub uniqs {
 
6275
    # Usage: uniq2( strings )
 
6276
    # Returns array of strings sorted and with duplicates deleted
 
6277
    return uniq( sort @_ );
 
6278
}
 
6279
 
 
6280
#************************************************************
 
6281
 
 
6282
sub ext {
 
6283
    # Return extension of filename.  Extension includes the period
 
6284
    my $file_name = $_[0];
 
6285
    my ($base_name, $path, $ext) = fileparseA( $file_name );
 
6286
    return $ext;
 
6287
 }
 
6288
 
 
6289
#************************************************************
 
6290
 
 
6291
sub ext_no_period {
 
6292
    # Return extension of filename.  Extension excludes the period
 
6293
    my $file_name = $_[0];
 
6294
    my ($base_name, $path, $ext) = fileparseA( $file_name );
 
6295
    $ext =~ s/^\.//;
 
6296
    return $ext;
 
6297
 }
 
6298
 
 
6299
#************************************************************
 
6300
 
 
6301
sub fileparseA {
 
6302
    # Like fileparse but replace $path for current dir ('./' or '.\') by ''
 
6303
    # Also default second argument to get normal extension.
 
6304
    my $given = $_[0];
 
6305
    my $pattern = '\.[^\.]*';
 
6306
    if  ($#_ > 0 ) { $pattern = $_[1]; }
 
6307
    my ($base_name, $path, $ext) = fileparse( $given, $pattern );
 
6308
    if ( ($path eq './') || ($path eq '.\\') ) { 
 
6309
        $path = ''; 
 
6310
    }
 
6311
    return ($base_name, $path, $ext);
 
6312
 }
 
6313
 
 
6314
#************************************************************
 
6315
 
 
6316
sub fileparseB {
 
6317
    # Like fileparse but with default second argument for normal extension
 
6318
    my $given = $_[0];
 
6319
    my $pattern = '\.[^\.]*';
 
6320
    if  ($#_ > 0 ) { $pattern = $_[1]; }
 
6321
    my ($base_name, $path, $ext) = fileparse( $given, $pattern );
 
6322
    return ($base_name, $path, $ext);
 
6323
 }
3619
6324
 
3620
6325
#************************************************************
3621
6326
 
3642
6347
    return @list;
3643
6348
}
3644
6349
 
 
6350
#################################
 
6351
 
 
6352
 
 
6353
sub tempfile1 {
 
6354
    # Makes a temporary file of a unique name.  I could use file::temp,
 
6355
    # but it is not present in all versions of perl
 
6356
    # Filename is of form $tmpdir/$_[0]nnn$suffix, where nnn is an integer
 
6357
    my $tmp_file_count = 0;
 
6358
    my $prefix = $_[0];
 
6359
    my $suffix = $_[1];
 
6360
    while (1==1) {
 
6361
        # Find a new temporary file, and make it.
 
6362
        $tmp_file_count++;
 
6363
        my $tmp_file = "${tmpdir}/${prefix}${tmp_file_count}${suffix}";
 
6364
        if ( ! -e $tmp_file ) {
 
6365
            open( TMP, ">$tmp_file" ) 
 
6366
               or next;
 
6367
            close(TMP);
 
6368
            return $tmp_file;
 
6369
         }
 
6370
     }
 
6371
     die "$My_name.tempfile1: BUG TO ARRIVE HERE\n";
 
6372
}
 
6373
 
 
6374
#################################
 
6375
 
3645
6376
#************************************************************
3646
6377
#************************************************************
3647
6378
#      Process/subprocess routines
3648
6379
 
 
6380
sub Run_msg {
 
6381
    # Same as Run, but give message about my running
 
6382
    warn_running( "Running '$_[0]'" );
 
6383
    Run($_[0]);
 
6384
}
 
6385
 
3649
6386
sub Run {
3650
6387
# Usage: Run ("program arguments ");
3651
6388
#    or  Run ("start program arguments");
3675
6412
 
3676
6413
# Split command line into one word per element, separating words by 
3677
6414
#    one (OR MORE) spaces:
3678
 
    my @cmdline = split (/ +/, $_[0]);
3679
 
    if (! @cmdline ) {
3680
 
        warn "Latexmk::Run: Attempt to run a null program.";
 
6415
# The purpose of this is to identify latexmk-defined pseudocommands
 
6416
#  'start' and 'NONE'.
 
6417
# After dealing with them, the command line is reassembled
 
6418
    my $cmd_line = $_[0];
 
6419
    if ( $cmd_line eq '' ) {
 
6420
        traceback( "$My_name: Bug OR configuration error\n".
 
6421
                   "   In run of'$rule', attempt to run a null program" );
3681
6422
        return (0, 1);
3682
6423
    }
3683
 
    if ( "$cmdline[0]" eq "start" ) {
 
6424
    if ( $cmd_line =~ /^start +/ ) {
 
6425
        #warn "Before: '$cmd_line'\n";
3684
6426
        # Run detached.  How to do this depends on the OS
3685
6427
        # But first remove extra starts (which may have been inserted
3686
6428
        # to force a command to be run detached, when the command
3687
6429
        # already contained a "start").
3688
 
        while ($cmdline[0] eq "start") {shift (@cmdline);}
3689
 
        return &Run_Detached (@cmdline);
 
6430
        while ( $cmd_line =~ s/^start +// ) {}
 
6431
        #warn "After: '$cmd_line'\n";
 
6432
        return &Run_Detached( $cmd_line );
3690
6433
    }
3691
 
    elsif ( "$cmdline[0]" eq "NONE" ) {
3692
 
        warn "Latexmk::Run: ",
 
6434
    elsif ( $cmd_line =~ /^NONE/ ) {
 
6435
        warn "$My_name: ",
3693
6436
             "Program not implemented for this version.  Command line:\n";
3694
 
        warn "   \"@cmdline\"\n";
 
6437
        warn "   '$cmd_line'\n";
3695
6438
        return (0, 1);
3696
6439
    }
3697
6440
    else { 
3698
6441
       # The command is given to system as a single argument, to force shell
3699
6442
       # metacharacters to be interpreted:
3700
 
       return (0, system( join( ' ', @cmdline) ) );
 
6443
       return( 0, system( $cmd_line ) );
3701
6444
   }
3702
6445
}
3703
6446
 
3718
6461
#   else if I fail to spawn a process
3719
6462
#       return (0, 1)
3720
6463
 
3721
 
 
3722
 
 
3723
 
##    warn "Running \"@_\" detached...\n";
 
6464
    my $cmd_line = $_[0];
 
6465
 
 
6466
##    warn "Running '$cmd_line' detached...\n";
 
6467
    if ( $cmd_line =~ /^NONE / ) {
 
6468
        warn "$My_name: ",
 
6469
             "Program not implemented for this version.  Command line:\n";
 
6470
        warn "   '$cmd_line'\n";
 
6471
        return (0, 1);
 
6472
    }
3724
6473
 
3725
6474
    if ( "$^O" eq "MSWin32" ){
3726
6475
        # Win95, WinNT, etc: Use MS's start command:
3727
 
        return (0, system( "start", @_) );
 
6476
        # Need extra double quotes to deal with quoted filenames: 
 
6477
        #    MSWin start takes first quoted argument to be a Window title. 
 
6478
        return( 0, system( "start \"\" $cmd_line" ) );
3728
6479
    } else {
3729
6480
        # Assume anything else is UNIX or clone
3730
6481
        # For this purpose cygwin behaves like UNIX.
3733
6484
        ## warn "Run_Detached.UNIX: B pid=$pid\n";
3734
6485
        if ( ! defined $pid ) {
3735
6486
            ## warn "Run_Detached.UNIX: C\n";
3736
 
            warn "Latexmk:: Could not fork to run the following command:\n";
3737
 
            warn "   \"@_\"\n";
 
6487
            warn "$My_name: Could not fork to run the following command:\n";
 
6488
            warn "   '$cmd_line'\n";
3738
6489
            return (0, 1);
3739
6490
        }
3740
6491
        elsif( $pid == 0 ){
3745
6496
           # Perhaps this works if setpgrp doesn't exist 
3746
6497
           #    (and therefore gives fatal error):
3747
6498
           eval{ setpgrp(0,0);};
3748
 
           exec(@_);
 
6499
           exec( $cmd_line );
3749
6500
           # Exec never returns; it replaces current process by new process
3750
 
           die "Latexmk forked process: could not run the command\n",
3751
 
               "  \"@_\"\n";
 
6501
           die "$My_name forked process: could not run the command\n",
 
6502
               "  '$cmd_line'\n";
3752
6503
        }
3753
6504
        ##warn "Run_Detached.UNIX: E\n";
3754
6505
        # Original process arrives here
3776
6527
    my $looking_for = $_[0];
3777
6528
    my @ps_output = `$pscmd`;
3778
6529
 
 
6530
# There may be multiple processes.  Find only latest, 
 
6531
#   almost surely the one with the highest process number
 
6532
# This will deal with cases like xdvi where a script is used to 
 
6533
#   run the viewer and both the script and the actual viewer binary
 
6534
#   have running processes.
 
6535
    my @found = ();
 
6536
 
3779
6537
    shift(@ps_output);  # Discard the header line from ps
3780
6538
    foreach (@ps_output)   {
3781
6539
        next unless ( /$looking_for/ ) ;
3782
6540
        my @ps_line = split (' ');
3783
 
        return($ps_line[$pid_position]);
3784
 
    }
3785
 
 
3786
 
    # No luck in finding the specified process.
3787
 
    return(0);
3788
 
}
3789
 
 
3790
 
#************************************************************
3791
 
 
3792
 
 
 
6541
# OLD       return($ps_line[$pid_position]);
 
6542
        push @found, $ps_line[$pid_position];
 
6543
    }
 
6544
 
 
6545
    if ($#found < 0) {
 
6546
       # No luck in finding the specified process.
 
6547
       return(0);
 
6548
    }
 
6549
    @found = reverse sort @found;
 
6550
    if ($diagnostics) {
 
6551
       print "Found the following processes concerning '$looking_for'\n",
 
6552
             "   @found\n",
 
6553
             "   I will use $found[0]\n";
 
6554
    }
 
6555
    return $found[0];
 
6556
}
 
6557
 
 
6558
#************************************************************
 
6559
#************************************************************
 
6560
#************************************************************
 
6561
 
 
6562
#   Directory stack routines
 
6563
 
 
6564
sub pushd {
 
6565
    push @dir_stack, cwd();
 
6566
    if ( $#_ > -1) { chdir $_[0]; }
 
6567
}
 
6568
 
 
6569
#************************************************************
 
6570
 
 
6571
sub popd {
 
6572
    if ($#dir_stack > -1 ) { chdir pop @dir_stack; }
 
6573
}
 
6574
 
 
6575
#************************************************************
 
6576
 
 
6577
sub ifcd_popd {
 
6578
    if ( $do_cd ) {
 
6579
        warn "$My_name: Undoing directory change\n";
 
6580
        &popd;
 
6581
    }
 
6582
}
 
6583
 
 
6584
#************************************************************
 
6585
 
 
6586
sub finish_dir_stack {
 
6587
    while ($#dir_stack > -1 ) { &popd; }
 
6588
}
 
6589
 
 
6590
#************************************************************
 
6591
#************************************************************
 
6592
# Break handling routines (for wait-loop in preview continuous)
 
6593
 
 
6594
sub end_wait {
 
6595
    #  Handler for break: Set global variable $have_break to 1.
 
6596
    # Some systems (e.g., MSWin reset) appear to reset the handler.
 
6597
    # So I'll re-enable it
 
6598
    &catch_break;
 
6599
    $have_break = 1;
 
6600
}
 
6601
 
 
6602
#========================
 
6603
 
 
6604
sub catch_break {
 
6605
# Capture ctrl/C and ctrl/break.
 
6606
# $SIG{INT} corresponds to ctrl/C on LINUX/?UNIX and MSWin
 
6607
# $SIG{BREAK} corresponds to ctrl/break on MSWin, doesn't exist on LINUX
 
6608
    $SIG{INT} = \&end_wait;
 
6609
    if ( exists $SIG{BREAK} ) {
 
6610
        $SIG{BREAK} = \&end_wait;
 
6611
    }
 
6612
}
 
6613
 
 
6614
#========================
 
6615
 
 
6616
sub default_break {
 
6617
# Arrange for ctrl/C and ctrl/break to give default behavior
 
6618
    $SIG{INT} = 'DEFAULT';
 
6619
    if ( exists $SIG{BREAK} ) {
 
6620
        $SIG{BREAK} = 'DEFAULT';
 
6621
    }
 
6622
}
 
6623
 
 
6624
#************************************************************
 
6625
#************************************************************