Debian Codegraph @

texk/texlive/linked_scripts/latexmk/latexmk.pl

raw
1 #!/usr/bin/env perl
2 use warnings;
3 use strict;
4
5 ## Copyright John Collins 1998-2025
6 ## (username jcc8 at node psu.edu)
7 ## (and thanks to David Coppit (username david at node coppit.org)
8 ## for suggestions)
9 ## Copyright Evan McLean
10 ## (modifications up to version 2)
11 ## Copyright 1992 by David J. Musliner and The University of Michigan.
12 ## (original version)
13 ##
14 ## This program is free software; you can redistribute it and/or modify
15 ## it under the terms of the GNU General Public License as published by
16 ## the Free Software Foundation; either version 2 of the License, or
17 ## (at your option) any later version.
18 ##
19 ## This program is distributed in the hope that it will be useful,
20 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ## GNU General Public License for more details.
23 ##
24 ## You should have received a copy of the GNU General Public License
25 ## along with this program; if not, write to the Free Software
26 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
27 ##
28 ## See file CHANGES for list of main version-to-version changes.
29 ##
30 ## Modified by Evan McLean (no longer available for support)
31 ## Original script (RCS version 2.3) called "go" written by David J. Musliner
32 ##
33 ##-----------------------------------------------------------------------
34
35 ## Explicit exit codes:
36 ## 10 = bad command line arguments
37 ## 11 = file specified on command line not found
38 ## or other file not found
39 ## 12 = failure in some part of making files
40 ## 13 = error in initialization file
41 ## 20 = probable bug
42 ## or retcode from called program.
43
44 our ($my_name, $My_name, $version_num, $version_details);
45 BEGIN {
46 # Make sure the following are available when printing diagnostics in BEGIN
47 # blocks.
48 $my_name = 'latexmk';
49 $My_name = 'Latexmk';
50 $version_num = '4.87';
51 $version_details = "$My_name, John Collins, 15 June 2025. Version $version_num";
52 }
53
54 # Ensure that when STDERR and STDOUT are both redirected, the results are
55 # in the order they are written. Otherwise, the default situation for
56 # redirected output is that STDERR is always autoflushed, but STDOUT is
57 # not, and therefore output does not appear in the order is was written.
58 STDOUT->autoflush(1);
59
60 use Config;
61 use File::Basename;
62 use File::Copy;
63 use File::Spec::Functions qw( catfile file_name_is_absolute rel2abs );
64
65 # If possible, use better glob, which does not use space as item separator.
66 # It's either File::Glob::bsd_glob or File::Glob::glob
67 # The first does not exist in old versions of Perl, while the second
68 # is deprecated in more recent versions and will be removed
69 our $have_bsd_glob = 0;
70 use File::Glob;
71 if ( eval{ File::Glob->import('bsd_glob'); 1; } ) {
72 # Success in importing bsd_glob
73 $have_bsd_glob = 1;
74 }
75 elsif ( eval{ File::Glob->import('glob'); 1; } ) {
76 warn( "$My_name: I could not import File::Glob:bsd_glob, probably because your\n",
77 " Perl is too old. I have arranged to use the deprecated File::Glob:glob\n",
78 " instead.\n",
79 " WARNING: It may malfunction on clean up operation on filenames containing\n",
80 " spaces.\n" );
81 $have_bsd_glob = 0;
82 }
83 else {
84 die "Could not import 'File::Glob:bsd_glob' or 'File::Glob:glob'\n";
85 }
86
87 use File::Path 2.08 qw( make_path );
88 use FileHandle;
89 use File::Find;
90 use List::Util qw( max );
91 use Cwd;
92 use Cwd "abs_path";
93 use Cwd "chdir"; # Ensure $ENV{PWD} tracks cwd.
94 use Digest::MD5;
95
96 our %HiRes_non_imports;
97 use Time::HiRes;
98 BEGIN {
99 # Import some HiRes functions to override standard ones.
100 # However, Time::HiRes's documentation says that some of its functions
101 # may be unimplemented on some systems.
102 # So take precautions in case the ones I need aren't implemented.
103 # I must do the import in a BEGIN block, i.e., during compilation
104 # phase, else calls to time() etc get compiled to use std time(), i.e.,
105 # CORE::time(), instead of the HiRes versions.
106 #
107 # Notes:
108 # (a) On Windows with a standard Windows perl, the HiRes functions still
109 # only give 1 sec resolution, and utime is not imported.
110 # (b) Other cases, may or may not give better than 1 sec, depending on
111 # combination of OS, file system, and server (for remote system).
112 %HiRes_non_imports = ();
113 foreach ( ( qw( time stat sleep utime ) ) ) {
114 if ( ! eval{ Time::HiRes->import($_); 1; } ) {
115 $HiRes_non_imports{$_} = 1;
116 # warn "$My_name: Cannot import Time::HiRes::$_ on this system because:\n",
117 # "$@";
118 }
119 }
120 }
121
122 #################################################
123 #
124 # Unicode set up to be used in latexmk
125 #
126 use Encode qw( decode encode );
127 use Unicode::Normalize;
128 use utf8; # Strings are coded in UTF-8 in this file, stored internally
129 # decoded into Perl's internal character representation.
130 use feature 'unicode_strings';
131 use feature 'say';
132
133
134 # Coding:
135 # 1. $CS_system = CS for file names in file system calls, and for CL.
136 # It's to be UTF-8 on all except: MSWin when the MSWin system code page is
137 # not 65001.
138 # 2. Internally use CS_system generally, and especially for filenames.
139 # Then standard file system calls, print to terminal don't need encoding,
140 # and things in rc files work unchanged from earlier versions of latexmk,
141 # when I didn't treat non-ASCII coding issues explicitly.
142 # 3. But must set console codepage to system codepage on MSWin, otherwise
143 # display on terminal is garbled.
144 # 4. fdb_latexmk: write and read UTF-8, convert to and from CS_system for
145 # strings.
146 # 5. .fls, .log, .aux are all UTF-8, so if necessary convert to CS_system.
147 # 6. However, with TeXLive on MSWin with system CP not equal to 65001,
148 # the PWD is in CS_system on all but most recent *latex (that's a bug).
149 # Convert file/path names to CS_system.
150 # 7. Don't support non-UTF-8 on *nix.
151 # 8. Do NOT do any conversion to a NF for Unicode: File systems and OS calls
152 # to access them are **either** normalization-sensitive (I think, e.g.,
153 # ext4) and we need to preserve normalization, **or** they are
154 # normalization-insensitve (e.g., hfs+, apfs), in which case we can access
155 # a file with any normalization for its name.
156 #
157 # N.B. I18N::Langinfo often doesn't give useful enough information.
158
159
160
161 # My default CSs: UTF-8
162 our $CS_system = 'UTF-8';
163 # Quick short cut for tests of whether conversions needed:
164 our $no_CP_conversions = 1;
165
166 # Win32 specific CP **numbers**. Initialize to 65001 (utf-8), and change
167 # by results of system calls.
168 # Corresponding CS name: Prefix by 'CP'.
169 # Preserve intial values for console/terminal to allow restore on exit.
170 our ($CP_Win_system, $CP_init_Win_console_in, $CP_init_Win_console_out);
171 $CP_Win_system = $CP_init_Win_console_in = $CP_init_Win_console_out = '65001';
172
173 # Whether to revert Windows console CPs on exit:
174 our $Win_revert_settings = 0;
175
176 if ($^O eq "MSWin32") {
177 eval { require Win32;
178 $CP_Win_system = Win32::GetACP();
179 $CS_system = 'CP' . $CP_Win_system;
180 $CP_init_Win_console_in = Win32::GetConsoleCP();
181 $CP_init_Win_console_out = Win32::GetConsoleOutputCP();
182 if ( Win32::SetConsoleOutputCP($CP_Win_system)
183 && Win32::SetConsoleCP($CP_Win_system) ) {
184 } else {
185 warn "Cannot set Windows Console Output CP to $CP_Win_system.\n";
186 }
187 };
188 if ($@) { warn "Trouble finding and setting code pages used by Windows:\n",
189 " $@",
190 " I'LL CONTINUE WITH UTF-8.\n";
191 }
192 else {
193 $Win_revert_settings =
194 ($CP_init_Win_console_in ne $CP_Win_system)
195 || ($CP_init_Win_console_out ne $CP_Win_system);
196 print
197 "Initial Win CP for (console input, console output, system): ",
198 "(CP$CP_init_Win_console_in, CP$CP_init_Win_console_out, CP$CP_Win_system)\n",
199 "I changed them all to CP$CP_Win_system\n";
200 }
201 }
202 $no_CP_conversions = ($CS_system eq 'UTF-8') || ($CS_system eq 'CP65001');
203
204 # Ensure that on ctrl/C interruption, etc, Windows console CPs are restored:
205 use sigtrap qw(die untrapped normal-signals);
206 END {
207 if ($Win_revert_settings ) {
208 warn "Reverting Windows console CPs to ",
209 "(in,out) = ($CP_init_Win_console_in,$CP_init_Win_console_out)\n";
210 Win32::SetConsoleCP($CP_init_Win_console_in);
211 Win32::SetConsoleOutputCP($CP_init_Win_console_out);
212 }
213 }
214
215 ########################################################
216
217 ################################################################
218 ################################################################
219 #============ Deal with how I'm invoked: name and CL args:
220
221 # Name that I'm invoked with indicates default behavior (latexmk
222 # v. pdflatexmk, etc):
223 our ($invoked_name) = fileparseA($0);
224 # Save name, since I override it if I don't recognize it
225 our $invoked_kind = $invoked_name;
226 print "$My_name: Invoked as '$invoked_name'\n"
227 if ($invoked_name ne 'latexmk');
228
229 # Map my invoked name to pointer to array of default values for $dvi_mode,
230 # $postscript_mode, $pdf_mode, $xdv_mode. These are used if after processing
231 # rc files and CL args, no values are set for any of these variables.
232 # Thus default compilation for latexmk is by latex,
233 # for pdflatexmk is by pdflatex, etc.
234 our %compilation_defaults =
235 ( 'latexmk' => [1,0,0,0],
236 'lualatexmk' => [0,0,4,0],
237 'pdflatexmk' => [0,0,1,0],
238 'xelatexmk' => [0,0,5,0],
239 );
240 # If name isn't in canonical set, change it to a good default:
241 unless (exists $compilation_defaults{$invoked_name}) { $invoked_name = 'latexmk'; }
242
243 #==================
244
245 ################################################################
246 ################################################################
247
248 # Translation of signal names to numbers and vv:
249 our %signo = ();
250 our @signame = ();
251 if ( defined $Config{sig_name} ) {
252 my $i = 0;
253 foreach my $name (split('\s+', $Config{sig_name})) {
254 $signo{$name} = $i;
255 $signame[$i] = $name;
256 $i++;
257 }
258 }
259 else {
260 warn "Something wrong with the perl configuration: No signals?\n";
261 }
262
263
264 # Line length in log file that indicates wrapping.
265 # This number EXCLUDES line-end characters, and is one-based.
266 # It is the parameter max_print_line in the TeX program. (tex.web)
267 our $log_wrap = 79;
268
269 # Expected biggest construct in log file in bytes.
270 # Use to limit number of (potentially) wrapped lines to combine into single line.
271 our $max_log_construct = 600;
272
273 # Whether to search for ^^ notation in log file for non-7-bit characters,
274 # and convert to bytes. (Note: ^^ notation is produced by hilatex in
275 # TeXLive 2023..., and by pdflatex in MiKTeX 22.1... if no special option is
276 # used (-enable-8bit-chars). (Also pdflatex in TeXLive 2025 (and earlier)
277 # gives it if -translate-file=empty is used.)
278 # Same applies to .aux file.
279 # But .fls file is always UTF-8, so we don't need the conversion there.
280 our $conv_hathat = 1;
281
282 #########################################################################
283 ## Default parsing and file-handling settings
284
285 ## Array of reg-exps for patterns in log-file for file-not-found
286 ## Each item is the string in a regexp, without the enclosing slashes.
287 ## First parenthesized part is the filename.
288 ## Note the need to quote slashes and single right quotes to make them
289 ## appear in the regexp.
290 ## Add items by push, e.g.,
291 ## push @file_not_found, '^No data file found `([^\\\']*)\\\'';
292 ## will give match to line starting "No data file found `filename'"
293 our @file_not_found = (
294 '^No file\\s+(.*): Run ',
295 # That first pattern is used by recent versions (from 2024 onwards),
296 # and must appear ahead of other patterns starting 'No file', since
297 # the parsing of the target line is ambiguous between patterns.
298 '^No file\\s+(.*)\\.$',
299 '^No file\\s+(.+)\s*$',
300 '^\\! LaTeX Error: File `([^\\\']*)\\\' not found\\.',
301 '^\\! I can\\\'t find file `([^\\\']*)\\\'\\.',
302 '.*?:\\d*: LaTeX Error: File `([^\\\']*)\\\' not found\\.',
303 '^LaTeX Warning: File `([^\\\']*)\\\' not found',
304 '^Package .* [fF]ile `([^\\\']*)\\\' not found',
305 '^Package .* No file `([^\\\']*)\\\'',
306 'Error: pdflatex \(file ([^\)]*)\): cannot find image file',
307 ': File (.*) not found:\s*$',
308 '! Unable to load picture or PDF file \\\'([^\\\']+)\\\'.',
309 );
310
311 # Array of reg-exps for patterns in log file for certain latex warnings
312 # that we will call bad warnings. They are not treated as errors by
313 # *latex, but depending on the $bad_warning_is_error setting
314 # we will treat as if they were actual errors.
315 our @bad_warnings = (
316 # Remember: \\ in perl inside single quotes gives a '\', so we need
317 # '\\\\' to get '\\' in the regexp.
318 '^\(\\\\end occurred when .* was incomplete\)',
319 '^\(\\\\end occurred inside .*\)',
320 );
321 our $bad_warning_is_error = 0;
322
323 # Characters that we won't allow in the name of a TeX file.
324 # Notes: Some are disallowed by TeX itself (at least, not without dirty
325 # tricks à la David Carlisle).
326 # '\' results in TeX macro expansion
327 # '$' results in possible variable substitution by kpsewhich called from tex.
328 # '"' gets special treatment.
329 # NULL never allowed in file/path name.
330 # See subroutine test_fix_texnames and its call for their use.
331 # The full range of these excluded characters only applies when the
332 # filename is used in TeX code, directly or indirectly. (E.g.,
333 # .tex filename given on the command line to *tex, or in \input
334 # statements, and the like.) It does not apply in other
335 # situations, e.g., for the name of the directory given to the
336 # -output-directory option. The name of the output directory can
337 # correctly appear as part of the names of files read in both the
338 # .log file and the .fls file. So this list of disallowed
339 # characters definitely does not apply to filenames obtained from
340 # the .log and .fls files etc.
341 # (Of course, some of these characters are prohibited in file and
342 # path names, either (like NULL) in all current OSs and file
343 # systems, or on particular combinations of OS and file system. We
344 # won't try to implement all the restrictions; it's too hard.)
345 our $illegal_in_texname = "\x00\t\f\n\r\$%\\~\x7F";
346
347 # Whether to normalize aux_dir and out_dir where possible.
348 # This is important when these directories aren't subdirectories of the cwd,
349 # and TeXLive's makeindex and/or bibtex are used.
350 our $normalize_names = 2; # Strongest kind.
351
352 ## Hash mapping file extension (w/o period, e.g., 'eps') to a single regexp,
353 # whose matching by a line in a file with that extension indicates that the
354 # line is to be ignored in the calculation of the hash number (md5 checksum)
355 # for the file. Typically used for ignoring datestamps in testing whether
356 # a file has changed.
357 # Add items e.g., by
358 # $hash_calc_ignore_pattern{'eps'} = '^%%CreationDate: ';
359 # This makes the hash calculation for an eps file ignore lines starting with
360 # '%%CreationDate: '
361 # ?? Note that a file will be considered changed if
362 # (a) its size changes
363 # or (b) its hash changes
364 # So it is useful to ignore lines in the hash calculation only if they
365 # are of a fixed size (as with a date/time stamp).
366 our %hash_calc_ignore_pattern =();
367
368 # Specification of templates for extra rules.
369 # See subroutine rdb_initialize_rules for examples of rule templates, and
370 # how they get used to construct rules.
371 # (Documentation obviously needs to be improved!)
372 our %extra_rule_spec = ();
373
374
375 #??????? !!!!!!!!! If @aux_hooks and @latex_file_hooks are still needed,
376 # should I incorporate them into the general hook hash???
377 #
378 # Hooks for customized extra processing on aux files. The following
379 # variable is an array of references to functions. Each function is
380 # invoked in turn when a line of an aux file is processed (if none
381 # of the built-in actions have been done). On entry to the function,
382 # the following variables are set:
383 # $_ = current line of aux file
384 # $rule = name of rule during the invocation of which, the aux file
385 # was supposed to have been generated.
386 our @aux_hooks = ();
387 #
388 # Hooks for customized processing on lists of source and missing files.
389 # The following variable is an array of references to functions. Each
390 # function is invoked in turn after a run of latex (or pdflatex etc) and
391 # latexmk has analyzed the .log and .fls files for dependency information.
392 # On entry to each called function, the following variables are set:
393 # $rule = name of *latex rule
394 # %dependents: maps source files and possible source files to a status.
395 # See begining of sub parse_log for possible values.
396 our @latex_file_hooks = ();
397 #
398 # Single hash for various stacks of hooks:
399 our %hooks = ();
400 for ( 'before_xlatex', 'after_xlatex', 'after_xlatex_analysis', 'after_main_pdf',
401 'cleanup', 'cleanup_extra_full' ) {
402 $hooks{$_} = [];
403 }
404 $hooks{aux_hooks} = \@aux_hooks;
405 $hooks{latex_file_hooks} = \@latex_file_hooks;
406
407 #########################################################################
408 ## Default document processing programs, and related settings,
409 ## These are mostly the same on all systems.
410 ## Most of these variables represents the external command needed to
411 ## perform a certain action. Some represent switches.
412
413
414 ## Which TeX distribution is being used
415 ## E.g., "MiKTeX 2.9", "TeX Live 2018"
416 ## "" means not determined. Obtain from first line of .log file.
417 our $tex_distribution = '';
418
419 # List of known *latex rules:
420 our %possible_primaries = ( 'dvilualatex' => 'primary', 'hilatex' => 'primary',
421 'latex' => 'primary',
422 'lualatex' => 'primary', 'pdflatex' => 'primary',
423 'xelatex' => 'primary' );
424 # Command strings for them:
425 our ($dvilualatex, $hilatex, $latex, $lualatex, $pdflatex, $xelatex );
426 std_tex_cmds();
427
428 # Possible code to execute by *latex before inputting source file.
429 # Not used by default.
430 our $pre_tex_code = '';
431
432 ## Default switches:
433 our $hilatex_default_switches = '';
434 our $latex_default_switches = '';
435 our $pdflatex_default_switches = '';
436 our $dvilualatex_default_switches = '';
437 our $lualatex_default_switches = '';
438 # Note that xelatex is used to give xdv file, not pdf file, hence
439 # we need the -no-pdf option.
440 our $xelatex_default_switches = '-no-pdf';
441
442 ## Switch(es) to make them silent:
443 our $hilatex_silent_switch = '-interaction=batchmode';
444 our $latex_silent_switch = '-interaction=batchmode';
445 our $pdflatex_silent_switch = '-interaction=batchmode';
446 our $dvilualatex_silent_switch = '-interaction=batchmode';
447 our $lualatex_silent_switch = '-interaction=batchmode';
448 our $xelatex_silent_switch = '-interaction=batchmode';
449
450 # Whether to emulate -aux-directory, so we can use it on system(s) (TeXLive)
451 # that don't support it.
452 # Possible values: 0: I don't do any emulation, and use -aux-directory &
453 # -out-directory options to *latex.
454 # 1: Emulate MiKTeX behavior: Use -output-directory=<aux dir>
455 # in call to *latex. Then move pdf (etc) files after run.
456 our $emulate_aux = 1;
457 # Whether emulate_aux had to be switched on during a run:
458 our $emulate_aux_switched = 0;
459
460 #--------------------
461 # Specification of extensions/files that need special treatment,
462 # e.g., in cleanup or in analyzing missing dependent files.
463 #
464 # %input_extensions maps primary_rule_name to pointer to hash of file extensions
465 # used for extensionless files specified in the source file by constructs
466 # like \input{file} \includegraphics{file}
467 our %input_extensions = ();
468 set_input_ext( 'latex', 'tex', 'eps' );
469 set_input_ext( 'pdflatex', 'tex', 'jpg', 'pdf', 'png' );
470 $input_extensions{lualatex} = $input_extensions{pdflatex};
471 $input_extensions{xelatex} = $input_extensions{pdflatex};
472 # Save these values as standards to be used when switching output,
473 # i.e., when actual primary rule differs from standard.
474 our %standard_input_extensions = %input_extensions;
475
476 # Possible extensions for main output file of *latex:
477 our %allowed_output_ext = ( ".dvi" => 1, ".xdv" => 1, ".pdf" => 1 );
478
479 # Extensions etc, of special use by latexmk
480 our $save_error_suffix = '-SAVE-ERROR'; # Suffix to be added to filename, when an
481 # erroneous file is saved insted of being deleted.
482 our $fdb_ext = 'fdb_latexmk'; # Extension for the file for latexmk's
483 # file-database
484 # Make it long to avoid possible collisions.
485 our $fdb_ver = 4; # Version number for kind of fdb_file.
486
487
488 # Variables relevant to specifying cleanup.
489 # The first set of variables is intended to be user configurable.
490 #
491 # The @generated_exts array contains list of extensions (without
492 # period) for files that are generated by rules run by latexmk.
493 #
494 # Instead of an extension, an item in the array can be a string containing
495 # the placeholder %R for the root of the filenames. This is used for more
496 # general patterns. Such a pattern may contain wildcards (bsd_glob
497 # definitions).
498 #
499 # By default, it excludes "final output files" that
500 # are normally only deleted on a full cleanup, not a small cleanup.
501 # These files get two kinds of special treatment:
502 # 1. In clean up, where depending on the kind of clean up, some
503 # or all of these generated files are deleted.
504 # (Note that special treatment is given to aux files.)
505 # 2. In analyzing the results of a run of *LaTeX, to
506 # determine if another run is needed. With an error free run,
507 # a rerun should be provoked by a change in any source file,
508 # whether a user file or a generated file. But with a run
509 # that ends in an error, only a change in a user file during
510 # the run (which might correct the error) should provoke a
511 # rerun, but a change in a generated file should not.
512 # Also at the start of a round of processing, only user-file
513 # changes are relevant.
514 # Special cases for extensions aux and bbl
515 # aux files beyond the standard one are found by a special analysis
516 # bbl files get special treatment because their deletion is conditional
517 # and because of the possibility of extra bibtex/biber rules with
518 # non-standard basename.
519 our @generated_exts = ( 'aux', 'bcf', 'bcf'.$save_error_suffix, 'fls',
520 'idx', 'ind', 'lof', 'lot',
521 'out', 'run.xml', 'toc',
522 'blg', 'ilg', 'log',
523 'xdv'
524 );
525 # N.B. 'out' is generated by hyperref package
526 our $clean_ext = ""; # For backward compatibility: Space separated
527 # extensions to be added to @generated_exts after
528 # startup (and rc file reading).
529 # Extensions of files to be deleted by -C, but aren't normally included
530 # in the small clean up by -c. Analogous to @generated_exts and $clean_ext,
531 # except that pattern rules (with %R) aren't applied.
532 our @final_output_exts = ( 'dvi', 'dviF', 'hnt', 'ps', 'psF', 'pdf',
533 'synctex', 'synctex.gz' );
534 our $clean_full_ext = "";
535
536
537 # Set of extra specific files to be deleted in small cleanup. These are
538 # ones that get generated under some kinds of error conditions. All cases:
539 # Relative to current directory, and relative to aux and out directories.
540 our @std_small_cleanup_files = ( 'texput.log', "texput.aux", "missfont.log" );
541
542 #-------------------------
543
544 # Information about options to latex and pdflatex that latexmk will simply
545 # pass through to *latex
546 # Option without arg. maps to itself.
547 # Option with arg. maps the option part to the full specification
548 # e.g., -kpathsea-debug => -kpathsea-debug=NUMBER
549 our %allowed_latex_options = ();
550 our %allowed_latex_options_with_arg = ();
551 foreach (
552 #####
553 # TeXLive options
554 "-cnf-line=STRING parse STRING as a configuration file line",
555 "-draftmode switch on draft mode (generates no output PDF)",
556 "-enc enable encTeX extensions such as \\mubyte",
557 "-etex enable e-TeX extensions",
558 "-file-line-error enable file:line:error style messages",
559 "-no-file-line-error disable file:line:error style messages",
560 "-fmt=FMTNAME use FMTNAME instead of program name or a %& line",
561 "-halt-on-error stop processing at the first error",
562 "-interaction=STRING set interaction mode (STRING=batchmode/nonstopmode/\n".
563 " scrollmode/errorstopmode)",
564 "-ipc send DVI output to a socket as well as the usual\n".
565 " output file",
566 "-ipc-start as -ipc, and also start the server at the other end",
567 "-kpathsea-debug=NUMBER set path searching debugging flags according to\n".
568 " the bits of NUMBER",
569 "-mktex=FMT enable mktexFMT generation (FMT=tex/tfm/pk)",
570 "-no-mktex=FMT disable mktexFMT generation (FMT=tex/tfm/pk)",
571 "-mltex enable MLTeX extensions such as \charsubdef",
572 "-output-comment=STRING use STRING for DVI file comment instead of date\n".
573 " (no effect for PDF)",
574 "-parse-first-line enable parsing of first line of input file",
575 "-no-parse-first-line disable parsing of first line of input file",
576 "-progname=STRING set program (and fmt) name to STRING",
577 "-shell-escape enable \\write18{SHELL COMMAND}",
578 "-no-shell-escape disable \\write18{SHELL COMMAND}",
579 "-shell-restricted enable restricted \\write18",
580 "-src-specials insert source specials into the DVI file",
581 "-src-specials=WHERE insert source specials in certain places of\n".
582 " the DVI file. WHERE is a comma-separated value\n".
583 " list: cr display hbox math par parend vbox",
584 "-synctex=NUMBER generate SyncTeX data for previewers if nonzero",
585 "-translate-file=TCXNAME use the TCX file TCXNAME",
586 "-8bit make all characters printable by default",
587
588 #####
589 # MikTeX options not in TeXLive
590 "-alias=app pretend to be app",
591 "-buf-size=n maximum number of characters simultaneously present\n".
592 " in current lines",
593 "-c-style-errors C-style error messages",
594 "-disable-installer disable automatic installation of missing packages",
595 "-disable-pipes disable input (output) from (to) child processes",
596 "-disable-write18 disable the \\write18{command} construct",
597 "-dont-parse-first-line disable checking whether the first line of the main\n".
598 " input file starts with %&",
599 "-enable-enctex enable encTeX extensions such as \\mubyte",
600 "-enable-installer enable automatic installation of missing packages",
601 "-enable-mltex enable MLTeX extensions such as \charsubdef",
602 "-enable-pipes enable input (output) from (to) child processes",
603 "-enable-write18 fully enable the \\write18{command} construct",
604 "-error-line=n set the width of context lines on terminal error\n".
605 " messages",
606 "-extra-mem-bot=n set the extra size (in memory words) for large data\n".
607 " structures",
608 "-extra-mem-top=n set the extra size (in memory words) for chars,\n".
609 " tokens, et al",
610 "-font-max=n set the maximum internal font number",
611 "-font-mem-size=n set the size, in TeX memory words, of the font memory",
612 "-half-error-line=n set the width of first lines of contexts in terminal\n".
613 " error messages",
614 "-hash-extra=n set the extra space for the hash table of control\n".
615 " sequences",
616 "-job-time=file set the time-stamp of all output files equal to\n".
617 " file's time-stamp",
618 "-main-memory=n change the total size (in memory words) of the main\n".
619 " memory array",
620 "-max-in-open=n set the maximum number of input files and error\n".
621 " insertions that can be going on simultaneously",
622 "-max-print-line=n set the width of longest text lines output",
623 "-max-strings=n set the maximum number of strings",
624 "-nest-size=n set the maximum number of semantic levels\n".
625 " simultaneously active",
626 "-no-c-style-errors standard error messages",
627 "-param-size=n set the the maximum number of simultaneous macro\n".
628 " parameters",
629 "-pool-size=n set the maximum number of characters in strings",
630 "-record-package-usages=file record all package usages and write them into\n".
631 " file",
632 "-restrict-write18 partially enable the \\write18{command} construct",
633 "-save-size=n set the the amount of space for saving values\n".
634 " outside of current group",
635 "-stack-size=n set the maximum number of simultaneous input sources",
636 "-string-vacancies=n set the minimum number of characters that should be\n".
637 " available for the user's control sequences and font\n".
638 " names",
639 "-tcx=name process the TCX table name",
640 "-time-statistics show processing time statistics",
641 "-trace enable trace messages",
642 "-trace=tracestreams enable trace messages. The tracestreams argument is\n".
643 " a comma-separated list of trace stream names",
644 "-trie-size=n set the amount of space for hyphenation patterns",
645 "-undump=name use name as the name of the format to be used,\n".
646 " instead of the name by which the program was\n".
647 " called or a %& line.",
648
649 #####
650 # Options passed to *latex that have special processing by latexmk,
651 # so they are commented out here.
652 #-jobname=STRING set the job name to STRING
653 #-aux-directory=dir Set the directory dir to which auxiliary files are written
654 #-output-directory=DIR use existing DIR as the directory to write files in
655 # "-output-format=FORMAT use FORMAT for job output; FORMAT is `dvi\" or `pdf\"",
656 #-quiet
657 #-recorder enable filename recorder
658 #
659 # Options with different processing by latexmk than *latex
660 #-help
661 #-version
662 #
663 # Options NOT used by latexmk
664 #-includedirectory=dir prefix dir to the search path
665 #-initialize become the INI variant of the compiler
666 #-ini be pdfinitex, for dumping formats; this is implicitly
667 # true if the program name is `pdfinitex'
668 ) {
669 if ( /^([^\s=]+)=/ ) {
670 $allowed_latex_options_with_arg{$1} = $_;
671 }
672 elsif ( /^([^\s=]+)\s/ ) {
673 $allowed_latex_options{$1} = $_;
674 }
675 }
676
677 # Arrays of options that will be added to latex and pdflatex.
678 # These need to be stored until after the command line parsing is finished,
679 # in case the values of $latex and/or $pdflatex change after an option
680 # is added.
681 our @extra_dvilualatex_options = ();
682 our @extra_hilatex_options = ();
683 our @extra_latex_options = ();
684 our @extra_pdflatex_options = ();
685 our @extra_lualatex_options = ();
686 our @extra_xelatex_options = ();
687
688
689 ## Command to invoke biber & bibtex
690 our $biber = 'biber %O %S';
691 our $bibtex = 'bibtex %O %S';
692 # Switch(es) to make biber & bibtex silent:
693 our $biber_silent_switch = '--onlylog';
694 our $bibtex_silent_switch = '-terse';
695 our $bibtex_use = 1; # Whether to actually run bibtex to update bbl files.
696 # This variable is also used in deciding whether to
697 # delete bbl files in clean up operations.
698 # 0: Never run bibtex.
699 # Do NOT delete bbl files on clean up.
700 # 1: Run bibtex only if the bibfiles exists
701 # according to kpsewhich, and the bbl files
702 # appear to be out-of-date.
703 # Do NOT delete bbl files on clean up.
704 # 1.5: Run bibtex only if the bibfiles exists
705 # according to kpsewhich, and the bbl files
706 # appear to be out-of-date.
707 # Only delete bbl files on clean up if bibfiles exist.
708 # 2: Run bibtex when the bbl files are out-of-date
709 # Delete bbl files on clean up.
710 #
711 # In any event bibtex is only run if the log file
712 # indicates that the document uses bbl files.
713 our $bibtex_fudge = 1; # Whether or not to cd to aux dir when running bibtex.
714 # If the cd is not done, and bibtex is passed a
715 # filename with a path component, then it can easily
716 # happen that (a) bibtex refuses to write bbl and blg
717 # files to the aux directory, for security reasons,
718 # and/or (b) bibtex in pre-2019 versions fails to find
719 # some input file(s). But in some other cases, the cd
720 # method fails.
721
722 ## Command to invoke makeindex
723 our $makeindex = 'makeindex %O -o %D %S';
724 # Switch(es) to make makeinex silent:
725 our $makeindex_silent_switch = '-q';
726 our $makeindex_fudge = 1; # Whether or not to cd to aux dir when running makeindex.
727 # Set to 1 to avoid security-related prohibition on
728 # makeindex writing to aux_dir when it is not specified
729 # as a subdirectory of cwd.
730
731 ## Command to convert dvi file to pdf file directly.
732 # Use option -dALLOWPSTRANSPARENCY so that it works with documents
733 # using pstricks etc:
734 our $dvipdf = 'dvipdf -dALLOWPSTRANSPARENCY %O %S %D';
735 # N.B. Standard dvipdf runs dvips and gs with their silent switch, so for
736 # standard dvipdf $dvipdf_silent_switch is unneeded, but innocuous.
737 # But dvipdfmx can be used instead, and it has a silent switch (-q).
738 # So implementing $dvipdf_silent_switch is useful.
739 our $dvipdf_silent_switch = '-q';
740
741 ## Command to convert dvi file to ps file:
742 our $dvips = 'dvips %O -o %D %S';
743 ## Command to convert dvi file to ps file in landscape format:
744 our $dvips_landscape = 'dvips -tlandscape %O -o %D %S';
745 # Switch(es) to get dvips to make ps file suitable for conversion to good pdf:
746 # (If this is not used, ps file and hence pdf file contains bitmap fonts
747 # (type 3), which look horrible under acroread. An appropriate switch
748 # ensures type 1 fonts are generated. You can put this switch in the
749 # dvips command if you prefer.)
750 our $dvips_pdf_switch = '-P pdf';
751 # Switch(es) to make dvips silent:
752 our $dvips_silent_switch = '-q';
753
754 ## Command to convert ps file to pdf file.
755 # Use option -dALLOWPSTRANSPARENCY so that it works with documents
756 # using pstricks etc:
757 our $ps2pdf = 'ps2pdf -dALLOWPSTRANSPARENCY %O %S %D';
758
759 ## Command to convert xdv file to pdf file
760 our $xdvipdfmx = 'xdvipdfmx -E -o %D %O %S';
761 our $xdvipdfmx_silent_switch = '-q';
762
763
764 ## Command to search for tex-related files
765 our $kpsewhich = 'kpsewhich %S';
766
767 ## Command to run make:
768 our $make = 'make';
769
770 ##Printing:
771 our $print_type = 'auto'; # When printing, print the postscript file.
772 # Possible values: 'dvi', 'ps', 'pdf', 'auto', 'none'
773 # 'auto' ==> set print type according to the printable
774 # file(s) being made: priority 'ps', 'pdf', 'dvi'
775
776 # Viewers. These are system dependent, so default to none:
777 our ( $pdf_previewer, $ps_previewer, $ps_previewer_landscape, $dvi_previewer,
778 $dvi_previewer_landscape, $hnt_previewer );
779 $pdf_previewer = $ps_previewer = $ps_previewer_landscape = $dvi_previewer = $dvi_previewer_landscape = $hnt_previewer = "NONE";
780
781 our $dvi_update_signal = undef;
782 our $ps_update_signal = undef;
783 our $pdf_update_signal = undef;
784
785 our $dvi_update_command = undef;
786 our $ps_update_command = undef;
787 our $pdf_update_command = undef;
788 # Viewer update methods:
789 # 0 => auto update: viewer watches file (e.g., gv)
790 # 1 => manual update: user must do something: e.g., click on window.
791 # (e.g., ghostview, MSWIN previewers, acroread under UNIX)
792 # 2 => send signal. Number of signal in $dvi_update_signal,
793 # $ps_update_signal, $pdf_update_signal
794 # 3 => viewer can't update, because it locks the file and the file
795 # cannot be updated. (acroread under MSWIN)
796 # 4 => run a command to force the update. The commands are
797 # specified by the variables $dvi_update_command,
798 # $ps_update_command, $pdf_update_command
799 our $dvi_update_method = 1;
800 our $hnt_update_method = 1;
801 our $ps_update_method = 1;
802 our $pdf_update_method = 1;
803
804 # Whether to allow latexmk to create subdirectories of aux_dir when there's
805 # a report in the log file that *latex "can't write on file ...".
806 # Values: 0: no subdir creation,
807 # 1: only for aux files (occurs with \include{chapters/chap} etc
808 # 2: generally
809 our $allow_subdir_creation = 1;
810
811 our $new_viewer_always = 0; # If 1, always open a new viewer in pvc mode.
812 # If 0, only open a new viewer if no previous
813 # viewer for the same file is detected.
814
815 # Commands for use in pvc mode for compiling, success, warnings, and failure;
816 # they default to empty, i.e., not to use:
817 our ($compiling_cmd, $success_cmd, $warning_cmd, $failure_cmd) =
818 ( '', '', '', '' );
819
820 # Commands for printing are highly system dependent, so default to NONE:
821 our $lpr = 'NONE $lpr variable is not configured to allow printing of ps files';
822 our $lpr_dvi = 'NONE $lpr_dvi variable is not configured to allow printing of dvi files';
823 our $lpr_pdf = 'NONE $lpr_pdf variable is not configured to allow printing of pdf files';
824
825
826 # The $pscmd below holds a **system-dependent** command to list running
827 # processes. It is used to find the process ID of the viewer looking at
828 # the current output file. The output of the command must include the
829 # process number and the command line of the processes, since the
830 # relevant process is identified by the name of file to be viewed.
831 # Its use is not essential.
832 our $pscmd = 'NONE $pscmd variable is not configured to detect running processes';
833 our $pid_position = -1; # offset of PID in output of pscmd.
834 # Negative means I cannot use ps
835
836
837 our $quote_filenames = 1; # Quote filenames in external commands
838
839 our $del_dir = ''; # Directory into which cleaned up files are to be put.
840 # If $del_dir is '', just delete the files in a clean up.
841
842 our @rc_system_files = ();
843
844 #########################################################################
845
846 ################################################################
847 ## Special variables for system-dependent fudges, etc.
848 # ???????? !!!!!!!!!!
849 our $log_file_binary = 0; # Whether to treat log file as binary
850 # Normally not, since the log file SHOULD be pure text.
851 # But Miktex 2.7 sometimes puts binary characters
852 # in it. (Typically in construct \OML ... after
853 # overfull box with mathmode.)
854 # Sometimes there is ctrl/Z, which is not only non-text,
855 # but is end-of-file marker for MS-Win in text mode.
856
857 our $MSWin_fudge_break = 1; # Give special treatment to ctrl/C and ctrl/break
858 # in -pvc mode under MSWin
859 # Under MSWin32 (at least with perl 5.8 and WinXP)
860 # when latexmk is running another program, and the
861 # user gives ctrl/C or ctrl/break, to stop the
862 # daughter program, not only does it reach
863 # the daughter, but also latexmk/perl, so
864 # latexmk is stopped also. In -pvc mode,
865 # this is not normally desired. So when the
866 # $MSWin_fudge_break variable is set,
867 # latexmk arranges to ignore ctrl/C and
868 # ctrl/break during processing of files;
869 # only the daughter programs receive them.
870 # This fudge is not applied in other
871 # situations, since then having latexmk also
872 # stopping because of the ctrl/C or
873 # ctrl/break signal is desirable.
874 # The fudge is not needed under UNIX (at least
875 # with Perl 5.005 on Solaris 8). Only the
876 # daughter programs receive the signal. In
877 # fact the inverse would be useful: In
878 # normal processing, as opposed to -pvc, if
879 # force mode (-f) is set, a ctrl/C is
880 # received by a daughter program does not
881 # also stop latexmk. Under tcsh, we get
882 # back to a command prompt, while latexmk
883 # keeps running in the background!
884
885 ## Substitute backslashes in file and directory names for
886 ## MSWin command line
887 our $MSWin_back_slash = 0;
888
889 ## Separator of elements in search_path. Default is unix value
890 our $search_path_separator = ':';
891
892
893 # Directory for temporary files. Default to current directory.
894 our $tmpdir = ".";
895
896
897 # Latexmk does tests on whether a particular generated file, e.g., log or
898 # fls, has been generated on a current run of a rule, especially *latex, or
899 # is leftover from previous runs. An expected file can fail to be
900 # generated or generated in other than the expected place because of errors
901 # or because of misconfiguration of latexmk. There are also files (notably
902 # bcf files) that are generated or not according to the current set of
903 # packages, options, etc used by a document.
904 #
905 # The test for whether a file was generated on the current run of a rule is
906 # that the modification time of the file is at least as recent as the
907 # system time at the start of the run. A file with a modification time
908 # significantly less than the time at the start of the run is presumably
909 # left over from a previous run and not generated in the currrent run. (An
910 # allowance is made in this comparison for the effects of granularity of
911 # file-system times. Such granularity can make a file time a second or two
912 # earlier than the system time at which the file was last modified.)
913 #
914 # But generated files may be on a file system hosted by a server computer
915 # that is different than the computer running latexmk. There may be an
916 # offset between the time on the two computers; this can make it
917 # incorrectly appear that the generated files were made before the
918 # run. Most of the time, this problem does not arise, since (a) typical
919 # usage of latexmk is with a local file system, and (b) current-day
920 # computers and operating systems have their time synchronized accurately
921 # with a time server. Difficulties are most acute with small documents
922 # compiled on a fast computer, e.g., with sub-second compilation times.
923 #
924 # When latexmk sees symptoms of an excessive offset, it measures the offset
925 # between the filesystem time and the system time. This involves writing a
926 # temporary file, getting its modification time, and deleting it. Then
927 # when testing for whether a file was made on the current run or not, an
928 # allowance is then made for the measured time offset between the two
929 # computers.
930 #
931 # Note that typically an invocation of latexmk's processing of a document
932 # occurs after some human action, e.g., editting a document or a
933 # configuration file. So a file that is left over from a previous run and
934 # not overwritten on the current run will have a file time at least many
935 # seconds less than the current time, corresponding to the time scale for a
936 # human run-edit-run cycle. So one does NOT have to particularly precise
937 # about time differences.
938 #
939 # Granularity of file system etc:
940 # FAT file system: 2 sec granularity. Others 1 sec or often much less.
941 #
942 # Functions available to latexmk from Perl:
943 # mtime from Perl's CORE::stat: 1 sec, but 2 sec on FAT file system;
944 # mtime from Time_HiRes::stat: can be much less than 1 sec, if the
945 # combination of Perl, the OS and the file system support it.
946 # system time from CORE::time(): 1 sec;
947 # system time from Time::HiRes::time(): Much less than 1 sec.
948
949 # Variables controlling the assessment of time offset between file system
950 # and computer:
951
952 our $filetime_causality_threshold = 5;
953 # This is the size of time differences below which latexmk doesn't
954 # worry. It allows for (a) different granularity between system time
955 # and filesystem time, (b) for a modest mismatch between file and system
956 # time. This allowance can be generous; it merely needs to be below the
957 # human time-scale for editing documents, reconfiguring (or
958 # misconfiguring) latexmk, etc.
959
960 our $filetime_offset_measured = 0; # Measurement not yet done.
961 our $filetime_offset = 0; # Filetime relative to system time.
962 # Assume zero to start (corresponding to
963 # local file system).
964 # Will be updated if necessary.
965 our $filetime_offset_report_threshold = 10; # Threshold beyond which filetime offsets
966 # are reported at end of run; large
967 # offsets indicate incorrect system
968 # time on at least one system.
969
970
971
972 ################################################################
973 ################################################################
974
975
976 # System-dependent overrides:
977 # Currently, the cases I have tests for are: MSWin32, cygwin, linux and
978 # darwin, msys, with the main complications being for MSWin32 and cygwin.
979 # Further special treatment may also be useful for MSYS (for which $^O reports
980 # "msys"). This is another *nix-emulation/system for MSWindows. At
981 # present it is treated as unix-like, but the environment variables
982 # are those of Windows. (The test for USERNAME as well as USER was
983 # to make latexmk work under MSYS's perl.)
984 #
985 our $start_NT = 'NONE';
986 if ( $^O eq "MSWin32" ) {
987 # Pure MSWindows configuration
988
989 ## Configuration parameters:
990
991 ## Use first existing case for $tmpdir:
992 $tmpdir = $ENV{TMPDIR} || $ENV{TEMP} || '.';
993 $log_file_binary = 1; # Protect against ctrl/Z in log file from
994 # Miktex 2.7.
995
996 ## List of possibilities for the system-wide initialization file.
997 ## The first one found (if any) is used.
998 @rc_system_files = ( "C:/latexmk/LatexMk", "C:/latexmk/latexmkrc" );
999
1000 $search_path_separator = ';'; # Separator of elements in search_path
1001
1002 # For a pdf-file, "start x.pdf" starts the pdf viewer associated with
1003 # pdf files, so no program name is needed:
1004 $pdf_previewer = 'start %O %S';
1005 $ps_previewer = 'start %O %S';
1006 $ps_previewer_landscape = $ps_previewer;
1007 $dvi_previewer = 'start %O %S';
1008 $dvi_previewer_landscape = "$dvi_previewer";
1009 $hnt_previewer = 'start %O %S';
1010 $pdf_update_method = 3; # acroread locks the pdf file
1011 }
1012 elsif ( $^O eq "cygwin" ) {
1013 # The problem is a mixed MSWin32 and UNIX environment.
1014 # Perl decides the OS is cygwin in two situations:
1015 # 1. When latexmk is run from a cygwin shell under a cygwin
1016 # environment. Perl behaves in a UNIX way. This is OK, since
1017 # the user is presumably expecting UNIXy behavior.
1018 # 2. When CYGWIN exectuables are in the path, but latexmk is run
1019 # from a native NT shell. Presumably the user is expecting NT
1020 # behavior. But perl behaves more UNIXy. This causes some
1021 # clashes.
1022 # The issues to handle are:
1023 # 1. Perl sees both MSWin32 and cygwin filenames. This is
1024 # normally only an advantage.
1025 # 2. Perl uses a UNIX shell in the system command
1026 # This is a nasty problem: under native NT, there is a
1027 # start command that knows about NT file associations, so that
1028 # we can do, e.g., (under native NT) system("start file.pdf");
1029 # But this won't work when perl has decided the OS is cygwin,
1030 # even if it is invoked from a native NT command line. An
1031 # NT command processor must be used to deal with this.
1032 # 3. External executables can be native NT (which only know
1033 # NT-style file names) or cygwin executables (which normally
1034 # know both cygwin UNIX-style file names and NT file names,
1035 # but not always; some do not know about drive names, for
1036 # example).
1037 # Cygwin executables for tex and latex may only know cygwin
1038 # filenames.
1039 # 4. The BIBINPUTS environment variables may be
1040 # UNIX-style or MSWin-style depending on whether native NT or
1041 # cygwin executables are used. They are therefore parsed
1042 # differently. Here is the clash:
1043 # a. If a user is running under an NT shell, is using a
1044 # native NT installation of tex (e.g., fptex or miktex),
1045 # but has the cygwin executables in the path, then perl
1046 # detects the OS as cygwin, but the user needs NT
1047 # behavior from latexmk.
1048 # b. If a user is running under an UNIX shell in a cygwin
1049 # environment, and is using the cygwin installation of
1050 # tex, then perl detects the OS as cygwin, and the user
1051 # needs UNIX behavior from latexmk.
1052 # Latexmk has no way of detecting the difference. The two
1053 # situations may even arise for the same user on the same
1054 # computer simply by changing the order of directories in the
1055 # path environment variable
1056
1057
1058 ## Configuration parameters: We'll assume native NT executables.
1059 ## The user should override if they are not.
1060
1061 # This may fail: perl converts MSWin temp directory name to cygwin
1062 # format. Names containing this string cannot be handled by native
1063 # NT executables.
1064 $tmpdir = $ENV{TMPDIR} || $ENV{TEMP} || '.';
1065
1066 ## List of possibilities for the system-wide initialization file.
1067 ## The first one found (if any) is used.
1068 ## We could stay with MSWin files here, since cygwin perl understands them
1069 ## @rc_system_files = ( 'C:/latexmk/LatexMk', 'C:/latexmk/latexmkrc' );
1070 ## But they are deprecated in v. 1.7. So use the UNIX version, prefixed
1071 ## with a cygwin equivalent of the MSWin location
1072 ## In addition, we need to add the same set of possible locations as with
1073 ## unix, so that the user use a unix-style setup.
1074 @rc_system_files = ();
1075 foreach ( 'LatexMk', 'latexmkrc' ) {
1076 push @rc_system_files,
1077 ( "/cygdrive/c/latexmk/$_",
1078 "/etc/$_",
1079 "/opt/local/share/latexmk/$_",
1080 "/usr/local/share/latexmk/$_",
1081 "/usr/local/lib/latexmk/$_" );
1082 }
1083 $search_path_separator = ';'; # Separator of elements in search_path
1084 # This is tricky. The search_path_separator depends on the kind
1085 # of executable: native NT v. cygwin.
1086 # So the user will have to override this.
1087
1088 # We will assume that files can be viewed by native NT programs.
1089 # Then we must fix the start command/directive, so that the
1090 # NT-native start command of a cmd.exe is used.
1091 # For a pdf-file, "start x.pdf" starts the pdf viewer associated with
1092 # pdf files, so no program name is needed:
1093 $start_NT = "cmd /c start \"\"";
1094 $pdf_previewer = "$start_NT %O %S";
1095 $ps_previewer = "$start_NT %O %S";
1096 $ps_previewer_landscape = $ps_previewer;
1097 $dvi_previewer = "$start_NT %O %S";
1098 $dvi_previewer_landscape = $dvi_previewer;
1099 $hnt_previewer = "$start_NT %O %S";
1100 # Viewer update methods:
1101 # 0 => auto update: viewer watches file (e.g., gv)
1102 # 1 => manual update: user must do something: e.g., click on window.
1103 # (e.g., ghostview, MSWIN previewers, acroread under UNIX)
1104 # 2 => send signal. Number of signal in $dvi_update_signal,
1105 # $ps_update_signal, $pdf_update_signal
1106 # 3 => viewer can't update, because it locks the file and the file
1107 # cannot be updated. (acroread under MSWIN)
1108 $pdf_update_method = 3; # acroread locks the pdf file
1109 }
1110 elsif ( $^O eq "msys" ) {
1111 $search_path_separator = ';'; # Separator of elements in search_path
1112 # I think MS-Win value is OK, since
1113 # msys is running under MS-Win
1114 $pdf_previewer = q[sh -c 'start %S'];
1115 $ps_previewer = q[sh -c 'start %S'];
1116 $dvi_previewer = q[sh -c 'start %S'];
1117 $hnt_previewer = q[sh -c 'start %S'];
1118 $ps_previewer_landscape = $ps_previewer;
1119 $dvi_previewer_landscape = "$dvi_previewer";
1120 }
1121 else {
1122 # Assume anything else is UNIX or clone
1123 # Do special cases (e.g., linux, darwin (i.e., OS-X)) inside this block.
1124
1125 ## Use first existing case for $tmpdir:
1126 $tmpdir = $ENV{TMPDIR} || '/tmp';
1127
1128 ## List of possibilities for the system-wide initialization file.
1129 ## The first one found (if any) is used.
1130 @rc_system_files = ();
1131 foreach ( 'LatexMk', 'latexmkrc' ) {
1132 push @rc_system_files,
1133 ( "/etc/$_",
1134 "/opt/local/share/latexmk/$_",
1135 "/usr/local/share/latexmk/$_",
1136 "/usr/local/lib/latexmk/$_" );
1137 }
1138 $search_path_separator = ':'; # Separator of elements in search_path
1139
1140 $dvi_update_signal = $signo{USR1}
1141 if ( defined $signo{USR1} ); # Suitable for xdvi
1142 $ps_update_signal = $signo{HUP}
1143 if ( defined $signo{HUP} ); # Suitable for gv
1144 $pdf_update_signal = $signo{HUP}
1145 if ( defined $signo{HUP} ); # Suitable for gv
1146 ## default document processing programs.
1147 # Viewer update methods:
1148 # 0 => auto update: viewer watches file (e.g., gv)
1149 # 1 => manual update: user must do something: e.g., click on window.
1150 # (e.g., ghostview, MSWIN previewers, acroread under UNIX)
1151 # 2 => send signal. Number of signal in $dvi_update_signal,
1152 # $ps_update_signal, $pdf_update_signal
1153 # 3 => viewer can't update, because it locks the file and the file
1154 # cannot be updated. (acroread under MSWIN)
1155 # 4 => Run command to update. Command in $dvi_update_command,
1156 # $ps_update_command, $pdf_update_command.
1157 $dvi_previewer = 'start xdvi %O %S';
1158 $dvi_previewer_landscape = 'start xdvi -paper usr %O %S';
1159 if ( defined $dvi_update_signal ) {
1160 $dvi_update_method = 2; # xdvi responds to signal to update
1161 } else {
1162 $dvi_update_method = 1;
1163 }
1164 # if ( defined $ps_update_signal ) {
1165 # $ps_update_method = 2; # gv responds to signal to update
1166 # $ps_previewer = 'start gv -nowatch';
1167 # $ps_previewer_landscape = 'start gv -swap -nowatch';
1168 # } else {
1169 # $ps_update_method = 0; # gv -watch watches the ps file
1170 # $ps_previewer = 'start gv -watch';
1171 # $ps_previewer_landscape = 'start gv -swap -watch';
1172 # }
1173 # Turn off the fancy options for gv. Regular gv likes -watch etc
1174 # GNU gv likes --watch etc. User must configure
1175 $ps_update_method = 0; # gv -watch watches the ps file
1176 $ps_previewer = 'start gv %O %S';
1177 $ps_previewer_landscape = 'start gv -swap %O %S';
1178 $pdf_previewer = 'start acroread %O %S';
1179 $pdf_update_method = 1; # acroread under unix needs manual update
1180 $lpr = 'lpr %O %S'; # Assume lpr command prints postscript files correctly
1181 $lpr_dvi =
1182 'NONE $lpr_dvi variable is not configured to allow printing of dvi files';
1183 $lpr_pdf =
1184 'NONE $lpr_pdf variable is not configured to allow printing of pdf files';
1185 # The $pscmd below holds a command to list running processes. It
1186 # is used to find the process ID of the viewer looking at the
1187 # current output file. The output of the command must include the
1188 # process number and the command line of the processes, since the
1189 # relevant process is identified by the name of file to be viewed.
1190 # Uses:
1191 # 1. In preview_continuous mode, to save running a previewer
1192 # when one is already running on the relevant file.
1193 # 2. With xdvi in preview_continuous mode, xdvi must be
1194 # signalled to make it read a new dvi file.
1195 #
1196 # The following works on Solaris, LINUX, HP-UX, IRIX
1197 # Use -f to get full listing, including command line arguments.
1198 # Use -u $ENV{USER} to get all processes started by current user (not just
1199 # those associated with current terminal), but none of other users'
1200 # processes.
1201 # However, the USER environment variable may not exist. Windows uses
1202 # USERNAME instead. (And this propagates to a situation of
1203 # unix-emulation software running under Windows.)
1204 if ( exists $ENV{USER} ) {
1205 $pscmd = "ps -f -u $ENV{USER}";
1206 }
1207 elsif ( exists $ENV{USERNAME} ) {
1208 $pscmd = "ps -f -u $ENV{USERNAME}";
1209 }
1210 else {
1211 $pscmd = "ps -f";
1212 }
1213 $pid_position = 1; # offset of PID in output of pscmd; first item is 0.
1214 if ( $^O eq "linux" ) {
1215 # Ps on Redhat (at least v. 7.2) appears to truncate its output
1216 # at 80 cols, so that a long command string is truncated.
1217 # Fix this with the --width option. This option works under
1218 # other versions of linux even if not necessary (at least
1219 # for SUSE 7.2).
1220 # However the option is not available under other UNIX-type
1221 # systems, e.g., Solaris 8.
1222 # But (19 Aug 2010), the truncation doesn't happen on RHEL4 and 5,
1223 # unless the output is written to a terminal. So the --width
1224 # option is now unnecessary
1225 # $pscmd = "ps --width 200 -f -u $ENV{USER}";
1226 }
1227 elsif ( $^O eq "darwin" ) {
1228 # OS-X on Macintosh
1229 # open starts command associated with a file.
1230 # For pdf, this is set by default to OS-X's preview, which is suitable.
1231 # Manual update is simply by clicking on window etc, which is OK.
1232 # For ps, this is set also to preview. This works, but since it
1233 # converts the file to pdf and views the pdf file, it doesn't
1234 # see updates, and a refresh cannot be done. This is far from
1235 # optimal.
1236 # For a full installation of MacTeX, which is probably the most common
1237 # on OS-X, an association is created between dvi files and TeXShop.
1238 # This also converts the file to pdf, so again while it works, it
1239 # does not deal with changed dvi files, as far as I can see.
1240 $pdf_previewer = 'open %S';
1241 $pdf_update_method = 1; # manual
1242 $hnt_previewer = 'open %S';
1243 $hnt_update_method = 1; # manual
1244 $dvi_previewer = $dvi_previewer_landscape = 'NONE';
1245 $ps_previewer = $ps_previewer_landscape = 'NONE';
1246 # Others
1247 $lpr_pdf = 'lpr %O %S';
1248 $pscmd = "ps -ww -u $ENV{USER}";
1249 }
1250 }
1251
1252 ## default parameters
1253 our $auto_rc_use = 1; # Whether to read rc files automatically
1254 our $user_deleted_file_treated_as_changed = 0; # Whether when testing for changed
1255 # files, a user file that changes status from existing
1256 # to non-existing should be regarded as changed.
1257 # Value 1: only in non-preview-continuous mode.
1258 # Value 2: always.
1259 # Primary purpose is to cover cases where behavior of
1260 # compilation of .tex file tests for file existence and
1261 # adjusts behavior accordingly, instead of simply giving an
1262 # error.
1263 our $max_repeat = 5; # Maximum times I repeat latex. Normally
1264 # 3 would be sufficient: 1st run generates aux file,
1265 # 2nd run picks up aux file, and maybe toc, lof which
1266 # contain out-of-date information, e.g., wrong page
1267 # references in toc, lof and index, and unresolved
1268 # references in the middle of lines. But the
1269 # formatting is more-or-less correct. On the 3rd
1270 # run, the page refs etc in toc, lof, etc are about
1271 # correct, but some slight formatting changes may
1272 # occur, which mess up page numbers in the toc and lof,
1273 # Hence a 4th run is conceivably necessary.
1274 # At least one document class (JHEP.cls) works
1275 # in such a way that a 4th run is needed.
1276 # We allow an extra run for safety for a
1277 # maximum of 5. Needing further runs is
1278 # usually an indication of a problem; further
1279 # runs may not resolve the problem, and
1280 # instead could cause an infinite loop.
1281 our @cus_dep_list = (); # Custom dependency list
1282 our @default_files = ( '*.tex' ); # Array of LaTeX files to process when
1283 # no files are specified on the command line.
1284 # Wildcards allowed
1285 # Best used for project specific files.
1286 our @default_excluded_files = ( );
1287 # Array of LaTeX files to exclude when using
1288 # @default_files, i.e., when no files are specified
1289 # on the command line.
1290 # Wildcards allowed
1291 # Best used for project specific files.
1292 our $texfile_search = ""; # Specification for extra files to search for
1293 # when no files are specified on the command line
1294 # and the @default_files variable is empty.
1295 # Space separated, and wildcards allowed.
1296 # These files are IN ADDITION to *.tex in current
1297 # directory.
1298 # This variable is obsolete, and only in here for
1299 # backward compatibility.
1300
1301 our $jobname = ''; # Jobname: as with current tex, etc indicates
1302 # basename of generated files. Defined so
1303 # that --jobname=STRING on latexmk's command
1304 # line has same effect as with current tex,
1305 # etc, with the exception listed below. (If
1306 # $jobname is non-empty, then the
1307 # --jobname=... option is used on tex.)
1308 # Extension: $jobname is allowed to contain
1309 # placeholder(s) (currently only %A),
1310 # which allows construction of jobnames
1311 # dependent on name of main TeX file; this is
1312 # useful when a jobname is used and latexmk is
1313 # invoked on multiple files.
1314 our $out2_dir = ''; # Directory for final output files.
1315 our $out_dir = ''; # Directory for output files.
1316 # Cf. --output-directory of current *latex
1317 # Blank means default, i.e., cwd.
1318 our $aux_dir = ''; # Directory for aux files (log, aux, etc).
1319 # Cf. --aux-directory of current *latex in MiKTeX.
1320 # Blank means default, i.e., same as $out_dir.
1321 # Note that these values get modified when
1322 # processing a .tex file.
1323 # Corresponding forms that can be concatenated (e.g., when $aux_dir is '.', $aux_dir1 is './').
1324 our $aux_dir1 = '';
1325 our $out_dir1 = '';
1326 our $out2_dir1 = '';
1327
1328 # Use the following for saving original values, before directories are normalized.
1329 our ( $aux_dir_requested, $out_dir_requested, $out2_dir_requested );
1330
1331
1332
1333 # Extensions for files to be copied to $out2_dir.
1334 # Specify as for @generated_exts: I.e., extension w/o period
1335 # or string including %R to be substituted by basename.
1336 our @out2_exts = ( 'hnt', 'pdf', 'ps', 'synctex', 'synctex.gz' );
1337
1338 ## default flag settings.
1339 our $recorder = 1; # Whether to use recorder option on latex/pdflatex
1340 our $silent = 0; # Whether fo silence latex's messages (and others)
1341 our $warnings_as_errors = 0;# Treat warnings as errors and exit with non-zero exit code
1342 our $silence_logfile_warnings = 0; # Do list warnings in log file
1343 # The warnings reported are those about undefined refs
1344 # and citations, and the like.
1345 our $max_logfile_warnings = 7; # Max. # number of log file warnings to report
1346 our $rc_report = 1; # Whether to report on rc files read
1347 our $aux_out_dir_report = 0; # Whether to report on aux_dir & out_dir after
1348 # initialization and normalization.
1349 # When $aux_out_dir_report is set to 2, latexmk
1350 # does no further processing after the report of
1351 # the aux and out directories.
1352 our $report_cwd_mismatch = 0; # Whether to report mismatch of name of cwd
1353 # between report by .fls and from Perl.
1354
1355 our $kpsewhich_show = 0; # Show calls to and results from kpsewhich
1356 our $analyze_input_log_always = 1; # Always analyze .log for input files in the
1357 # <...> and (...) constructions. Otherwise, only
1358 # do the analysis when fls file doesn't exist or is
1359 # out of date.
1360 # Under normal circumstances, the data in the fls file
1361 # is reliable, and the test of the log file gets lots
1362 # of false positives; usually $analyze_input_log_always
1363 # is best set to zero. But the test of the log file
1364 # is needed at least in the following situation:
1365 # When a user needs to persuade latexmk that a certain
1366 # file is a source file, and latexmk doesn't otherwise
1367 # find it. User code causes line with (...) to be
1368 # written to log file. One important case is for
1369 # lualatex, which doesn't always generate lines in the
1370 # .fls file for input lua files. (The situation with
1371 # lualatex is HIGHLY version dependent, e.g., between
1372 # 2016 and 2017.)
1373 # To keep backward compatibility with older versions
1374 # of latexmk, the default is to set
1375 # $analyze_input_log_always to 1.
1376 our $fls_uses_out_dir = 0; # Whether fls file is to be in out directory (as with
1377 # pre-Oct-2020 MiKTeX), or in aux directory (as with
1378 # newer versions of MiKTeX).
1379 # If the implementation of *latex puts the fls file in
1380 # the other directory, I will copy it to the directory
1381 # I am configured to use.
1382
1383
1384 # Which kinds of file do I have requests to make?
1385 our ($dvi_mode, $hnt_mode, $pdf_mode, $postscript_mode, $xdv_mode,
1386 $landscape_mode );
1387 # If no requests at all are made, then I will make dvi file
1388 # If particular requests are made then other files may also have to be
1389 # made. E.g., ps file requires a dvi file
1390 $dvi_mode = 0; # No dvi file requested.
1391 # Possible values:
1392 # 0: no request for dvi file
1393 # 1: use latex to make dvi file
1394 # 2: use dvilualatex to make dvi file
1395 $hnt_mode = 0; # No hnt file requested
1396 $postscript_mode = 0; # No postscript file requested
1397 $pdf_mode = 0; # No pdf file requested to be made by pdflatex
1398 # Possible values:
1399 # 0 don't create pdf file
1400 # 1 to create pdf file by pdflatex
1401 # 2 to create pdf file by compile-to-dvi+dvips+ps2pdf
1402 # 3 to create pdf file by compile-to-dvi+dvipdf
1403 # 4 to create pdf file by lualatex
1404 # 5 to create pdf file by xelatex + xdvipdfmx
1405 $xdv_mode = 0; # No xdv file requested
1406 $landscape_mode = 0; # default to portrait mode
1407
1408 our $view = 'default'; # Default preview is of highest of dvi, ps, pdf
1409 our $min_sleep_time = 0.01; # Minimum non-zero sleep time
1410 our $sleep_time = 2; # time to sleep b/w checks for file changes in -pvc mode
1411
1412 # The following banner variables are no longer used by latexmk itself
1413 # (since v. 3.21) . They are left here for backward compatibility, in
1414 # case any user configurations use them.
1415 our $banner = 0; # Non-zero if we have a banner to insert
1416 our $banner_scale = 220; # Original default scale
1417 our $banner_intensity = 0.95; # Darkness of the banner message
1418 our $banner_message = 'DRAFT'; # Original default message
1419
1420 our $do_cd = 0; # Do not do cd to directory of source file.
1421 # Thus behave like latex.
1422 our $dependents_list = 0; # Whether to display list(s) of dependencies
1423 our $dependents_phony = 0; # Whether list(s) of dependencies includes phony targets
1424 # (as with 'gcc -MP').
1425 our $deps_file = '-'; # File for dependency list output. Default stdout.
1426 our $rules_list = 0; # Whether to display list(s) of dependencies
1427 # Kind of escaping in names of files written to deps file.
1428 our $deps_escape = 'none';
1429 # Allowed kinds of escape:
1430 our %deps_escape_kinds = ( 'none' => ' ', 'unix' => '\ ', 'nmake' => '^ ');
1431
1432 our @dir_stack = (); # Stack of pushed directories, each of form of
1433 # pointer to array [ cwd, good_cwd ], where
1434 # good_cwd differs from cwd by being converted
1435 # to native MSWin path when cygwin is used.
1436 our $cleanup_mode = 0; # No cleanup of nonessential LaTex-related files.
1437 # $cleanup_mode = 0: no cleanup
1438 # $cleanup_mode = 1: full cleanup
1439 # $cleanup_mode = 2: cleanup except for dvi,
1440 # dviF, pdf, ps, psF & xdv
1441 our $cleanup_fdb = 0; # On normal run, no removal of file for latexmk's file-database
1442 our $cleanup_only = 0; # When doing cleanup, do not go on to making files
1443 our $cleanup_includes_generated = 0;
1444 # Determines whether cleanup deletes files generated by
1445 # *latex (found from \openout lines in log file).
1446 # It's more than that. BUG
1447 our $cleanup_includes_cusdep_generated = 0;
1448 # Determines whether cleanup deletes files generated by
1449 # custom dependencies
1450 our $diagnostics = 0;
1451 our $dvi_filter = ''; # DVI filter command
1452 our $ps_filter = ''; # Postscript filter command
1453
1454 our $force_mode = 0; # =1: to force processing past errors
1455 our $go_mode = 0; # =1: to force processing regardless of time-stamps
1456 # =2: full clean-up first
1457 # =3: Just force primary rule(s) to run
1458 our $preview_mode = 0;
1459 our $preview_continuous_mode = 0;
1460 our $printout_mode = 0; # Don't print the file
1461
1462 ## Control pvc inactivity timeout:
1463 our $pvc_timeout = 0;
1464 our $pvc_timeout_mins = 30;
1465
1466 # Timing information
1467 # Whether to report processing time:
1468 our $show_time = 0;
1469
1470 # Whether times computed are clock times (HiRes) since Epoch, or are
1471 # processing times for this process and child processes, as reported by
1472 # times(). Second is the best, if accurate. But on MSWin32, times()
1473 # appears not to include subprocess times, so we use clock time instead.
1474 our $times_are_clock = ($^O eq "MSWin32" ? 1 : 0);
1475
1476
1477 # Data for 1 run and global (ending in '0'):
1478 our ( $clock1, $processing_time1, $processing_time0, @timings1, @timings0);
1479 &init_timing_all;
1480
1481
1482 our $use_make_for_missing_files = 0; # Whether to use make to try to make missing files.
1483
1484 # Do we make view file in temporary then move to final destination?
1485 # (To avoid premature updating by viewer).
1486 our $always_view_file_via_temporary = 0; # Set to 1 if viewed file is always
1487 # made through a temporary.
1488 our $pvc_view_file_via_temporary = 1; # Set to 1 if only in -pvc mode is viewed
1489 # file made through a temporary.
1490
1491 # State variables initialized here:
1492
1493 our $updated = 0; # Flags whether something has been remade in this round
1494 # of compilation.
1495 our $failure = 0; # Set nonzero to indicate failure at some point of
1496 # a make. Use value as exit code if I exit.
1497 our $failure_msg = ''; # Indicate reason for failure
1498 our $waiting = 0; # Flags whether we are in loop waiting for an event
1499 # Used to avoid unnecessary repeated o/p in wait loop
1500
1501 # The following are used for some results of parsing log file
1502 # Global variables, so results can be reported in main program.
1503 our $reference_changed = 0;
1504 our $mult_defined = 0;
1505 our $bad_reference = 0;
1506 our $bad_character = 0;
1507 our $bad_citation = 0;
1508 our @primary_warning_summary = ();
1509
1510 # Cache of expensive-to-compute state variables, e.g., cwd in form
1511 # fixed to deal with cygwin issues.
1512 our %cache = ();
1513 &cache_good_cwd;
1514
1515 # Set search paths for includes.
1516 # Set them early so that they can be overridden
1517 our $BIBINPUTS = $ENV{'BIBINPUTS'};
1518 if (!$BIBINPUTS) { $BIBINPUTS = '.'; }
1519
1520 # ???!!!
1521 # Old configuration variable @BIBINPUTS to be equivalent to environment
1522 # variable BIBINPUTS. It was to be easier to work with inside latexmk. But
1523 # under present conditions, it's better to manipulate $ENV{BIBINPUTS}.
1524 # ??? Need to explain better.
1525 # Why only for BIBINPUTS, not TEXINPUTS.
1526 #
1527 # But retain @BIBINPUTS for backward compatibility, since users may have
1528 # configured it. We'll save the values, allow for possible user changes in
1529 # @BIBINPUTS or $ENV{BIBINPUTS} in rc files and from command line
1530 # arguments. Then funnel changes back to $ENV{BIBINPUTS}, ...
1531 #
1532 # Convert search paths to arrays:
1533 # If any of the paths end in '//' then recursively search the
1534 # directory. After these operations, @BIBINPUTS should
1535 # have all the directories that need to be searched
1536 #
1537 our @BIBINPUTS = find_dirs1( $BIBINPUTS );
1538 our @BIBINPUTS_SAVE = @BIBINPUTS;
1539 our $BIBINPUTS_ENV_SAVE = $ENV{BIBINPUTS};
1540
1541
1542 ######################################################################
1543 ######################################################################
1544 #
1545 # ??? UPDATE THE FOLLOWING!!
1546 #
1547 # We will need to determine whether source files for runs of various
1548 # programs are out of date. In a normal situation, this is done by
1549 # asking whether the times of the source files are later than the
1550 # destination files. But this won't work for us, since a common
1551 # situation is that a file is written on one run of latex, for
1552 # example, and read back in on the next run (e.g., an .aux file).
1553 # Some situations of this kind are standard in latex generally; others
1554 # occur with particular macro packages or with particular
1555 # postprocessors.
1556 #
1557 # The correct criterion for whether a source is out-of-date is
1558 # therefore NOT that its modification time is later than the
1559 # destination file, but whether the contents of the source file have
1560 # changed since the last successful run. This also handles the case
1561 # that the user undoes some changes to a source file by replacing the
1562 # source file by reverting to an earlier version, which may well have
1563 # an older time stamp. Since a direct comparison of old and new files
1564 # would involve storage and access of a large number of backup files,
1565 # we instead use the md5 signature of the files. (Previous versions
1566 # of latexmk used the backup file method, but restricted to the case
1567 # of .aux and .idx files, sufficient for most, but not all,
1568 # situations.)
1569 #
1570 # We will have a database of (time, size, md5) for the relevant
1571 # files. If the time and size of a file haven't changed, then the file
1572 # is assumed not to have changed; this saves us from having to
1573 # determine its md5 signature, which would involve reading the whole
1574 # file, which is naturally time-consuming, especially if network file
1575 # access to a server is needed, and many files are involved, when most
1576 # of them don't change. It is of course possible to change a file
1577 # without changing its size, but then to adjust its timestamp
1578 # to what it was previously; this requires a certain amount of
1579 # perversity. We can safely assume that if the user edits a file or
1580 # changes its contents, then the file's timestamp changes. The
1581 # interesting case is that the timestamp does change, because the file
1582 # has actually been written to, but that the contents do not change;
1583 # it is for this that we use the md5 signature. However, since
1584 # computing the md5 signature involves reading the whole file, which
1585 # may be large, we should avoid computing it more than necessary.
1586 #
1587 # So we get the following structure:
1588 #
1589 # 1. For each relevant run (latex, pdflatex, each instance of a
1590 # custom dependency) we have a database of the state of the
1591 # source files that were last used by the run.
1592 # 2. On an initial startup, the database for a primary tex file
1593 # is read that was created by a previous run of latex or
1594 # pdflatex, if this exists.
1595 # 3. If the file doesn't exist, then the criterion for
1596 # out-of-dateness for an initial run is that it goes by file
1597 # timestamps, as in previous versions of latexmk, with due
1598 # (dis)regard to those files that are known to be generated by
1599 # latex and re-read on the next run.
1600 # 4. Immediately before a run, the database is updated to
1601 # represent the current conditions of the run's source files.
1602 # 5. After the run, it is determined whether any of the source
1603 # files have changed. This covers both files written by the
1604 # run, which are therefore in a dependency loop, and files that
1605 # the user may have updated during the run. (The last often
1606 # happens when latex takes a long time, for a big document,
1607 # and the user makes edits before latex has finished. This is
1608 # particularly prevalent when latexmk is used with
1609 # preview-continuous mode.)
1610 # 6. In the case of latex or pdflatex, the custom dependencies
1611 # must also be checked and redone if out-of-date.
1612 # 7. If any source files have changed, the run is redone,
1613 # starting at step 1.
1614 # 8. There is naturally a limit on the number of reruns, to avoid
1615 # infinite loops from bugs and from pathological or unforeseen
1616 # conditions.
1617 # 9. After the run is done, the run's file database is updated.
1618 # (By hypothesis, the sizes and md5s are correct, if the run
1619 # is successful.)
1620 # 10. To allow reuse of data from previous runs, the file database
1621 # is written to a file after every complete set of passes
1622 # through latex or pdflatex. (Note that there is separate
1623 # information for latex and pdflatex; the necessary
1624 # information won't coincide: Out-of-dateness for the files
1625 # for each program concerns the properties of the files when
1626 # the other program was run, and the set of source files could
1627 # be different, e.g., for graphics files.)
1628 #
1629 # We therefore maintain the following data structures.:
1630 #
1631 # a. For each run (latex, pdflatex, each custom dependency) a
1632 # database is maintained. This is a hash from filenames to a
1633 # reference to an array: [time, size, md5]. The semantics of
1634 # the database is that it represents the state of the source
1635 # files used in the run. During a run it represents the state
1636 # immediately before the run; after a run, with all reruns, it
1637 # represents the state of the files used, modified by having
1638 # the latest timestamps for generated files.
1639 # b. There is a global database for all files, which represents
1640 # the current state. This saves having to recompute the md5
1641 # signatures of a changed file used in more than one run
1642 # (e.g., latex and pdflatex).
1643 # c. Each of latex and pdflatex has a list of the relevant custom
1644 # dependencies.
1645 #
1646 # In all the following a fdb-hash is a hash of the form:
1647 # filename -> [time, size, md5]
1648 # If a file is found to disappear, its entry is removed from the hash.
1649 # In returns from fdb access routines, a size entry of -1 indicates a
1650 # non-existent file.
1651
1652
1653
1654 # Hashes, whose keys give names of particular kinds of rule, and targets.
1655 # We use hashes for ease of lookup.
1656 our %possible_one_time = ( 'view' => 1, 'print' => 1, 'update_view' => 1, );
1657 our %target_files = (); # Hash for target files.
1658 # The keys are the filenames and the value is
1659 # currently irrelevant.
1660 our %target_rules = (); # Hash for target rules beyond those corresponding to files.
1661 # The keys are the rule names and the value is
1662 # currently irrelevant.
1663 # The target **files** can only be set inside the FILE loop.
1664 our $current_primary = 'latex';# Rule to compile .tex file.
1665 # It will be overridden at rule-initialization time, and
1666 # is subject to document-dependent override if .tex document
1667 # uses metcommands and obeying them is implemented/enabled.
1668 our $pdf_method = ''; # How to make pdf file. '' if not requested,
1669 # else 'ps2pdf', 'dvipdf', 'pdflatex', 'lualatex' or 'xelatex'
1670 # Subject to document-dependent override if .tex document
1671 #uses \pdfoutput or c.
1672 our %requested_filetypes = (); # Hash of requested file types (dvi, dviF, etc)
1673 our %one_time = (); # Hash for requested one-time-only rules, currently
1674 # possible values 'print' and 'view'.
1675
1676 our %actives = (); # Hash of active rules
1677
1678 our $allow_switch = 1; # Allow switch of rule structure to accommodate
1679 # changed output file name of primary. Even if
1680 # this flag is set on, the switch may be
1681 # prohibited by other issues.
1682
1683 our %rule_db = (); # Database of all rules:
1684 # Hash: rulename -> [array of rule data]
1685 # Rule data:
1686 # 0: [ cmd_type, ext_cmd, int_cmd, no_history,
1687 # source, dest, base,
1688 # out_of_date, out_of_date_user,
1689 # time_of_last_run, time_of_last_file_check,
1690 # changed
1691 # last_result, last_result_info, last_message,
1692 # default_extra_generated,
1693 # ]
1694 # where
1695 # cmd_type is 'primary', 'external', or 'cusdep'
1696 # ext_cmd is string for associated external command
1697 # with substitutions (%D for destination, %S
1698 # for source, %B for base of current rule,
1699 # %R for base of primary tex file, %T for
1700 # texfile name, %O for options,
1701 # %V=$aux_dir, %W=$out_dir,
1702 # %X for $out2_dir1
1703 # %Y for $aux_dir1, and %Z for $out_dir1
1704 # int_cmd specifies any internal command to be
1705 # used to implement the application of the
1706 # rule. If this is present, it overrides
1707 # **direct** execution of the external command, and
1708 # it is the responsibility of the perl subroutine
1709 # specified in intcmd to execute the specified
1710 # external command if this is appropriate.
1711 # This variable intcmd is a reference to an array,
1712 # $$intcmd[0] = internal routine
1713 # $$intcmd[1...] = its arguments (if any)
1714 # no_history being true indicates that there was no
1715 # data on the file state from a previous run. In
1716 # this case the implication is that when the next
1717 # test for whether a run of the rule is needed,
1718 # the file-contents criterion won't be useful.
1719 # Then a time-based criterion (as in normal make)
1720 # is used, i.e., if a source file is newer than
1721 # the destination file, then a rerun is needed.
1722 # After that first test for a rerun has been
1723 # done, a run or no run is made according as
1724 # appropriate. After that the file-change
1725 # criterion works, and no_history is turned off.
1726 # source = name of primary source file, if any
1727 # dest = name of primary destination file,
1728 # if any
1729 # base = base name, if any, of files for
1730 # this rule
1731 # out_of_date = 1 if it has been detected that
1732 # this rule needs to be run
1733 # (typically because a source
1734 # file has changed).
1735 # Other values may be used for special cases.
1736 # 0 otherwise
1737 # out_of_date_user is like out_of_date, except
1738 # that the detection of out-of-dateness
1739 # has been made from a change of a
1740 # putative user file, i.e., one that is
1741 # not a generated file (e.g., aux). This
1742 # kind of out-of-dateness should provoke a
1743 # rerun whether or not there was an error
1744 # during a run of *LaTeX. Normally,
1745 # if there is an error, one should wait
1746 # for the user to correct the error. But
1747 # it is possible the error condition is
1748 # already corrected during the run, e.g.,
1749 # by the user changing a source file in
1750 # response to an error message.
1751 # time_of_last_run = time that this rule was
1752 # last applied. (In standard units
1753 # from perl, to be directly compared
1754 # with file modification times.)
1755 # time_of_last_file_check = last time that a check
1756 # was made for changes in source files.
1757 # changed flags whether special changes have been made
1758 # that require file-existence status to be ignored
1759 # last_result is
1760 # -1 if no run has been made
1761 # 0 if the last run was successful
1762 # 1 if last run was successful, but
1763 # failed to create an output file
1764 # 2 if last run failed
1765 # 200 if last run gave a warning that is
1766 # important enough to be reported with
1767 # the error summary. The warning
1768 # message is stored in last_message.
1769 # last_result_info is info about run that gave
1770 # code in last_result. Currently used values:
1771 # '' No record of this rule being run
1772 # 'CURR' Run of rule was in current
1773 # round of compilation.
1774 # 'PREV' Run of rule was in a previous
1775 # round of compilation (as with
1776 # -pvc), but in current invocation
1777 # of latexmk.
1778 # 'CACHE' Run of rule was in a previous
1779 # invocation of latexmk, with
1780 # last_result having been read
1781 # from fdb_latexmk file.
1782 # last_message is error message for last run
1783 # default_extra_generated is a reference to an array
1784 # of specifications of extra generated files (beyond
1785 # the main dest file. Standard place holders are used.
1786 # 1: {Hash sourcefile -> [source-file data] }
1787 # Source-file data array:
1788 # 0: time
1789 # 1: size
1790 # 2: md5
1791 # 3: DUMMY. Not used any more. ?? Lots of code depends
1792 # on array structure, Let's not change things now.
1793 # 4: whether the file is of the kind made by epstopdf.sty
1794 # during a primary run. It will have been read during
1795 # the run, so that even though the file changes during
1796 # a primary run, there is no need to trigger another
1797 # run because of this.
1798 # Size and md5 correspond to the values at the last run.
1799 # But time may be updated to correspond to the time
1800 # for the file, if the file is otherwise unchanged.
1801 # This saves excessive md5 calculations, which would
1802 # otherwise be done everytime the file is checked,
1803 # in the following situation:
1804 # When the file has been rewritten after a run
1805 # has started (commonly aux, bbl files etc),
1806 # but the actual file contents haven't
1807 # changed. Then because the filetime has
1808 # changed, on every file-change check latexmk
1809 # would normally redo the md5 calculation to
1810 # test for actual changes. Once one such
1811 # check is done, and the contents are
1812 # unchanged, later checks are superfluous, and
1813 # can be avoided by changing the file's time
1814 # in the source-file list.
1815 # 2: {Hash generated_file -> 1 }
1816 # This lists all generated files.
1817 # The values for the hash are currently unused, only the keys.
1818 # 3: {Hash rewritten_before_read_file -> 1 }
1819 # This lists all files that are only read after being
1820 # written **and** that existed before being
1821 # written, i.e., that existed at the beginning of
1822 # the run. These are listed in both the source-
1823 # and generated-file hashes, but do not need
1824 # to be checked for changes in testing whether
1825 # another run is needed, i.e., they aren't true
1826 # source files. **IMPORTANT NOTE:** If a file is
1827 # read only after being written, but the file didn't
1828 # exist at the beginning of the run, it is
1829 # possible (and often true) that on a subsequent
1830 # run the file would be read, then written, and
1831 # perhaps read again. That is, it can be that
1832 # before the file is written, there is a test for
1833 # file existence, and the file is read, but only
1834 # if it exists. Examples: .aux and .toc
1835 # files. Such files are true dependencies and must
1836 # be checked for changes. Only when the file
1837 # existed at the start of the run and was then
1838 # written before being read, do we know that
1839 # write-before-read shows that the file is not a
1840 # true source-dependency.
1841 # This issue is significant: under some situations,
1842 # like the use of latexmk and tex4ht, the file may
1843 # be changed by other software before the next run
1844 # of the current rule. That must not trigger
1845 # another run.
1846 # The values for the hash are currently unused, only the keys.
1847 # (Some packages that exhibit the
1848 # rewrite-before-read behavior: pythontex, showexpl.)
1849 # 4: {Hash source_rule -> last_pass }
1850 # This lists rules that are to be considered source
1851 # rules for the current rule, separately from the
1852 # source_rules of the source files. Its main use
1853 # (the only one at present) is when the list of
1854 # known source files, at item 1, is/may be
1855 # incomplete. This is notably the case for rules
1856 # applied to dvi and xdv files when graphics files
1857 # are involved. Their names are coded inside the
1858 # dvi/xdv file, but not the contents. It would
1859 # need parsing of the contents of the file to
1860 # determine the actual source files. In the case
1861 # of rules that process dvi and xdv files, the
1862 # source_rule is the *latex rule that generates
1863 # the dvi or xdv file.
1864 #
1865 # In determining whether a rerun of the current
1866 # rule is needed at some stage in a round of
1867 # compilation, the following is added to the
1868 # basic source-file-change criterion.
1869 # The value that a source rule in this hash maps
1870 # to is its pass number when the current rule was
1871 # last run. The current rule is flagged
1872 # out-of-date if the saved last_pass for a source
1873 # rule is less than the current pass number for
1874 # that source rule (as known to the compilation
1875 # process).
1876 # An implication of using a source_rule in this
1877 # way is that the source_rule passes files (or
1878 # other information) to the current rule, and that
1879 # the current rule is to be rerun whenever the
1880 # source_rule has been run.
1881 # 5: {Hash keys -> values}
1882 # Used for any extra information needed for a specific
1883 # rule. The first one I'll set up is for cached
1884 # datasource information for the biber rule. The
1885 # key is 'bcf_datasources', and the value is a
1886 # reference to a hash mapping filename
1887 # specifications in the bcf file to actual files
1888 # (if found).
1889 # The aim of this item is for flexible
1890 # rule-dependent add-ons.
1891
1892 our %fdb_current = (); # Hash of information for all files used.
1893 # It maps filename to a reference to an array
1894 # (time, size, md5_checksum).
1895 our @nofile = (0,-1,0); # What we use for initializing a new entry in fdb
1896 # or flagging non-existent file.
1897
1898 # The following are variables which are set by the routine rdb_set_rule_net.
1899 # They are **derived** from information in %rule_db, and provide information
1900 # about the structure of the network of rules and files. This derived
1901 # information is in a form useful for using the network of rules.
1902
1903 # For recursing backwards through the network of rules:
1904 our %from_rules = (); # This maps file names to rule names.
1905 # $from_rules{'File'} is the name of the rule that
1906 # generates file 'File'. If there is no rule to
1907 # generate the file, then $from_rules{'File'} is
1908 # not defined (or possibly the null string '').
1909
1910 # Classification of rules, for determining order of application
1911 our @pre_primary = (); # Array of rules that are thought of as pre-primary,
1912 # Should be in an appropriate order for invoking
1913 # them, to optimize making.
1914 our @post_primary = (); # Array of rules that are thought of as post-primary.
1915 # In suitable order for invocation
1916 our @unusual_one_time = ();# Array of rules that are special cases of
1917 # one-time rules.
1918 # Currently not used.
1919
1920 # Variables set in applying rules:
1921 our ($rule, $PA_extra_gen, $PAint_cmd, $PArule_data, $Pbase, $Pchanged,
1922 $Pcheck_time, $Pcmd_type, $Pdest, $Pext_cmd,
1923 $PHdest, $PHextra, $PHrewritten_before_read, $PHsource, $PHsource_rules,
1924 $Plast_message, $Plast_result, $Plast_result_info,
1925 $Pno_history, $Pout_of_date, $Pout_of_date_user, $Prun_time, $Psource,
1926 $file, $PAfile_data, $Ptime, $Psize, $Pmd5, $DUMMY, $Pcorrect_after_primary
1927 );
1928
1929 # User's home directory
1930 our $HOME = '';
1931 if (exists $ENV{'HOME'} ) {
1932 $HOME = $ENV{'HOME'};
1933 }
1934 elsif (exists $ENV{'USERPROFILE'} ) {
1935 $HOME = $ENV{'USERPROFILE'};
1936 }
1937 # XDG configuration home
1938 our $XDG_CONFIG_HOME = '';
1939 if (exists $ENV{'XDG_CONFIG_HOME'} ) {
1940 $XDG_CONFIG_HOME = $ENV{'XDG_CONFIG_HOME'};
1941 }
1942 elsif ($HOME ne '') {
1943 if ( -d "$HOME/.config") {
1944 $XDG_CONFIG_HOME = "$HOME/.config";
1945 }
1946 }
1947
1948
1949 #==================================================
1950
1951 # Which rc files did I read?
1952 our @rc_files_read = (); # In order of reading
1953 our %rc_files_read2 = (); # Map **abs** filename to 1; used to check duplicate reads.
1954
1955 # Options that are to be obeyed before rc files are read:
1956 # Also under MSWin32 and msys, CL arguments sometimes get quotes in them.
1957 # (Specific example: TeXLive 2023 with msys's perl and arguments containing
1958 # both non-ASCII character, when latexmk.exe invoked from cmd.exe. In some
1959 # other situations (powershell and msys's terminal+bash), it seems that both
1960 # space and non-ASCII character are needed to trigger a problem.)
1961 # Recently (June 2025), I've not been able to reproduce this.
1962 foreach $_ ( @ARGV ) {
1963 if ( ($^O eq "MSWin32") || ($^O eq 'msys') ) {
1964 # "arg" -> arg.
1965 # -..="arg" -> -..=arg.
1966 # In both cases, only do this if there are no other ". Otherwise I
1967 # my run afoul of " that are intended to be there.
1968 s/^\"([^\"]+)\"$/$1/;
1969 s/^(-[^\"=]+=)\"([^\"]+)\"$/$1$2/;
1970 }
1971 if (/^-{1,2}norc$/ ) {
1972 $auto_rc_use = 0;
1973 }
1974 }
1975
1976 #==================================================
1977 ## Read rc files with this subroutine
1978
1979 sub read_first_rc_file_in_list {
1980 foreach my $rc_file ( @_ ) {
1981 if ( -d $rc_file ) {
1982 warn "$My_name: I have found a DIRECTORY named \"$rc_file\".\n",
1983 " Have you perhaps misunderstood latexmk's documentation?\n",
1984 " This name is normally used for a latexmk configuration (rc) file,\n",
1985 " and in that case it should be a regular text file, not a directory.\n";
1986 }
1987 elsif ( -e $rc_file ) {
1988 process_rc_file( $rc_file );
1989 return;
1990 }
1991 }
1992 }
1993
1994 # Note that each rc file may unset $auto_rc_use to
1995 # prevent lower-level rc files from being read.
1996 # So test on $auto_rc_use in each case.
1997 if ( $auto_rc_use ) {
1998 # System rc file:
1999 if (exists $ENV{LATEXMKRCSYS} ) {
2000 unshift @rc_system_files, $ENV{LATEXMKRCSYS};
2001 if ( !-e $ENV{LATEXMKRCSYS} ) {
2002 warn "$My_name: you've specified a system rc file `$ENV{LATEXMKRCSYS}`\n",
2003 " in environment variable LATEXMKRCSYS, but the file doesn't exist.\n",
2004 " I won't read any system rc file.\n";
2005 }
2006 else {
2007 process_rc_file( $ENV{LATEXMKRCSYS} );
2008 }
2009 }
2010 else {
2011 read_first_rc_file_in_list( @rc_system_files );
2012 }
2013 }
2014 if ( $auto_rc_use && ($HOME ne "" ) ) {
2015 # User rc file:
2016 my @user_rc = ();
2017 if ( $XDG_CONFIG_HOME ) {
2018 push @user_rc, "$XDG_CONFIG_HOME/latexmk/latexmkrc";
2019 }
2020 # N.B. $HOME equals "" if latexmk couldn't determine a home directory.
2021 # In that case, we shouldn't look for an rc file there.
2022 if ( $HOME ) {
2023 push @user_rc, "$HOME/.latexmkrc";
2024 }
2025 read_first_rc_file_in_list( @user_rc );
2026 }
2027 if ( $auto_rc_use ) {
2028 # Rc file in current directory:
2029 read_first_rc_file_in_list( ".latexmkrc", "latexmkrc" );
2030 }
2031
2032 ## Process command line args.
2033 our @command_line_file_list = ();
2034 our $bad_options = 0;
2035
2036 while (defined(local $_ = $ARGV[0])) {
2037 # Make -- and - equivalent at beginning of option,
2038 # but save original for possible use in *latex command line
2039 my $original = $_;
2040 s/^--/-/;
2041 shift;
2042 if ( /^-aux-directory=(.*)$/ || /^-auxdir=(.*)$/ ) {
2043 $aux_dir = $1;
2044 }
2045 elsif (/^-bib(tex|)fudge$/) { $bibtex_fudge = 1; }
2046 elsif (/^-bib(tex|)fudge-$/) { $bibtex_fudge = 0; }
2047 elsif (/^-bibtex$/) { $bibtex_use = 2; }
2048 elsif (/^-bibtex-$/) { $bibtex_use = 0; }
2049 elsif (/^-nobibtex$/) { $bibtex_use = 0; }
2050 elsif (/^-bibtex-cond$/) { $bibtex_use = 1; }
2051 elsif (/^-bibtex-cond1$/) { $bibtex_use = 1.5; }
2052 elsif (/^-c$/) { $cleanup_mode = 2; $cleanup_only = 1; }
2053 elsif (/^-C$/ || /^-CA$/ ) { $cleanup_mode = 1; $cleanup_only = 1; }
2054 elsif (/^-CF$/) { $cleanup_fdb = 1; }
2055 elsif (/^-cd$/) { $do_cd = 1; }
2056 elsif (/^-cd-$/) { $do_cd = 0; }
2057 elsif (/^-commands$/) { &print_commands; exit; }
2058 elsif (/^-d$/) {
2059 warn "$My_name: Option -d is no longer used by latexmk.\n";
2060 $banner = 1;
2061 }
2062 elsif (/^-dependents$/ || /^-deps$/ || /^-M$/ ) { $dependents_list = 1; }
2063 elsif (/^-nodependents$/ || /^-dependents-$/ || /^-deps-$/) { $dependents_list = 0; }
2064 elsif (/^-deps-escape=(.*)$/) {
2065 if ( $deps_escape_kinds{$1} ) { $deps_escape = $1; }
2066 else { warn "$My_name: In '$_', kind of escape is not one of those I know, which are\n",
2067 " ", join( ' ', sort( keys %deps_escape_kinds )), "\n";
2068 }
2069 }
2070 elsif (/^-deps-out=(.*)$/) {
2071 $deps_file = $1;
2072 $dependents_list = 1;
2073 }
2074 elsif (/^-diagnostics/) { $diagnostics = 1; }
2075 elsif (/^-dir-report-only$/) { $aux_out_dir_report = 2; }
2076 elsif (/^-dir-report$/) { $aux_out_dir_report = 1; }
2077 elsif (/^-dir-report-$/) { $aux_out_dir_report = 0; }
2078 elsif (/^-dvi$/) { $dvi_mode = 1;
2079 $hnt_mode = $xdv_mode = 0;
2080 # Postscript mode OK
2081 if ( ($pdf_mode != 2) && ($pdf_mode != 3) ) {
2082 # if pdf_mode is not via dvi or ps, turn it off
2083 $pdf_mode = 0;
2084 }
2085 }
2086 elsif (/^-dvilua$/) { $dvi_mode = 2;
2087 $hnt_mode = $xdv_mode = 0;
2088 # Postscript mode OK
2089 if ( ($pdf_mode != 2) && ($pdf_mode != 3) ) {
2090 # if pdf_mode is not via dvi or ps, turn it off
2091 $pdf_mode = 0;
2092 }
2093 }
2094 elsif (/^-dvi-$/) { $dvi_mode = 0; }
2095 elsif ( /^-dvilualatex=(.*)$/ ) {
2096 $dvilualatex = $1;
2097 }
2098 elsif (/^-emulate-aux-dir$/) { $emulate_aux = 1; }
2099 elsif (/^-emulate-aux-dir-$/) { $emulate_aux = 0; }
2100 elsif (/^-f$/) { $force_mode = 1; }
2101 elsif (/^-f-$/) { $force_mode = 0; }
2102 elsif (/^-g$/) { $go_mode = 1; }
2103 elsif (/^-g-$/) { $go_mode = 0; }
2104 elsif (/^-gg$/) {
2105 $go_mode = 2;
2106 }
2107 elsif (/^-gt$/) {
2108 $go_mode = 3;
2109 }
2110 elsif ( /^-h$/ || /^-help$/ ) { &print_help; exit;}
2111 elsif (/^-hnt$/) { $hnt_mode = 1;
2112 $dvi_mode = $postscript_mode = $pdf_mode = $xdv_mode = 0;
2113 }
2114 elsif (/^-jobname=(.*)$/) {
2115 $jobname = $1;
2116 }
2117 elsif (/^-l$/) { $landscape_mode = 1; }
2118 elsif (/^-l-$/) { $landscape_mode = 0; }
2119 elsif ( /^-latex$/ ) { $dvi_mode = 1;
2120 $hnt_mode = $postscript_mode = $xdv_mode = 0;
2121 # Postscript mode OK
2122 if ( ($pdf_mode != 2) && ($pdf_mode != 3) ) {
2123 # if pdf_mode is not via dvi or ps, turn it off
2124 $pdf_mode = 0;
2125 }
2126 }
2127 elsif (/^-latex=(.*)$/) {
2128 $latex = $1;
2129 }
2130 elsif (/^-latexoption=(.*)$/) {
2131 push @extra_dvilualatex_options, $1;
2132 push @extra_latex_options, $1;
2133 push @extra_pdflatex_options, $1;
2134 push @extra_lualatex_options, $1;
2135 push @extra_xelatex_options, $1;
2136 }
2137 elsif ( /^-logfilewarninglist$/ || /^-logfilewarnings$/ )
2138 { $silence_logfile_warnings = 0; }
2139 elsif ( /^-logfilewarninglist-$/ || /^-logfilewarnings-$/ )
2140 { $silence_logfile_warnings = 1; }
2141 elsif ( /^-lualatex$/ || /^-pdflualatex$/ ) {
2142 $pdf_mode = 4;
2143 $dvi_mode = $hnt_mode = $postscript_mode = $xdv_mode = 0;
2144 }
2145 # See below for -lualatex=...
2146 # See above for -M
2147 elsif (/^-MF$/) {
2148 if ( $ARGV[0] eq '' ) {
2149 &exit_help( "No file name specified after -MF switch");
2150 }
2151 $deps_file = $ARGV[0];
2152 shift;
2153 }
2154 elsif ( /^-MP$/ ) { $dependents_phony = 1; }
2155 elsif (/^-(make|)indexfudge$/) { $makeindex_fudge = 1; }
2156 elsif (/^-(make|)indexfudge-$/) { $makeindex_fudge = 0; }
2157 elsif ( /-MSWinBackSlash$/ ) { $MSWin_back_slash = 1; }
2158 elsif ( /-MSWinBackSlash-$/ ) { $MSWin_back_slash = 0; }
2159 elsif (/^-new-viewer$/) {
2160 $new_viewer_always = 1;
2161 }
2162 elsif (/^-new-viewer-$/) {
2163 $new_viewer_always = 0;
2164 }
2165 elsif (/^-norc$/ ) {
2166 $auto_rc_use = 0;
2167 # N.B. This has already been obeyed.
2168 }
2169 elsif (/^-nobib(tex|)fudge$/) { $bibtex_fudge = 0; }
2170 elsif (/^-noemulate-aux-dir$/) { $emulate_aux = 0; }
2171 elsif (/^-no(make|)indexfudge$/) { $makeindex_fudge = 0; }
2172 elsif ( /^-output-directory=(.*)$/ ||/^-outdir=(.*)$/ ) {
2173 $out_dir = $1;
2174 }
2175 elsif ( /^-out2dir=(.*)$/ ) {
2176 $out2_dir = $1;
2177 }
2178 elsif ( /^-output-format=(.*)$/ ) {
2179 my $format = $1;
2180 if ($format eq 'dvi' ) {
2181 $dvi_mode = 1;
2182 $hnt_mode = $xdv_mode = 0;
2183 # Postscript mode OK
2184 if ( ($pdf_mode != 2) && ($pdf_mode != 3) ) {
2185 # if pdf_mode is not via dvi or ps, turn it off
2186 $pdf_mode = 0;
2187 }
2188 }
2189 elsif ($format eq 'pdf' ) {
2190 $pdf_mode = 1;
2191 $dvi_mode = $hnt_mode = $postscript_mode = $xdv_mode = 0;
2192 }
2193 else {
2194 warn "$My_name: unknown format in option '$_'\n";
2195 $bad_options++;
2196 }
2197 }
2198 elsif (/^-p$/) { $printout_mode = 1;
2199 $preview_continuous_mode = 0; # to avoid conflicts
2200 $preview_mode = 0;
2201 }
2202 elsif (/^-p-$/) { $printout_mode = 0; }
2203 elsif (/^-pdf$/) { $pdf_mode = 1; $dvi_mode = $hnt_mode = $postscript_mode = $xdv_mode = 0; }
2204 elsif (/^-pdf-$/) { $pdf_mode = 0; }
2205 elsif (/^-pdfdvi$/){ $pdf_mode = 3; $hnt_mode = $xdv_mode = 0; }
2206 elsif (/^-pdflua$/){ $pdf_mode = 4; $dvi_mode = $hnt_mode = $postscript_mode = $xdv_mode = 0; }
2207 elsif (/^-pdfps$/) { $pdf_mode = 2; $hnt_mode = $xdv_mode = 0; }
2208 elsif (/^-pdfxe$/) { $pdf_mode = 5; $dvi_mode = $hnt_mode = $postscript_mode = 0; }
2209 elsif (/^-pdflatex$/) {
2210 $pdf_mode = 1;
2211 $dvi_mode = $hnt_mode = $postscript_mode = $xdv_mode = 0;
2212 }
2213 elsif (/^-pdflatex=(.*)$/) {
2214 $pdflatex = $1;
2215 }
2216 elsif ( /^-pdflualatex=(.*)$/ || /^-lualatex=(.*)$/ ) {
2217 $lualatex = $1;
2218 }
2219 elsif ( /^-pdfxelatex=(.*)$/ || /^-xelatex=(.*)$/ ) {
2220 $xelatex = $1;
2221 }
2222 elsif (/^-pretex=(.*)$/) {
2223 $pre_tex_code = $1;
2224 }
2225 elsif (/^-print=(.*)$/) {
2226 my $value = $1;
2227 if ( $value =~ /^dvi$|^ps$|^pdf$|^auto$/ ) {
2228 $print_type = $value;
2229 $printout_mode = 1;
2230 }
2231 else {
2232 &exit_help("$My_name: unknown print type '$value' in option '$_'");
2233 }
2234 }
2235 elsif (/^-ps$/) { $postscript_mode = 1;
2236 # dvi mode OK
2237 $hnt_mode = $xdv_mode = 0;
2238 if ( ($pdf_mode != 2) && ($pdf_mode != 3) ) {
2239 # if pdf_mode is not via dvi or pdf, turn it off
2240 $pdf_mode = 0;
2241 }
2242 }
2243 elsif (/^-ps-$/) { $postscript_mode = 0; }
2244 elsif (/^-pv$/) { $preview_mode = 1;
2245 $preview_continuous_mode = 0; # to avoid conflicts
2246 $printout_mode = 0;
2247 }
2248 elsif (/^-pv-$/) { $preview_mode = 0; }
2249 elsif (/^-pvc$/) { $preview_continuous_mode = 1;
2250 $force_mode = 0; # So that errors do not cause loops
2251 $preview_mode = 0; # to avoid conflicts
2252 $printout_mode = 0;
2253 }
2254 elsif (/^-pvc-$/) { $preview_continuous_mode = 0; }
2255 elsif (/^-pvctimeout$/) { $pvc_timeout = 1; }
2256 elsif (/^-pvctimeout-$/) { $pvc_timeout = 0; }
2257 elsif (/^-pvctimeoutmins=(.*)$/) { $pvc_timeout_mins = $1; }
2258 elsif (/^-rc-report$/) { $rc_report = 1; }
2259 elsif (/^-rc-report-$/) { $rc_report = 0; }
2260 elsif (/^-recorder$/ ){ $recorder = 1; }
2261 elsif (/^-recorder-$/ ){ $recorder = 0; }
2262 elsif (/^-rules$/ ) { $rules_list = 1; }
2263 elsif (/^-norules$/ || /^-rules-$/ ) { $rules_list = 0; }
2264 elsif (/^-showextraoptions$/) {
2265 print "List of extra latex and pdflatex options recognized by $my_name.\n",
2266 "These are passed as is to *latex. They may not be recognized by\n",
2267 "particular versions of *latex. This list is a combination of those\n",
2268 "for TeXLive and MikTeX.\n",
2269 "\n",
2270 "Note that in addition to the options in this list, there are several\n",
2271 "options known to the *latex programs that are also recognized by\n",
2272 "latexmk and trigger special behavior by latexmk. Since these options\n",
2273 "appear in the main list given by running 'latexmk --help', they do not\n",
2274 "appear in the following list\n",
2275 "NOTE ALSO: Not all of these options are supported by all versions of *latex.\n",
2276 "\n";
2277 foreach my $option ( sort( keys %allowed_latex_options, keys %allowed_latex_options_with_arg ) ) {
2278 if (exists $allowed_latex_options{$option} ) { print " $allowed_latex_options{$option}\n"; }
2279 if (exists $allowed_latex_options_with_arg{$option} ) { print " $allowed_latex_options_with_arg{$option}\n"; }
2280 }
2281 exit;
2282 }
2283 elsif (/^-silent$/ || /^-quiet$/ ){ $silent = 1; }
2284 elsif (/^-stdtexcmds$/) { &std_tex_cmds; }
2285 elsif (/^-time$/) { $show_time = 1;}
2286 elsif (/^-time-$/) { $show_time = 0;}
2287 elsif (/^-use-make$/) { $use_make_for_missing_files = 1; }
2288 elsif (/^-use-make-$/) { $use_make_for_missing_files = 0; }
2289 elsif (/^-usepretex$/) { &alt_tex_cmds; }
2290 elsif (/^-usepretex=(.*)$/) {
2291 &alt_tex_cmds;
2292 $pre_tex_code = $1;
2293 }
2294 elsif (/^-v$/ || /^-version$/) {
2295 print "$version_details\n";
2296 exit;
2297 }
2298 elsif (/^-verbose$/) { $silent = 0; }
2299 elsif (/^-view=default$/) { $view = "default";}
2300 elsif (/^-view=dvi$/) { $view = "dvi";}
2301 elsif (/^-view=hnt$/) { $view = "hnt";}
2302 elsif (/^-view=none$/) { $view = "none";}
2303 elsif (/^-view=ps$/) { $view = "ps";}
2304 elsif (/^-view=pdf$/) { $view = "pdf"; }
2305 elsif (/^-Werror$/){ $warnings_as_errors = 1; }
2306 elsif (/^-xdv$/) { $xdv_mode = 1;
2307 $dvi_mode = $hnt_mode = $postscript_mode = 0;
2308 if ( $pdf_mode != 5 ) {
2309 # if pdf_mode is not by xelatex
2310 $pdf_mode = 0;
2311 }
2312 }
2313 elsif (/^-xdv-$/) { $xdv_mode = 0; }
2314 elsif ( /^-xelatex$/ || /^-pdfxelatex$/ ) {
2315 $pdf_mode = 5;
2316 # Xdv mode OK, since use xelatex to make xdv file
2317 $dvi_mode = $hnt_mode = $postscript_mode = 0;
2318 }
2319 # See above for -xelatex=...
2320 elsif (/^-e$/) {
2321 if ( $#ARGV < 0 ) {
2322 &exit_help( "No code to execute specified after -e switch");
2323 }
2324 execute_code_string( $ARGV[0] );
2325 shift;
2326 }
2327 elsif (/^-r$/) {
2328 if ( $ARGV[0] eq '' ) {
2329 &exit_help( "No RC file specified after -r switch");
2330 }
2331 if ( -e $ARGV[0] ) {
2332 # Give process_rc_file a non-zero argument so that there is a warning
2333 # if $ARGV[0] has already been processed as an rc file:
2334 process_rc_file( $ARGV[0], 1 );
2335 }
2336 else {
2337 die "$My_name: RC file [$ARGV[0]] does not exist\n";
2338 }
2339 shift;
2340 }
2341 elsif (/^-bm$/) {
2342 if ( $ARGV[0] eq '' ) {
2343 &exit_help( "No message specified after -bm switch");
2344 }
2345 warn "$My_name: Option -bm is no longer used by latexmk.\n";
2346 $banner = 1; $banner_message = $ARGV[0];
2347 shift;
2348 }
2349 elsif (/^-bi$/) {
2350 if ( $ARGV[0] eq '' ) {
2351 &exit_help( "No intensity specified after -bi switch");
2352 }
2353 warn "$My_name: Option -bi is no longer used by latexmk.\n";
2354 $banner_intensity = $ARGV[0];
2355 shift;
2356 }
2357 elsif (/^-bs$/) {
2358 if ( $ARGV[0] eq '' ) {
2359 &exit_help( "No scale specified after -bs switch");
2360 }
2361 warn "$My_name: Option -bs is no longer used by latexmk.\n";
2362 $banner_scale = $ARGV[0];
2363 shift;
2364 }
2365 elsif (/^-dF$/) {
2366 if ( $ARGV[0] eq '' ) {
2367 &exit_help( "No dvi filter specified after -dF switch");
2368 }
2369 $dvi_filter = $ARGV[0];
2370 shift;
2371 }
2372 elsif (/^-pF$/) {
2373 if ( $ARGV[0] eq '' ) {
2374 &exit_help( "No ps filter specified after -pF switch");
2375 }
2376 $ps_filter = $ARGV[0];
2377 shift;
2378 }
2379 elsif ( ( exists( $allowed_latex_options{$_} ) )
2380 || ( /^(-[^=]+)=/ && exists( $allowed_latex_options_with_arg{$1} ) )
2381 )
2382 {
2383 push @extra_dvilualatex_options, $original;
2384 push @extra_hilatex_options, $original;
2385 push @extra_latex_options, $original;
2386 push @extra_pdflatex_options, $original;
2387 push @extra_lualatex_options, $original;
2388 push @extra_xelatex_options, $original;
2389 }
2390 elsif (/^-/) {
2391 warn "$My_name: $_ unknown option\n";
2392 $bad_options++;
2393 }
2394 else {
2395 push @command_line_file_list, $_ ;
2396 }
2397 }
2398
2399 if ( $diagnostics || $rc_report ) {
2400 show_array( "Rc files read:", @rc_files_read );
2401 }
2402
2403 if ( $bad_options > 0 ) {
2404 &exit_help( "Bad options specified" );
2405 }
2406
2407 print "$My_name: This is $version_details.\n",
2408 unless $silent;
2409
2410 &config_to_mine;
2411
2412 # Save original values for use in diagnositics.
2413 # We may change $aux_dir and $out_dir after a detection
2414 # of results of misconfiguration.
2415 $aux_dir_requested = $aux_dir;
2416 $out_dir_requested = $out_dir;
2417 $out2_dir_requested = $out2_dir;
2418
2419 if ($out_dir eq '' ){
2420 # Default to cwd
2421 $out_dir = '.';
2422 }
2423 if ($out2_dir eq '' ){
2424 # Default to cwd
2425 $out2_dir = $out_dir;
2426 }
2427 if ( $aux_dir eq '' ){
2428 # Default to out_dir
2429 $aux_dir = $out_dir;
2430 }
2431
2432 if ($bibtex_use > 1) {
2433 push @generated_exts, 'bbl';
2434 }
2435
2436 # For backward compatibility, convert $texfile_search to @default_files
2437 # Since $texfile_search is initialized to "", a nonzero value indicates
2438 # that an initialization file has set it.
2439 if ( $texfile_search ne "" ) {
2440 @default_files = split /\s+/, "*.tex $texfile_search";
2441 }
2442
2443 #Glob the filenames command line if the script was not invoked under a
2444 # UNIX-like environment.
2445 # Cases: (1) MS/MSwin native Glob
2446 # (OS detected as MSWin32)
2447 # (2) MS/MSwin cygwin Glob [because we do not know whether
2448 # the cmd interpreter is UNIXy (and does glob) or is
2449 # native MS-Win (and does not glob).]
2450 # (OS detected as cygwin)
2451 # (3) UNIX Don't glob (cmd interpreter does it)
2452 # (Currently, I assume this is everything else)
2453 our @file_list;
2454 if ( ($^O eq "MSWin32") || ($^O eq "cygwin") ) {
2455 # Preserve ordering of files
2456 @file_list = glob_list1(@command_line_file_list);
2457 #print "A1:File list:\n";
2458 #for ($i = 0; $i <= $#file_list; $i++ ) { print "$i: '$file_list[$i]'\n"; }
2459 }
2460 else {
2461 @file_list = @command_line_file_list;
2462 }
2463 @file_list = uniq1( @file_list );
2464
2465
2466 # Check we haven't selected mutually exclusive modes.
2467 # Note that -c overrides all other options, but doesn't cause
2468 # an error if they are selected.
2469 if (($printout_mode && ( $preview_mode || $preview_continuous_mode ))
2470 || ( $preview_mode && $preview_continuous_mode ))
2471 {
2472 # Each of the options -p, -pv, -pvc turns the other off.
2473 # So the only reason to arrive here is an incorrect inititalization
2474 # file, or a bug.
2475 &exit_help( "Conflicting options (print, preview, preview_continuous) selected");
2476 }
2477
2478 if ( @command_line_file_list ) {
2479 # At least one file specified on command line (before possible globbing).
2480 if ( !@file_list ) {
2481 &exit_help( "Wildcards in file names didn't match any files");
2482 }
2483 }
2484 else {
2485 # No files specified on command line, try and find some
2486 # Evaluate in order specified. The user may have some special
2487 # for wanting processing in a particular order, especially
2488 # if there are no wild cards.
2489 # Preserve ordering of files
2490 my @file_list1 = uniq1( glob_list1(@default_files) );
2491 my @excluded_file_list = uniq1( glob_list1(@default_excluded_files) );
2492 # Make hash of excluded files, for easy checking:
2493 my %excl = ();
2494 foreach my $file (@excluded_file_list) {
2495 $excl{$file} = '';
2496 }
2497 foreach my $file (@file_list1) {
2498 push( @file_list, $file) unless ( exists $excl{$file} );
2499 }
2500 if ( !@file_list ) {
2501 &exit_help(
2502 "No file name(s) specified on command line, and no files match the\n".
2503 "patterns in the default list."
2504 );
2505 }
2506 }
2507
2508 our $num_files = $#file_list + 1;
2509 our $num_specified = $#command_line_file_list + 1;
2510
2511 #print "Command line file list:\n";
2512 #for ($i = 0; $i <= $#command_line_file_list; $i++ ) { print "$i: '$command_line_file_list[$i]'\n"; }
2513 #print "File list:\n";
2514 #for ($i = 0; $i <= $#file_list; $i++ ) { print "$i: '$file_list[$i]'\n"; }
2515
2516
2517 # If selected a preview-continuous mode, make sure exactly one filename was specified
2518 if ($preview_continuous_mode && ($num_files != 1) ) {
2519 if ($num_specified > 1) {
2520 &exit_help(
2521 "Need to specify exactly one filename for ".
2522 "preview-continuous mode\n".
2523 " but $num_specified were specified"
2524 );
2525 }
2526 elsif ($num_specified == 1) {
2527 &exit_help(
2528 "Need to specify exactly one filename for ".
2529 "preview-continuous mode\n".
2530 " but wildcarding produced $num_files files"
2531 );
2532 }
2533 else {
2534 &exit_help(
2535 "Need to specify exactly one filename for ".
2536 "preview-continuous mode.\n".
2537 " Since none were specified on the command line, I looked for \n".
2538 " files in '@default_files'.\n".
2539 " But I found $num_files files, not 1."
2540 );
2541 }
2542 }
2543
2544 # If selected jobname, can only apply that to one file:
2545 if ( ($jobname ne '') && ($jobname !~ /%A/) && ($num_files > 1) ) {
2546 &exit_help(
2547 "Need to specify at most one filename if ".
2548 "jobname specified without a %A, \n".
2549 " but $num_files were found (after defaults and wildcarding)."
2550 );
2551 }
2552 if ( $jobname =~ /%[^A]/ ) {
2553 &exit_help(
2554 "Jobname '$jobname' contains placeholder other than %A."
2555 );
2556 }
2557
2558 # Normalize the commands, to have place-holders for source, dest etc:
2559 &fix_cmds;
2560
2561 # Add common options
2562 add_option( $dvilualatex_default_switches, \$dvilualatex );
2563 add_option( $hilatex_default_switches, \$hilatex );
2564 add_option( $latex_default_switches, \$latex );
2565 add_option( $pdflatex_default_switches, \$pdflatex );
2566 add_option( $lualatex_default_switches, \$lualatex );
2567 add_option( $xelatex_default_switches, \$xelatex );
2568
2569 foreach (@extra_dvilualatex_options) { add_option( $_, \$dvilualatex ); }
2570 foreach (@extra_hilatex_options) { add_option( $_, \$hilatex ); }
2571 foreach (@extra_latex_options) { add_option( $_, \$latex ); }
2572 foreach (@extra_pdflatex_options) { add_option( $_, \$pdflatex ); }
2573 foreach (@extra_lualatex_options) { add_option( $_, \$lualatex ); }
2574 foreach (@extra_xelatex_options) { add_option( $_, \$xelatex ); }
2575
2576
2577 # If landscape mode, change dvips processor, and the previewers:
2578 if ( $landscape_mode )
2579 {
2580 $dvips = $dvips_landscape;
2581 $dvi_previewer = $dvi_previewer_landscape;
2582 $ps_previewer = $ps_previewer_landscape;
2583 }
2584
2585 { my $array_changed = 0;
2586 if ($#BIBINPUTS != $#BIBINPUTS_SAVE) { $array_changed = 1; }
2587 else {
2588 for( my $i = 0; $i <= $#BIBINPUTS; $i++ ) {
2589 if ($BIBINPUTS[$i] ne $BIBINPUTS_SAVE[$i]) {
2590 $array_changed = 1;
2591 last;
2592 }
2593 }
2594 }
2595 if ($array_changed) {
2596 foreach (@BIBINPUTS) { ensure_path( 'BIBINPUTS', $_ ); }
2597 }
2598 }
2599
2600 if ( $silent ) {
2601 add_option( "$dvilualatex_silent_switch", \$dvilualatex );
2602 add_option( "$hilatex_silent_switch", \$hilatex );
2603 add_option( "$latex_silent_switch", \$latex );
2604 add_option( "$pdflatex_silent_switch", \$pdflatex );
2605 add_option( "$lualatex_silent_switch", \$lualatex );
2606 add_option( "$xelatex_silent_switch", \$xelatex );
2607 add_option( "$biber_silent_switch", \$biber );
2608 add_option( "$bibtex_silent_switch", \$bibtex );
2609 add_option( "$makeindex_silent_switch", \$makeindex );
2610 add_option( "$dvipdf_silent_switch", \$dvipdf );
2611 add_option( "$dvips_silent_switch", \$dvips );
2612 add_option( "$xdvipdfmx_silent_switch", \$xdvipdfmx );
2613 }
2614
2615 if ( $recorder ) {
2616 add_option( "-recorder", \$dvilualatex, \$hilatex, \$latex, \$pdflatex, \$lualatex, \$xelatex );
2617 }
2618
2619 # If the output and/or aux directories are specified, fix the *latex
2620 # commands to use them.
2621 # N.B. We'll ensure that the directories actually exist only after a
2622 # possible cd to the document directory, since the directories can be
2623 # relative to the document.
2624
2625 if ( $jobname ne '' ) {
2626 # Since $jobname may include placeholder(s), put %R placeholder
2627 # in option, and let %R be substituted by actual jobname at runtime.
2628 add_option( "--jobname=%R", \$dvilualatex, \$hilatex, \$latex, \$lualatex, \$pdflatex, \$xelatex );
2629 }
2630
2631 # Make sure we make the kind of file we want to view:
2632 if ( ($view eq 'dvi') && ($dvi_mode == 0) ) { $dvi_mode = 1; }
2633 if ( ($view eq 'hnt') && ($hnt_mode == 0) ) { $hnt_mode = 1; }
2634 if ( $view eq 'ps' ) { $postscript_mode = 1; }
2635 if ( ($view eq 'pdf') && ($pdf_mode == 0) ) {
2636 warn "$my_name: Viewing of pdf requested, but pdf_mode off, so I'll turn it on.\n";
2637 $pdf_mode = 1;
2638 }
2639
2640 # Make sure that we make something if all requests are turned off
2641 unless ( $dvi_mode || $hnt_mode || $pdf_mode || $postscript_mode || $printout_mode || $xdv_mode ) {
2642 print "No specific requests made, so using default for $invoked_name.\n";
2643 ($dvi_mode, $hnt_mode, $postscript_mode, $pdf_mode, $xdv_mode )
2644 = @{$compilation_defaults{$invoked_name}};
2645 }
2646
2647
2648 # Which kind of file do we preview?
2649 if ( $view eq "default" ) {
2650 # If default viewer requested, use "highest" of dvi, ps and pdf
2651 # that was requested by user.
2652 # No explicit request means view dvi.
2653 if ( $pdf_mode ) { $view = "pdf"; }
2654 elsif ( $postscript_mode ) { $view = "ps"; }
2655 elsif ( $xdv_mode ) { $view = "none"; }
2656 elsif ( $hnt_mode ) { $view = "hnt"; }
2657 else { $view = "dvi"; }
2658 }
2659
2660 # Determine and normalize requests for actions:
2661
2662 if ($go_mode == 2) { $cleanup_mode = 1; $cleanup_only = 0; }
2663
2664 if ( $banner ) { $postscript_mode = 1; }
2665 if ( $dvi_mode ) {
2666 $requested_filetypes{'dvi'} = 1;
2667 if ( length($dvi_filter) != 0 ) { $requested_filetypes{'dviF'} = 1; }
2668 }
2669 if ( $postscript_mode ) {
2670 $requested_filetypes{'ps'} = 1;
2671 if ( length($ps_filter) != 0 ) { $requested_filetypes{'psF'} = 1; }
2672 }
2673
2674 if ($pdf_mode > 5) {
2675 warn "$My_name: Non-allowed value of \$pdf_mode = $pdf_mode,",
2676 " replaced by 1.\n";
2677 $pdf_mode = 1;
2678 }
2679
2680 if ( ($dvi_mode || $postscript_mode) && $pdf_mode ) {
2681 my %disallowed = ();
2682 foreach (1,4,5) { $disallowed{$_} = 1; }
2683 if ($disallowed{$pdf_mode}) {
2684 warn
2685 "$My_name: \$pdf_mode = $pdf_mode is incompatible with dvi and postscript modes\n",
2686 " which are required by other requests.\n",
2687 " Some requests may be implicit in the kind of file to view: '$view'.\n";
2688 if ($postscript_mode) { $pdf_mode = 2; }
2689 else { $pdf_mode = 3; }
2690 warn
2691 " I set pdf_mode to $pdf_mode, to be compatible with those other requests.\n";
2692 }
2693 }
2694 if ( $xdv_mode && $pdf_mode ) {
2695 my %disallowed = ();
2696 foreach (1,2,3,4) { $disallowed{$_} = 1; }
2697 if ($disallowed{$pdf_mode}) {
2698 warn
2699 "$My_name: \$pdf_mode = $pdf_mode is incompatible with dvi and postscript modes\n",
2700 " which are required by other requests.\n";
2701 if ($postscript_mode) { $pdf_mode = 2; }
2702 else { $pdf_mode = 3; }
2703 warn
2704 " I replaced it by $pdf_mode, to be compatible with those other requests.\n";
2705 }
2706 }
2707 if ( $pdf_mode == 0 ) {
2708 $pdf_method = '';
2709 }
2710 elsif ( $pdf_mode == 1 ) {
2711 $requested_filetypes{'pdf'} = 1;
2712 $pdf_method = 'pdflatex';
2713 }
2714 elsif ( $pdf_mode == 2 ) {
2715 $requested_filetypes{'pdf'} = 1;
2716 $pdf_method = 'ps2pdf';
2717 }
2718 elsif ( $pdf_mode == 3 ) {
2719 $requested_filetypes{'pdf'} = 1;
2720 $pdf_method = 'dvipdf';
2721 }
2722 elsif ( $pdf_mode == 4 ) {
2723 $requested_filetypes{'pdf'} = 1;
2724 $pdf_method = 'lualatex';
2725 }
2726 elsif ( $pdf_mode == 5 ) {
2727 $requested_filetypes{'pdf'} = 1;
2728 $pdf_method = 'xelatex';
2729 }
2730
2731 if ($print_type eq 'auto') {
2732 if ( $postscript_mode ) { $print_type = 'ps'; }
2733 elsif ( $pdf_mode ) { $print_type = 'pdf'; }
2734 elsif ( $dvi_mode ) { $print_type = 'dvi'; }
2735 else { $print_type = 'none'; }
2736 }
2737 if ( $printout_mode ) {
2738 $one_time{'print'} = 1;
2739 if ($print_type eq 'none'){
2740 warn "$My_name: You have requested printout, but \$print_type is set to 'none'\n";
2741 }
2742 }
2743 if ( $preview_continuous_mode || $preview_mode ) { $one_time{'view'} = 1; }
2744
2745 our $can_switch = $allow_switch;
2746 if ( $dvi_mode || $hnt_mode || $postscript_mode || $xdv_mode
2747 || ( $printout_mode && ($print_type eq 'ps') || ($print_type eq 'dvi') )
2748 || ( ($preview_mode || $preview_continuous_mode) && ( ($view eq 'ps') || ($view eq 'dvi') ) )
2749 ) {
2750 # Automatic switching (e.g., pdf<->dvi o/p) requires pdf files to be
2751 # the only destinations. So if ps or dvi files needed, we cannot
2752 # allow switching. (There will then be an error condition if a TeX
2753 # engine fails to produce the correct type of output file.)
2754 if ($diagnostics) {
2755 warn "$My_name: Disallowing switch of output file as incompatible\n",
2756 " with file requests.\n";
2757 }
2758 $can_switch = 0;
2759 }
2760
2761
2762 if ( $pdf_mode == 2 ) {
2763 # We generate pdf from ps. Make sure we have the correct kind of ps.
2764 add_option( "$dvips_pdf_switch", \$dvips );
2765 }
2766
2767 # Note that 100% CPU usage may not be terribly bad with a multi-core CPU,
2768 # and an SSD, especially when the OS caches file metadata reliably.
2769 if ( $sleep_time == 0 ) {
2770 warn "$My_name: sleep_time was configured to zero.\n",
2771 " Do you really want to do this? It can give 100% CPU usage.\n";
2772 }
2773 elsif ( $sleep_time < $min_sleep_time ) {
2774 warn "$My_name: Correcting nonzero sleep_time of less than $min_sleep_time sec to $min_sleep_time sec.\n";
2775 $sleep_time = $min_sleep_time;
2776 }
2777
2778
2779 # Standardize specifications for generated file extensions:
2780 #
2781 # Remove leading and trailing space in the following space-separated lists,
2782 # and collapse multiple spaces to one,
2783 # to avoid getting incorrect blank items when they are split.
2784 foreach ($clean_ext, $clean_full_ext) { s/^\s+//; s/\s+$//; s/\s+/ /g; }
2785 # Put everything in the arrays:
2786 push @generated_exts, split('\s+',$clean_ext);
2787 push @final_output_exts, split('\s+',$clean_full_ext);
2788
2789 # Convert the arrays to hashes, for ease of deletion:
2790 # Keep extension without period!
2791 our %generated_exts = ();
2792 foreach (@generated_exts ) { $generated_exts{$_} = 1; }
2793
2794 our $quell_uptodate_msgs = $silent;
2795 # Whether to quell informational messages when files are uptodate
2796 # Will turn off in -pvc mode
2797
2798 our $failure_count = 0;
2799 our @failed_primaries = ();
2800
2801 if ($deps_file eq '' ) {
2802 # Standardize name used for stdout
2803 $deps_file = '-';
2804 }
2805
2806 # Since deps_file is global (common to all processed files), we must
2807 # delete it here when doing a clean up, and not in the FILE loop, where
2808 # per-file processing (including clean-up) is done
2809 if ( ($cleanup_mode > 0) && $dependents_list && ( $deps_file ne '-' ) ) {
2810 unlink_or_move( $deps_file );
2811 }
2812
2813 # In non-pvc mode, the dependency list is global to all processed TeX files,
2814 # so we open a single file here, and add items to it after processing
2815 # each file. But in -pvc mode, the dependency list should be written
2816 # after round of processing the single TeX file (as if each round were
2817 # a separate run of latexmk).
2818 # If we are cleaning up ($cleanup_mode != 0) AND NOT continuing to
2819 # make files (--gg option and $go_mode == 2), deps_file should not be
2820 # created.
2821 # I will use definedness of $deps_handle as flag for global deps file having
2822 # been opened and therefore being available to be written to after
2823 # compiling a file.
2824
2825 our $deps_handle = undef;
2826 if ( $dependents_list
2827 && ! $preview_continuous_mode
2828 && ( ($cleanup_mode == 0) || ($go_mode == 2) )
2829 ) {
2830 open( $deps_handle, ">$deps_file" );
2831 if (! $deps_handle ) {
2832 die "Cannot open '$deps_file' for output of dependency information\n";
2833 }
2834 }
2835
2836 # Deal with illegal and problematic characters in filename:
2837 test_fix_texnames( @file_list );
2838
2839 our $quote = $quote_filenames ? '"' : '';
2840 # Primary filename and path are variables of overall context, and hence global.
2841 our $filename;
2842 our $path;
2843 # Other globals
2844 our ( @default_includes, $texfile_name, $root_filename, $log_name,
2845 $tex_basename, $bcf_name, $fls_name, $fls_name_alt, $fdb_name, $aux_main,
2846 $dvi_name, $dviF_name, $hnt_name, $ps_name, $psF_name, $pdf_name,
2847 $xdv_name,
2848 $dvi_final, $hnt_final, $ps_final, $pdf_final, $xdv_final,
2849 $dvi_final2, $hnt_final2, $ps_final2, $pdf_final2,
2850 $view_file,
2851 %rule_list,
2852 $missing_dvi_pdf, $switched_primary_output
2853 );
2854 # Defaults for when rule-using subroutines are used outside a rule:
2855 $rule = '';
2856 $Pbase = \$root_filename;
2857 $Psource = \$texfile_name;
2858 my $start_time = time();
2859 $Prun_time = \$start_time;
2860
2861
2862 FILE:
2863 foreach $filename ( @file_list )
2864 {
2865 # Global variables for making of current file:
2866 $updated = 0;
2867 $failure = 0; # Set nonzero to indicate failure at some point of
2868 # a make. Use value as exit code if I exit.
2869 $failure_msg = ''; # Indicate reason for failure
2870
2871 my $path = '';
2872 if ( $do_cd ) {
2873 # Use my fileparse routine rather than the built-in one, otherwise
2874 # under msys, a directory separator \ won't be recognized by fileparse.
2875 # My routines fix that. At this point, $filename ought to have had its
2876 # \s changed to /s. But I won't leave boobytrapped code.
2877 # I use fileparseB rather than fileparseA, because fileparseA changes
2878 # path './' to '', but fileparseB keeps the fileparse behavior there.
2879 # I have to supply an explicit pattern of '' to keep extension in $filename.
2880 ($filename, $path) = fileparseB( $filename, '' );
2881 print "$My_name: Changing directory to '$path'\n"
2882 if !$silent;
2883 pushd( dirname_no_tail( $path ) );
2884 }
2885
2886 # Localize the following, because they may get changed because of
2887 # conditions specific to the current tex file, notably:
2888 # Change of emulation state of aux_dir
2889 # Use of $do_cd, which can affect how $aux_dir and $out_dir get normalized.
2890 local $aux_dir = $aux_dir;
2891 local $out_dir = $out_dir;
2892 local $out2_dir = $out2_dir;
2893
2894 local $dvilualatex = $dvilualatex;
2895 local $hilatex = $hilatex;
2896 local $latex = $latex;
2897 local $lualatex = $lualatex;
2898 local $pdflatex = $pdflatex;
2899 local $xelatex = $xelatex;
2900
2901 &normalize_aux_out_ETC;
2902 # Set -output-directory and -aux-directory options for *latex here,
2903 # since at least: Their method of use depends on the dynamically
2904 # set $emulate_aux, and the exact strings for the directory names are
2905 # not known until after the call to normalize_aux_out_ETC:
2906 &set_aux_out_options;
2907 &set_names; # Names of standard files
2908 if ($diagnostics || $aux_out_dir_report ) {
2909 print "$My_name: Cwd: '", good_cwd(), "'\n";
2910 print "$My_name: Normalized aux dir, out dir, out2 dir:\n",
2911 " '$aux_dir', '$out_dir', '$out2_dir'\n";
2912 print "$My_name: Combining forms of aux dir, out dir, out2 dir:\n",
2913 " '$aux_dir1', '$out_dir1', '$out2_dir1'\n";
2914 print "$My_name: Base name of generated files:\n",
2915 " '$root_filename'\n";
2916 if ($aux_out_dir_report == 2) {
2917 next FILE;
2918 }
2919 }
2920
2921 # For use under error conditions:
2922 @default_includes = ($texfile_name, $aux_main);
2923 # Set rules here for current conditions
2924 &rdb_initialize_rules;
2925 $view_file = '';
2926 rdb_one_rule( 'view', sub{ $view_file = $$Psource; } );
2927
2928 if ( $diagnostics ) {
2929 print "$My_name: Rules after start up for '$texfile_name'\n";
2930 rdb_show();
2931 }
2932
2933 if ($cleanup_fdb) {
2934 print "$My_name: Deleting '$fdb_name' (file of cached information)\n";
2935 unlink_or_move( $fdb_name );
2936 }
2937
2938 # Set rules from fdb_latexmk file, if possible.
2939 # Allow adaptation of output extension for primary rule to cached
2940 # value, but not if we are doing a cleanup (since then the rules
2941 # will all be reset after the cleanup).
2942 if ( -e $fdb_name ) {
2943 if (0 != rdb_read( $fdb_name, $cleanup_mode ) ) {
2944 # There were some problems with the file of cached rules, so
2945 # the resulting set of rules may be problematic: file status
2946 # data may be incorrect.
2947 # So use filetime criterion for make instead of file change from
2948 # previous run, until we have done our own make.
2949 # ???!!! CHECK: WHY ONLY PRIMARIES????
2950 rdb_recurse( [$current_primary],
2951 sub{ $$Pno_history = 1; }
2952 );
2953 }
2954 }
2955 elsif ( -e $log_name ) {
2956 # At least we can use dependency information from previous run of
2957 # *latex, which may not have been under latexmk control, otherwise
2958 # the fdb_latexmk file would have been made.
2959 rdb_for_some( [$current_primary],
2960 sub{ rdb_set_latex_deps($cleanup_mode) }
2961 );
2962 &rdb_set_rule_net;
2963 }
2964
2965 # At this point, the file and rule databases are correctly initialized
2966 # either from the fdb_latexmk database (corresponding to the state at
2967 # the end of the previous run of latexmk), or from default initialization,
2968 # assisted by dependency information from log files about previous
2969 # run, if the log file exists.
2970
2971 if ( $cleanup_mode ) { do_cleanup( $cleanup_mode ); }
2972 if ($cleanup_only) { next FILE; }
2973
2974 if ( ! -e $aux_main ) {
2975 # No aux file => set up trivial aux file
2976 # and corresponding fdb_file. Arrange them to provoke one run
2977 # as minimum, but no more if actual aux file is trivial.
2978 # (Useful on short simple files.)
2979 # If aux file doesn't exist, then any fdb file is surely
2980 # wrong. So updating it to current state is sensible.
2981 print( "No existing .aux file, so I'll make a simple one, and require run of *latex.\n")
2982 unless $silent;
2983 &set_trivial_aux_fdb;
2984 }
2985
2986 if ($go_mode == 3) {
2987 # Force primaries to be remade.
2988 if (!$silent) { print "Force *latex to be remade.\n"; }
2989 rdb_for_some( [keys %possible_primaries], sub{$$Pout_of_date = 'go_mode=3';} );
2990 }
2991 elsif ($go_mode) {
2992 # Force everything to be remade.
2993 if (!$silent) { print "Force everything to be remade.\n"; }
2994 rdb_recurse( [ &rdb_target_array], sub{$$Pout_of_date = 'go_mode';} );
2995 }
2996
2997
2998 if ( $diagnostics ) {
2999 print "$My_name: Rules after initialization\n";
3000 rdb_show();
3001 }
3002
3003 #************************************************************
3004
3005 if ( $preview_continuous_mode ) {
3006 &make_preview_continuous;
3007 next FILE;
3008 }
3009
3010
3011 ## Handling of failures:
3012 ## Variable $failure is set to indicate a failure, with information
3013 ## put in $failure_msg.
3014 ## These variables should be set to 0 and '' at any point at which it
3015 ## should be assumed that no failures have occurred.
3016 ## When after a routine is called it is found that $failure is set, then
3017 ## processing should normally be aborted, e.g., by return.
3018 ## Then there is a cascade of returns back to the outermost level whose
3019 ## responsibility is to handle the error.
3020 ## Exception: An outer level routine may reset $failure and $failure_msg
3021 ## after initial processing, when the error condition may get
3022 ## ameliorated later.
3023 #Initialize failure flags now.
3024 $failure = 0;
3025 $failure_msg = '';
3026 &init_timing1;
3027
3028 $failure = rdb_make();
3029 if ( ( $failure <= 0 ) || $force_mode ) {
3030 rdb_for_some( [keys %one_time], \&rdb_run1 );
3031 }
3032 if ($#primary_warning_summary > -1) {
3033 # N.B. $mult_defined, $bad_reference, $bad_character, $bad_citation also available here.
3034 if ($warnings_as_errors) {
3035 $failure = 1;
3036 $failure_msg = "Warning(s) from latex (or c.) for '$filename'; treated as error";
3037 }
3038 }
3039
3040 if ($failure > 0) {
3041 if ($failure_cmd) { Run_subst( $failure_cmd ); }
3042 next FILE;
3043 } else {
3044 if ($success_cmd) { Run_subst( $success_cmd ); }
3045 }
3046 } # end FILE
3047 continue {
3048 if ($deps_handle) { deps_list($deps_handle); }
3049 # If requested, print the list of rules. But don't do this in -pvc
3050 # mode, since the rules list has already been printed.
3051 if ($rules_list && ! $preview_continuous_mode) { rdb_list(); }
3052 # Handle any errors
3053 my $error_message_count = rdb_show_rule_errors();
3054 if ( ($error_message_count == 0) || ($failure > 0) ) {
3055 if ( $failure_msg ) {
3056 #Remove trailing space
3057 $failure_msg =~ s/\s*$//;
3058 warn "----------------------\n";
3059 warn "This message may duplicate earlier message.\n";
3060 warn "$My_name: Failure in processing file '$filename':\n",
3061 " $failure_msg\n";
3062 warn "----------------------\n";
3063 $failure = 1;
3064 }
3065 }
3066 if ( ($failure > 0) || ($error_message_count > 0) ) {
3067 $failure_count ++;
3068 push @failed_primaries, $filename;
3069 }
3070 &ifcd_popd;
3071 if ($show_time && ! $preview_continuous_mode) { &show_timing1; };
3072 print "\n";
3073 }
3074 close($deps_handle) if ( $deps_handle );
3075
3076 if ( $show_time && ( ($#file_list > 0) || $preview_continuous_mode ) ) {
3077 print "\n";
3078 show_timing_grand();
3079 }
3080
3081 # If we get here without going through the continue section:
3082 if ( $do_cd && ($#dir_stack > -1) ) {
3083 # Just in case we did an abnormal exit from the loop
3084 warn "$My_name: Potential bug: dir_stack not yet unwound, undoing all directory changes now\n";
3085 &finish_dir_stack;
3086 }
3087
3088 if ($filetime_offset_measured) {
3089 if ( (abs($filetime_offset) >= $filetime_offset_report_threshold)
3090 && ($diagnostics || ! $silent) )
3091 {
3092 warn "$My_name: I am working around an offset relative to my system time by\n",
3093 " $filetime_offset secs for file times in directory '$aux_dir1'.\n",
3094 " This **probably** indicates that \n",
3095 " (a) I ($my_name) am running on one computer, while the filesystem is\n",
3096 " hosted on a different computer/\n",
3097 " (b) There is a substantial time offset between system times on the two\n",
3098 " computers.\n",
3099 " (c) Therefore at least one of the computers has a misconfigured operating\n",
3100 " system such that its system time is not correctly synchronized with a\n",
3101 " time server.\n",
3102 " These issues are likely to cause problems with other software, and any\n",
3103 " such operating-system misconfigurations should be corrected. By default\n",
3104 " current operating systems are configured to correctly synchronize system\n",
3105 " time when they are connected to the Internet\n";
3106 }
3107 }
3108
3109 if ($failure_count > 0) {
3110 if ( $#file_list > 0 ) {
3111 # Error occured, but multiple files were processed, so
3112 # user may not have seen all the error messages
3113 warn "\n------------\n";
3114 warn_array(
3115 "$My_name: Some operations failed, for the following tex file(s)",
3116 @failed_primaries);
3117 }
3118 if ( !$force_mode ) {
3119 warn
3120 "$My_name: Sometimes, the -f option can be used to get latexmk\n",
3121 " to try to force complete processing.\n",
3122 " But normally, you will need to correct the file(s) that caused the\n",
3123 " error, and then rerun latexmk.\n",
3124 " In some cases, it is best to clean out generated files before rerunning\n",
3125 " latexmk after you've corrected the files.\n";
3126 }
3127 exit 12;
3128 }
3129
3130 if ( $emulate_aux_switched ) {
3131 warn "$My_name: I had to switch emulate-aux-dir on after it was initially off,\n",
3132 " because your *latex program appeared not to support -aux-directory. You\n",
3133 " probably should either use the option -emulate-aux-dir, or in a\n",
3134 " latexmkrc file set \$emulate_aux = 1;\n";
3135 }
3136
3137 # end MAIN PROGRAM
3138
3139 #############################################################
3140 #############################################################
3141
3142 # Subroutines for working with processing time
3143
3144 ############################
3145
3146 sub add_timing {
3147 # Usage: add_timing( time_for_run, rule );
3148 # Adds time_for_run to @timings1, @timings0
3149 my ( $time, $rule ) = @_;
3150 push @timings1, "'$rule': time = " . sprintf('%.2f',$time) . "\n";
3151 push @timings0, "'$rule': time = " . sprintf('%.2f',$time) . "\n";
3152 }
3153
3154 ############################
3155
3156 sub init_timing1 {
3157 # Initialize timing for one run.
3158 @timings1 = ();
3159 $processing_time1 = processing_time();
3160 $clock1 = time();
3161 }
3162
3163 ############################
3164
3165 sub init_timing_all {
3166 # Initialize timing for totals and for one run:
3167 @timings0 = ();
3168 $processing_time0 = processing_time();
3169 &init_timing1;
3170 }
3171
3172 ############################
3173
3174 sub show_timing1 {
3175 # Show timing for one run.
3176 my $processing_time = processing_time() - $processing_time1;
3177 my $invoked_time = 0;
3178 for (@timings1) {
3179 if (/: time = (.*)\s$/) {
3180 $invoked_time += $1;
3181 }}
3182 print @timings1, "Processing time = ",
3183 sprintf('%.2f', $processing_time),
3184 ", of which invoked processes = $invoked_time, other = ",
3185 sprintf( '%.2f', $processing_time-$invoked_time ), ".\n";
3186 print "Elapsed clock time = ",
3187 sprintf( '%.2f', time()-$clock1 ), ".\n";
3188 print "Number of rules run = ", 1+$#timings1, "\n";
3189 }
3190
3191 ############################
3192
3193 sub show_timing_grand {
3194 # Show grand total timing.
3195 my $processing_time = processing_time() - $processing_time0;
3196 print # @timings0,
3197 "Grand total processing time = ",
3198 sprintf('%.2f', $processing_time), "\n";
3199 print "Total number of rules run = ", 1+$#timings0, "\n";
3200 }
3201
3202 #############################################################
3203 #############################################################
3204
3205 sub set_tex_cmds {
3206 # Usage, e.g., set_tex_cmds( '%O %S' )
3207 # or set_tex_cmds( '%C-dev %O %S' )
3208 my $args = $_[0];
3209 no strict "refs";
3210 foreach my $cmd ( keys %possible_primaries ) {
3211 my $spec = $args;
3212 if ( $spec =~ /%C/ ) { $spec =~ s/%C/$cmd/g; }
3213 else { $spec = "$cmd $args"; }
3214 ${$cmd} = $spec;
3215 }
3216 # N.B. See setting of $latex_default_switches, ...,
3217 # $xelatex_default_switches, etc, for any special options needed.
3218 }
3219
3220 sub std_tex_cmds { set_tex_cmds( '%O %S' ); }
3221
3222 sub alt_tex_cmds { set_tex_cmds( '%O %P' ); }
3223
3224 #========================
3225
3226 sub test_fix_texnames {
3227 my $illegal_char = 0;
3228 my $unbalanced_quote = 0;
3229 my $balanced_quote = 0;
3230 foreach (@_) {
3231 if ( ($^O eq "MSWin32") || ($^O eq "msys") ) {
3232 # On MS-Win, change directory separator '\' to '/', as needed
3233 # by the TeX engines, for which '\' introduces a macro name.
3234 # Remember that '/' is a valid directory separator in MS-Win.
3235 s[\\][/]g;
3236 }
3237 if ($do_cd) {
3238 my ($filename, $path) = fileparse( $_ );
3239 if ($filename =~ /[\Q$illegal_in_texname\E]/ ) {
3240 $illegal_char++;
3241 warn "$My_name: Filename '$filename' contains character not allowed for TeX file.\n";
3242 }
3243 if ($filename =~ /^&/) {
3244 $illegal_char++;
3245 warn "$My_name: Filename '$filename' contains initial '&', which is\n",
3246 " not allowed for TeX file.\n";
3247 }
3248 }
3249 else {
3250 if ( /[\Q$illegal_in_texname\E]/ ) {
3251 $illegal_char++;
3252 warn "$My_name: Filename '$_' contains character not allowed for TeX file.\n";
3253 }
3254 if (/^&/ ) {
3255 $illegal_char++;
3256 warn "$My_name: Filename '$_' contains initial '&', which is not allowed\n",
3257 " for TeX file.\n";
3258 }
3259 }
3260 my $count_q = ($_ =~ tr/\"//);
3261 if ( ($count_q % 2) != 0 ) {
3262 warn "$My_name: Filename '$_' contains unbalanced quotes, not allowed.\n";
3263 $unbalanced_quote++;
3264 }
3265 elsif ( $count_q > 0 ) {
3266 print "$My_name: Removed (balanced quotes) from filename '$_',\n";
3267 s/\"//g;
3268 print " and obtained '$_'.\n";
3269 $balanced_quote++;
3270 }
3271 }
3272 if ($illegal_char || $unbalanced_quote) {
3273 die "$My_name: Stopping because of bad filename(s).\n";
3274 }
3275 }
3276
3277 #############################################################
3278
3279 sub ensure_path {
3280 # Usage: ensure_path( var, values ...)
3281 # $ENV{var} is an environment variable (e.g. $ENV{TEXINPUTS}.
3282 # Ensure the values are in it, prepending them if not, and
3283 # creating the environment variable if it doesn't already exist.
3284 my $var = shift;
3285 my %cmpts = ();
3286 if ( exists $ENV{$var} ) {
3287 foreach ( split $search_path_separator, $ENV{$var} ) {
3288 if ($_ ne '') { $cmpts{$_} = 1; }
3289 }
3290 }
3291 foreach (@_) {
3292 next if ( ($_ eq '') || (exists $cmpts{$_}) );
3293 if (exists $ENV{$var}) {
3294 $ENV{$var} = $_ . $search_path_separator . $ENV{$var};
3295 }
3296 else {
3297 $ENV{$var} = $_ . $search_path_separator;
3298 }
3299 if ($diagnostics) {
3300 print "Set environment variable $var='$ENV{$var}'\n";
3301 }
3302 }
3303 } #END ensure_path
3304
3305 #############################################################
3306
3307 sub path_fudge {
3308 # Usage: path_fudge( var1[, var2 ...])
3309 # For each argument, $ENV{var} is an environment variable
3310 # (e.g. $ENV{BIBINPUTS}, that is a search path.
3311 # Adjust each of these environment variables so that it is
3312 # appropriately set for use when a program is run with a changed wd,
3313 # as with bibtex when $bibtex_fudge is set.
3314 # Specifically:
3315 # 1. Prepend current wd to each $ENV{var}, if it exists; otherwise
3316 # set $ENV{var} to current wd followed by search-path separator,
3317 # so that search path is cwd and then default.
3318 # Hence files in cwd are found by a program run in another
3319 # directory.
3320 # 2. For each item in $ENV{var} that isn't an absolute path, i.e.,
3321 # that is relative, replace it by itself followed by the same path
3322 # converted to an absolute path, with the relative path being
3323 # assumed to be relative to the current wd.
3324 # Hence a program run in another directory finds files that were
3325 # originally intended to be in a directory relative to the orginal
3326 # cwd. In addition, in the conceivable case that the item in the
3327 # search path is actually intended to be relative to the directory
3328 # in which the program is run (normally the aux dir), it also
3329 # works correctly.
3330
3331 my $cwd = good_cwd();
3332 foreach my $var ( @_ ) {
3333 if ( exists $ENV{$var} ) {
3334 $ENV{$var} = $cwd.$search_path_separator.$ENV{$var};
3335 }
3336 else {
3337 $ENV{$var} = $cwd.$search_path_separator;
3338 }
3339
3340 my @items = split_search_path( $search_path_separator, '', $ENV{$var} );
3341 my $changed = 0;
3342
3343 foreach (@items) {
3344 if ($_ eq '' ) {
3345 # Empty item => std search path => nothing to do.
3346 }
3347 elsif ( ! file_name_is_absolute($_) ) {
3348 my $abs = rel2abs($_);
3349 $_ .= $search_path_separator.$abs;
3350 $changed = 1;
3351 }
3352 }
3353
3354 if ($changed) {
3355 # Correct the env. var.
3356 $ENV{$var} = join( $search_path_separator, @items );
3357 print "====== ENV{$var} changed to '$ENV{$var}'\n";
3358 }
3359 } # END loop over env. vars.
3360 } #END path_fudge
3361
3362 #############################################################
3363
3364 sub normalize_aux_out_ETC {
3365 # 1. Normalize $out_dir and $aux_dir, so that if they have a non-trivial last
3366 # component, any trailing '/' is removed.
3367 # 2. They should be non-empty.
3368 # 3. Set $out_dir1 and $aux_dir1 to have a directory separator character
3369 # '/' added if needed to give forms suitable for direct concatenation with
3370 # a filename. These are needed for substitutions like %Y%R.
3371 # Nasty cases of dir_name: "/" on all systems, "A:", "A:/" etc on MS-Win
3372 # 4. Set some TeX-related environment variables.
3373 # 5. Ensure the aux and out directories exist
3374
3375 # Ensure the output/auxiliary directories exist, if need be, **with error checking**.
3376 my $ret1 = 0;
3377 my $ret2 = 0;
3378 my $ret3 = 0;
3379 eval {
3380 if ( $out_dir ) {
3381 $ret1 = make_path_mod( $out_dir, 'output' );
3382 }
3383 if ( $out2_dir ) {
3384 $ret2 = make_path_mod( $out2_dir, 'final output' );
3385 }
3386 if ( $aux_dir && ($aux_dir ne $out_dir) ) {
3387 $ret3 = make_path_mod( $aux_dir, 'auxiliary' );
3388 }
3389 };
3390 if ($ret1 || $ret2 || $ret3 || $@ ) {
3391 if ($@) { print "Error message:\n $@"; }
3392 die "$My_name: Since there was trouble making the output (and aux) dirs, I'll stop\n"
3393 }
3394
3395 if ($normalize_names) {
3396 foreach ( $aux_dir, $out_dir, $out2_dir ) {
3397 $_ = normalize_filename_abs($_);
3398 }
3399 }
3400 $aux_dir1 = $aux_dir;
3401 $out_dir1 = $out_dir;
3402 $out2_dir1 = $out2_dir;
3403 foreach ( $aux_dir1, $out_dir1, $out2_dir1 ) {
3404 if ($_ eq '.') {$_ = '';}
3405 if ( ($_ ne '') && ! m([\\/\:]$) ) {
3406 # Add a trailing '/' if necessary to give a string that can be
3407 # correctly concatenated with a filename:
3408 $_ .= '/';
3409 }
3410 }
3411 if ($aux_dir) {
3412 # Ensure $aux_dir is in BIBINPUTS and TEXINPUTS search paths.
3413 # TEXINPUTS is used by dvips for files generated by mpost.
3414 # For BIBINPUTS,
3415 # at least one widely package (revtex4-1) generates a bib file
3416 # (which is used in revtex4-1 for putting footnotes in the reference
3417 # list), and bibtex must be run to use it. But latexmk needs to
3418 # determine the existence of the bib file by use of kpsewhich, otherwise
3419 # there is an error. So cope with this situation (and any analogous
3420 # cases by adding the aux_dir to the relevant path search environment
3421 # variables. BIBINPUTS seems to be the only one currently affected.
3422 # Convert $aux_dir to absolute path to make the search path invariant
3423 # under change of directory.
3424 foreach ( 'BIBINPUTS', 'TEXINPUTS' ) {
3425 ensure_path( $_, $aux_dir );
3426 }
3427 # Set TEXMFOUTPUT so that when the aux_dir is not a subdirectory
3428 # of the cwd (or below), bibtex and makeindex can write to it.
3429 # Otherwise, security precautions in these programs will prevent
3430 # them from writing there, on TeXLive. MiKTeX is different: see
3431 # below.
3432 # The security issues concern **document-controlled** writing of
3433 # files, when bibtex or makeindex is invoked directly by a
3434 # document. In contrast, here $aux_dir is set by latexmk, not by
3435 # the document. (See the main texmf.cnf file in a TeXLive
3436 # distribution for some information on security issues.)
3437 #
3438 # PROPERTIES:
3439 # 1. In TeXLive, the use of TEXMFOUTPUT works if
3440 # (a) the directory given is an an absolute path,
3441 # AND (b) the path contains no .. pieces
3442 # AND (c) the directory component of the filename(s) on the command
3443 # line for makeindex and bibtex is exactly the same string as
3444 # for the directory named in TEXMFOUTPUT.
3445 # 2. In MiKTeX, bibtex has none of the security restrictions; but
3446 # makeindex has, and the use of TEXMFOUTPUT has no effect.
3447 # So the following is only needed for TeXLive.
3448 $ENV{TEXMFOUTPUT} = $aux_dir;
3449 }
3450 } #END normalize_aux_out_ETC
3451
3452 #############################################################
3453
3454 sub set_aux_out_options {
3455 # Set -output-directory and -aux-directory options for *latex. Use
3456 # placeholders for substitutions so that correct value is put in at
3457 # runtime.
3458 # N.B. At this point, $aux_dir and $out_dir should be non-empty, unlike the
3459 # case after the reading of latexmkrc files, where empty string means
3460 # use default. Let's be certain, however:
3461 if ($out_dir eq '') { $out_dir = '.'; $out_dir1 = ''; }
3462 if ($aux_dir eq '') { $aux_dir = $out_dir; $aux_dir1 = $out_dir1; }
3463
3464 if ($emulate_aux) {
3465 if ( $aux_dir ne '.' ) {
3466 # N.B. Set **output** directory to **aux_dir**, rather than
3467 # out_dir. If aux and out dirs are are different, then we'll move
3468 # the relevant files (.pdf, .ps, .dvi, .xdv, .fls to the output
3469 # directory after running *latex.
3470 add_option( "-output-directory=%V",
3471 \$dvilualatex, \$hilatex, \$latex, \$pdflatex, \$lualatex, \$xelatex );
3472 }
3473 }
3474 else {
3475 if ( $out_dir && ($out_dir ne '.') ) {
3476 add_option( "-output-directory=%W",
3477 \$dvilualatex, \$hilatex, \$latex, \$pdflatex, \$lualatex, \$xelatex );
3478 }
3479 if ( $aux_dir ne $out_dir ) {
3480 # N.B. If $aux_dir and $out_dir are the same, then the
3481 # -output-directory option is sufficient, especially because
3482 # the -aux-directory exists only in MiKTeX, not in TeXLive.
3483 add_option( "-aux-directory=%V",
3484 \$dvilualatex, \$hilatex, \$latex, \$pdflatex, \$lualatex, \$xelatex );
3485 }
3486 }
3487 } #END set_aux_out_options
3488
3489 #############################################################
3490
3491 sub fix_cmds {
3492 # If commands do not have placeholders for %S etc, put them in
3493 foreach ($hilatex, $latex, $lualatex, $pdflatex, $xelatex, $lpr, $lpr_dvi, $lpr_pdf,
3494 $pdf_previewer, $ps_previewer, $ps_previewer_landscape,
3495 $dvi_previewer, $dvi_previewer_landscape,
3496 $kpsewhich
3497 ) {
3498 # Source only
3499 if ( $_ && ! /%/ ) { $_ .= " %O %S"; }
3500 }
3501 foreach ($pdf_previewer, $ps_previewer, $ps_previewer_landscape,
3502 $dvi_previewer, $dvi_previewer_landscape,
3503 ) {
3504 # Run previewers detached
3505 if ( $_ && ! /^(nostart|NONE|internal) / ) {
3506 $_ = "start $_";
3507 }
3508 }
3509 foreach ($biber, $bibtex) {
3510 # Base only
3511 if ( $_ && ! /%/ ) { $_ .= " %O %B"; }
3512 }
3513 foreach ($dvipdf, $ps2pdf) {
3514 # Source and dest without flag for destination
3515 if ( $_ && ! /%/ ) { $_ .= " %O %S %D"; }
3516 }
3517 foreach ($dvips, $makeindex) {
3518 # Source and dest with -o dest before source
3519 if ( $_ && ! /%/ ) { $_ .= " %O -o %D %S"; }
3520 }
3521 foreach ($dvi_filter, $ps_filter) {
3522 # Source and dest, but as filters
3523 if ( $_ && ! /%/ ) { $_ .= " %O <%S >%D"; }
3524 }
3525 } #END fix_cmds
3526
3527 #############################################################
3528
3529 sub add_option {
3530 # Call add_option( $opt, \$cmd ... )
3531 # Add option to one or more commands
3532 no strict "refs";
3533 my $option = shift;
3534 while (@_) {
3535 if ( ${$_[0]} !~ /%/ ) { &fix_cmds; }
3536 ${$_[0]} =~ s/%O/$option %O/;
3537 shift;
3538 }
3539 } #END add_option
3540
3541 #############################################################
3542
3543 sub rdb_initialize_rules {
3544 # Initialize rule database.
3545 # (The rule database may get overridden/extended after the fdb_latexmk
3546 # file is read, and after running commands to adjust to dependencies
3547 # determined from document.
3548
3549 %rule_db = ();
3550 %target_rules = ();
3551 %target_files = ();
3552 %actives = ();
3553 %from_rules = ();
3554
3555 local %rule_list = ();
3556 &rdb_set_rule_templates;
3557
3558 my %rule_template = %rule_list;
3559 while ( my ($key, $value) = each %extra_rule_spec ) {
3560 $rule_template{$key} = $value;
3561 }
3562 # ???!!! REVISE
3563 foreach my $rule ( keys %rule_template ) {
3564 my ( $cmd_type, $ext_cmd, $int_cmd, $source, $dest, $base,
3565 $DUMMY, $PA_extra_gen, $PA_extra_source )
3566 = @{$rule_template{$rule}};
3567 if ( ! $PA_extra_gen ) { $PA_extra_gen = []; }
3568 if ( ! $PA_extra_source ) { $PA_extra_source = []; }
3569 my $needs_making = 0;
3570 # Substitute in the filename variables, since we will use
3571 # those for determining filenames. But delay expanding $cmd
3572 # until run time, in case of changes.
3573 foreach ($base, $source, $dest, @$PA_extra_gen, @$PA_extra_source ) {
3574 s/%R/$root_filename/g;
3575 s/%X/$out2_dir1/;
3576 s/%Y/$aux_dir1/;
3577 s/%Z/$out_dir1/;
3578 }
3579 foreach ($source, $dest ) {
3580 s/%B/$base/;
3581 s/%T/$texfile_name/;
3582 }
3583 rdb_create_rule( $rule, $cmd_type, $ext_cmd, $int_cmd, $DUMMY,
3584 $source, $dest, $base,
3585 $needs_making, undef, undef, 1, $PA_extra_gen, $PA_extra_source );
3586 } # End rule iteration
3587
3588 # At this point, all the rules are active.
3589 # The rules that are used are determined by starting with the desired
3590 # final files and going backwards in the rule network to find what rules
3591 # have to be run to make the final files.
3592 # The only problem in doing this is if there is more than one way of making
3593 # a given file. This arises only for rules that make pdf or dvi files,
3594 # since we have multiple rules for making them.
3595
3596 # Ensure we only have one way to make pdf file, and only one active primary:
3597 # Deactivate pdf-making rules and primary rules,
3598 # then reactivating only one pdf producing rule and current primary,
3599 # setting $current_primary as side-effect.
3600
3601 rdb_deactivate( 'dvipdf', 'ps2pdf', 'xdvipdfmx', keys %possible_primaries );
3602
3603 $current_primary = 'latex'; #
3604 # Activate needed non-primary pdf-making rules, set current primary (if
3605 # it isn't latex, and activate the current primary:
3606 if ($pdf_mode == 1) { $current_primary = 'pdflatex'; }
3607 elsif ($pdf_mode == 2) { rdb_activate( 'ps2pdf' ); }
3608 elsif ($pdf_mode == 3) { rdb_activate( 'dvipdf' ); }
3609 elsif ($pdf_mode == 4) { $current_primary = 'lualatex'; }
3610 elsif ($pdf_mode == 5) { rdb_activate( 'xdvipdfmx' ); $current_primary = 'xelatex'; }
3611 if ($dvi_mode == 2) { $current_primary = 'dvilualatex'; }
3612 if ($hnt_mode) { $current_primary = 'hilatex'; }
3613 if ($xdv_mode) { $current_primary = 'xelatex'; }
3614
3615 rdb_activate( $current_primary );
3616
3617 if ($dvi_mode) { $target_files{$dvi_final} = 1; }
3618 if ($hnt_mode) { $target_files{$hnt_final} = 1; }
3619 if ($postscript_mode) { $target_files{$ps_final} = 1; }
3620 if ($pdf_mode) { $target_files{$pdf_final} = 1; }
3621 if ($xdv_mode) { $target_files{$xdv_final} = 1; }
3622 &rdb_set_rule_net;
3623 } # END rdb_initialize_rules
3624
3625 #************************************************************
3626
3627 sub rdb_set_rule_templates {
3628 # Set up specifications for standard rules, adjusted to current conditions
3629 # Substitutions: %S = source, %D = dest, %B = this rule's base
3630 # %T = texfile, %R = root = base for latex.
3631 # %X for $out2_dir1,
3632 # %Y for $aux_dir1, %Z for $out_dir1
3633
3634
3635 my $print_file = '';
3636 my $print_cmd = 'NONE';
3637 if ( $print_type eq 'dvi' ) {
3638 $print_file = $dvi_final2;
3639 $print_cmd = $lpr_dvi;
3640 }
3641 elsif ( $print_type eq 'pdf' ) {
3642 $print_file = $pdf_final2;
3643 $print_cmd = $lpr_pdf;
3644 }
3645 elsif ( $print_type eq 'ps' ) {
3646 $print_file = $ps_final2;
3647 $print_cmd = $lpr;
3648 }
3649 elsif ( $print_type eq 'none' ) {
3650 $print_cmd = 'NONE echo NO PRINTING CONFIGURED';
3651 }
3652
3653 my $view_file = '';
3654 my $viewer = '';
3655 my $viewer_update_method = 0;
3656 my $viewer_update_signal = undef;
3657 my $viewer_update_command = undef;
3658
3659 if ( ($view eq 'dvi') || ($view eq 'hnt') || ($view eq 'pdf') || ($view eq 'ps') ) {
3660 no strict "refs";
3661 $view_file = ${$view.'_final2'};
3662 $viewer = ${$view.'_previewer'};
3663 $viewer_update_method = ${$view.'_update_method'};
3664 $viewer_update_signal = ${$view.'_update_signal'};
3665 if (defined ${$view.'_update_command'}) {
3666 $viewer_update_command = ${$view.'_update_command'};
3667 }
3668 }
3669 # Specification of internal command for viewer update:
3670 my $PA_update = ['do_update_view', $viewer_update_method, $viewer_update_signal, 0, 1];
3671
3672 # Base name is to be without path for *latex-type rules
3673 # With path for others.
3674 %rule_list = (
3675 'dvilualatex' => [ 'primary', "$dvilualatex", '', "%T", $dvi_name, "%R", 1, [$aux_main, $log_name], [$aux_main] ],
3676 'hilatex' => [ 'primary', "$hilatex", '', "%T", $hnt_name, "%R", 1, [$aux_main, $log_name], [$aux_main] ],
3677 'latex' => [ 'primary', "$latex", '', "%T", $dvi_name, "%R", 1, [$aux_main, $log_name], [$aux_main] ],
3678 'lualatex' => [ 'primary', "$lualatex", '', "%T", $pdf_name, "%R", 1, [$aux_main, $log_name], [$aux_main] ],
3679 'pdflatex' => [ 'primary', "$pdflatex", '', "%T", $pdf_name, "%R", 1, [$aux_main, $log_name], [$aux_main] ],
3680 'xelatex' => [ 'primary', "$xelatex", '', "%T", $xdv_name, "%R", 1, [$aux_main, $log_name], [$aux_main] ],
3681
3682 'dvipdf' => [ 'external', "$dvipdf", 'do_viewfile', $dvi_final, $pdf_name, "%Z%R", 1 ],
3683 'xdvipdfmx' => [ 'external', "$xdvipdfmx", 'do_viewfile', $xdv_final, $pdf_name, "%Z%R", 1 ],
3684 'dvips' => [ 'external', "$dvips", 'do_viewfile', $dvi_final, $ps_name, "%Z%R", 1 ],
3685 'dvifilter' => [ 'external', $dvi_filter, 'do_viewfile', $dvi_name, $dviF_name, "%Z%R", 1 ],
3686 'ps2pdf' => [ 'external', "$ps2pdf", 'do_viewfile', $ps_final, $pdf_name, "%Z%R", 1 ],
3687 'psfilter' => [ 'external', $ps_filter, 'do_viewfile', $ps_name, $psF_name, "%Z%R", 1 ],
3688
3689 'print' => [ 'external', "$print_cmd", 'if_source', $print_file, "", "", 1 ],
3690 'update_view' => [ 'external', $viewer_update_command, $PA_update,
3691 $view_file, "", "", 2 ],
3692 'view' => [ 'external', "$viewer", 'if_source', $view_file, "", "", 2 ],
3693 );
3694 } # END rdb_set_rule_templates
3695
3696 #************************************************************
3697
3698 sub rdb_set_rule_net {
3699 # Set network of rules, including links and classifications.
3700 #
3701 # ?? Problem if there are multiple rules for getting a file. Notably pdf.
3702 # Which one to choose?
3703 # ?? Problem: what if a rule is inactive,
3704 # e.g., bibtex because biber is in use,
3705 # or xelatex when pdflatex is in use
3706 # or bibtex when $bibtex_use is 0.
3707 # What if both latex and pdflatex are being used?
3708 # That has been allowed. But .aux file (also
3709 # .log file) are made by both.
3710
3711 # Other case: package (like bibtopic) creates bbl or other file when
3712 # it doesn't exist. Later a rule is created by latexmk to make that
3713 # file. Then the rule's main destination file should have priority
3714 # over non-main generated files from other rules.
3715 our %from_rules_old;
3716 local %from_rules_old = %from_rules;
3717 %from_rules = (); # File to rule.
3718 rdb_for_actives( \&set_file_links_for_rule );
3719 rdb_for_actives( \&rdb_set_source_rules );
3720 &rdb_classify_rules;
3721 }
3722
3723 #------------
3724
3725 sub set_file_links_for_rule {
3726 foreach my $dest ( @$PA_extra_gen, keys %$PHdest ) {
3727 if ( exists $from_rules{$dest} ) {
3728 my $old_rule = $from_rules{$dest};
3729 if ( $old_rule eq $rule ) {
3730 # OK
3731 }
3732 elsif ( exists($possible_primaries{$old_rule})
3733 && exists($possible_primaries{$rule}) ) {
3734 # This could be problematic. But we'll let it go,
3735 # because it is a common case for .aux and .log files
3736 # (etc), and these cases do not appear to mess up
3737 # anything (by experience).
3738 # Once we allow an active flag for rules and only
3739 # examine active rules, the only case of this that
3740 # will appear (in the absence of other problems) will
3741 # be where two primary rules are active, notably a
3742 # latex rule to make dvi and a pdflatex (or other
3743 # rule) to make pdf.
3744 }
3745 else {
3746 warn "$My_name: Possible bug:\n",
3747 " In linking rules I already set source_rules{$dest} to '$old_rule'\n",
3748 " But now I want to set it to '$rule'\n";
3749 }
3750 }
3751 $from_rules{$dest} = $rule;
3752 }
3753 } # END set_file_links_for_rule
3754
3755 #------------
3756
3757 sub rdb_set_source_rules {
3758 # This assumes rule context, and sets explicit source rules in the hash
3759 # %$PHsource_rules. These are to be rules on which the current rule
3760 # depends, but that aren't determined by using the known set of source
3761 # files of the current rule together with the known sets of destination
3762 # files for other rules.
3763 #
3764 # The standard case, and the only one used at the moment is for rules
3765 # whose **main** source file is a dvi or xdv file. These programs used
3766 # by these rules (dvips etc) do not provide easily accessible
3767 # information on the set of graphics files that they read in.
3768 # So such rules are given a source rule that is the *latex that
3769 # generates them.
3770 #
3771 # These cases need special treatment coded here and in the algorithms
3772 # in rdb_make etc.
3773 #
3774 my ($base, $path, $ext) = fileparseA( $$Psource );
3775 our %from_rules_old;
3776 if ( ($ext eq '.dvi') || ($ext eq '.dviF') || ($ext eq '.xdv') ) {
3777 # Rules that use .dvi, .dviF, .xdv don't get all dependencies,
3778 # notably about included graphics files.
3779 # So use a pass criterion instead.
3780 my $old_rule = $from_rules_old{$$Psource};
3781 my $new_rule = $from_rules{$$Psource};
3782 if ( defined $old_rule
3783 && defined $new_rule
3784 && ($old_rule eq $new_rule)
3785 && defined $$PHsource_rules{$new_rule}
3786 )
3787 { # Nothing to do: source rule is correct.
3788 }
3789 else {
3790 if ( defined $old_rule ) { delete $$PHsource_rules{$old_rule}; }
3791 if ( defined $new_rule ) { $$PHsource_rules{$new_rule} = 0; }
3792 }
3793 }
3794 } # END rdb_set_source_rules
3795
3796 #------------
3797
3798 sub rdb_classify_rules {
3799 # Usage: &rdb_classify_rules
3800 # Assume the following variables are available (global or local):
3801 # Input:
3802 # %target_rules # Set to target rules
3803 # %target_files # Set to target files
3804 # %possible_primaries
3805
3806 # Output:
3807 # @pre_primary # Array of rules
3808 # @post_primary # Array of rules
3809 # @unusual_one_time # Array of rules
3810 # @pre_primary and @post_primary are in natural order of application.
3811
3812 my @requested_targets = &rdb_target_array;
3813 our (@classify_stack, $state);
3814 local $state = 0; # Post-primary
3815 local @classify_stack = ();
3816
3817 @pre_primary = ();
3818 @post_primary = ();
3819 @unusual_one_time = ();
3820
3821 rdb_recurse( \@requested_targets, \&rdb_classify1, 0,0, \&rdb_classify2 );
3822
3823 # Reverse, as tendency is to find last rules first.
3824 @pre_primary = reverse @pre_primary;
3825 @post_primary = reverse @post_primary;
3826
3827 if ($diagnostics) {
3828 print "Rule classification: \n";
3829 show_array( " Requested rules:", @requested_targets );
3830 show_array( " Pre-primaries:", @pre_primary );
3831 show_array( " Primary:", $current_primary );
3832 show_array( " Post-primaries:", @post_primary );
3833 show_array( " Inner-level one_time rules:", @unusual_one_time );
3834 show_array( " Outer-level one_time rules:", keys %one_time );
3835 } #end diagnostics
3836
3837 } #END rdb_classify_rules
3838
3839 #-------------------
3840
3841 sub rdb_classify1 {
3842 # Helper routine for rdb_classify_rules
3843 # Applied as rule_act1 in recursion over rules
3844 # Assumes rule context, and local variables from rdb_classify_rules
3845 our (@classify_stack, $state, $depth);
3846 push @classify_stack, [$state];
3847 if ( exists $possible_one_time{$rule} ) {
3848 # Normally, we will have already extracted the one_time rules,
3849 # and they will never be accessed here. But just in case of
3850 # problems or generalizations, we will cover all possibilities:
3851 if ($depth > 1) {
3852 warn "ONE TIME rule not at outer level '$rule'\n";
3853 }
3854 push @unusual_one_time, $rule;
3855 }
3856 elsif ($state == 0) {
3857 if ( exists $possible_primaries{$rule} ) {
3858 $state = 1; # In primary rule
3859 }
3860 else {
3861 push @post_primary, $rule;
3862 }
3863 }
3864 else {
3865 $state = 2; # in post-primary rule
3866 push @pre_primary, $rule;
3867 }
3868 } #END rdb_classify1
3869
3870 #-------------------
3871
3872 sub rdb_classify2 {
3873 # Helper routine for rdb_classify_rules
3874 # Applied as rule_act2 in recursion over rules
3875 # Assumes rule context
3876 our (@classify_stack, $state);
3877 ($state) = @{ pop @classify_stack };
3878 } #END rdb_classify2
3879
3880 #================================
3881
3882 #************************************************************
3883
3884 sub set_trivial_aux_fdb {
3885 # 1. Write aux file as would be written if the tex file had no cross
3886 # cross references, etc. i.e., a minimal .aux file, as would be
3887 # written by latex with a simple document.
3888 # That saves a run of latex on such simple documents.
3889 # Before about 2020, latex only wrote one line, containing '\relax '
3890 # in the aux file. After that a reference to the last page was
3891 # added. So now I write what is written for a one page document.
3892 # But shift file time to past, so that test_gen_file distinguishes
3893 # whether the .aux file got written during the following run of
3894 # *latex or was the one written here.
3895 # 2. Write a corresponding fdb file
3896 # 3. Provoke a run of *latex (actually of all primaries).
3897
3898 # Use raw mode for writing aux file, so that line endings are \n.
3899 # Otherwise on Windows, the aux file file will have \r\n line endings.
3900 # Since both TeXLive and MiKTeX write \n rather than \r\n, latexmk will
3901 # unnecessarily detect a change in the aux file because of the changed
3902 # line endings, and thereby provoke a superfluous extra *latex run.
3903 open( my $aux_file, '> :raw', $aux_main )
3904 or die "Cannot write file '$aux_main'\n";
3905 fprint8( $aux_file, "\\relax \n" );
3906 # The following is added by recent versions of latex for a
3907 # one page document
3908 fprint8( $aux_file, "\\gdef \\\@abspage\@last{1}\n" );
3909 close($aux_file);
3910
3911 # Shift aux time, so that file appears to have been generated in past,
3912 # and not in current run. Shift enough so that test_gen_file's
3913 # causality threshold doesn't cause misdiagnosis.
3914 my $aux_time = get_mtime( $aux_main ) - $filetime_causality_threshold - 3;
3915 utime $aux_time, $aux_time, $aux_main;
3916
3917 foreach my $rule (keys %possible_primaries ) {
3918 rdb_one_rule( $rule,
3919 sub{ $$Pout_of_date = 'Initial setup'; }
3920 );
3921 }
3922 &rdb_write( $fdb_name );
3923 } #END set_trivial_aux_fdb
3924
3925 #************************************************************
3926 #### Particular actions
3927 #************************************************************
3928 #************************************************************
3929
3930 sub do_cleanup {
3931 my $kind = $_[0];
3932 if (! $kind ) { return; }
3933 my @files_to_delete = ();
3934 # Set @dirs to list of directories for generated files.
3935 # Use trick with hash to avoid duplicates.
3936 my %dirs = ();
3937 foreach ($aux_dir1, $out_dir1, $out2_dir1) { $dirs{$_} = 1; }
3938 my @dirs = keys %dirs;
3939
3940 if (! $silent) {
3941 if ($kind == 1) {
3942 print "$My_name: Doing full clean up for '$texfile_name'\n";
3943 }
3944 else {
3945 print "$My_name: Doing main clean up for '$texfile_name'\n",
3946 " (all but extensions @final_output_exts).\n";
3947 }
3948 }
3949 push @files_to_delete, &get_small_cleanup;
3950 if ($kind == 1) {
3951 foreach my $dir1 (@dirs) {
3952 push @files_to_delete, cleanup_get1( $dir1, @final_output_exts );
3953 }
3954 }
3955
3956 # Run the hooks first, since to determine what custom deletions they
3957 # are to make, the hook subroutines may need access to files that
3958 # cleanup later deletes (log, aux, ...).
3959 run_hooks( 'cleanup' );
3960 if ($kind == 1) { run_hooks( 'cleanup_extra_full' ); }
3961
3962 # Names of contents of directory are longer than the name of the
3963 # directory, but contain the directory name as an initial segment.
3964 # Therefore deleting files and directories in the order given by
3965 # reverse sort deletes contents of directory before attempting to
3966 # delete the directory:
3967 unlink_or_move( reverse sort @files_to_delete );
3968
3969 # If the fdb file (or log, fls and/or aux files) exist, it/they will
3970 # have been used to make a changed rule database. But a cleanup
3971 # implies that we need a virgin rule database, corresponding to
3972 # current state of files (after cleanup) so we reset the rule
3973 # database and rule net:
3974 &rdb_initialize_rules;
3975 }
3976
3977 #----------------------------------------
3978
3979 sub cleanup_get1 {
3980 # Usage: cleanup_get1( directory, patterns_or_exts_without_period, ... )
3981 # Return array of files obeying the specification in the given directory.
3982 # Specifications are either extensions to be appended to root_filename
3983 # or are patterns containing %R for root_filename of job, with possible
3984 # wildcards.
3985 # Directory name must include directory separator, e.g., './' or 'output/',
3986 # or be blank, i.e., suitable for prepending to file name.
3987
3988 # The directory and the root file name are fixed names, so I must escape
3989 # any glob metacharacters in them:
3990 my $dir = fix_pattern( shift );
3991 my $root_fixed = fix_pattern( $root_filename );
3992 my @files = ();
3993 foreach (@_) {
3994 my $name = ( /%R/ ? $_ : "%R.$_" );
3995 $name =~ s/%R/${root_fixed}/;
3996 $name = $dir.$name;
3997 push @files, my_glob( "$name" );
3998 }
3999 return @files;
4000 } #END cleanup_get1
4001
4002 #----------------------------------------
4003
4004 sub get_small_cleanup {
4005 # Get list of files to be deleted in a small cleanup.
4006 # Assume dependency information from previous run has been obtained.
4007
4008 my @files = ();
4009 my %other_generated = ();
4010 my %cusdep_generated = ();
4011 my @index_bibtex_generated = ();
4012 my @aux_files = ();
4013 my @missing_bib_files = ();
4014 my $bibs_all_exist = 0;
4015 my %final_output_files = ();
4016
4017 foreach (@final_output_exts) {
4018 $final_output_files{"$out_dir1$root_filename.$_"} = 1;
4019 }
4020 rdb_for_actives(
4021 sub { # Find generated files at rule level
4022 my ($base, $path, $ext) = fileparseA( $$Psource );
4023 $base = $path.$base;
4024 if ( $rule =~ /^makeindex/ ) {
4025 push @index_bibtex_generated, $$Psource, $$Pdest, "$base.ilg";
4026 }
4027 elsif ( $rule =~ /^(bibtex|biber)/ ) {
4028 push @index_bibtex_generated, $$Pdest, "$base.blg";
4029 push @aux_files, $$Psource;
4030 if ( $bibtex_use == 1.5) {
4031 foreach ( keys %$PHsource ) {
4032 if ( ( /\.bib$/ ) && (! -e $_) ) {
4033 push @missing_bib_files, $_;
4034 }
4035 }
4036 }
4037 }
4038 elsif ( exists $possible_primaries{$rule} ) {
4039 foreach my $key (keys %$PHdest) {
4040 $other_generated{$key} = 1;
4041 }
4042 }
4043 elsif ( ($rule =~ /^cusdep/) && (-e $$Psource) ) {
4044 # N.B. Deleting cusdep generated files is wrong if source file doesn't exist.
4045 # But that will be taken care of in the rule-network setup.
4046 # So just have a test for safety in the elsif line, without diagnostics.
4047 foreach my $key (keys %$PHdest) {
4048 $cusdep_generated{$key} = 1;
4049 }
4050 }
4051 },
4052 sub { # Find generated files at source file level
4053 if ( $file =~ /\.aux$/ ) { push @aux_files, $file; }
4054 }
4055 );
4056 if ($#missing_bib_files == -1) { $bibs_all_exist = 1; }
4057
4058 my $keep_bbl = 1;
4059 if ( ($bibtex_use > 1.6)
4060 ||
4061 ( ($bibtex_use == 1.5) && ($bibs_all_exist) )
4062 ) {
4063 $keep_bbl = 0;
4064 }
4065 if ($keep_bbl) {
4066 delete $generated_exts{'bbl'};
4067 }
4068 # Convert some arrays to hashes, since deletions are easier to handle:
4069 my %index_bibtex_generated = ();
4070 my %aux_files = ();
4071 my %aux_files_to_save = ();
4072 foreach (@index_bibtex_generated) {
4073 $index_bibtex_generated{$_} = 1
4074 unless ( /\.bbl$/ && ($keep_bbl) );
4075 delete( $other_generated{$_} );
4076 }
4077 foreach (@aux_files) {
4078 if (exists $other_generated{$_} ) {
4079 $aux_files{$_} = 1;
4080 }
4081 else {
4082 $aux_files_to_save{$_} = 1;
4083 }
4084 }
4085
4086 foreach (keys %final_output_files) { delete $other_generated{$_}; }
4087
4088 if ($diagnostics) {
4089 print "For deletion, files are as follows. Lists are non-exclusive.\n";
4090 show_array( " Files specified by patterns\n"
4091 ." (explicit pattern with %R or root-filename.extension):",
4092 sort keys %generated_exts );
4093 show_array( " Files determined from fdb file or log file that were generated by makeindex\n"
4094 ." or bibtex:",
4095 sort keys %index_bibtex_generated );
4096 show_array( " Aux files (from analysis of rules):", keys %aux_files );
4097 show_array( " Aux files to SAVE and not delete:", keys %aux_files_to_save );
4098 show_array( " Other non-cusdep generated files from *latex:\n"
4099 ." (only deleted if \$cleanup_includes_generated is set and file\n"
4100 ." doesn't appear in another list):",
4101 sort keys %other_generated );
4102 show_array( " Cusdep generated files:\n"
4103 ." (only deleted if \$cleanup_includes_cusdep_generated is set and file\n"
4104 ." doesn't appear in another list):",
4105 sort keys %cusdep_generated );
4106 }
4107
4108 my @clean_args = keys %generated_exts;
4109 push @files, cleanup_get1( $aux_dir1, @clean_args );
4110 if ( $out_dir1 ne $aux_dir1 ) { push @files, cleanup_get1( $out_dir1, @clean_args ); }
4111
4112 push @files, @std_small_cleanup_files;
4113 foreach my $file (@std_small_cleanup_files) {
4114 foreach my $dir ($aux_dir1, $out_dir1 ) {
4115 if ($dir) { push @files, "$dir$file"; }
4116 }
4117 }
4118 push @files, keys %index_bibtex_generated, keys %aux_files;
4119
4120 if ($cleanup_includes_generated) { push @files, keys %other_generated; }
4121 if ( $cleanup_includes_cusdep_generated) { push @files, keys %cusdep_generated; }
4122 push @files, $fdb_name;
4123 return @files;
4124 } # END get_small_cleanup
4125
4126 #************************************************************
4127
4128 sub do_cusdep {
4129 # Unconditional application of custom-dependency
4130 # except that rule is not applied if the source file source
4131 # does not exist, and an error is returned if the dest is not made.
4132 #
4133 # Assumes rule context for the custom-dependency, and that my first
4134 # argument is the name of the subroutine to apply
4135 my $func_name = $_[0];
4136 my $return = 0;
4137 no strict "refs";
4138 if ( !-e $$Psource ) {
4139 # Source does not exist. Users of this rule will need to turn
4140 # it off when custom dependencies are reset
4141 if ( !$silent ) {
4142 print "$My_name: In trying to apply custom-dependency rule\n",
4143 " to make '$$Pdest' from '$$Psource'\n",
4144 " the source file has disappeared since the last run\n";
4145 }
4146 # Treat as successful
4147 }
4148 elsif ( !$func_name ) {
4149 warn "$My_name: Possible misconfiguration or bug:\n",
4150 " In trying to apply custom-dependency rule\n",
4151 " to make '$$Pdest' from '$$Psource'\n",
4152 " the function name is blank.\n";
4153 }
4154 elsif ( ! defined &$func_name ) {
4155 warn "$My_name: Misconfiguration or bug,",
4156 " in trying to apply custom-dependency rule\n",
4157 " to make '$$Pdest' from '$$Psource'\n",
4158 " function name '$func_name' does not exists.\n";
4159 }
4160 else {
4161 my $cusdep_ret = &$func_name( $$Pbase );
4162 if ( defined $cusdep_ret && ($cusdep_ret != 0) ) {
4163 $return = $cusdep_ret;
4164 if ($return) {
4165 warn "Rule '$rule', function '$func_name'\n",
4166 " failed with return code = $return\n";
4167 }
4168 }
4169 elsif ( !-e $$Pdest ) {
4170 # Destination non-existent, but routine failed to give an error
4171 warn "$My_name: In running custom-dependency rule\n",
4172 " to make '$$Pdest' from '$$Psource'\n",
4173 " function '$func_name' did not make the destination.\n";
4174 $return = -1;
4175 }
4176 }
4177 return $return;
4178 } # END do_cusdep
4179
4180 #************************************************************
4181
4182 sub do_viewfile {
4183 # Unconditionally make file for viewing, going through temporary file if
4184 # Assumes rule context
4185
4186 my $return = 0;
4187 my ($base, $path, $ext) = fileparseA( $$Pdest );
4188 if ( &view_file_via_temporary ) {
4189 if ( $$Pext_cmd =~ /%D/ ) {
4190 my $tmpfile = tempfile1( "${root_filename}_tmp", $ext );
4191 print "$My_name: Making '$$Pdest' via temporary '$tmpfile'...\n";
4192 $return = &Run_subst( undef, undef, undef, undef, $tmpfile );
4193 move( $tmpfile, $$Pdest );
4194 }
4195 else {
4196 warn "$My_name is configured to make '$$Pdest' via a temporary file\n",
4197 " but the command template '$$Pext_cmd' does not have a slot\n",
4198 " to set the destination file, so I won't use a temporary file\n";
4199 $return = &Run_subst();
4200 }
4201 }
4202 else {
4203 $return = &Run_subst();
4204 }
4205 return $return;
4206 } #END do_viewfile
4207
4208 #************************************************************
4209
4210 sub do_update_view {
4211 # Update viewer
4212 # Assumes rule context
4213 # Arguments: (method, signal, viewer_process)
4214
4215 my $return = 0;
4216
4217 # Although the process is passed as an argument, we'll need to update it.
4218 # So (FUDGE??) bypass the standard interface for the process.
4219 # We might as well do this for all the arguments.
4220 my $viewer_update_method = ${$PAint_cmd}[1];
4221 my $viewer_update_signal = ${$PAint_cmd}[2];
4222 my $Pviewer_process = \${$PAint_cmd}[3];
4223 my $Pneed_to_get_viewer_process = \${$PAint_cmd}[4];
4224
4225 if ($viewer_update_method == 2) {
4226 if ($$Pneed_to_get_viewer_process) {
4227 $$Pviewer_process = &find_process_id( $$Psource );
4228 if ($$Pviewer_process != 0) {
4229 $$Pneed_to_get_viewer_process = 0;
4230 }
4231 }
4232 if ($$Pviewer_process == 0) {
4233 print "$My_name: need to signal viewer for file '$$Psource', but didn't get \n",
4234 " process ID for some reason, e.g., no viewer, bad configuration, bug\n"
4235 if $diagnostics;
4236 }
4237 elsif ( defined $viewer_update_signal) {
4238 print "$My_name: signalling viewer, process ID $$Pviewer_process ",
4239 "with signal $viewer_update_signal\n"
4240 if $diagnostics;
4241 kill $viewer_update_signal, $$Pviewer_process;
4242 }
4243 else {
4244 warn "$My_name: viewer is supposed to be sent a signal\n",
4245 " but no signal is defined. Misconfiguration or bug?\n";
4246 $return = 1;
4247 }
4248 }
4249 elsif ($viewer_update_method == 4) {
4250 if (defined $$Pext_cmd) {
4251 $return = &Run_subst();
4252 }
4253 else {
4254 warn "$My_name: viewer is supposed to be updated by running a command,\n",
4255 " but no command is defined. Misconfiguration or bug?\n";
4256 }
4257 }
4258 return $return;
4259 } #END do_update_view
4260
4261 #************************************************************
4262
4263 sub if_source {
4264 # Unconditionally apply rule if source file exists.
4265 # Assumes rule context
4266 if ( -e $$Psource ) {
4267 return &Run_subst();
4268 }
4269 else {
4270 warn "Needed source file '$$Psource' does not exist.\n";
4271 return -1;
4272 }
4273 } #END if_source
4274
4275 #************************************************************
4276 #### Subroutines
4277 #************************************************************
4278 #************************************************************
4279
4280 sub find_basename {
4281 # Finds the basename of the root file
4282 # Arguments:
4283 # 1 - Filename to breakdown
4284 # 2 - Where to place base file
4285 # 3 - Where to place tex file
4286 # Returns non-zero if tex file does not exist
4287
4288 my $fail = 0;
4289 my ( $given_name, $base_name, $ext, $path, $tex_name, $source_name );
4290 $given_name = $_[0];
4291
4292 $source_name = '';
4293 $tex_name = $given_name; # Default name if I don't find the tex file
4294 ($base_name, $path, $ext) = fileparseB( $given_name );
4295 # Treatment of extensions (in TeXLive 2019), with omission of path search:
4296 # Exists: always means exists as a file, i.e., not as a directory.
4297 # A. Finding of tex file:
4298 # 1. If extension is .tex and given_name exists, use it.
4299 # 2. Else if given_name.tex exists, use it.
4300 # 3. Else if given_name exists, use it.
4301 # B. The base filename is obtained by deleting the path
4302 # component and the extension.
4303 # C. The names of generated files (log, aux) are obtained by appending
4304 # .log, .aux, etc to the basename. Note that these are all in the
4305 # CURRENT directory (or the output or aux directory, as appropriate).
4306 # The drive/path part of the originally given filename is ignored.
4307
4308 # Here we'll do:
4309 # 1. Find the tex file by the above method, if possible.
4310 # 2. If not, find a custom dependency with a source file that exists to
4311 # make the tex file so that after the tex file is made, the above
4312 # rules find the tex file.
4313 # 3. If that also fails, use kpsewhich on given_name to find the tex
4314 # file
4315 # 4. If that also fails, report non-existent tex file.
4316
4317 if ( ($ext eq '.tex') && (-f $given_name) ) {
4318 $tex_name = "$given_name";
4319 }
4320 elsif ( -f "$given_name.tex" ) {
4321 $tex_name = "$given_name.tex";
4322 $base_name .= $ext;
4323 }
4324 elsif ( -f $given_name ) {
4325 $tex_name = $given_name;
4326 }
4327 elsif ( ($ext eq '.tex') && find_cus_dep( $given_name, $source_name ) ) {
4328 $tex_name = $given_name;
4329 }
4330 elsif ( find_cus_dep( "$given_name.tex", $source_name ) ) {
4331 $tex_name = "$given_name.tex";
4332 $base_name .= $ext;
4333 }
4334 elsif ( ($ext =~ /^\..+/) && find_cus_dep( $given_name, $source_name ) ) {
4335 $tex_name = $given_name;
4336 }
4337 else {
4338 my @kpse_result = kpsewhich( $given_name );
4339 if ($#kpse_result < 0) {
4340 $fail = 1;
4341 }
4342 else {
4343 $tex_name = $kpse_result[0];
4344 ($base_name) = fileparseB( $tex_name );
4345 }
4346 }
4347
4348 $_[1] = $base_name;
4349 $_[2] = $tex_name;
4350
4351 if ($diagnostics) {
4352 print "Given='$given_name', tex='$tex_name', base='$base_name', ext= $ext";
4353 if ($source_name) { print ", source='$source_name'"; }
4354 print "\n";
4355 }
4356 return $fail;
4357
4358 } #END find_basename
4359
4360 #************************************************************
4361
4362 sub make_preview_continuous {
4363
4364 local $failure = 0;
4365 local $updated = 0;
4366
4367 # ???!!!
4368 print "======= Need to update make_preview_continuous for target files\n";
4369
4370 $quell_uptodate_msgs = 1;
4371
4372 if ( ($view eq 'dvi') || ($view eq 'hnt') || ($view eq 'pdf') || ($view eq 'ps') ) {
4373 print "Viewing $view\n";
4374 }
4375 elsif ( $view eq 'none' ) {
4376 print "Not using a previewer\n";
4377 $view_file = '';
4378 }
4379 else {
4380 warn "$My_name: BUG: Invalid preview method '$view'\n";
4381 exit 20;
4382 }
4383
4384 my $viewer_running = 0; # No viewer known to be running yet
4385 # Get information from update_view rule
4386 my $viewer_update_method = 0;
4387 # Pointers so we can update the following:
4388 my $Pviewer_process = undef;
4389 my $Pneed_to_get_viewer_process = undef;
4390 rdb_one_rule( 'update_view',
4391 sub{ $viewer_update_method = $$PAint_cmd[1];
4392 $Pviewer_process = \$$PAint_cmd[3];
4393 $Pneed_to_get_viewer_process = \$$PAint_cmd[4];
4394 }
4395 );
4396 # Note that we don't get the previewer process number from the program
4397 # that starts it; that might only be a script to get things set up and the
4398 # actual previewer could be (and sometimes **is**) another process.
4399
4400 if ( ($view_file ne '') && (-e $view_file) && !$new_viewer_always ) {
4401 # Is a viewer already running?
4402 # (We'll save starting up another viewer.)
4403 $$Pviewer_process = &find_process_id( $view_file );
4404 if ( $$Pviewer_process ) {
4405 print "$My_name: Previewer is already running\n"
4406 if !$silent;
4407 $viewer_running = 1;
4408 $$Pneed_to_get_viewer_process = 0;
4409 }
4410 }
4411
4412 # Loop forever, rebuilding .dvi and .ps as necessary.
4413 # Set $first_time to flag first run (to save unnecessary diagnostics)
4414 my $last_action_time = time();
4415 my $timed_out = 0;
4416 CHANGE:
4417 for (my $first_time = 1; 1; $first_time = 0 ) {
4418
4419 my %rules_to_watch = array_to_hash( &rdb_accessible );
4420
4421 &init_timing1;
4422 $updated = 0;
4423 $failure = 0;
4424 $failure_msg = '';
4425 if ( $MSWin_fudge_break && ($^O eq "MSWin32") ) {
4426 # Fudge under MSWin32 ONLY, to stop perl/latexmk from
4427 # catching ctrl/C and ctrl/break, and let it only reach
4428 # downstream programs. See comments at first definition of
4429 # $MSWin_fudge_break.
4430 $SIG{BREAK} = $SIG{INT} = 'IGNORE';
4431 }
4432 $failure = rdb_make();
4433
4434 if ( $MSWin_fudge_break && ($^O eq "MSWin32") ) {
4435 $SIG{BREAK} = $SIG{INT} = 'DEFAULT';
4436 }
4437 # Start viewer if needed.
4438 if ( ($failure > 0) && (! $force_mode) ) {
4439 # No viewer yet
4440 }
4441 elsif ( ($view_file ne '') && (-e $view_file) && $updated && $viewer_running ) {
4442 # A viewer is running. Explicitly get it to update screen if we have to do it:
4443 rdb_one_rule( 'update_view', \&rdb_run1 );
4444 }
4445 elsif ( ($view_file ne '') && (-e $view_file) && !$viewer_running ) {
4446 # Start the viewer
4447 if ( !$silent ) {
4448 if ($new_viewer_always) {
4449 print "$My_name: starting previewer for '$view_file'\n",
4450 "------------\n";
4451 }
4452 else {
4453 print "$My_name: I have not found a previewer that ",
4454 "is already running. \n",
4455 " So I will start it for '$view_file'\n",
4456 "------------\n";
4457 }
4458 }
4459 my $retcode = 0;
4460 rdb_one_rule( 'view', sub { $retcode = &rdb_run1;} );
4461 if ( $retcode != 0 ) {
4462 if ($force_mode) {
4463 warn "$My_name: I could not run previewer\n";
4464 }
4465 else {
4466 &exit_msg1( "I could not run previewer", $retcode);
4467 }
4468 }
4469 else {
4470 $viewer_running = 1;
4471 $$Pneed_to_get_viewer_process = 1;
4472 } # end analyze result of trying to run viewer
4473 } # end start viewer
4474
4475 # Updated rule collection, and the set of rules whose source files
4476 # the WAIT loop examines for changes:
4477 &rdb_set_rule_net;
4478 %rules_to_watch = array_to_hash( &rdb_accessible );
4479
4480 if ( $failure > 0 ) {
4481 if ( !$failure_msg ) {
4482 $failure_msg = 'Failure to make the files correctly';
4483 }
4484 $failure_msg =~ s/\s*$//; #Remove trailing space
4485 warn "$My_name: $failure_msg\n",
4486 " ==> You will need to change a source file before I do another run <==\n";
4487 if ($failure_cmd) {
4488 Run_subst( $failure_cmd );
4489 }
4490
4491 # In the WAIT loop, we will test for changes in source files
4492 # that trigger a remake. Special considerations after an error:
4493 # 1. State of **user** source files for a rule is that before
4494 # the last run of the rule. Any changes since trigger
4495 # rerun.
4496 # 2. .aux files etc may have changed during an error run of a
4497 # rule, but no further runs were made to get them
4498 # stabilized. So they can have changed since start of
4499 # run. To avoid triggering an incorrect remake, rdb_make
4500 # has updated generated source files to their current state
4501 # after the whole make. User changes (e.g., deletion of aux
4502 # file) are still able to trigger a remake.
4503 # 3. Post_primary rules may not have been run (e.g., to make ps
4504 # and pdf from dvi). Depending on the criterion for rerun,
4505 # they may be out-of-date by some criterion, but they should
4506 # not be run until after another *latex run. Such rules
4507 # must be excluded from the rules whose source files the
4508 # WAIT loop scans for changes.
4509 # Set this up as follows:
4510 foreach (@post_primary) { delete $rules_to_watch{$_}; }
4511 }
4512 else {
4513 if ( ($#primary_warning_summary > -1) && $warning_cmd ) {
4514 Run_subst( $warning_cmd );
4515 }
4516 elsif ( ($#primary_warning_summary > -1) && $warnings_as_errors && $failure_cmd ) {
4517 Run_subst( $failure_cmd );
4518 }
4519 elsif ($success_cmd) {
4520 Run_subst( $success_cmd );
4521 }
4522 }
4523 rdb_show_rule_errors();
4524 if ($rules_list) { rdb_list(); }
4525 if ( $dependents_list && ($updated || $failure) ) {
4526 if ( open( my $deps_handle, ">$deps_file" ) ) {
4527 deps_list($deps_handle);
4528 close($deps_handle);
4529 }
4530 else {
4531 warn "Cannot open '$deps_file' for output of dependency information\n";
4532 }
4533 }
4534 if ($show_time) { &show_timing1; };
4535
4536
4537 # Now wait for a file to change...
4538 # During waiting for file changes, handle ctrl/C and ctrl/break here,
4539 # rather than letting system handle them by terminating script (and
4540 # code in the following command line to work: any script that calls
4541 # it). This allows, for example, the command cleanup in the following
4542 # command line to work:
4543 # latexmk -pvc foo; cleanup;
4544 &catch_break;
4545 our $have_break;
4546 local $have_break = 0;
4547 $last_action_time = time();
4548 $waiting = 1;
4549 rdb_for_some(
4550 [keys %rule_db],
4551 sub{
4552 if ($$Plast_result_info eq 'CURR') {
4553 $$Plast_result_info = 'PREV';
4554 }
4555 }
4556 );
4557 print "\n=== Watching for updated files. Use ctrl/C to stop ...\n";
4558 WAIT: while (1) {
4559 sleep( $sleep_time );
4560 if ($have_break) { last WAIT; }
4561 my %changes = ();
4562 if ( rdb_remake_needed(\%changes, 1, keys %rules_to_watch) ) {
4563 if (!$silent) {
4564 print "\n$My_name: Need to remake files.\n";
4565 &rdb_diagnose_changes2( \%changes, "", 1 );
4566 print "\n";
4567 }
4568 last WAIT;
4569 }
4570 # Don't count waiting time in processing:
4571 $processing_time1 = processing_time();
4572 # Does this do this job????!!!
4573 my $new_files = 0;
4574 rdb_for_some( [$current_primary], sub{ $new_files += &rdb_find_new_files } );
4575 if ($new_files > 0) {
4576 print "$My_name: New file(s) found.\n";
4577 last WAIT;
4578 }
4579 if ($have_break) { last WAIT; }
4580 if ($pvc_timeout && ( time() > $last_action_time+60*$pvc_timeout_mins ) ) {
4581 $timed_out = 1;
4582 last WAIT;
4583 }
4584 } # end WAIT:
4585 &default_break;
4586 if ($have_break) {
4587 print "$My_name: User typed ctrl/C or ctrl/break. I'll finish.\n";
4588 return;
4589 }
4590 if ($timed_out) {
4591 print "$My_name: More than $pvc_timeout_mins mins of inactivity. I'll finish.\n";
4592 return;
4593 }
4594 $waiting = 0; if ($diagnostics) { print "NOT WAITING\n"; }
4595 } #end infinite_loop CHANGE:
4596 } #END sub make_preview_continuous
4597
4598 #************************************************************
4599
4600 sub process_rc_file {
4601 # Usage process_rc_file( rc_file, [repeat_reaction] )
4602 # 2nd argument controls action if the the file rc_file has already been
4603 # processed:
4604 # Omitted, undef, or 0: Silently ignore. Used for processing
4605 # standard rc files (system, user, current
4606 # directory) since this situation legitimately
4607 # occurs when cwd is one of the directories
4608 # for the previously processed file.
4609 # other: Give a warning, and don't process the file
4610 #
4611 # Run rc_file whose name is given in first argument
4612 # Exit with code 0 on success
4613 # Exit with code 1 if file cannot be read or does not exist.
4614 # Stop if there is a syntax error or other problem.
4615 # PREVIOUSLY:
4616 # Exit with code 2 if is a syntax error or other problem.
4617 my ($rc_file, $repeat_reaction) = @_;
4618 my $abs_rc = abs_path($rc_file);
4619 my $ret_code = 0;
4620 if ( (!-e $rc_file) || ( ! defined $abs_rc ) ) {
4621 warn "$My_name: The rc-file '$rc_file' does not exist\n";
4622 return 1;
4623 }
4624 elsif ( -d $rc_file ) {
4625 warn "$My_name: The supposed rc-file '$rc_file' is a directory; but it\n",
4626 " should be a normal text file\n";
4627 return 1;
4628 }
4629 elsif ( exists $rc_files_read2{$abs_rc} ) {
4630 if ( $repeat_reaction ) {
4631 warn
4632 "$My_name: A user -r option asked me to process an rc file an extra time.\n",
4633 " Name of file = '$rc_file'\n",
4634 ( ($rc_file ne $abs_rc) ? " Abs. path = '$abs_rc'\n": ""),
4635 " I'll not process it\n";
4636 }
4637 return 0;
4638 }
4639 else {
4640 $rc_files_read2{$abs_rc} = 1;
4641 }
4642 push @rc_files_read, $rc_file;
4643
4644 # I could use the do function of perl, but:
4645 # 1. The preceeding -r test (in an earlier version of latexmk) to get
4646 # good diagnostics gets the wrong result under cygwin (e.g., on
4647 # /cygdrive/c/latexmk/LatexMk). I forget now (Nov. 2022) what the
4648 # problem was exactly.
4649 # 2. The do function searches directories in @INC, which is not wanted
4650 # here, where the aim is to execute code in a specific file in a
4651 # specific directory. In addition, '.' isn't in the default @INC in
4652 # current versions of Perl (Nov. 2022), so "do latexmkrc;" for
4653 # latexmkrc in cwd fails.
4654 # So I'll read the rc file and eval its contents.
4655 if ( open( my $RCH, "<", $rc_file ) ) {
4656 my $code = '';
4657 # Read all contents of file into $code:
4658 { local $/ = undef; $code = <$RCH>;}
4659 close $RCH;
4660 if (! is_valid_utf8($code) ) {
4661 die "$My_name: Rc-file '$rc_file' is not in UTF-8 coding. You should save\n",
4662 " it in UTF-8 coding for use with current latexmk.\n";
4663 }
4664 my $BOM = Encode::encode( 'UTF-8', "\N{U+FEFF}" );
4665 $code =~ s/^$BOM//;
4666 no strict;
4667 # !!!??? For backward compatibility, turn off strictness for evaluating rc files.
4668 eval $code;
4669 }
4670 else {
4671 warn "$My_name: I cannot read the rc-file '$rc_file'\n";
4672 return 1;
4673 }
4674 if ( $@ ) {
4675 # Indent each line of possibly multiline message:
4676 my $message = prefix( $@, " " );
4677 warn "$My_name: Initialization file '$rc_file' gave an error:\n",
4678 "$message\n";
4679 die "$My_name: Stopping because of problem with rc file\n";
4680 # Use the following if want non-fatal error.
4681 return 2;
4682 }
4683 return 0;
4684 } #END process_rc_file
4685
4686 #************************************************************
4687
4688 sub execute_code_string {
4689 # Usage execute_code_string( string_of_code )
4690 # Run the perl code contained in first argument
4691 # Halt if there is a syntax error or other problem.
4692 # ???Should I leave the exiting to the caller (perhaps as an option)?
4693 # But I can always catch it with an eval if necessary.
4694 # That confuses ctrl/C and ctrl/break handling.
4695 my $code = $_[0];
4696 print "$My_name: Executing initialization code specified by -e:\n",
4697 " '$code'...\n"
4698 if $diagnostics;
4699 {
4700 no strict;
4701 eval $code;
4702 }
4703 # The return value from the eval is not useful, since it is the value of
4704 # the last expression evaluated, which could be anything.
4705 # The correct test of errors is on the value of $@.
4706
4707 if ( $@ ) {
4708 # Indent each line of possibly multiline message:
4709 my $message = prefix( $@, " " );
4710 die "$My_name: ",
4711 "Stopping because executing following code from command line\n",
4712 " $code\n",
4713 "gave an error:\n",
4714 "$message\n";
4715 }
4716 } #END execute_code_string
4717
4718 #************************************************************
4719
4720 sub cleanup_cusdep_generated {
4721 # Remove files generated by custom dependencies
4722 rdb_for_actives( \&cleanup_one_cusdep_generated );
4723 } #END cleanup_cusdep_generated
4724
4725 #************************************************************
4726
4727 sub cleanup_one_cusdep_generated {
4728 # Remove destination file generated by one custom dependency
4729 # Assume rule context, but not that the rule is a custom dependency.
4730 # Only delete destination file if source file exists (so destination
4731 # file can be recreated)
4732 if ( $$Pcmd_type ne 'cusdep' ) {
4733 # NOT cusdep
4734 return;
4735 }
4736 if ( ! -e $$Psource ) {
4737 print "$My_name: For custom dependency '$rule',\n",
4738 " I won't delete destination file '$$Pdest'\n",
4739 " and any other generated files,\n",
4740 " because the source file '$$Psource' doesn't exist,\n",
4741 " so the destination file may not be able to be recreated\n";
4742 return;
4743 }
4744 unlink_or_move( $$Pdest, keys %$PHdest );
4745 } #END cleanup_one_cusdep_generated
4746
4747 #************************************************************
4748 #************************************************************
4749 #************************************************************
4750
4751 # Error handling routines, warning routines, help
4752
4753 #************************************************************
4754
4755 sub die_trace {
4756 # Call: die_trace( message );
4757 &traceback; # argument(s) passed unchanged
4758 die "\n";
4759 } #END die_trace
4760
4761 #************************************************************
4762
4763 sub traceback {
4764 # Call: traceback()
4765 # or traceback( message )
4766 # NOT &traceback, normally!!!
4767 my $msg = shift;
4768 if ($msg) { warn "$msg\n"; }
4769 warn "Traceback:\n";
4770 my $i=0; # Start with immediate caller
4771 while ( my ($pack, $file, $line, $func) = caller($i++) ) {
4772 if ($func eq 'die_trace') { next; }
4773 warn " $func called from line $line\n";
4774 }
4775 } #END traceback
4776
4777 #************************************************************
4778
4779 sub exit_msg1
4780 {
4781 # exit_msg1( error_message, retcode )
4782 # 1. display error message
4783 # 2. exit with retcode
4784 warn "\n------------\n";
4785 warn "$My_name: $_[0].\n";
4786 warn "-- Use the -f option to force complete processing.\n";
4787
4788 my $retcode = $_[1];
4789 if ($retcode >= 256) {
4790 # Retcode is the kind returned by system from an external command
4791 # which is 256 * command's_retcode
4792 $retcode /= 256;
4793 }
4794 exit $retcode;
4795 } #END exit_msg1
4796
4797 #************************************************************
4798
4799 sub warn_running {
4800 # Message about running program:
4801 if ( $silent ) {
4802 print "$My_name: @_\n";
4803 }
4804 else {
4805 print "------------\n@_\n------------\n";
4806 }
4807 } #END warn_running
4808
4809 #************************************************************
4810
4811 sub exit_help
4812 # Exit giving diagnostic from arguments and how to get help.
4813 {
4814 print "\n$My_name: @_\n",
4815 "Use\n",
4816 " $my_name -help\nto get usage information\n";
4817 exit 10;
4818 } #END exit_help
4819
4820
4821 #************************************************************
4822
4823 sub print_help
4824 {
4825 print
4826 "$My_name $version_num: Automatic LaTeX document generation routine\n\n",
4827 "Usage: $my_name [latexmk_options] [filename ...]\n\n",
4828 " Latexmk_options:\n",
4829 " -aux-directory=dir or -auxdir=dir \n",
4830 " - set name of directory for auxiliary files (aux, log)\n",
4831 " - See also the -emulate-aux-dir option\n",
4832 " -bibtex - use bibtex when needed (default)\n",
4833 " -bibtex- - never use bibtex\n",
4834 " -bibtex-cond - use bibtex when needed, but only if the bib file exists\n",
4835 " -bibtex-cond1 - use bibtex when needed, but only if the bib file exists;\n",
4836 " on cleanup delete bbl file only if bib file exists\n",
4837 " -bibfudge or -bibtexfudge - change directory to output directory when\n",
4838 " running bibtex\n",
4839 " -bibfudge- or -bibtexfudge- - don't change directory when running bibtex\n",
4840 " -commands - list commands used by $my_name for processing files\n",
4841 " -c - clean up (remove) all nonessential files, except\n",
4842 " dvi, ps and pdf files.\n",
4843 " This and the other clean-ups are instead of a regular make.\n",
4844 " -C - clean up (remove) all nonessential files\n",
4845 " including aux, dep, dvi, postscript and pdf files\n",
4846 " and file of database of file information\n",
4847 " -CA - clean up (remove) all nonessential files.\n",
4848 " Equivalent to -C option.\n",
4849 " -CF - Remove file of database of file information before doing \n",
4850 " other actions\n",
4851 " -cd - Change to directory of source file when processing it\n",
4852 " -cd- - Do NOT change to directory of source file when processing it\n",
4853 " -dependents or -deps - Show list of dependent files after processing\n",
4854 " -dependents- or -deps- - Do not show list of dependent files\n",
4855 " -deps-escape=<kind> - Set kind of escaping of spaces in names in deps file\n",
4856 " (Possible values: ", join( ' ', sort keys %deps_escape_kinds ), ")\n",
4857 " -deps-out=file - Set name of output file for dependency list,\n",
4858 " and turn on showing of dependency list\n",
4859 " -dF <filter> - Filter to apply to dvi file\n",
4860 " -dir-report - Before processing a tex file, report aux and out dir settings\n",
4861 " Report includes cwd and basename of output files\n",
4862 " -dir-report- - Before processing a tex file, do not report aux and out dir\n",
4863 " settings\n",
4864 " -dir-report-only - Report aux and out dir settings after initialization for\n",
4865 " each tex file, without compiling it\n",
4866 " -dvi - generate dvi by latex\n",
4867 " -dvilua - generate dvi by dvilualatex\n",
4868 " -dvi- - turn off required dvi\n",
4869 " -dvilualatex=<program> - set program used for dvilualatex.\n",
4870 " (replace '<program>' by the program name)\n",
4871 " -e <code> - Execute specified Perl code (as part of latexmk start-up\n",
4872 " code)\n",
4873 " -emulate-aux-dir - emulate -aux-directory option for *latex\n",
4874 " This enables the -aux-directory option to work properly with TeX\n",
4875 " Live as well as MiKTeX\n",
4876 " -emulate-aux-dir- - use -aux-directory option with *latex\n",
4877 " -f - force continued processing past errors\n",
4878 " -f- - turn off forced continuing processing past errors\n",
4879 " -g - process at least one run of all rules\n",
4880 " -g- - Turn off -g and -gg\n",
4881 " -gg - Super go mode: clean out generated files (-CA), and then\n",
4882 " process files regardless of file timestamps\n",
4883 " -gt - Require at least one run of *latex independently of file state\n",
4884 " -h - print help\n",
4885 " -hnt - generate hnt by hilatex\n",
4886 " -help - print help\n",
4887 " -indexfudge or -makeindexfudge - change directory to output directory when\n",
4888 " running makeindex\n",
4889 " -indexfudge- or -makeindexfudge- - don't change directory when running\n",
4890 " makeindex\n",
4891 " -jobname=STRING - set basename of output file(s) to STRING.\n",
4892 " (Like --jobname=STRING on command line for many current\n",
4893 " implementations of latex/pdflatex.)\n",
4894 " -l - force landscape mode\n",
4895 " -l- - turn off -l\n",
4896 " -latex=<program> - set program used for latex.\n",
4897 " (replace '<program>' by the program name)\n",
4898 " -latexoption=<option> - add the given option to the *latex command\n",
4899 " -logfilewarninglist or -logfilewarnings \n",
4900 " give list of warnings after run of *latex\n",
4901 " -logfilewarninglist- or -logfilewarnings- \n",
4902 " do not give list of warnings after run of *latex\n",
4903 " -lualatex - use lualatex for processing files to pdf\n",
4904 " and turn dvi/ps modes off\n",
4905 " -M - Show list of dependent files after processing\n",
4906 " -MF file - Specifies name of file to receives list dependent files\n",
4907 " -MP - List of dependent files includes phony target for each source\n",
4908 " file.\n",
4909 " -makeindexfudge - change directory to output directory when running\n",
4910 " makeindex\n",
4911 " -makeindexfudge- - don't change directory to output directory when\n",
4912 " running makeindex\n",
4913 " -MSWinBackSlash under MSWin use backslash (\\) for directory separators\n",
4914 " for filenames given to called programs\n",
4915 " -MSWinBackSlash- under MSWin use forward slash (/) for directory separators\n",
4916 " for filenames given to called programs\n",
4917 " -new-viewer - in -pvc mode, always start a new viewer\n",
4918 " -new-viewer- - in -pvc mode, start a new viewer only if needed\n",
4919 " -nobibtex - never use bibtex\n",
4920 " -nobibfudge or -nobibtexfudge - don't change directory when running bibtex\n",
4921 " -nodependents - Do not show list of dependent files after processing\n",
4922 " -noemulate-aux-dir - use -aux-directory option with *latex\n",
4923 " -noindexfudge or -nomakeindexfudge - don't change directory when running\n",
4924 " makeindex\n",
4925 " -norc - omit automatic reading of system, user and project rc files\n",
4926 " -output-directory=dir or -outdir=dir\n",
4927 " - set name of directory for output files\n",
4928 " -out2dir=dir\n",
4929 " - set name of directory for final output files\n",
4930 " -output-format=FORMAT\n",
4931 " - if FORMAT is dvi, turn on dvi output, turn off others\n",
4932 " - if FORMAT is pdf, turn on pdf output, turn off others\n",
4933 " - otherwise error\n",
4934 " -pdf - generate pdf by pdflatex\n",
4935 " -pdfdvi - generate pdf by latex (or dvilualatex) + dvipdf\n",
4936 " -- see -dvilua for how to get dvilualatex used\n",
4937 " -pdflatex=<program> - set program used for pdflatex.\n",
4938 " (replace '<program>' by the program name)\n",
4939 " -pdflualatex=<program> - set program used for lualatex.\n",
4940 " (replace '<program>' by the program name)\n",
4941 " -pdfps - generate pdf by latex (or dvilualatex) + dvips + ps2pdf\n",
4942 " -- see -dvilua for how to get dvilualatex used\n",
4943 " -pdflua - generate pdf by lualatex\n",
4944 " -pdfxe - generate pdf by xelatex\n",
4945 " -pdfxelatex=<program> - set program used for xelatex.\n",
4946 " (replace '<program>' by the program name)\n",
4947 " -pdf- - turn off pdf\n",
4948 " -pF <filter> - Filter to apply to postscript file\n",
4949 " -p - print document after generating postscript.\n",
4950 " (Can also .dvi or .pdf files -- see documentation)\n",
4951 " -pretex=<TeX code> - Sets TeX code to be executed before inputting source\n",
4952 " file, if commands suitable configured\n",
4953 " -print=dvi - when file is to be printed, print the dvi file\n",
4954 " -print=ps - when file is to be printed, print the ps file (default)\n",
4955 " -print=pdf - when file is to be printed, print the pdf file\n",
4956 " -ps - generate postscript\n",
4957 " -ps- - turn off postscript\n",
4958 " -pv - preview document. (Side effect turn off continuous preview)\n",
4959 " -pv- - turn off preview mode\n",
4960 " -pvc - preview document and continuously update. (This also turns\n",
4961 " on force mode, so errors do not cause $my_name to stop.)\n",
4962 " (Side effect: turn off ordinary preview mode.)\n",
4963 " -pvc- - turn off -pvc\n",
4964 " -pvctimeout - timeout in pvc mode after period of inactivity\n",
4965 " -pvctimeout- - don't timeout in pvc mode after inactivity\n",
4966 " -pvctimeoutmins=<time> - set period of inactivity (minutes) for pvc timeout\n",
4967 " -quiet - silence progress messages from called programs\n",
4968 " -r <file> - Read custom RC file\n",
4969 " (N.B. This file could override options specified earlier\n",
4970 " on the command line.)\n",
4971 " -rc-report - After initialization, report names of rc files read\n",
4972 " -rc-report- - After initialization, do not report names of rc files read\n",
4973 " -recorder - Use -recorder option for *latex\n",
4974 " (to give list of input and output files)\n",
4975 " -recorder- - Do not use -recorder option for *latex\n",
4976 " -rules - Show list of rules after processing\n",
4977 " -rules- - Do not show list of rules after processing\n",
4978 " -showextraoptions - Show other allowed options that are simply passed\n",
4979 " as is to latex and pdflatex\n",
4980 " -silent - silence progress messages from called programs\n",
4981 " -stdtexcmds - Sets standard commands for *latex\n",
4982 " -time - show CPU time used\n",
4983 " -time- - don't show CPU time used\n",
4984 " -use-make - use the make program to try to make missing files\n",
4985 " -use-make- - don't use the make program to try to make missing files\n",
4986 " -usepretex - Sets commands for *latex to use extra code before inputting\n",
4987 " source file\n",
4988 " -usepretex=<TeX code> - Equivalent to -pretex=<TeX code> -usepretex\n",
4989 " -v - display program version\n",
4990 " -verbose - display usual progress messages from called programs\n",
4991 " -version - display program version\n",
4992 " -view=default - viewer is default (dvi, ps, pdf)\n",
4993 " -view=dvi - viewer is for dvi\n",
4994 " -view=hnt - viewer is for hnt\n",
4995 " -view=none - no viewer is used\n",
4996 " -view=ps - viewer is for ps\n",
4997 " -view=pdf - viewer is for pdf\n",
4998 " -Werror - treat warnings from called programs as errors\n",
4999 " -xdv - generate xdv by xelatex\n",
5000 " -xdv- - turn off required xdv\n",
5001 " -xelatex - use xelatex for processing files to pdf\n",
5002 " and turn dvi/ps modes off\n",
5003 "\n",
5004 " filename = the root filename of LaTeX document\n",
5005 "\n",
5006 "-p, -pv and -pvc are mutually exclusive\n",
5007 "-h, -c and -C override all other options.\n",
5008 "-pv and -pvc require one and only one filename specified\n",
5009 "All options can be introduced by '-' or '--'. (E.g., --help or -help.)\n",
5010 " \n",
5011 "In addition, latexmk recognizes many other options that are passed to\n",
5012 "latex and/or pdflatex without interpretation by latexmk. Run latexmk\n",
5013 "with the option -showextraoptions to see a list of these\n",
5014 "\n",
5015 "Report bugs etc to John Collins <jcc8 at psu.edu>.\n";
5016
5017 } #END print_help
5018
5019 #************************************************************
5020
5021 sub print_commands {
5022 print "Commands used by $my_name:\n",
5023 " To run hilatex, I use \"$hilatex\"\n",
5024 " To run latex, I use \"$latex\"\n",
5025 " To run pdflatex, I use \"$pdflatex\"\n",
5026 " To run dvilualatex, I use \"$dvilualatex\"\n",
5027 " To run lualatex, I use \"$lualatex\"\n",
5028 " To run xelatex, I use \"$xelatex\"\n",
5029 " To run biber, I use \"$biber\"\n",
5030 " To run bibtex, I use \"$bibtex\"\n",
5031 " To run makeindex, I use \"$makeindex\"\n",
5032 " To make a ps file from a dvi file, I use \"$dvips\"\n",
5033 " To make a ps file from a dvi file with landscape format, ",
5034 "I use \"$dvips_landscape\"\n",
5035 " To make a pdf file from a dvi file, I use \"$dvipdf\"\n",
5036 " To make a pdf file from a ps file, I use \"$ps2pdf\"\n",
5037 " To make a pdf file from an xdv file, I use \"$xdvipdfmx\"\n",
5038 " To view a pdf file, I use \"$pdf_previewer\"\n",
5039 " To view a ps file, I use \"$ps_previewer\"\n",
5040 " To view a ps file in landscape format, ",
5041 "I use \"$ps_previewer_landscape\"\n",
5042 " To view a dvi file, I use \"$dvi_previewer\"\n",
5043 " To view a dvi file in landscape format, ",
5044 "I use \"$dvi_previewer_landscape\"\n",
5045 " To view an hnt file, I use \"$hnt_previewer\"\n",
5046 " To print a ps file, I use \"$lpr\"\n",
5047 " To print a dvi file, I use \"$lpr_dvi\"\n",
5048 " To print a pdf file, I use \"$lpr_pdf\"\n",
5049 " To find running processes, I use \"$pscmd\", \n",
5050 " and the process number is at position $pid_position\n";
5051 print "Notes:\n",
5052 " Command starting with \"start\" is run detached\n",
5053 " Command that is just \"start\" without any other command, is\n",
5054 " used under MS-Windows to run the command the operating system\n",
5055 " has associated with the relevant file.\n",
5056 " Command starting with \"NONE\" is not used at all\n";
5057 } #END print_commands
5058
5059 #************************************************************
5060
5061 sub view_file_via_temporary {
5062 return $always_view_file_via_temporary
5063 || ($pvc_view_file_via_temporary && $preview_continuous_mode);
5064 } #END view_file_via_temporary
5065
5066 #************************************************************
5067
5068 #### Tex-related utilities #######################
5069
5070 #**************************************************
5071
5072 sub after_biber {
5073 # Analyze results of biber run, take appropriate actions on dependencies.
5074 # Assumes rule context for biber
5075 # Call
5076 # after_biber( \$return ),
5077 # where $return is code returned by running of biber (maybe modified by
5078 # caller, which is normally rdb_run1). Can adjust its value to provoke
5079 # better diagnosis of results of run to caller.
5080 use strict;
5081 # Rule variables used:
5082 our ( $rule, $Pbase, $Pdest, $PHextra, $Plast_message, $Plast_result,
5083 $Pout_of_date, $Psource, $PHsource );
5084 # Global variables used
5085 our ( $diagnostics, $My_name, $save_error_suffix, $silent );
5086 my $Preturn = $_[0];
5087 my @biber_datasource = ( );
5088 my @biber_remote = ();
5089 my @warnings = ();
5090 my $add_bcf_datasources = 0;
5091
5092 my $retcode = check_biber_log( $$Pbase, \@biber_datasource, \@biber_remote );
5093 if ($$Preturn) {
5094 print
5095 "$My_name: Error return from '$rule'\n",
5096 "I will add to its source list, anything cached from analysis of bcf file.\n";
5097 $add_bcf_datasources = 1;
5098 }
5099 if ( ! -e $$Psource ) {
5100 $retcode = 10;
5101 if (!$silent) {
5102 print "Source '$$Psource' for '$rule' doesn't exist,\n",
5103 "so I'll force *latex to run to try and make it.\n";
5104 }
5105 rdb_for_some( [$current_primary], sub{ $$Pout_of_date = "to make '$$Psource' for '$rule'"; } );
5106 }
5107 rdb_set_source_here( @biber_datasource, $$Psource );
5108
5109 if ($retcode == 6) {
5110 # Missing control file. Need to remake it (if possible)
5111 # Don't treat missing bbl file as error.
5112 print "$My_name: bibtex control file missing. Since that can\n",
5113 " be recreated, I'll try to do so.\n";
5114 $$Preturn = -2;
5115 rdb_for_some( [$current_primary], sub{ $$Pout_of_date = "to make missing control file"; } );
5116 }
5117 elsif ($retcode == 4) {
5118 $$Plast_result = 2;
5119 $$Plast_message = "Could not find all biber source files for '$$Pbase'";
5120 push @warnings, "Not all biber source files found for '$$Pbase'";
5121 }
5122 elsif ($retcode == 3) {
5123 $$Plast_result = 2;
5124 $$Plast_message = "Could not open biber log file '$$Pbase.blg'";
5125 warn "$My_name: $$Plast_message\n";
5126 $add_bcf_datasources = 1;
5127 push @warnings, $$Plast_message;
5128 }
5129 elsif ($retcode == 2) {
5130 $$Plast_message = "Biber errors: See file '$$Pbase.blg'";
5131 push @warnings, $$Plast_message;
5132 }
5133 elsif ($retcode == 1) {
5134 push @warnings, "Biber warnings for '$$Pbase'";
5135 }
5136 elsif ($retcode == 11) {
5137 $$Plast_message = "Biber: malformed bcf file '$$Psource'";
5138 push @warnings, $$Plast_message;
5139 my $save_bcf = "$$Psource$save_error_suffix";
5140 warn "$My_name: biber found malformed bcf file '$$Psource'.\n",
5141 " I'll delete any bbl file '$$Pdest', and\n",
5142 " rename the bcf file to '$save_bcf'\n";
5143 # Malformed bcf file is a downstream consequence, normally,
5144 # of an error in *latex run.
5145 # Current version of biber deletes bbl file.
5146 # Older versions (pre-2016) made an incorrect bbl file, which
5147 # tended to cause latex errors, and give a self-perpetuating error.
5148 # Ensure the bbl file doesn't exist.
5149 # I could delete the bcf file, since it is not usable. But in
5150 # non-trivial cases, the user may want to examine the file, so
5151 # I'll rename it instead. (Trivial common case: *latex exited
5152 # early because of an error, and the resulting bcf file is
5153 # incomplete. I should have deleted the file after the error
5154 # run of *latex, since there is then no value in the bcf for
5155 # diagnostics.)
5156 unlink $$Pdest;
5157 rename $$Psource, $save_bcf;
5158 }
5159 if ($add_bcf_datasources) {
5160 my $PA_bcf_datasources = $$PHextra{bcf_datasources};
5161 if ( ref($PA_bcf_datasources) eq 'ARRAY' ) {
5162 rdb_ensure_files_here( @$PA_bcf_datasources );
5163 }
5164 }
5165 } #END after_biber
5166
5167 #**************************************************
5168
5169 sub check_biber_log {
5170 # Check for biber warnings, and report source files.
5171 # Usage: check_biber_log( base_of_biber_run, \@datasource, \@remote )
5172 # I use a hash for the collection of significant warnings. It maps
5173 # categories of warnings to array references (or c.) to allow
5174 # flexibility in what I report.
5175 # (Return codes compatible with check_bibtex_log, but only used when applicable.)
5176 # return 0: OK;
5177 # 1: biber warnings;
5178 # 2: biber errors;
5179 # 3: could not open .blg file;
5180 # 4: failed to find one or more source files, except for bibfile;
5181 # 6: missing file;
5182 # 11: Malformed bcf file (normally due to error in pdflatex run)
5183 # Side effect: add source files to @datasource
5184 # N.B. @datasource is already initialized by caller.
5185 # So do **not** initialize it here.
5186 use strict;
5187 # Global variables used
5188 our ($My_name, $silent);
5189
5190 my ($base, $PAdatasource, $PAremote ) = @_;
5191 my $blg_name = "$base.blg";
5192 open( my $blg_file, "<", $blg_name )
5193 or return 3;
5194 my $have_warning = 0;
5195 my $have_error = 0;
5196 my $no_citations = 0;
5197 my $error_count = 0; # From my counting of error messages
5198 my $warning_count = 0; # From my counting of warning messages
5199 # The next two occur only from biber
5200 my $biber_error_count = 0; # From biber's counting of errors
5201 my $biber_warning_count = 0; # From biber's counting of warnings
5202 my $not_found_count = 0;
5203 my $control_file_missing = 0;
5204 my $control_file_malformed = 0;
5205 my @not_found = (); # Files, normally .bib files, not found.
5206 my @missing_citations = ();
5207
5208 while (local $_ = <$blg_file>) {
5209 $_ = utf8_to_mine($_);
5210 if (/> WARN /) {
5211 print "Biber warning: $_";
5212 $have_warning = 1;
5213 $warning_count ++;
5214 }
5215 # Note that WARN is not exclusive with some of the following,
5216 # so we can't use elsif here
5217 if (/> (FATAL|ERROR) /) {
5218 print "Biber error: $_";
5219 if ( /> (FATAL|ERROR) - Cannot find file '([^']+)'/ #'
5220 || /> (FATAL|ERROR) - Cannot find '([^']+)'/ ) { #'
5221 $not_found_count++;
5222 push @not_found, $2;
5223 }
5224 elsif ( /> (FATAL|ERROR) - Cannot find control file '([^']+)'/ ) { #'
5225 $not_found_count++;
5226 $control_file_missing = 1;
5227 push @not_found, $2;
5228 }
5229 elsif ( /> ERROR - .*\.bcf is malformed/ ) {
5230 # Special treatment: Malformed .bcf file commonly results from error
5231 # in *latex run. This error must be ignored.
5232 $control_file_malformed = 1;
5233 }
5234 else {
5235 $have_error = 1;
5236 $error_count ++;
5237 }
5238 }
5239 elsif ( /> INFO - Data source '([^']*)' is a remote BibTeX data source - fetching/
5240 ){
5241 push @$PAremote, $1;
5242 }
5243 elsif ( /> INFO - Found .* '([^']+)'\s*$/
5244 || /> INFO - Found '([^']+)'\s*$/
5245 || /> INFO - Reading '([^']+)'\s*$/
5246 || /> INFO - Processing .* file '([^']+)'.*$/
5247 || /> INFO - Config file is '([^']+)'.*$/
5248 || /> WARN - Data source .*'([^']+)'.*$/
5249 ) {
5250 my $file = $1;
5251 my ( $base, $path, $ext ) = fileparseA( $file );
5252 if ( $base =~ /^biber_remote_data_source/ ) {
5253 # Ignore the file, which appears to be a temporary local copy
5254 # of a remote file. Treating the file as a source file will
5255 # be misleading, since it will normally have been deleted by
5256 # biber itself.
5257 }
5258 elsif ( -e $file ) {
5259 # Note that biber log file gives full path to file. (No search is
5260 # needed to find it.) The file must have existed when biber was
5261 # run. If it doesn't exist now, a few moments later, it must
5262 # have gotten deleted, probably by biber (e.g., because it is a
5263 # copy of a remote file).
5264 # So I have included a condition above that the file must
5265 # exist to be included in the source-file list.
5266 push @$PAdatasource, $file;
5267 }
5268 }
5269 elsif ( /> WARN - I didn't find a database entry for '([^']+)'/ ) {
5270 push @missing_citations, $1;
5271 }
5272 elsif ( /> INFO - WARNINGS: ([\d]+)\s*$/ ) {
5273 $biber_warning_count = $1;
5274 }
5275 elsif ( /> INFO - ERRORS: ([\d]+)\s*$/ ) {
5276 $biber_error_count = $1;
5277 }
5278 }
5279 close $blg_file;
5280 @$PAdatasource = uniqs( @$PAdatasource );
5281 @$PAremote = uniqs( @$PAremote );
5282 @not_found = uniqs( @not_found );
5283 push @$PAdatasource, @not_found;
5284
5285 if ($control_file_malformed){return 11;}
5286
5287 if ( ($#not_found < 0) && ($#$PAdatasource >= 0) ) {
5288 print "$My_name: Found biber source file(s) [",
5289 join( ', ', @$PAdatasource), "]\n"
5290 unless $silent;
5291 }
5292 else {
5293 warn "$My_name: Failed to find one or more biber source files:\n";
5294 foreach (@not_found) { warn " '$_'\n"; }
5295 if ($force_mode) {
5296 warn "==== Force_mode is on, so I will continue. ",
5297 "But there may be problems ===\n";
5298 }
5299 if ($control_file_missing) {
5300 return 6;
5301 }
5302 return 4;
5303 }
5304 if ( @missing_citations ) {
5305 @missing_citations = uniqs( @missing_citations );
5306 show_array( "$My_name: Biber reported missing citations", @missing_citations );
5307 }
5308 if ($have_error) {return 2;}
5309 if ($have_warning) {return 1;}
5310 return 0;
5311 } #END check_biber_log
5312
5313 #**************************************************
5314
5315 sub run_bibtex {
5316 use strict;
5317 # Rule variables used
5318 our ( $rule, $Pdest, $Psource );
5319 # Global variables used
5320 our ( $bibtex_fudge, $My_name, $silent );
5321
5322 my $return = 999;
5323 # Prevent changes we make to environment becoming global:
5324 local %ENV = %ENV;
5325
5326 my ( $base, $path, $ext ) = fileparseA( $$Psource );
5327 # Define source and dest base to include extension, no path.
5328 my $source_base = $base.$ext;
5329 my $dest_base = basename( $$Pdest );
5330 if ( $path && $bibtex_fudge ) {
5331 # Up to TeXLive 2018, the following was true; situation has changed since.
5332 # When an output directory is specified and with a bibtex from 2018 or
5333 # earlier, running 'bibtex output/main.aux' doesn't find subsidiary .aux
5334 # files, as from \@include{chap.aux}. To evade the bug, we change
5335 # directory to the directory of the top-level .aux file to run bibtex.
5336 # But we have to fix search paths for .bib and .bst, since they may be
5337 # specified relative to the document directory.
5338 # There is also another problem: Depending on the exact
5339 # specification of the aux dir, bibtex may refuse to write to the
5340 # aux dir, for security reasons.
5341 # This prevents changing the default $bibtex_fudge to off,
5342 # without breaking backward compatibility. (???!!! Perhaps I
5343 # should change the default, and give a special message if the
5344 # security issue of not being able to write arises.)
5345
5346 path_fudge( 'BIBINPUTS', 'BSTINPUTS' );
5347 pushd( $path );
5348 if (!$silent) {
5349 print "$My_name: Change directory to '$path'.\n",
5350 "To assist finding of files in document directory, I set\n",
5351 " BIBINPUTS='$ENV{BIBINPUTS}'\n",
5352 " BSTINPUTS='$ENV{BSTINPUTS}'.\n";
5353 }
5354 # Override standard substitutions for source, dest, and base names in
5355 # default external command:
5356 $return = &Run_subst( undef, undef, '', $source_base, $dest_base, $base );
5357 popd();
5358 if (!$silent) {
5359 print "$My_name: Change directory back to '", cwd(), "'\n";
5360 }
5361 }
5362 else {
5363 # Use default substitutions etc for rule:
5364 $return = Run_subst();
5365 }
5366 return $return;
5367 } #END run_bibtex
5368
5369 #**************************************************
5370
5371 sub after_bibtex {
5372 # Analyze results of bibtex run, take appropriate actions on dependencies.
5373 # Assumes rule context for bibtex
5374 # Call
5375 # after_bibtex( \$return ),
5376 # where $return is code returned by running of bibtex (maybe modified by
5377 # caller, which is normally rdb_run1). Can adjust its value to provoke
5378 # better diagnosis of results of run to caller.
5379
5380 use strict;
5381 # Rule variables used
5382 our ( $rule, $Pbase, $Pdest, $Plast_message, $Plast_result,
5383 $Pout_of_date, $Psource );
5384 # Global variables used
5385 our ( $diagnostics, $failure, $My_name, $silent );
5386
5387 my $Preturn = $_[0];
5388 my $retcode = check_bibtex_log($$Pbase);
5389 my @warnings = ();
5390
5391 if ( ! -e $$Psource ) {
5392 $retcode = 10;
5393 if (!$silent) {
5394 print "Source '$$Psource' for '$rule' doesn't exist,\n",
5395 "so I'll force *latex to run to try and make it.\n";
5396 }
5397 rdb_for_some( [$current_primary], sub{ $$Pout_of_date = "to make '$$Psource' for '$rule'"; } );
5398 }
5399 if ($retcode == 3) {
5400 $$Plast_result = 2;
5401 $$Plast_message = "Could not open bibtex log file for '$$Pbase'";
5402 push @warnings, $$Plast_message;
5403 }
5404 elsif ($retcode == 2) {
5405 $$Plast_message = "Bibtex errors: See file '$$Pbase.blg'";
5406 $failure = 1;
5407 push @warnings, $$Plast_message;
5408 }
5409 elsif ($retcode == 1) {
5410 push @warnings, "Bibtex warnings for '$$Pbase'";
5411 }
5412 elsif ($retcode == 10) {
5413 push @warnings, "Bibtex found no citations for '$$Pbase',\n",
5414 " or had missing aux or bib file(s)\n";
5415 if (! -e $$Pdest ) {
5416 print "$My_name: Bibtex did not produce '$$Pdest'. But that\n",
5417 " was because of missing files, so I will continue.\n";
5418 $$Preturn = -2;
5419 }
5420 else {
5421 $$Preturn = 0;
5422 }
5423 }
5424 } #END after_bibtex
5425
5426 #**************************************************
5427
5428 sub check_bibtex_log {
5429 # Check for bibtex warnings and errors:
5430 # Usage: check_bibtex_log( base_of_bibtex_run )
5431 # (Return codes compatible with check_biber_log, but only used when applicable.)
5432 # return 0: OK, 1: bibtex warnings, 2: bibtex errors,
5433 # 3: could not open .blg file.
5434 # 10: only error is missing \citation commands or a missing aux file
5435 # (which would normally be corrected after a later run of
5436 # *latex).
5437 use strict;
5438 # Variable used in context of a rule action
5439 our ( $Pout_of_date );
5440 # Global variables used
5441 our ( $My_name );
5442
5443 my $base = $_[0];
5444 my $blg_name = "$base.blg";
5445 open( my $blg_file, "<", $blg_name )
5446 or return 3;
5447 my $have_warning = 0;
5448 my $have_error = 0;
5449 my $no_citations = 0;
5450 my @missing_aux = ();
5451 my @missing_bib = ();
5452 my $error_count = 0;
5453
5454 while (local $_ = <$blg_file>) {
5455 $_ = utf8_to_mine($_);
5456 if (/^Warning--/) {
5457 #print "Bibtex warning: $_";
5458 $have_warning = 1;
5459 }
5460 elsif ( /^I couldn\'t open auxiliary file (.*\.aux)/ ) {
5461 push @missing_aux, $1;
5462 }
5463 elsif ( /^I found no \\citation commands---while reading file/ ) {
5464 $no_citations++;
5465 }
5466 elsif ( /^I couldn't open database file (.*\.bib)/ ) {
5467 push @missing_bib, $1;
5468 }
5469 elsif (/There (were|was) (\d+) error message/) {
5470 $error_count = $2;
5471 #print "Bibtex error: count=$error_count $_";
5472 $have_error = 1;
5473 }
5474 }
5475 close $blg_file;
5476 my $weak_errors = $no_citations + $#missing_aux + 1 + $#missing_bib + 1;
5477 if ( $#missing_aux > -1 ) {
5478 # Need to make the missing files.
5479 print "$My_name: One or more aux files is missing for bibtex. I'll try\n",
5480 " to get *latex to remake them.\n";
5481 rdb_for_some( [$current_primary], sub{ $$Pout_of_date = "to get missing aux file(s) made"; } );
5482 }
5483 #print "Bibtex errors = $error_count, missing aux files and citations = $missing\n";
5484 if ($have_error && ($error_count <= $weak_errors )
5485 && ($weak_errors > 0) ) {
5486 # If the only error(s), are:
5487 # lack of any \citation commands in aux file
5488 # missing aux file(s)
5489 # missing bib file(s)
5490 # that should count as a warning.
5491 # Note that a missing aux file is generally innocuous, that's
5492 # commonly because the document has an include of a file in a
5493 # subdirectory, an aux dir is in use, and the sub directory hasn't
5494 # yet been made in the aux dir. That situation should be handled
5495 # by latexmk by creating the directory and rerunning *latex.
5496 # But have to deal with the problem that bibtex gives a non-zero
5497 # exit code.
5498 # Let caller know:
5499 return 10;
5500 }
5501 if ($have_error) {return 2;}
5502 if ($have_warning) {return 1;}
5503 return 0;
5504 } #END check_bibtex_log
5505
5506 #**************************************************
5507
5508 sub run_makeindex {
5509 my $return = 999;
5510 my ( $base, $path, $ext ) = fileparseA( $$Psource );
5511
5512 # Define source and dest base to include extension, no path.
5513 my $source_base = $base.$ext;
5514 my $dest_base = basename( $$Pdest );
5515 if ( $path && $makeindex_fudge ) {
5516 my $cwd = good_cwd();
5517 pushd( $path );
5518 if (!$silent) {
5519 print "$My_name: Change directory to '$path'.\n";
5520 }
5521 # Override standard substitutions for source, dest, and base names in
5522 # default external command:
5523 $return = &Run_subst( undef, undef, '', $source_base, $dest_base, $base );
5524 popd();
5525 if (!$silent) {
5526 print "$My_name: Change directory back to '$cwd'\n";
5527 }
5528 }
5529 else {
5530 # Use default substitutions etc for rule:
5531 $return = Run_subst();
5532 }
5533 return $return;
5534 } #END run_makeindex
5535
5536 #**************************************************
5537
5538 sub normalize_force_directory {
5539 # Usage, normalize_force_directory( dir, filename )
5540 # Filename is assumed to be relative to dir (terminated with directory separator).
5541 # Perform the following operations:
5542 # Clean filename
5543 # Prefix filename with dir
5544 # Normalize filename
5545 # Return result
5546 my $dir = $_[0];
5547 my $filename = clean_filename( $_[1] );
5548 $filename = "$dir$filename";
5549 return normalize_filename( $filename );
5550 } #END normalize force_directory
5551
5552 #**************************************************
5553
5554 sub set_names {
5555 # Set names of standard files. These are global variables.
5556
5557 ## Remove extension from filename if was given.
5558 if ( find_basename($filename, $root_filename, $texfile_name) ) {
5559 if ( $force_mode ) {
5560 warn "$My_name: Could not find file '$texfile_name'\n";
5561 }
5562 else {
5563 &ifcd_popd;
5564 &exit_msg1( "Could not find file '$texfile_name'",
5565 11);
5566 }
5567 }
5568 $tex_basename = $root_filename; # Base name of TeX file itself
5569 if ($jobname ne '' ) {
5570 $root_filename = $jobname;
5571 $root_filename =~ s/%A/$tex_basename/g;
5572 }
5573
5574 $aux_main = "%Y%R.aux";
5575 $log_name = "%Y%R.log";
5576 $bcf_name = "%Y%R.bcf";
5577 $fdb_name = "%Y%R.$fdb_ext";
5578 # Note: Of the TeX distributions, only MiKTeX allows out_dir ne aux_dir,
5579 # natively. It puts (or used to put) the .fls file in out_dir,
5580 # not aux_dir, which seems not natural, but we have to allow for
5581 # that possibility, but also to allow for the opposite (.fls file
5582 # in aux_dir), and to configure what latexmk does in emulating
5583 # aux_dir.
5584 if ($fls_uses_out_dir) {
5585 $fls_name = "%Z%R.fls";
5586 $fls_name_alt = "%Y%R.fls";
5587 }
5588 else {
5589 $fls_name = "%Y%R.fls";
5590 $fls_name_alt = "%Z%R.fls";
5591 }
5592 $dvi_name = "%Z%R.dvi";
5593 $dviF_name = "%Z%R.dviF";
5594 $hnt_name = "%Z%R.hnt";
5595 $ps_name = "%Z%R.ps";
5596 $psF_name = "%Z%R.psF";
5597 $pdf_name = "%Z%R.pdf";
5598 $dvi_final2 = "%X%R.dvi";
5599 $hnt_final2 = "%X%R.hnt";
5600 $pdf_final2 = "%X%R.pdf";
5601 $ps_final2 = "%X%R.ps";
5602 ## It would be logical for a .xdv file to be put in the out_dir,
5603 ## just like a .dvi file. But the only program, MiKTeX, that
5604 ## currently implements aux_dir, and hence allows aux_dir ne out_dir,
5605 ## puts .xdv file in aux_dir. So we must use %Y not %Z:
5606 $xdv_name = "%Y%R.xdv";
5607
5608 foreach ( $aux_main, $log_name, $bcf_name, $fdb_name, $fls_name, $fls_name_alt,
5609 $dvi_name, $hnt_name, $ps_name, $pdf_name, $xdv_name,
5610 $dviF_name, $psF_name,
5611 $dvi_final2, $hnt_final2, $pdf_final2, $ps_final2,
5612 ) {
5613 s/%R/$root_filename/g;
5614 s/%X/$out2_dir1/;
5615 s/%Y/$aux_dir1/;
5616 s/%Z/$out_dir1/;
5617 }
5618
5619 $dvi_final = $dvi_name;
5620 $hnt_final = $hnt_name;
5621 $ps_final = $ps_name;
5622 $pdf_final = $pdf_name;
5623 $xdv_final = $xdv_name;
5624
5625 if ( length($dvi_filter) > 0) {
5626 $dvi_final = $dviF_name;
5627 }
5628 if ( length($ps_filter) > 0) {
5629 $ps_final = $psF_name;
5630 }
5631 } #END set_names
5632
5633 #**************************************************
5634
5635 sub do_moves_aux_to_out {
5636 # do_moves_aux_to_out( source, dest )
5637 # Moves appropriate output files from source dir (e.g., $aux_dir1) to
5638 # dest dir (e.g., $out_dir1).
5639 # Veto move of file if it wasn't generated on current compilation.
5640 # Special treatment of .fls file
5641 # Assume rule context, which may be global context.
5642 # Directory names should end in /, so that concatenation OK.
5643 my ($source1, $dest1) = @_;
5644 foreach my $ext ( 'fls', 'dvi', 'hnt', 'pdf', 'ps', 'synctex', 'synctex.gz' ) {
5645 if ( ($ext eq 'fls') && ! $fls_uses_out_dir ) {next;}
5646 my $from = "$source1$$Pbase.$ext";
5647 my $to = "$dest1$$Pbase.$ext" ;
5648 if ( test_gen_file_time( $from ) ) {
5649 if (! $silent) { print "$My_name: Moving '$from' to '$to'\n"; }
5650 my $ret = move( $from, $to );
5651 if ( ! $ret ) { die " That failed, with message '$!'\n";}
5652 }
5653 }
5654 } #END do_moves_aux_to_out
5655
5656 #*************************************************************************
5657
5658 sub do_copies_out_to_out2 {
5659 # do_copies_out_to_out2( source, dest )
5660 # Copies final output files from source dir (e.g., $out_dir1) to
5661 # dest dir (e.g., $out2_dir1).
5662 # Note copy, not move, otherwise rules complain about non-existent
5663 # destination pdf file (etc).
5664 # Assume rule context, which is normally global context.
5665 # Directory names should end in /, so that concatenation OK.
5666 my ($source1, $dest1) = @_;
5667
5668 # Ideally, guard against source and destination being same.
5669 # Easy case:
5670 my $absSource = abs_path($source1);
5671 my $absDest = abs_path($dest1);
5672 if ( defined($absSource) && defined($absDest) && ($absSource eq $absDest) ) {
5673 # Directories are same. Nothing to do.
5674 # Note that abs_path can return undef under certain error conditions.
5675 # I'll leave the diagnosis to the copy subroutine.
5676 return;
5677 }
5678 # !!! HOWEVER: !!
5679 # There can be multiple ways of referring to the same directories
5680 # without that being detectable by the use of abs_path
5681 # on the names: E.g., on Windows one directory is referred to via a
5682 # drive letter that is used for files on a server, and the second
5683 # uses the '\\...' (or '//...'construction to refer to the server directly.
5684 # Also, on a OS/FS combination that is insensitive to case, the
5685 # abs_paths can differ in case while referring to the same entity
5686 # On UNIX, I can use a dev and inode test for equality, from the
5687 # results of stat.
5688 # But that doesn't work on Windows (where the inode numbers
5689 # returned by stat are always zero).
5690 # Easiest is to let the copy subroutine do the work, and just
5691 # diagnose the situation when it fails
5692
5693 say "$My_name: Copying final output files from '$source1' to '$dest1'";
5694
5695 foreach ( @out2_exts ) {
5696 my $name = ( /%R/ ? $_ : "%R.$_" );
5697 $name =~ s/%R/$$Pbase/;
5698 my $from = "$source1$name";
5699 my $to = "$dest1$name";
5700 if ( test_gen_file_time( $from ) ) {
5701 if (! $silent) { print "$My_name: Copying '$from' to '$to'\n"; }
5702 # Work around problem that if $from and $to refer to the same
5703 # file, then copy returns zero, for error, but does **not** set
5704 # $!. (This is surely a bug, since copy (i.e.,
5705 # File::Copy::copy) is documented to set $! when it encounters
5706 # an error.) So in this situation $! contains whatever error
5707 # code was set by something else earlier.
5708 # I'll reset $! to 0 here, which corresponds to no error.
5709 # If after running copy, it's still zero, but copy reports
5710 # failure, then that indicates that $from and $to are the same
5711 # file, and we didn't actually need a copy; for latexmk it's a
5712 # non-error.
5713 local $! = 0;
5714 my $ret = copy( $from, $to );
5715 if ( $ret ) { } # Success
5716 elsif ($!) { warn "$My_name: Failure of copy from '$from' to '$to', error =\n $!\n"; }
5717 else { } # Non-error.
5718 }
5719 }
5720 } #END do_copies_out_to_out2
5721
5722 #*************************************************************************
5723
5724 sub correct_locations {
5725 # Deal with situations after a *latex run where files are in different
5726 # directories than expected (specifically aux v. output directory).
5727 # Do minimal fix ups to allow latexmk to analyze dependencies with log
5728 # and fls files in expected places.
5729
5730
5731 # Deal with log file in unexpected place (e.g., lack of support by *latex
5732 # of -aux-directory option. This is to be done first, since a run of
5733 # *latex always produces a log file unless there is a bad error, so
5734 # this gives the best chance of diagnosing errors.
5735
5736 # Assumes rule context.
5737
5738 my $where_log = &find_set_log;
5739
5740 if ( ($aux_dir_requested ne '') && $emulate_aux && ($aux_dir ne $out_dir) ) {
5741 do_moves_aux_to_out( $aux_dir1, $out_dir1 );
5742 }
5743
5744 # Fix ups on fls file:
5745 if ($recorder) {
5746 # Deal with following special cases:
5747 # 1. Some implementations of *latex give fls files of name latex.fls
5748 # or pdflatex.fls instead of $$Pbase.fls.
5749 # 2. In some implementations, the writing of the fls file (memory
5750 # of old implementations) may not respect the -output-directory
5751 # and -aux-directory options.
5752 # 3. Implementations don't agree on which directory (aux or output)
5753 # the fls is written to. (E.g., MiKTeX changed its behavior in
5754 # Oct 2020.)
5755 # 4. Some implementations (TeXLive) don't use -aux-directory.
5756 # Situation on implementations, when $emulate_aux is off:
5757 # TeXLive: implements -output-directory only, and gives a non-fatal
5758 # warning for -aux-directory. Symptoms:
5759 # .log, .fls, .aux files written to intended output directory.
5760 # .log file reports TeXLive implementation
5761 # Correct reaction: Turn $emulate_aux on and rerun *latex. The
5762 # variety of files that can be written by packages is too
5763 # wide to allow simple prescription of a fix up.
5764 # MiKTeX: Pre-Oct-2020: fls file written to out dir.
5765 # Post-Oct-2020: fls file written to aux dir.
5766 # Other names:
5767 # Some older versions wrote pdflatex.fls or latex.fls
5768 # Current TeXLive: the fls file is initially written with the name
5769 # <program name><process number>.fls, and then changed to the
5770 # correct name. Under some error conditions, the change of name
5771 # does not happen.
5772
5773 my $std_fls_file = $fls_name;
5774 my @other_fls_names = ( );
5775 if ( $rule =~ /^pdflatex/ ) {
5776 push @other_fls_names, "pdflatex.fls";
5777 }
5778 else {
5779 push @other_fls_names, "latex.fls";
5780 }
5781 if ( $aux_dir1 ne '' ) {
5782 push @other_fls_names, "$$Pbase.fls";
5783 # The fls file may be in the opposite directory to the
5784 # one configured by $fls_uses_out_dir:
5785 push @other_fls_names, $fls_name_alt;
5786 }
5787 # Find the first non-standard fls file and copy it to the standard
5788 # place. But only do this if the file time is compatible with being
5789 # generated in the current run, and if the standard fls file hasn't
5790 # been made in the current run, as tested by the use of
5791 # test_gen_file_time; that avoids problems with fls files left over from
5792 # earlier runs with other versions of latex.
5793 if ( ! test_gen_file_time ( $std_fls_file ) ) {
5794 foreach my $cand (@other_fls_names) {
5795 if ( test_gen_file_time( $cand ) ) {
5796 print "$My_name: Copying '$cand' to '$std_fls_file'.\n";
5797 copy $cand, $std_fls_file;
5798 last;
5799 }
5800 }
5801 }
5802 if ( ! test_gen_file_time( $std_fls_file ) ) {
5803 warn "$My_name: fls file doesn't appear to have been made.\n";
5804 }
5805 }
5806 } # END correct_locations
5807
5808 #-----------------
5809
5810 sub find_log {
5811 # Locate log file generated on this run.
5812 # Usage find_log( $log_aux, $log_out, $log_cwd)
5813 # Side effect: measure filetime offset if necessary.
5814 # Don't take other actions.
5815 # Returns
5816 # 0 log file not found;
5817 # 1 log file in aux_dir i.e., correct place;
5818 # 2 log file **not** in aux_dir but in out_dir
5819 # (only applies if $emulate_aux off)
5820 # 3 log file is in ., not aux_dir or out_dir.
5821 # 4 log file in aux_dir, but out-of-date
5822 # 5 log file in out_dir, but out-of-date,
5823 # (only applies if $emulate_aux off)
5824 # 6 log file is in ., but out-of-date
5825
5826 # Assumes rule context.
5827 my ( $log_aux, $log_out, $log_cwd ) = @_;
5828 my $where_log = -1; # Nothing analyzed yet
5829
5830 # Basic tests first that assume accuracy of time of file system:
5831 if ( test_gen_file_time( $log_aux ) ) {
5832 # Expected case
5833 return 1;
5834 }
5835 elsif ( (! $emulate_aux) && test_gen_file_time( $log_out ) ) {
5836 # *latex was called with -aux-directory option, but does not
5837 # implement it (e.g., TeXLive's version)
5838 return 2;
5839 }
5840 elsif ( test_gen_file_time( $log_cwd ) ) {
5841 # Arrive here typically with configuration error so that aux_dir
5842 # and/or out_dir aren't supplied to *latex.
5843 return 3;
5844 }
5845
5846 # Arrive here only if a log file with a time stamp not too much earlier
5847 # than the run time has not found in a relevant place.
5848 # If relevant files exist, then we must test for a serious offset
5849 # between system time and filesystem time (i.e., filesystem server
5850 # time).
5851 if ( ! $filetime_offset_measured ) {
5852 $filetime_offset = get_filetime_offset( $aux_dir1."tmp" );
5853 $filetime_offset_measured = 1;
5854 }
5855
5856 my @candidates = ( );
5857 my $latest_mtime = undef;
5858 my $latest_log = undef;
5859
5860 if ( -e $log_aux ) {
5861 if ( test_gen_file_time( $log_aux ) ) { return 1; }
5862 return 4;
5863 }
5864 # Get here if log file in aux doesn't exist or is apparently too old.
5865 if ( (! $emulate_aux) && ( -e $log_out ) ) {
5866 if (test_gen_file_time( $log_out ) ) { return 2; }
5867 return 5;
5868 }
5869 if ( -e $log_cwd ) {
5870 if (test_gen_file_time( $log_cwd ) ) { return 3; }
5871 return 6;
5872 }
5873 return 0;
5874 } #END find_log
5875
5876 #---------------------
5877
5878 sub find_set_log {
5879 # Locate the log file, generated on this run.
5880 # It should be in aux_dir. But:
5881 # a. With aux_dir ne out_dir and emulate_aux off and a (TeXLive) *latex
5882 # that doesn't support aux_dir, the log file is in out_dir.
5883 # b. If the specified command has no %O or if *latex doesn't support
5884 # out_dir (hence not TeXLive and not MiKTeX), the log file would
5885 # be in cwd.
5886 # c. With a sufficiently severe error in *latex, no log file was generated.
5887 # Any log file that exists will be a left over from a previous run,
5888 # and hence have a filetime less than the system time at the start of
5889 # the current run. (The strict filetime criterion is modified in the
5890 # implementation to allow for issues from file system's time
5891 # granularity, and mismatch of time on server hosting file system.)
5892 #
5893 # Possible return values, and side effects.
5894 # 0 log file not found;
5895 # 1 log file in aux_dir i.e., correct place;
5896 # 2 log file **not** in aux_dir but in out_dir
5897 # (only applies if $emulate_aux off)
5898 # $emulate_aux turned on, commands fixed, log file copied to
5899 # aux_dir, and flags set to cause rerun
5900 # 3 log file is in ., not aux_dir or out_dir.
5901 # Fatal error raised here, since cause is normally a configuration error
5902 # not an error caused by contents of user file.
5903 # 4 log file in aux_dir, but out-of-date
5904 # 5 log file in out_dir, but out-of-date,
5905 # (only applies if $emulate_aux off)
5906 # 6 log file is in ., but out-of-date
5907 #
5908 # Cases: 0, 4, 5, 6 are error conditions to be handled by caller
5909 # 2 is to be handled by caller by a rerun
5910 # 1 is success.
5911 my $log_aux = "$aux_dir1$$Pbase.log";
5912 my $log_out = "$out_dir1$$Pbase.log";
5913 my $log_cwd = "./$$Pbase.log";
5914
5915 my $where_log = find_log( $log_aux, $log_out, $log_cwd );
5916 my $good_log_found = 0;
5917
5918 if ($where_log == 1 ) {
5919 # As expected
5920 $good_log_found = 1;
5921 }
5922 elsif ($where_log == 2 ) {
5923 warn "$My_name: .log file in '$out_dir' instead of expected '$aux_dir'\n",
5924 " But emulate_aux is off. So I'll turn it on.\n",
5925 " I'll copy the log file to the correct place.\n",
5926 " The next run of *latex **SHOULD** not have this problem.\n";
5927 copy( $log_out, $log_aux );
5928 $where_log = 2;
5929 $emulate_aux = 1;
5930 $emulate_aux_switched = 1;
5931 # Fix up commands to have fudged use of directories for
5932 # use with non-aux-dir-supported *latex engines.
5933 foreach ( $$Pext_cmd ) {
5934 s/ -output-directory=[^ ]*(?= )//g;
5935 s/ -aux(-directory=[^ ]*)(?= )/ -output$1/g;
5936 }
5937 $good_log_found = 1;
5938 }
5939 if ($where_log == 3 ) {
5940 # .log file is not in out_dir nor in aux_dir, but is in cwd.
5941 # Presumably there is a configuration error
5942 # that prevents the directories from being used by latex.
5943 die "$My_name: The log file found was '$log_cwd' instead of\n",
5944 " '$log_aux'. Probably a configuration error\n",
5945 " prevented the use of the -aux-directory and/or the -output-directory\n",
5946 " options with the *latex command.\n",
5947 " I'll stop.\n";
5948 }
5949 elsif ($where_log == 4 ) {
5950 warn "$My_name: The expected log file, '$log_aux', does exist, but it appears\n",
5951 " to be left over from a previous run: The time at the start of the\n",
5952 " current run was $$Prun_time, but the log file appears to have been\n",
5953 " created significantly earlier, at ", get_mtime($log_aux), ".\n";
5954 }
5955 elsif ($where_log == 5 ) {
5956 warn "$My_name: The expected log file, '$log_aux', does not exist, but one is found\n",
5957 " in '$out_dir', but it apears to be left over from a previous run. The time\n",
5958 " at the start of the current run was $$Prun_time, but the log file appears to\n",
5959 " have been created significantly earlier, at ", get_mtime($log_out), ".\n";
5960 }
5961 elsif ($where_log == 6 ) {
5962 warn "$My_name: The expected log file, '$log_aux', does not exist, but one is found\n",
5963 " in '.', but it apears to be left over from a previous run. The time\n",
5964 " at the start of the current run was $$Prun_time, but the log file appears to\n",
5965 " have been created significantly earlier, at ", get_mtime($log_cwd), ".\n";
5966 }
5967 elsif ($where_log == 0) {
5968 warn "$My_name: No log file was found, neither the expected one, '$log_aux', nor one in '.'.\n";
5969 if (! $emulate_aux) { warn " I also looked in '$out_dir'\n"; }
5970 }
5971 if ( ! $good_log_found ) {
5972 $failure = 1;
5973 $$Plast_result = 2;
5974 $failure_msg
5975 = "*LaTeX didn't generate the expected log file '$log_aux'\n";
5976 }
5977
5978 return $where_log;
5979 } #END find_set_log
5980
5981 #************************************************************
5982
5983 sub parse_log {
5984 # Use: parse_log( log_file_name,
5985 # ref to array containing lines,
5986 # ref to hash containing diagnostic etc information )
5987 # Given lines from already read log file, scan them for: dependent files
5988 # reference_changed, bad_reference, bad_citation.
5989 # Assume in the lines array, lines are already wrapped, and converted to my CS.
5990 # Return value: 1 if success, 0 if problems.
5991 # Put results in UPDATES of global variables (which are normally declared
5992 # local in calling routine, to be suitably scoped):
5993 # %dependents: maps definite dependents to code:
5994 # 0 = from missing-file line or other reason to consider file missing.
5995 # May have no extension
5996 # May be missing path
5997 # 1 = from 'File: ... Graphic file (type ...)' line
5998 # no path. Should exist, but may need a search, by kpsewhich.
5999 # 2 = from regular '(...' coding for input file,
6000 # Has NO path, which it would do if LaTeX file
6001 # Highly likely to be mis-parsed line
6002 # 3 = ditto, but has a path character ('/').
6003 # Should be LaTeX file that exists.
6004 # If it doesn't exist, we have probably a mis-parsed line.
6005 # There's no need to do a search.
6006 # 4 = definitive, which in this subroutine is only done:
6007 # for default dependents,
6008 # and for files that exist and are source of conversion
6009 # reported by epstopdf et al.
6010 # 5 = Had a missing file line. Now the file exists.
6011 # 6 = File was written during run. (Overrides 5)
6012 # 7 = File was created during run to be read in, as a conversion
6013 # from some other file (e.g., by epstopdf package).
6014 # (Overrides 5 and 6)
6015 # 8 = File was rewritten during run to be read in. (Overrides 5 and 6)
6016 # Treat the following specially, since they have special rules
6017 # @bbl_files gives list of .bbl files.
6018 # %idx_files gives information on .idx files to .ind files.
6019 # %generated_log: keys give set of files written by *latex (e.g., aux, idx)
6020 # as determined by \openout = ... lines in log file.
6021 # @missing_subdirs = list of needed subdirectories of aux_dir
6022 # These are needed for writing aux_files when an included file is in
6023 # a subdirectory relative to the directory of the main TeX file.
6024 # This variable is only set when the needed subdirectories don't exist,
6025 # and the aux_dir is non-trivial, which results in an error message in
6026 # the log file
6027 # %conversions Internally made conversions from one file to another
6028 #
6029 # These may have earlier found information in them, so they should NOT
6030 # be initialized.
6031 #
6032 # Also SET
6033 # $reference_changed, $bad_reference, $bad_citation
6034 # $pwd_latex
6035 #
6036 # Put in trivial or default values if log file does not exist/cannot be opened
6037 #
6038 # Input globals: $primary_out, $fls_file_analyzed
6039 #
6040 my ($log_name, $PAlines, $PHinfo) = @_;
6041 our ( $primary_out, $fls_file_analyzed, %generated_log, %idx_files,
6042 %dependents, @bbl_files, %log_info, @missing_subdirs,
6043 %conversions );
6044
6045 # $primary_out is actual output file (dvi or pdf)
6046 # It is initialized before the call to this routine, to ensure
6047 # a sensible default in case of misparsing
6048
6049 $reference_changed = 0;
6050 $mult_defined = 0;
6051 $bad_reference = 0;
6052 $bad_character = 0;
6053 $bad_citation = 0;
6054
6055 # ???!!! I don't know whether I will actually use these
6056 our @multiply_defined_references = ();
6057 our @undefined_citations = ();
6058 our @undefined_references = ();
6059
6060 print "$My_name: Examining '$log_name'\n"
6061 if not $silent;
6062
6063 my $engine = $$PHinfo{engine};
6064 my $tex_distribution = $$PHinfo{distribution};
6065
6066 # Now analyze the result:
6067 my $line_num = 0;
6068 my @pwd_log = (); # Working directory as reported. !!?? CHECK CORRECTNESS
6069 my $state = 0; # 0 => before ** line,
6070 # 1 => after **filename line, before next line (first file-reading line)
6071 # 2 => pwd_log determined.
6072 # For parsing multiple line blocks of info
6073 my $current_pkg = ""; # non-empty string for package name, if in
6074 # middle of parsing multi-line block of form:
6075 # Package name ....
6076 # (name) ...
6077 # ...
6078 my $block_type = ""; # Specify information in such a block
6079 my $delegated_source = ""; # If it is a file conversion, specify source
6080 my $delegated_output = ""; # and output file. (Don't put in
6081 # data structure until block is ended.)
6082 my %new_conversions = ();
6083 my $log_silent = ($silent || $silence_logfile_warnings);
6084 my $source_log; #Name of tex file that .log file reports as being on cmd line
6085 our @warning_list;
6086 @warning_list = (); # Warnings about undefined citations and the like
6087
6088 LINE:
6089 for (@$PAlines) {
6090 $line_num++;
6091 if ( /^! pdfTeX warning/ || /^pdfTeX warning/ ) {
6092 # This kind of warning is produced by some versions of pdftex
6093 # or produced by my reparse of warnings from other
6094 # versions.
6095 next;
6096 }
6097 if ( $line_num == 1 ){
6098 if ( /^This is / ) {
6099 # First line OK
6100 next LINE;
6101 } else {
6102 warn "$My_name: Error on first line of '$log_name'.\n".
6103 " This is apparently not a TeX log file. ",
6104 " The first line is:\n$_\n";
6105 $failure = 1;
6106 $failure_msg = "Log file '$log_name' appears to have wrong format.";
6107 return 0;
6108 }
6109 }
6110
6111 if ( ($state == 0) && /^\*\*(.*)$/ ) {
6112 # Line containing first line specified to tex
6113 # It's either a filename or a command starting with \
6114 my $first = $1;
6115 $state = 1;
6116 if ( ! /^\\/ ) {
6117 $source_log = $first;
6118 if ( -e "$source_log.tex" ) { $source_log .= '.tex'; }
6119 }
6120 else {
6121 $state = 2;
6122 }
6123 next LINE;
6124 }
6125 elsif ( $state == 1 ) {
6126 $state = 2;
6127 if (-e $source_log) {
6128 # then the string preceeding $source_log on the line after the
6129 # ** line is probably the PWD as it appears in filenames in the
6130 # log file, except if the file appears in two locations.
6131 if ( m{^\("([^"]*)[/\\]\Q$source_log\E"} ) {
6132 unshift @pwd_log, $1;
6133 }
6134 elsif ( m{^\((.*)[/\\]\Q$source_log\E} ) {
6135 unshift @pwd_log, $1;
6136 }
6137 }
6138 }
6139
6140 if ( $block_type ) {
6141 # In middle of parsing block
6142 if ( /^\($current_pkg\)/ ) {
6143 # Block continues
6144 if ( ($block_type eq 'conversion')
6145 && /^\($current_pkg\)\s+Output file: <([^>]+)>/ )
6146 {
6147 $delegated_output = normalize_clean_filename($1, @pwd_log);
6148 }
6149 next LINE;
6150 }
6151 # Block has ended.
6152 if ($block_type eq 'conversion') {
6153 $new_conversions{$delegated_source} = $delegated_output;
6154 }
6155 $current_pkg = $block_type
6156 = $delegated_source = $delegated_output = "";
6157 # Then process current line
6158 }
6159
6160 # ???!!! Use the extra items.
6161 # Check for changed references, bad references and bad citations:
6162 if (/Rerun to get/) {
6163 print "$My_name: References changed.\n" if ! $log_silent;
6164 $reference_changed = 1;
6165 }
6166 # if (/^LaTeX Warning: (Reference[^\001]*undefined on input line .*)\./) {
6167 if (/^LaTeX Warning: (Reference `([^']+)' on page .+ undefined on input line .*)\./) {
6168 push @warning_list, $1;
6169 push @undefined_references, $2;
6170 $bad_reference++;
6171 }
6172 elsif (/^LaTeX Warning: (Label `([^']+)' multiply defined.*)\./) {
6173 push @warning_list, $1;
6174 push @multiply_defined_references, $2;
6175 $mult_defined++;
6176 }
6177 elsif (/^LaTeX Warning: (Citation [`|']([^']+)' on page .* undefined on input line .*)\./) {
6178 push @warning_list, $1;
6179 push @undefined_citations, $2;
6180 $bad_citation++;
6181 }
6182 elsif (/^Package biblatex Warning: Please .* Biber /) {
6183 $log_info{biber} = 1;
6184 say "====== biblatex/biber in use";
6185 }
6186 elsif (/^Package natbib Warning: (Citation[^\001]*undefined on input line .*)\./) {
6187 push @warning_list, $1;
6188 push @undefined_citations, $2;
6189 $bad_citation++;
6190 }
6191 elsif ( /^Missing character: There is no /
6192 || /^! Package inputenc Error: Unicode character /
6193 || /^! Bad character code /
6194 || /^! LaTeX Error: Unicode character /
6195 ) {
6196 push @warning_list, $_;
6197 $bad_character++;
6198 }
6199 elsif ( /^Document Class: / ) {
6200 # Class sign-on line
6201 next LINE;
6202 }
6203 elsif ( /^\(Font\)/ ) {
6204 # Font info line
6205 next LINE;
6206 }
6207 elsif (/^No pages of output\./) {
6208 $primary_out = '';
6209 print "$My_name: Log file says no output from latex\n";
6210 next LINE;
6211 }
6212 elsif ( /^Output written on\s+(.*)\s+\(\d+\s+page/ ) {
6213 $primary_out = normalize_clean_filename($1, @pwd_log);
6214 print "$My_name: Log file says output to '$primary_out'\n"
6215 unless $silent;
6216 next LINE;
6217 }
6218 elsif ( /^Overfull /
6219 || /^Underfull /
6220 || /^or enter new name\. \(Default extension: .*\)/
6221 || /^\*\*\* \(cannot \\read from terminal in nonstop modes\)/
6222 ) {
6223 # Latex error/warning, etc.
6224 next LINE;
6225 }
6226 elsif ( /^\\openout\d+\s*=\s*(.*)\s*$/ ) {
6227 # \openout followed by filename followed by line end.
6228 # pdflatex and xelatex quote it and wrap,
6229 # lualatex leaves filename as is, and doesn't wrap.
6230 # Filename is always relative to aux_dir, given standard security
6231 # settings in TeXLive.
6232 my $cand = $1;
6233 if ( $cand =~ /\`\"([^\'\"]+)\"\'\.$/ ) {
6234 # One form of quoting by pdflatex, xelatex: `"..."'.
6235 $cand = $1;
6236 }
6237 elsif ( $cand =~ /\`([^\']+)\'\.$/ ) {
6238 # Another form of quoting by pdflatex, xelatex: `...'.
6239 $cand = $1;
6240 }
6241 if ( $cand =~ /[\`\'\"]/){
6242 # Bad quotes: e.g., incomplete wrapped line
6243 next LINE;
6244 }
6245 $generated_log{ normalize_force_directory($aux_dir1, $cand) } = 1;
6246 next LINE;
6247 }
6248 # Test for conversion produced by package:
6249 elsif ( /^Package (\S+) Info: Source file: <([^>]+)>/ ) {
6250 # Info. produced by epstopdf (and possibly others)
6251 # about file conversion
6252 $current_pkg = normalize_clean_filename($1, @pwd_log);
6253 $delegated_source = normalize_clean_filename($2, @pwd_log);
6254 $block_type = 'conversion';
6255 next LINE;
6256 }
6257 # Test for writing of index file. The precise format of the message
6258 # depends on which package (makeidx.sty , multind.sty or index.sty) and
6259 # which version writes the message.
6260 elsif ( /Writing index file (.*)$/ ) {
6261 my $idx_file = '';
6262 if ( /^Writing index file (.*)$/ ) {
6263 # From makeidx.sty or multind.sty
6264 $idx_file = $1;
6265 }
6266 elsif ( /^index\.sty> Writing index file (.*)$/ ) {
6267 # From old versions of index.sty
6268 $idx_file = $1;
6269 }
6270 elsif ( /^Package \S* Info: Writing index file (.*) on input line/ ) {
6271 # From new versions of index.sty
6272 $idx_file = $1;
6273 }
6274 else {
6275 warn "$My_name: A message suggests an index file may have been written\n",
6276 " but it is not of a form I understand. This is probably innocuous.\n",
6277 " The message is\n",
6278 " '$_'\n";
6279 next LINE;
6280 }
6281 # Typically, there is trailing space, not part of filename:
6282 $idx_file =~ s/\s*$//;
6283 # When *latex is run with an -output-directory
6284 # or an -aux_directory, the file name does not contain
6285 # the path. Fix this:
6286 $idx_file = normalize_force_directory( $aux_dir1, $idx_file );
6287 # Save the information, and
6288 # leave detailed processing to a higher level routine
6289 # (rdb_set_latex_deps), since that will have all the relevant
6290 # information to handle cases other than a standard conversion
6291 # of an .idx file to an .ind file by makeindex.
6292 $idx_files{$idx_file} = [];
6293 next LINE;
6294 }
6295 ### !!!!!!!!!!!!!!!!! ???? ISSUE: What if multiple patterns match in one line???;
6296 foreach my $pattern (@file_not_found) {
6297 if ( /$pattern/ ) {
6298 #??? print "!!! FOUND in '$pattern', candidate file '$file'\n";
6299 my $file = clean_filename($1);
6300 if ( $file =~ /\.bbl$/ ) {
6301 # Note that bbl's filename is always relative to aux_dir.
6302 my $bbl_file = normalize_force_directory( $aux_dir1, $file );
6303 warn "$My_name: Missing bbl file '$bbl_file' in following:\n $_\n";
6304 $dependents{$bbl_file} = 0;
6305 push @bbl_files, $bbl_file;
6306 next LINE;
6307 }
6308 warn "$My_name: Missing input file '$file' message in .log file:\n $_\n"
6309 unless $silent;
6310 $dependents{normalize_filename($file, @pwd_log)} = 0;
6311 my $file1 = $file;
6312 if ( $aux_dir && ($aux_dir ne '.') ) {
6313 # Allow for the possibility that latex generated
6314 # a file in $aux_dir, from which the missing file can
6315 # be created by a cusdep (or other) rule that puts
6316 # the result in $out_dir. If the announced missing file
6317 # has no path, then it would be effectively a missing
6318 # file in $aux_dir, with a path. So give this alternate
6319 # location.
6320 # It is also possible to have a file that is in a directory
6321 # relative to the aux_dir, so allow for that as well
6322 my $file1 = normalize_force_directory( $aux_dir1, $file );
6323 $dependents{$file1} = 0;
6324 }
6325 next LINE;
6326 }
6327 }
6328 foreach my $pattern (@bad_warnings) {
6329 if ( /$pattern/ ) {
6330 $log_info{bad_warning} = 1;
6331 warn "$My_name: Important warning:\n $_\n"
6332 unless $silent;
6333 }
6334 }
6335 if ( (! $fls_file_analyzed)
6336 && /^File: (.+) Graphic file \(type / ) {
6337 # First line of message from includegraphics/x
6338 # But this does NOT include full path information
6339 # (if exact match is not found and a non-trivial
6340 # kpsearch was done by *latex).
6341 # But the source-file information is in the fls file,
6342 # if we are using it.
6343 $dependents{normalize_clean_filename($1, @pwd_log)} = 1;
6344 next LINE;
6345 }
6346 # Now test for generic lines to ignore, only after special cases!
6347 if ( /^File: / ) {
6348 # Package sign-on line. Includegraphics/x also produces a line
6349 # with this signature, but I've already handled it.
6350 next LINE;
6351 }
6352 if ( /^Package: / ) {
6353 # Package sign-on line
6354 next LINE;
6355 }
6356 if (/^\! LaTeX Error: / ) {
6357 next LINE;
6358 }
6359 if ( m[^! I can't write on file `(.*)/([^/']*)'.\s*$] ) {
6360 my $dir = $1;
6361 my $file = $2;
6362 my $full_dir = $aux_dir1.$dir;
6363 if ( ($aux_dir ne '') && (! -e $full_dir)
6364 && ( ($file =~ /\.aux$/) || ($allow_subdir_creation == 2) )
6365 ) {
6366 warn "$My_name: === There were problems writing to '$file' in '$full_dir'\n",
6367 " I'll try to make the subdirectory later.\n"
6368 if $diagnostics;
6369 push @missing_subdirs, $full_dir;
6370 }
6371 else {
6372 warn "$My_name: ====== There were problems writing to",
6373 "----- '$file' in '$full_dir'.\n",
6374 "----- But this is not the standard situation of file to subdir of output\n",
6375 "----- directory, with non-existent subdir, and either file is aux file or\n",
6376 "----- or \$allow_subdir_creation is set to 2.\n";
6377 }
6378 }
6379
6380 if ( ($fls_file_analyzed) && (! $analyze_input_log_always) ) {
6381 # Skip the last part, which is all about finding input
6382 # file names which should all appear more reliably in the
6383 # fls file.
6384 next LINE;
6385 }
6386
6387 my @new_includes = ();
6388
6389 GRAPHICS_INCLUDE_CANDIDATE:
6390 while ( /<([^>\{]+)(>|\{|$)/g ) {
6391 if ( -f $1 ) { push @new_includes, $1; }
6392 } # GRAPHICS_INCLUDE_CANDIDATE:
6393
6394 INCLUDE_CANDIDATE:
6395 while ( /\((.*$)/ ) {
6396 # Filename found by
6397 # '(', then filename, then terminator.
6398 # Terminators: obvious candidates: ')': end of reading file
6399 # '(': beginning of next file
6400 # ' ': space is an obvious separator
6401 # ' [': start of page: latex
6402 # and pdflatex put a
6403 # space before the '['
6404 # '[': start of config file
6405 # in pdflatex, after
6406 # basefilename.
6407 # '{': some kind of grouping
6408 # Problem:
6409 # All or almost all special characters are allowed in
6410 # filenames under some OS, notably UNIX. Luckily most cases
6411 # are rare, if only because the special characters need
6412 # escaping. BUT 2 important cases are characters that are
6413 # natural punctuation
6414 # Under MSWin, spaces are common (e.g., "C:\Program Files")
6415 # Under VAX/VMS, '[' delimits directory names. This is
6416 # tricky to handle. But I think few users use this OS
6417 # anymore.
6418 #
6419 # Solution: use ' [', but not '[' as first try at delimiter.
6420 # Then if candidate filename is of form 'name1[name2]', then
6421 # try splitting it. If 'name1' and/or 'name2' exists, put
6422 # it/them in list, else just put 'name1[name2]' in list.
6423 # So form of filename is now:
6424 # '(',
6425 # then any number of characters that are NOT ')', '(', or '{'
6426 # (these form the filename);
6427 # then ' [', or ' (', or ')', or end-of-string.
6428 # That fails for pdflatex
6429 # In log file:
6430 # '(' => start of reading of file, followed by filename
6431 # ')' => end of reading of file
6432 # '[' => start of page (normally preceeded by space)
6433 # Remember:
6434 # filename (on VAX/VMS) may include '[' and ']' (directory
6435 # separators)
6436 # filenames (on MS-Win) commonly include space.
6437 # filenames on UNIX can included space.
6438 # Miktex quotes filenames
6439 # But web2c doesn't. Then
6440 # (string message
6441 # is ambiguous: is the filename "string" or "string message".
6442 # Allow both as candidates, since user filenames with spaces
6443 # are rare. System filenames with spaces are common, but
6444 # they are normally followed by a newline rather than messages.
6445
6446 # First step: replace $_ by whole of line after the '('
6447 # Thus $_ is putative filename followed by other stuff.
6448 $_ = $1;
6449 # Array of new candidate include files; sometimes more than one.
6450 my $quoted = 0;
6451 if ( /^\"([^\"]+)\"/ ) {
6452 # Quoted file name, as from MikTeX
6453 $quoted = 1;
6454 }
6455 elsif ( /^\"/ ) {
6456 # Incomplete quoted file, as in wrapped line before appending
6457 # next line
6458 next LINE;
6459 }
6460 elsif ( /^([^\(^\)]*?)\s+[\[\{\<]/ ) {
6461 # Terminator: space then '[' or '{' or '<'
6462 # Use *? in condition: to pick up first ' [' (etc)
6463 # as terminator
6464 }
6465 elsif ( /^([^\(^\)]*)\s+(?=\()/ ) {
6466 # Terminator is ' (', but '(' isn't in matched string,
6467 # so we keep the '(' ready for the next match
6468 }
6469 elsif ( /^([^\(^\)]*)(\))/ ) {
6470 # Terminator is ')'
6471 }
6472 else {
6473 #Terminator is end-of-string
6474 }
6475 $_ = $'; # Put $_ equal to the unmatched tail of string '
6476 my $include_candidate = $1;
6477 $include_candidate =~ s/\s*$//; # Remove trailing space.
6478 if ($quoted) {
6479 # Remove double quotes around filename.
6480 $include_candidate =~ s/^\"(.*)\"$/$1/;
6481 }
6482 if ($include_candidate =~ /[\"\'\`\x00]/) {
6483 # Quote or null inside candidate filename.
6484 # Quotes (", ', `) => very probably misparse, since quotes
6485 # are difficult to use in filenames in TeX.
6486 # Null is impossible in filename in all current OSs and file systems.
6487 # (Null appears in the .log file in some cases, so a test is needed.
6488 # (a) MiKTeX 2.7 on Windows.
6489 # (b) A report on tex.stackexchange 23 May 2025.
6490 next INCLUDE_CANDIDATE;
6491 }
6492 elsif ( !$quoted && ($include_candidate =~ /(\S+)\s/ ) ){
6493 # Non-space-containing filename-candidate
6494 # followed by space followed by message
6495 # (Common)
6496 push @new_includes, $1;
6497 }
6498 if ( $include_candidate eq "[]" ) {
6499 # Part of overfull hbox message
6500 next INCLUDE_CANDIDATE;
6501 }
6502 if ( $include_candidate =~ /^\\/ ) {
6503 # Part of font message
6504 next INCLUDE_CANDIDATE;
6505 }
6506
6507 push @new_includes, $include_candidate;
6508 if ( $include_candidate =~ /^(.+)\[([^\]]+)\]$/ ) {
6509 # Construct of form 'file1[file2]', as produced by pdflatex
6510 if ( -e $1 ) {
6511 # If the first component exists, we probably have the
6512 # pdflatex form
6513 push @new_includes, $1, $2;
6514 }
6515 else {
6516 # We have something else.
6517 # So leave the original candidate in the list
6518 }
6519 }
6520 } # INCLUDE_CANDIDATE
6521
6522 INCLUDE_NAME:
6523 foreach my $include_name (@new_includes) {
6524 if ( $include_name =~ /[\"\'\`\x00]/ ) {
6525 # Quote or null inside candidate filename.
6526 # Quotes (", ', `) => very probably misparse, since quotes
6527 # are difficult to use in filenames in TeX.
6528 # Null is impossible in filename in all current OSs and file systems.
6529 next INCLUDE_NAME;
6530 }
6531 # Most (but not all) implementations of TeX, put a non-empty path
6532 # in name of file read in .log file. Flag the situation of no path
6533 # separator in the file name: There's a high potential for misparse.
6534 # Do this before normalizing filename, and analyzing its components.
6535 my $no_path = ( $include_name !~ m'[/|\\]' );
6536 $include_name = normalize_filename( $include_name, @pwd_log );
6537 if ( ! defined $include_name ) { next INCLUDE_NAME; }
6538 if ( ! -e $include_name ) { next INCLUDE_NAME; }
6539 my ($base, $path, $ext) = fileparseB( $include_name );
6540 if ( ($path eq './') || ($path eq '.\\') ) {
6541 $include_name = $base.$ext;
6542 }
6543 if ( $no_path ) {
6544 $dependents{$include_name} = 2;
6545 } else {
6546 $dependents{$include_name} = 3;
6547 }
6548 if ( $ext eq '.bbl' ) {
6549 if ( -e $include_name ) {
6550 print "$My_name: Found input bbl file '$include_name'\n"
6551 unless $silent;
6552 }
6553 else {
6554 warn "$My_name: Bbl file '$include_name' is listed in .log file\n",
6555 " as having been read, but it doesn't exist\n";
6556 if ( ($path eq '') && ($aux_dir ne '' ) && ( -e "%aux_dir1$include_name" ) ) {
6557 warn " But it's in '$aux_dir'\n",
6558 " There's probably a bug in .log file writing\n";
6559 $include_name = "%aux_dir1$include_name";
6560 }
6561 else {
6562 next;
6563 }
6564 }
6565 push @bbl_files, $include_name;
6566 }
6567 } # INCLUDE_NAME
6568 } # LINE
6569
6570 # Default includes are always definitive:
6571 foreach (@default_includes) { $dependents{$_} = 4; }
6572
6573 my @misparse = ();
6574 my @missing = ();
6575 my @not_found = ();
6576
6577 my %kpsearch_candidates = ();
6578 CANDIDATE:
6579 foreach my $candidate (keys %dependents) {
6580 my $code = $dependents{$candidate};
6581 if ( -d $candidate ) {
6582 # If $candidate is directory, it was presumably found from a
6583 # mis-parse, so remove it from the list. (Misparse can
6584 # arise, for example from a mismatch of latexmk's $log_wrap
6585 # value and texmf.cnf value of max_print_line.)
6586 delete $dependents{$candidate};
6587 }
6588 elsif ( -e $candidate ) {
6589 if ( exists $generated_log{$candidate} ){
6590 $dependents{$candidate} = 6;
6591 }
6592 elsif ($code == 0) {
6593 $dependents{$candidate} = 5;
6594 }
6595 else {
6596 $dependents{$candidate} = 4;
6597 }
6598 }
6599 elsif ($code == 1) {
6600 # Graphics file that is supposed to have been read.
6601 # Candidate name is as given in source file, not as path
6602 # to actual file.
6603 # We have already tested that file doesn't exist, as given.
6604 # so use kpsewhich.
6605 # If the file still is not found, assume non-existent;
6606 $kpsearch_candidates{$candidate} = 1;
6607 delete $dependents{$candidate};
6608 }
6609 elsif ($code == 2) {
6610 # Candidate is from '(...' construct in log file, for input file
6611 # which should include pathname if valid input file.
6612 # Name does not have pathname-characteristic character (hence
6613 # $code==2.
6614 # We get here if candidate file does not exist with given name
6615 # Almost surely result of a misparsed line in log file.
6616 delete $dependents{$candidate};
6617 push @misparse, $candidate;
6618 }
6619 elsif ($code == 3) {
6620 # Candidate is from '(...' construct in log file, for input file
6621 # which should include pathname if valid input file.
6622 # Name does have pathname-characteristic character (hence
6623 # $code==3.
6624 # But we get here only if candidate file does not exist with
6625 # given name.
6626 # Almost surely result of a misparsed line in log file.
6627 # But with lower probability than $code == 2
6628 delete $dependents{$candidate};
6629 push @misparse, $candidate;
6630 }
6631 elsif ($code == 0) {
6632 my ($base, $path, $ext) = fileparseA($candidate);
6633 $ext =~ s/^\.//;
6634 if ( ($ext eq '') && (-e "$path$base.tex") ) {
6635 # I don't think the old version was correct.
6636 # If the missing-file report was of a bare
6637 # extensionless file, and a corresponding .tex file
6638 # exists, then the missing file does not correspond
6639 # to the missing file, unless the .tex file was
6640 # created during the run.
6641 $dependents{"$path$base.tex"} = 4;
6642 }
6643 push @missing, $candidate;
6644 }
6645 }
6646
6647 my @kpsearch_candidates = keys %kpsearch_candidates;
6648 if (@kpsearch_candidates) {
6649 foreach my $result ( kpsewhich( @kpsearch_candidates ) ) {
6650 $dependents{$result} = 4;
6651 }
6652 }
6653
6654 CANDIDATE_PAIR:
6655 foreach my $delegated_source (keys %new_conversions) {
6656 my $delegated_output = $new_conversions{$delegated_source};
6657 my $rule = "Delegated $delegated_source, $delegated_output";
6658 # N.B. $delegated_source eq '' means the output file
6659 # was created without a named input file.
6660 foreach my $candidate ($delegated_source, $delegated_output) {
6661 if (! -e $candidate ) {
6662 # The file might be somewhere that can be found
6663 # in the search path of kpathsea:
6664 my @kpse_result = kpsewhich( $candidate,);
6665 if ($#kpse_result > -1) {
6666 $candidate = $kpse_result[0];
6667 }
6668 }
6669 }
6670 if ( ( (-e $delegated_source) || ($delegated_source eq '') )
6671 && (-e $delegated_output) )
6672 {
6673 $conversions{$delegated_output} = $delegated_source;
6674 $dependents{$delegated_output} = 7;
6675 if ($delegated_source) {
6676 $dependents{$delegated_source} = 4;
6677 }
6678 }
6679 elsif (!$silent) {
6680 print "Logfile claimed conversion from '$delegated_source' ",
6681 "to '$delegated_output'. But:\n";
6682 if (! -e $delegated_output) {
6683 print " Output file does not exist\n";
6684 }
6685 if ( ($delegated_source ne '') && (! -e $delegated_source) ) {
6686 print " Input file does not exist\n";
6687 }
6688 }
6689 }
6690
6691 if ( $diagnostics ) {
6692 @misparse = uniqs( @misparse );
6693 @missing = uniqs( @missing );
6694 @not_found = uniqs( @not_found );
6695 my @dependents = sort( keys %dependents );
6696
6697 my $dependents = $#dependents + 1;
6698 my $misparse = $#misparse + 1;
6699 my $missing = $#missing + 1;
6700 my $not_found = $#not_found + 1;
6701 my $exist = $dependents - $not_found - $missing;
6702 my $bbl = $#bbl_files + 1;
6703
6704 print "$dependents dependent files detected, of which ",
6705 "$exist exist, $not_found were not found,\n",
6706 " and $missing appear not to exist.\n";
6707 print "Dependents:\n";
6708 foreach (@dependents) {
6709 print " '$_' ";
6710 if ( $dependents{$_} == 6 ) { print " written by *latex";}
6711 if ( $dependents{$_} == 7 ) { print " converted by *latex";}
6712 print "\n";
6713 }
6714 if ($not_found > 0) {
6715 show_array( "Not found:", @not_found );
6716 }
6717 if ($missing > 0) {
6718 show_array( "Not existent:", @missing );
6719 }
6720 if ( $bbl > 0 ) {
6721 show_array( "Input bbl files:", @bbl_files );
6722 }
6723
6724 if ( $misparse > 0 ) {
6725 show_array( "Possible input files, perhaps from misunderstood lines in .log file:", @misparse );
6726 }
6727 }
6728 return 1;
6729 } #END parse_log
6730
6731 #************************************************************
6732
6733 sub get_log_file {
6734 # Use: get_log_file( log_file_name,
6735 # ref to array to receive lines,
6736 # ref to hash to receive diagnostic etc informaion )
6737 # 3rd argument is optional
6738 # Lines are unwrapped and converted to the CS_system coding system (so
6739 # that filenames are suitable for use in file opening calls and on
6740 # command line to invoked programs).
6741 #
6742 # **Complication**: When writing to the .log file, *latex converts
6743 # lines longer than a given length (by default, 79) to a sequence
6744 # of lines with at most the maximum length.
6745 # This subroutine converts such sequences of lines to the original
6746 # unwrapped form.
6747 # **However**,
6748 # 1. The algorithm for line wrapping differs between all of pdflatex,
6749 # xelatex, and lualatex. See below for details.
6750 # 2. It is possible to write an unwrapped line L1 of a relevant
6751 # length followed by a shorter line L2, such that it is impossible
6752 # to distingish it from a wrapped line whose contents were those
6753 # of L1 concatenated with L2.
6754 # So when it is determined that a line is potentially wrapped,
6755 # several possibilities for the unwrapped lines are added to the
6756 # output array of lines (referenced by the second argument), so that
6757 # subsequent scanning of the lines in the subroutine parse_log picks
6758 # up the possible diagnostic messages independently of complications
6759 # in identifying wrapped lines versus unwrapped lines.
6760
6761 my ($file, $PAlines, $PHinfo) = @_;
6762 # Where lines are wrapped at. We'll sometimes override.
6763 # Note that TeXLive's hilatex, at least in TL 2023, with HINT 2.0,
6764 # doesn't obey max_print_line environment or the corresponding
6765 # -cnf-line option. They work for pdflatex.
6766 # Similarly for MiKTeX 23.10.12's hilatex, which reports the same version of
6767 # HINT.
6768 local $log_wrap = $log_wrap;
6769
6770 # Lines held for wrapping:
6771 my @held_lines = ();
6772 # Routine for setting wrapped lines; setup by assignment to keep visibility
6773 # in the enclosing subroutine, and to access its my-variables:
6774 my $Pwrap_sub =
6775 sub {
6776 for ( my $i=0; $i <= $#held_lines; $i++ ) {
6777 my $line = '';
6778 for ( my $j=$i; $j <= $#held_lines; $j++ ) {
6779 last if ($j-$i > 1 + ($max_log_construct /$log_wrap) );
6780 $line .= $held_lines[$j];
6781 push @$PAlines, $line;
6782 }
6783 }
6784 @held_lines = ();
6785 };
6786
6787
6788 my $engine = '';
6789 my $tex_distribution = '';
6790 my ($line_num, $max_len) = ( 0, 0 );
6791 my $lua_mode = 0; # Whether to use luatex-specific wrapping method.
6792 my $byte_wrapping = 1; # Assume by default that the wrapping occurs at
6793 # a certain number of bytes. Modify this
6794 # variable if we find that the log file was
6795 # generated by a tex program that does wrapping
6796 # at a certain number of Unicode code points.
6797 # The details for the different programs (underlying the *latex programs):
6798 # File encoding: pdftex: UTF-8 but with wrapping at $log_wrap BYTES.
6799 # (So individual wrapped lines can be malformed
6800 # UTF-8, but we get valid UTF-8 after unwrapping.)
6801 # luatex: UTF-8 but with wrapping at APPROXIMATELY
6802 # $log_wrap bytes. Rest as pdftex
6803 # xetex: UTF-8 with wrapping at $log_wrap codepoints.
6804 # hilatex: (TL 2023, HINT 2.0) Pure 7-bit ASCII with ^^
6805 # encoding of non-ASCII. Wrapping at 79 bytes.
6806 # So we read file as bytes. Then
6807 # first line gives which program was used and hence whether to wrap
6808 # according to byte or codepoint count.
6809 # wrapping is always performed on the encoded byte strings, but the
6810 # place to wrap is determined according to the length in bytes or
6811 # in codepoints, as needed.
6812 print "$My_name: Getting log file '$file'\n";
6813 open( my $fh, '<', $file )
6814 or return 0;
6815 LINE:
6816 while (local $_ = <$fh> ) {
6817 $line_num++;
6818 s/\r?\n$//;
6819 if ($line_num == 1) {
6820 if ( /^This is ([^,]+), [^\(]*\(([^\)]+)\)/ ) {
6821 $engine = $1;
6822 $tex_distribution = $2;
6823 }
6824 else {
6825 warn "$My_name: First line of .log file '$file' is not in standard format.\n";
6826 }
6827 if ( $engine =~ /XeTeX/i ) {
6828 $byte_wrapping = 0;
6829 }
6830 $lua_mode = ( $engine =~ /lua.*tex/i );
6831 # TeXLive's *tex take log wrap value from environment variable max_print_line, if it exists:
6832 if ( ($tex_distribution =~ /TeX\s*Live/) &&
6833 $ENV{max_print_line} ) {
6834 # See comment earlier about hilatex.
6835 $log_wrap = $ENV{max_print_line};
6836 print "$My_name: changed column for log file wrapping from standard to $log_wrap\n".
6837 " from env. var. max_print_line, which is obeyed by your TeXLive programs\n"
6838 if $diagnostics;
6839 }
6840 # First (signon) line of log file doesn't get wrapped
6841 push @$PAlines, $_;
6842 next LINE;
6843 }
6844 my $len = 0;
6845 if ($byte_wrapping) { $len = length($_); }
6846 else {
6847 no bytes;
6848 $len = length( decode('UTF-8', $_) );
6849 }
6850 if ($len > $max_len) { $max_len = $len }
6851
6852 # Is this line wrapped? I.e., is next line to be appended to it?
6853 # 2 cases:
6854 # pdflatex and xelatex wrap at exactly length $log_wrap
6855 # (default 79), and normally append empty line when line
6856 # is exactly of the maximimum length (so we shouldn't have a
6857 # problem of distinguishing a wrapped line from a line of
6858 # length exactly $log_wrap).
6859 # lualatex: Wrap at a variable position dependent in a complicated
6860 # way on contents. With default settings, wrapping occurs
6861 # between 77 and 80 bytes, according to my tests. It preserves
6862 # UTF-8 coding, and doesn't split multi-byte UTF-8 coding of
6863 # a code point between lines, unlike pdflatex. But details
6864 # of exactly where a line is wrapped is not clear.
6865 # It is not possible in all cases to distinguish whether
6866 # a pair of lines arise from wrapping of a longer line
6867 # or from actual writing of a pair of lines.
6868 # Determine whether line is potentially wrapped:
6869 my $cont = ($len == $log_wrap)
6870 || ( $lua_mode && ($len >= $log_wrap-2) && ($len <= $log_wrap+1) );
6871 if ($cont) {
6872 # Save lines that may be continued onto @held_lines
6873 print "====Continuing line $line_num of length $len\n$_\n"
6874 if $diagnostics;
6875 push @held_lines, $_;
6876 }
6877 elsif (@held_lines) {
6878 # No more continuation lines after this:
6879 push @held_lines, $_;
6880 # Put possibilities for lines before wrapping onto the main
6881 # array and then clear @held_lines
6882 &$Pwrap_sub();
6883 }
6884 else {
6885 push @$PAlines, $_;
6886 }
6887 }
6888 if (@held_lines) {
6889 # Get here if the last line of the file is of a length that
6890 # it may be a wrapped.
6891 &$Pwrap_sub();
6892 }
6893 close($fh);
6894 foreach (@$PAlines) {
6895 hathat_to_binary( $_ ) if ( $conv_hathat && /\^\^/ );
6896 $_ = utf8_to_mine($_);
6897 }
6898 push @$PAlines, ""; # Blank line to terminate. So multiline blocks
6899 # are always terminated by non-block line, rather than eof.
6900 $$PHinfo{max_len} = $max_len;
6901 $$PHinfo{num_lines} = $line_num;
6902 $$PHinfo{num_after} = 1 + $#$PAlines;
6903 $$PHinfo{engine} = $engine;
6904 $$PHinfo{distribution} = $tex_distribution;
6905 return 1;
6906 } #END get_log_file
6907
6908 #=====================================
6909
6910 sub parse_fls {
6911 my $start_time = processing_time();
6912 my ($fls_name, $Pinputs, $Poutputs, $Pfirst_read_after_write, $Ppwd_latex ) = @_;
6913 %$Pinputs = %$Poutputs = %$Pfirst_read_after_write = ();
6914 my $fls_file;
6915 # Make a note of current working directory
6916 # I'll update it from the fls file later
6917 # Currently I don't use this, but it would be useful to use
6918 # this when testing prefix for cwd in a filename, by
6919 # giving *latex's best view of the cwd. Note that the
6920 # value given by the cwd() function may be mangled, e.g., by cygwin
6921 # compared with native MSWin32.
6922 #
6923 # Two relevant forms of cwd exist: The system one, which we can find, and
6924 # the one reported by *latex in the fls file. It will be
6925 # useful to remove leading part of cwd in filenames --- see the
6926 # comments in sub rdb_set_latex_deps. Given the possible multiplicity
6927 # of representations of cwd, the one reported in the fls file should
6928 # be definitive in the fls file.
6929
6930 my $cwd = good_cwd();
6931 if ( ! open($fls_file, "<", $fls_name) ) {
6932 return 1;
6933 }
6934
6935 print "$My_name: Examining '$fls_name'\n"
6936 if not $silent;
6937
6938 # For use when checking for INPUT of normal OUTPUT file:
6939 my %danger_dirs = ( $aux_dir1 => 1, $out_dir1 => 1, $out2_dir1 => 1 );
6940 # The keys of %vetoed are the names of INPUT files that aren't to be treated as source files.
6941 # This variable is used to avoid repeated repeated warnings for the same file of this kind.
6942 # Such repeats would be common, since INPUT filename lines are often repeated in the .fls file.
6943 my %vetoed = ();
6944
6945 my $pwd_subst = undef; # Initial string for pwd that is to be removed to
6946 # make relative paths, when possible. It must end
6947 # in '/', if defined.
6948 my $line_no = 0;
6949 my $coding_errors = 0;
6950 my $coding_errors_max_print = 2;
6951 for ( <$fls_file> ) {
6952 # Remove trailing CR and LF. Thus we get correct behavior when an fls file
6953 # is produced by MS-Windows program (e.g., in MiKTeX) with CRLF line ends,
6954 # but is read by Unix Perl (which treats LF as line end, and preserves CRLF
6955 # in read-in lines):
6956 # And convert '\' to '/'
6957 s/\r?\n$//;
6958 s[\\][/]g;
6959 $line_no++;
6960 if ($no_CP_conversions) {
6961 # Assume same byte representations for filenames in .fls file as
6962 # for file system calls. No conversions needed.
6963 }
6964 else {
6965 # Deal with MS-Win issues when system CP isn't UTF-8
6966 # Situation is that the fls file should be in UTF-8 and
6967 # needs to be converted to system CP to fit with latexmk's
6968 # convention (determined by file-system calls).
6969 # However, under Windows' TeXLive 2021 (and maybe earlier) the
6970 # PWD uses the system CP while the rest of the file is UTF-8.
6971 # In TeXLive 2022 and 2023, the whole file, including the PWD
6972 # line is UTF-8.
6973 # So give special treatment to PWD line under Windows.
6974 # Also to guard against any other problems, check for non-UTF-8 lines.
6975 if ( ($^O eq 'MSWin32') && /PWD/ && ! is_valid_utf8($_) ) {
6976 print
6977 "PWD line not in UTF-8. This is normal for older TeXLives (2021 and earlier).\n".
6978 " I will handle it.\n";
6979 # Assume in CS_system, no change needed.
6980 }
6981 elsif ( ! is_valid_utf8($_) ) {
6982 $coding_errors++;
6983 warn "$My_name: In '$fls_name' =====Line $line_no is not in the expected UTF-8 coding:\n '$_'\n"
6984 unless ($coding_errors > $coding_errors_max_print);
6985 }
6986 else {
6987 my $orig = $_;
6988 $_ = utf8_to_mine_errors($_);
6989 if ($@) {
6990 $coding_errors++;
6991 if (!$silent) {
6992 warn "$@in conversion UTF-8 to system code page of line $line_no of $fls_name\n",
6993 "$orig\n"
6994 unless ($coding_errors > $coding_errors_max_print);
6995 }
6996 }
6997 }
6998 } # End of fudge on MS-Win code page.
6999 if (/^\s*PWD\s+(.*)$/) {
7000 my $cwd_fls = $1;
7001 $pwd_subst = $$Ppwd_latex = $cwd_fls;
7002 if ($pwd_subst !~ m[/$] ) { $pwd_subst .= '/'; }
7003 if ( $cwd_fls =~ /\"/ ) {
7004 warn "$My_name: The working directory has a '\"' character in its name:\n",
7005 " '$cwd'\n This can cause me trouble. Beware!\n";
7006 }
7007 if ( $report_cwd_mismatch
7008 && (normalize_filename($cwd_fls) ne normalize_filename($cwd) )
7009 ) {
7010 print
7011 "$My_name: ========= Mismatch of qcd name between .fls file and perl's report:\n",
7012 " '$cwd_fls'\n",
7013 " '$cwd'\n",
7014 "This is for your information and is not normally indicative of a bug.\n";
7015 }
7016 }
7017 elsif (/^\s*INPUT\s+(.*)$/) {
7018 # Take precautions against aliasing of foo, ./foo and other possibilities for cwd.
7019 my $file = $1;
7020 # Remove exactly pwd reported in this file, and following separator.
7021 # MiKTeX reports absolute pathnames, and this way of removing PWD insulates
7022 # us from coding issues if the PWD contains non-ASCII characters. What
7023 # coding scheme (UTF-8, code page, etc) is used depends on OS, TeX
7024 # implementation, ...
7025 if ( defined $pwd_subst ) {
7026 $file =~ s(^\Q$pwd_subst\E)();
7027 }
7028 $file = normalize_filename( $file );
7029 if ( (exists $$Poutputs{$file}) && (! exists $$Pinputs{$file}) ) {
7030 $$Pfirst_read_after_write{$file} = 1;
7031 }
7032
7033
7034 # PRECAUTIONS for main output pdf file (and potentially others) being INPUT
7035 #==========================================================================
7036 #
7037 # In almost all cases, the main output files (notably pdf, but
7038 # also dvi, ps, xdv, hnt, and also the log file) are pure
7039 # output files, and don't participate in circular dependences.
7040 # However, there are known situations where at least the pdf
7041 # file does. This siutation is potentially problematic, since
7042 # some of these normally output-only files, including the pdf
7043 # file, contain content that gives a time stamp. In a circular
7044 # dependency involving such files, latexmk's normal methods
7045 # give a perpetually out-of-date situation, and hence an
7046 # infinite loop.
7047 #
7048 # If such a file is listed as being INPUT in the .fls file,
7049 # then this needs to be detected, and special precautions
7050 # taken. In the one known case where there is both such a
7051 # circular dependency and the pdf file listed as INPUT in the
7052 # fls file, it suffices not to put that file in the list of
7053 # input files.
7054 #
7055 # Note that, in general, it is logically difficult to set up
7056 # such circular dependencies within *latex to get a desired
7057 # useful effect without the use of external software
7058 #
7059 # The known cases of the relevant kinds of circular dependency
7060 # both involve the output pdf file:
7061 #
7062 # (a) hyperxmp in some versions, e.g., 2020/10/05 v. 5.6, reads
7063 # metadata of the pdf file produced by pdflatex (to get the
7064 # filesize), which results in the pdf file being reported
7065 # as an INPUT file of pdflatex.
7066 # Without special precautions, latexmk gets into an
7067 # infinite loop. But correct functioning is achieved
7068 # simply by ensuring that the pdf file is not inserted in
7069 # the list of source files for *latex.
7070 # More recent versions of hyperxmp work differently, and so
7071 # do not cause
7072 #
7073 # (b) The memoize package uses non-trivial content from the pdf
7074 # file. There is a clear and essential circular
7075 # dependency. But given the way the package and its
7076 # associated script work, the pdf file doesn't appear any
7077 # where relevant to be detected by latexmk, and the package
7078 # and its script take care such that all necessary reruns
7079 # by latexmk get done.
7080 # In addition, there is a special configuration --- see
7081 # example_rcfiles/memoize_latexmkrc --- to allow memoize to
7082 # be used properly with latexmk. So that doesn't entail
7083 # special diagnosis here.
7084 #
7085 # The above illustrate that circular dependencies involving
7086 # these normally output-only files can exist, legitimately. So
7087 # we have to allow for the situation.
7088 #
7089 # The hyperxmp example shows that it does happen in reality
7090 # that the main pdf output file is listed in the .fls file, and
7091 # so that we do need an explicit test.
7092 # But there are no other known situations for other classes of
7093 # files that are normally only output (e.g., log, dvi, etc), so
7094 # I'll restrict the detection to the pdf case, but in a form
7095 # that can be generalized if need be.
7096 #
7097 # Given the vagaries of how the aux and output directories
7098 # could be used, the test allows for the file being in any of
7099 # the relevant directories. There is a potential issue that
7100 # different strings could be used for the name of the same
7101 # directories. That would entail a fancier test, but that issue
7102 # has not arisen in practice so far. Since the cases where the
7103 # test actually matters are already very rare, I won't handle
7104 # that extra complication.
7105
7106 my ($base, $path, $ext) = fileparseA( $file );
7107 if ( exists ($vetoed{$file}) ) {
7108 }
7109 elsif ( ( $base eq $root_filename )
7110 && ( $ext eq '.pdf' )
7111 && ( exists $danger_dirs{$path} )
7112 ) {
7113 warn "$My_name: !!!!!!!!!!! Fls file lists a normal output-only file\n",
7114 " '$file as an input file for rule '$rule'.\n",
7115 " Hence I won't treat '$file' as an input file.\n",
7116 " This kind of situation can be caused by the hyperxmp package in an old\n",
7117 " version, in which case you can safely ignore this message.\n";
7118 $vetoed{$file} = 1;
7119 }
7120 else {
7121 $$Pinputs{$file} = 1;
7122 }
7123
7124 } # end of handling INPUT line
7125 elsif (/^\s*OUTPUT\s+(.*)$/) {
7126 # Take precautions against aliasing of foo, ./foo and other possibilities for cwd.
7127 my $file = $1;
7128 $file =~ s(^\Q$$Ppwd_latex\E[\\/])();
7129 $file = normalize_filename( $file );
7130 $$Poutputs{$file} = 1;
7131 }
7132 }
7133 close( $fls_file );
7134 if ($coding_errors) {
7135 warn "$My_name.$fls_name. There were $coding_errors line(s) with character coding\n",
7136 " errors: Characters not available in system code page and/or non-UTF-8 in\n",
7137 " file when expected. Dependency information may be incomplete.\n";
7138 warn "The first few error lines are listed above\n";
7139 }
7140 return 0;
7141 } #END parse_fls
7142
7143 #************************************************************
7144
7145 sub hathat_to_binary {
7146 # Convert ^^ notation to bytes (log files from non-8bit configured latex).
7147 # In-line conversion.
7148 # Usage, e.g., hathat_to_binary( $line ) or hathat_to_binary( @array ).
7149 #
7150 foreach (@_){
7151 next unless /\^\^/;
7152 while ( /(\^\^([[:xdigit:]]{2}))/g ) {
7153 my $match = $1;
7154 my $hex = $2;
7155 my $pos = pos($_); # Regex analyzer positioned after match
7156 my $before = $pos - length($match);
7157 pos($_) = $before;
7158 my $subst = chr hex $hex;
7159 s/\G\Q$match/$subst/;
7160 pos($_) = $before + length($subst);
7161 }
7162 }
7163 }
7164
7165 #==============================================
7166
7167 sub dirname_no_tail {
7168 my $dirname = $_[0];
7169 foreach ($dirname) {
7170 # Normalize name to use / to separate directory components:
7171 # (Note both / and \ are allowed under MSWin.)
7172 s(\\)(/)g;
7173 # Change multiple trailing / to single /
7174 # (Note internal // or \\ can have special meaning on MSWin)
7175 s(/+$)(/);
7176 # Remove trailing /,
7177 # BUT **not** if that changes the semantics, i.e., if name is "/" or "C:/".
7178 if ( m(/$) ) {
7179 if ( ( ! m(^/+$) ) && ( ! m(:/+$) ) ) {
7180 s(/$)();
7181 }
7182 }
7183 }
7184 return $dirname;
7185 }
7186
7187 #************************************************************
7188
7189 sub clean_filename {
7190 # Convert quoted filename as found in log file to filename without quotes
7191 # Allows arbitrarily embedded double-quoted substrings, includes the
7192 # cases
7193 # 1. `"string".ext', which arises e.g., from \jobname.bbl:
7194 # when the base filename contains spaces, \jobname has quotes.
7195 # and from \includegraphics with basename specified.
7196 # Also deals with filenames written by asymptote.sty
7197 # 2. Or "string.ext" from \includegraphcs with basename and ext specified.
7198 # and from MiKTeX logfile for input files with spaces.
7199 # Doubled quotes (e.g., A""B) don't get converted.
7200 # Neither do unmatched quotes.
7201 my $filename = $_[0];
7202 while ( $filename =~ s/^([^\"]*)\"([^\"]+)\"(.*)$/$1$2$3/ ) {}
7203 return $filename;
7204 }
7205
7206 # ------------------------------
7207
7208 sub normalize_filename {
7209 # Usage: normalize_filename( filename [, extra forms of name of cwd] )
7210 # Returns filename with removal of various forms for cwd, and
7211 # with conversion of directory separator to '/' only,
7212 # and with use of my current choice of Unicode normalization.
7213 # Also when filename is name of a directory, with a trailing '/',
7214 # the trailing '/' is removed.
7215 # ????In presence of accented characters in directory names, intended
7216 # functioning is when all cwd strings are in my chosen NF.
7217 #
7218 my ( $file, @dirs ) = @_;
7219 my $cwd = good_cwd();
7220 # Normalize files to use / to separate directory components:
7221 # (Note both / and \ are allowed under MSWin.)
7222 foreach ($cwd, $file, @dirs) {
7223 s(\\)(/)g;
7224 # If this is directory name of form :.../", remove unnecessary
7225 # trailing directory separators:
7226 $_ = dirname_no_tail( $_ );
7227 }
7228
7229 # Remove initial component equal to current working directory.
7230 # Use \Q and \E round directory name in regex to avoid interpretation
7231 # of metacharacters in directory name:
7232 foreach my $dir ( @dirs, '.', $cwd ) {
7233 if ( $dir =~ /^\s*$/ ) {
7234 # All spaces, nothing to do.
7235 next;
7236 }
7237 if ($file eq $dir) {
7238 # Filename equals cwd, so it is . relative to cwd:
7239 $file = '.';
7240 last;
7241 }
7242 my $subst = $dir;
7243 if ($subst !~ m[/$]) { $subst .= '/'; }
7244 if ( $file =~ s(^\Q$subst\E)() ) {
7245 last;
7246 }
7247 }
7248 if ($file eq '' ) {
7249 # This only occurs for $file equal to a directory that
7250 # is the cwd. Our convention is always to set it to '.'
7251 #
7252 $file = '.';
7253 }
7254 return $file;
7255 } #END normalize_filename
7256
7257 # ------------------------------
7258
7259 sub normalize_filename_abs {
7260 # Convert filename to be either
7261 # absolute path in canonical form
7262 # or relative to cwd, if possible.
7263 # abs_path returns undef if it doesn't know how to get an absolute path.
7264 # Just work with the original path in that case.
7265 my $abs = abs_path($_[0]);
7266 if (! defined $abs) { $abs = $_[0]; }
7267 return normalize_filename( $abs );
7268 }
7269
7270 #-----------------------------
7271
7272 sub normalize_clean_filename {
7273 # Usage: normalize_clean_filename( filename [, extra forms of name of cwd] )
7274 # Same as normalize_filename, but first remove any double quotes, as
7275 # done by clean_filename, which is appropriate for filenames from log file.
7276 my ($file, @dirs) = shift;
7277 return normalize_filename( clean_filename( $file ) , @dirs );
7278 }
7279
7280 #************************************************************
7281
7282 sub fix_pattern {
7283 # Escape the characters [ and {, to give a pattern for use in glob
7284 # with these characters taken literally.
7285 my $pattern = shift;
7286 $pattern =~ s/\[/\\\[/g;
7287 $pattern =~ s/\{/\\\{/g;
7288 return $pattern;
7289 }
7290
7291 #************************************************************
7292
7293 sub parse_aux {
7294 # Usage: parse_aux( $aux_file, \@new_bib_files, \@new_aux_files, \@new_bst_files )
7295 # Parse aux_file (recursively) for bib files, and bst files.
7296 # If can't open aux file, then
7297 # Return 0 and leave @new_bib_files empty
7298 # Else set @new_bib_files and @new_bst_files from information in the
7299 # aux files
7300 # And:
7301 # Return 1 if no problems
7302 # Return 2 with @new_bib_files empty if there are no \bibdata
7303 # lines.
7304 # Return 3 if I couldn't locate all the bib_files
7305 # Set @new_aux_files to aux files parsed
7306
7307 our $Paux_files;
7308 my $aux_file = $_[0];
7309 my $Pbib_files = $_[1];
7310 local $Paux_files = $_[2];
7311 my $Pbst_files = $_[3];
7312 # Default return values
7313 @$Pbib_files = ();
7314 @$Pbst_files = ();
7315 @$Paux_files = ();
7316
7317
7318 # Map file specs (in \bibdata and \bibstyle lines) to actual filenames:
7319 our ( %bib_files, %bst_files, @bad_bib_data );
7320 local %bib_files = ();
7321 local %bst_files = ();
7322
7323 # Flag bad \bibdata lines in aux files:
7324 local @bad_bib_data = ( );
7325 # This array contains the offending lines, with trailing space (and
7326 # line terminator) removed. (Currently detected problems: Arguments
7327 # containing spaces, which bibtex refuses to accept.)
7328
7329 parse_aux1( $aux_file );
7330 if ($#{$Paux_files} < 0) {
7331 # No aux files found/read.
7332 return 0;
7333 }
7334 my @not_found_bib = ();
7335 my @not_found_bst = ();
7336 find_files( \%bib_files, 'bib', 'bib', $Pbib_files, \@not_found_bib );
7337 find_files( \%bst_files, 'bst', 'bst', $Pbst_files, \@not_found_bst );
7338 # ???!!! Should only get one bst file, of course.
7339 if ( $#{$Pbib_files} + $#bad_bib_data == -2 ) {
7340 #
7341 print "$My_name: No .bib files listed in .aux file '$aux_file'\n";
7342 return 2;
7343 }
7344
7345 show_array( "$My_name: Found bibliography file(s):", @$Pbib_files )
7346 unless $silent;
7347 if (@not_found_bib) {
7348 show_array(
7349 "Bib file(s) not found in search path:",
7350 @not_found_bib );
7351 }
7352
7353 if (@not_found_bst) {
7354 show_array( "$My_name: Bst file not found in search path:", @not_found_bst);
7355 }
7356
7357
7358 if ($#bad_bib_data >= 0) {
7359 warn
7360 "$My_name: White space in the argument for \\bibdata line(s) in an .aux file.\n",
7361 " This is caused by the combination of spaces in a \\bibliography line in\n",
7362 " a tex source file and the use of a pre-2018 version of *latex.\n",
7363 " The spaces will give a fatal error when bibtex is used. Bad lines:\n";
7364 foreach (@bad_bib_data ) { s/\s$//; warn " '$_'\n"; }
7365 return 3;
7366 }
7367 if (@not_found_bib) {
7368 if ($force_mode) {
7369 warn "$My_name: Failed to find one or more bibliography files in search path.\n";
7370 warn "====BUT force_mode is on, so I will continue. There may be problems ===\n";
7371 }
7372 return 3;
7373 }
7374 return 1;
7375 } #END parse_aux
7376
7377 #************************************************************
7378
7379 sub parse_aux1
7380 # Parse single aux file for bib files.
7381 # Usage: &parse_aux1( aux_file_name )
7382 # Append newly found names of .bib files to %bib_files, already
7383 # initialized/in use.
7384 # Append newly found names of .bst files to %bst_files, already
7385 # initialized/in use.
7386 # Append aux_file_name to @$Paux_files if aux file opened
7387 # Recursively check \@input aux files
7388 # Return 1 if success in opening $aux_file_name and parsing it
7389 # Return 0 if fail to open it
7390 {
7391 our ( %bib_files, %bst_files, @bad_bib_data, $Paux_files );
7392 my $aux_file = $_[0];
7393 my $aux_fh;
7394 if (! open($aux_fh, $aux_file) ) {
7395 warn "$My_name: Couldn't find aux file '$aux_file'\n";
7396 return 0;
7397 }
7398 push @$Paux_files, $aux_file;
7399
7400 AUX_LINE:
7401 while (local $_ = <$aux_fh>) {
7402 if ( /\^\^[[:xdigit:]]{2}/ ) {
7403 warn "$My_name: Line in '$aux_file' uses ^^ notation, which may\n".
7404 " cause trouble to bibtex:\n $_";
7405 # At least I need to be able to handle the line:
7406 hathat_to_binary( $_ ) if $conv_hathat;
7407 }
7408 $_ = utf8_to_mine($_);
7409 s/\s$//;
7410 if ( /^\\bibdata\{(.*)\}/ ) {
7411 # \\bibdata{comma_separated_list_of_bib_file_names}
7412 # This results from a \bibliography command in the document.
7413 my $arg = $1;
7414 if ($arg =~ /\s/) {
7415 # Bibtex will choke when the argument to \bibdata contains
7416 # spaces, so flag the error here.
7417 # N.B. *latex in TeX Live 2018 and later removes spaces from
7418 # the argument to \bibliography before placing it as the
7419 # argument to \bibdata in an aux file, so this error only
7420 # appears if a *latex from TeX Live 2017 or earlier is used.
7421 # Current MiKTeX's *latex (2022) also removes the space.
7422 push @bad_bib_data, $_;
7423 }
7424 else {
7425 foreach ( split /,/, $arg ) {
7426 # bib files are always required to have an extension .bib,
7427 # so provide the extension:
7428 if ( ! /\.bib$/ ) { $_ .= '.bib'; }
7429 $bib_files{$_} = '';
7430 }
7431 }
7432 }
7433 elsif ( /^\\bibstyle\{(.*)\}/ ) {
7434 # \\bibstyle{bst_file_name}
7435 # Normally without the '.bst' extension.
7436 $bst_files{$1} = '';
7437 }
7438 elsif ( /^\\\@input\{(.*)\}/ ) {
7439 # \\@input{next_aux_file_name}
7440 &parse_aux1( $aux_dir1.$1 );
7441 }
7442 else {
7443 run_hooks( 'aux_hooks' );
7444 }
7445 }
7446 close($aux_fh);
7447 return 1;
7448 } #END parse_aux1
7449
7450 #************************************************************
7451
7452 sub parse_bcf {
7453 # Parse bcf file for bib and other source files, and
7454 # do an elementary test for completeness.
7455 # Usage: parse_bcf( $bcf_file, \$status, \%bib_files, \@found,
7456 # \@not_found, \@remote )
7457 # If can't open bcf file, then
7458 # Return with $status = 0 and the hash and arrays empy.
7459 #
7460 # Else set the hash and the arrays from information in the bcf_file,
7461 # set $status to
7462 # 1 if no problems
7463 # 2 if there were no relevant datasource lines
7464 # Note this is not an error! *latex & biber will not report an
7465 # error, and will simply result in an empty b
7466 # 3 if I couldn't locate all the bib_files
7467 # 100 plus one of the codes 1..3 if the bcf file appears
7468 # incomplete.
7469 #
7470 # A full parse of .bcf file as XML would need an XML parsing module, which
7471 # is not in a default installation of Perl, notably in TeXLive's perl for
7472 # Win32 platform. To avoid requiring the installation, just search the
7473 # .bcf file for the relevant lines.
7474 #
7475
7476 use strict;
7477 # Global variables used
7478 our ( $My_name, $silent );
7479
7480 my ($bcf_file, $Pstatus, $PHbib_files, $PAfound, $PAnot_found, $PAremote ) = @_;
7481 $$Pstatus = 0;
7482
7483 my %glob_names = ();
7484 my @found = ();
7485 my @not_found = ();
7486 my %remote = ();
7487
7488 my $incomplete = 0; # Values 0 or 1
7489
7490 open(my $bcf_fh, $bcf_file)
7491 || do {
7492 warn "$My_name: Couldn't open bcf file '$bcf_file'\n";
7493 return 0;
7494 };
7495 $$Pstatus = 1;
7496 while (local $_ = <$bcf_fh>) {
7497 $_ = utf8_to_mine($_);
7498 if (eof($bcf_fh)) {
7499 if ( ! /^\s*<\/bcf:controlfile>/ ) {
7500 warn "$My_name: Incomplete (and hence corrupt) bcf file '$bcf_file'\n";
7501 $incomplete = 1;
7502 }
7503 }
7504 if ( /^\s*<bcf:datasource type=\"file\"\s+datatype=\"bibtex\"\s*(.*)>(.+)<\/bcf:datasource>/ ) {
7505 my $tail = $1; # Can contain a glob item, which will affect meaning of filename.
7506 my $file = $2;
7507 if ($file =~ /^http:|^https:|^ftp:|^ftps:/ ) { $remote{$file} = ''; }
7508 elsif ($tail =~ /glob=\"true\"/ ) { $glob_names{$file} = ''; }
7509 else { $$PHbib_files{$file} = ''; }
7510 }
7511 }
7512 close $bcf_fh;
7513
7514 foreach my $spec ( keys %glob_names ) {
7515 my @result = glob $spec;
7516 if ( ($#result == 0) && ($spec eq $result[0]) ) {
7517 # There was no wild card, and glob just returned the given
7518 # name, which applies whether or not the file exists.
7519 # We'll treat is the same as a non-globbed name.
7520 $$PHbib_files{$spec} = '';
7521 delete $glob_names{$spec};
7522 }
7523 else {
7524 foreach (@result) { $$PHbib_files{$_} = $_; }
7525 }
7526 }
7527 foreach (keys %$PHbib_files) { if (-e) { $$PHbib_files{$_} = $_; } }
7528 foreach my $spec (keys %$PHbib_files ) {
7529 next if $$PHbib_files{$spec};
7530 my @lines = kpsewhich( $spec );
7531 if (@lines) { $$PHbib_files{$spec} = $lines[0]; }
7532 }
7533 while (my ($spec, $file) = each %$PHbib_files ) {
7534 if ($file) { push @found, $file; }
7535 else { push @not_found, $spec; }
7536 }
7537
7538 @found = uniqs(@found);
7539 @not_found = uniqs(@not_found);
7540 push @$PAfound, @found;
7541 push @$PAnot_found, @not_found;
7542 push @$PAremote, sort keys %remote;
7543
7544 show_array( "$My_name: Bibliography file(s) from .bcf file:", sort( @found, @not_found ) )
7545 unless $silent;
7546 if (@not_found) {
7547 show_array( "Bib file(s) not found in search path:", @not_found );
7548 if ($force_mode && ! $incomplete) {
7549 warn "$My_name: Failed to find one or more bibliography files in search path.\n";
7550 warn "====BUT force_mode is on, so I will continue. There may be problems ===\n";
7551 }
7552 $$Pstatus = 3;
7553 }
7554 $$Pstatus += 100 * $incomplete;
7555
7556 } #END parse_bcf
7557
7558 #************************************************************
7559
7560 sub incomplete_bcf {
7561 # Do simple check of bcf file for completeness.
7562 # Usage: incomplete_bcf( $bcf_file )
7563 # Reason for this subroutine: If a run of *latex exits prematurely
7564 # because of an error, any bcf file generated would normally be
7565 # incomplete. It is useful to test for this before running biber,
7566 # especially as part of the end-of-run analysis for *latex, to do
7567 # appropriate clean up in an error situation.
7568 # Perhaps it would be ideal to check for other kinds of malformed bcf
7569 # file, but the incomplete run from error termination of *latex is
7570 # likely to be the most common case.
7571 # Return 1 if bcf file exists but does NOT have the expected final line.
7572 # Otherwise return 0.
7573
7574 my $bcf_file = $_[0];
7575 my $last_line = '';
7576
7577 open(my $bcf_fh, $bcf_file)
7578 || do {
7579 warn "$My_name: Couldn't find bcf file '$bcf_file'\n";
7580 return 0;
7581 };
7582 while (local $_ = <$bcf_fh>) {
7583 if (eof($bcf_fh)) { $last_line = $_; }
7584 }
7585 close $bcf_fh;
7586 if ( $last_line =~ /^\s*<\/bcf:controlfile>/ ) { return 0; }
7587 warn "$My_name: Incomplete (and hence corrupt) bcf file '$bcf_file'\n";
7588 return 1;
7589 } #END incomplete_bcf
7590
7591
7592 #************************************************************
7593 #************************************************************
7594 #************************************************************
7595
7596 # Manipulations of main file database:
7597
7598 #************************************************************
7599
7600 sub fdb_get {
7601 # Call: fdb_get(filename [, check_time])
7602 # Returns an array (time, size, md5) for the current state of the
7603 # named file.
7604 # The optional argument check_time is either the run_time of some command
7605 # that may have changed the file or the last time the file was checked
7606 # for changes --- see below.
7607 # For non-existent file, deletes its entry in fdb_current,
7608 # and returns (0,-1,0) (whatever is in @nofile).
7609 # As an optimization, the md5 value is taken from the cache in
7610 # fdb_current, if the time and size stamp indicate that the
7611 # file has not changed.
7612 # The md5 value is recalculated if
7613 # the current filetime differs from the cached value:
7614 # file has been written
7615 # the current filesize differs from the cached value:
7616 # file has definitely changed
7617 # But the file can also be rewritten without change in filetime when
7618 # file processing happens within the 1-second granularity of the
7619 # timestamp (notably for aux files from latex on a short source file).
7620 # The only case that concerns us is when the file is an input to a program
7621 # at some runtime t, the file is rewritten later by the same or another
7622 # program, with timestamp t, and when the initial file also has
7623 # timestamp t.
7624 # A test is applied for this situation if the check_time argument is
7625 # supplied and is nonzero.
7626
7627 my ($file, $check_time) = @_;
7628 if ( ! defined $check_time ) { $check_time = 0;}
7629 my ($new_time, $new_size) = get_time_size($file);
7630 if ( $new_size < 0 ) {
7631 delete $fdb_current{$file};
7632 return @nofile;
7633 }
7634 my $recalculate_md5 = 0;
7635 if ( ! exists $fdb_current{$file} ) {
7636 # Ensure we have a record.
7637 $fdb_current{$file} = [@nofile];
7638 $recalculate_md5 = 1;
7639 }
7640 my $file_data = $fdb_current{$file};
7641 my ( $time, $size, $md5 ) = @$file_data;
7642
7643 if ( ($new_time != $time) || ($new_size != $size)
7644 || ( $check_time && ($check_time == $time ) )
7645 ) {
7646 # Only force recalculation of md5 if time or size changed.
7647 # However, the physical file time may have changed without
7648 # affecting the value of the time coded in $time, because
7649 # times are computed with a 1-second granularity.
7650 # The only case to treat specially is where the file was created,
7651 # then used by the current rule, and then rewritten, all within
7652 # the granularity size, otherwise the value of the reported file
7653 # time changed, and we've handled it. But we may have already
7654 # checked this at an earlier time than the current check. So the
7655 # only dangerous case is where the file time equals a check_time,
7656 # which is either the run_time of the command or the time of a
7657 # previous check.
7658 # Else we assume file is really unchanged.
7659 $recalculate_md5 = 1;
7660 }
7661 if ($recalculate_md5) {
7662 @$file_data = ( $new_time, $new_size, get_checksum_md5( $file ) );
7663 }
7664 return @$file_data;;
7665 } #END fdb_get
7666
7667 #************************************************************
7668
7669 sub fdb_set {
7670 # Call: fdb_set(filename, $time, $size, $md5 )
7671 # Set data in file data cache, i.e., %fdb_current
7672 my ($file, $time, $size, $md5 ) = @_;
7673 if ( ! exists $fdb_current{$file} ) {
7674 $fdb_current{$file} = [@nofile];
7675 }
7676 @{$fdb_current{$file}} = ( $time, $size, $md5 );
7677 } #END fdb_set
7678
7679 #************************************************************
7680
7681 sub fdb_show {
7682 # Displays contents of fdb
7683 foreach my $file ( sort keys %fdb_current ) {
7684 print "'$file': @{$fdb_current{$file}}\n";
7685 }
7686 } #END fdb_show
7687
7688 #************************************************************
7689 #************************************************************
7690 #************************************************************
7691
7692 # Routines for manipulating rule database
7693
7694 #************************************************************
7695
7696 sub rdb_read {
7697 # Call: rdb_read( $in_name, inhibit_output_switch )
7698 # Sets rule database from saved file, in format written by rdb_write.
7699 # The second argument controls behavior when there's a mismatch between
7700 # output extensions for primary rule in the cache and current settings.
7701 # If the second argument is true, omit a switch of output extension,
7702 # otherwise let the cached setting be obeyed (if possible).
7703 #
7704 # Returns: -2 if file doesn't exist,
7705 # -1 if file existed but couldn't be read
7706 # else number of errors.
7707 # Thus return value on success is 0
7708 # Requires: Rule database initialized with standard rules, with
7709 # conditions corresponding to requests determined by
7710 # initialization and command line options.
7711 # Asssumption: Normally the fdb_latexmk file contains state of
7712 # rules and files corresponding to end of last
7713 # compilation, and the rules in the file were
7714 # active on that run.
7715 # Complications arise when that state does not correspond to current
7716 # rule set:
7717 # (a) Configuration etc may have changed: e.g., different out_dir,
7718 # different target rules and files, including different tex engine.
7719 # (b) Output extension of primary rule may be different from current
7720 # initialized one, because of document properties (use of
7721 # \pdfoutput etc).
7722 # (c) The same may arise because of misconfigured rules, a situation
7723 # that may or may not have changed in current run.
7724 # (d) The primary engine requested may not be the one used in
7725 # the previous run, possibly because (i) request has
7726 # changed, or (ii) document metacommand was obeyed to change
7727 # engine. (The last is not currently implemented, but
7728 # may/should be in the future.)
7729 # (e) Something else, e.g., copying/editing of fdb_latexmk file.
7730 #
7731
7732 our ( $dest, $run_time, $check_time, $inhibit_output_switch, $last_result );
7733 ( my $in_name, local $inhibit_output_switch ) = @_;
7734
7735 my $in_handle;
7736 if ( ! -e $in_name ) {
7737 # Note: This is NOT an error condition, since the fdb_latexmk file
7738 # can legitimately not exist.
7739 return -2;
7740 }
7741 if ( ! open( $in_handle, '<', $in_name ) ) {
7742 warn "$My_name: Couldn't read '$in_name' even though it exists\n";
7743 return -1;
7744 }
7745 print "$My_name: Examining fdb file '$fdb_name' for cached rules ...\n"
7746 if $diagnostics;
7747 my $errors = 0;
7748 my $state = -1; # Values:
7749 # -1: before start;
7750 # 0: outside rule;
7751 # 1: in source section;
7752 # 2: in generated file section;
7753 # 3: in rewritten-before-read file section;
7754 # 10: ignored rule.
7755 my $rule = '';
7756 local $run_time = 0;
7757 local $last_result = -1;
7758 my $source = '';
7759 local $dest = '';
7760 my $base = '';
7761 my %old_actives = (); # Hash: keys are rules in fdb_latexmk file
7762 my %new_sources = (); # Hash: rule => { file=>[ time, size, md5, fromrule ] }
7763 my $new_source = undef; # Reference to hash of sources for current rule
7764 LINE:
7765 while (local $_ = <$in_handle>) {
7766 # Remove leading and trailing white space.
7767 s/^\s*//;
7768 s/\s*$//;
7769 $_ = utf8_to_mine($_);
7770
7771 if ($state == -1) {
7772 if ( ! /^# Fdb version ([\d]+)$/ ) {
7773 warn "$My_name: File-database '$in_name' is not of correct format\n";
7774 return 1;
7775 }
7776 if ( $1 ne $fdb_ver) {
7777 warn "$My_name: File-database '$in_name' is of incompatible version, $1 v. current version $fdb_ver\n";
7778 return 1;
7779 }
7780 $state = 0;
7781 }
7782 # Ignore blank lines and comments
7783 if ( /^$/ || /^#/ || /^%/ ) { next LINE;}
7784 if ( /^\[\"([^\"]+)\"\]/ ) {
7785 # Start of section
7786 $rule = $1;
7787 my $tail = $'; #' Single quote in comment tricks the parser in
7788 # emacs from misparsing an isolated single quote
7789 $run_time = $check_time = 0;
7790 $source = $dest = $base = '';
7791 $old_actives{$rule} = 1;
7792 $last_result = -1;
7793 if ( $tail =~ /^\s*(\S+)\s+\"([^\"]*)\"\s+\"([^\"]*)\"\s+\"([^\"]*)\"\s+(\S+)\s+(\S+)/ ) {
7794 $run_time = $1;
7795 $source = $2;
7796 $dest = $3;
7797 $base = $4;
7798 $check_time = $5;
7799 $last_result = $6;
7800 }
7801 else {
7802 # Line is not in correct format
7803 warn "$My_name: In '$in_name' there's a rule line not in correct format:\n",
7804 " $_\n",
7805 "Perhaps the file has been edited, or there's a bug.\n";
7806 $errors ++;
7807 $state = 10;
7808 next LINE;
7809 }
7810 if ( rdb_rule_exists( $rule ) ) {
7811 # We need to set rule data from contents of fdb_latex file,
7812 # but we'll do that later, so that it can be done for both
7813 # existing and newly created rules.
7814 }
7815 elsif ($rule =~ /^cusdep\s+(\S+)\s+(\S+)\s+(.+)$/ ) {
7816 # create custom dependency
7817 my $fromext = $1;
7818 my $toext = $2;
7819 my $base = $3;
7820 # don't set $source and $dest here, but use the already-set values
7821 # from the rule definition line: under some situations the rule
7822 # may have these changed from normal.
7823 my $func_name = '';
7824 foreach my $dep ( @cus_dep_list ) {
7825 my ($tryfromext,$trytoext,$must,$try_func_name) = split('\s+',$dep);
7826 if ( ($tryfromext eq $fromext) && ($trytoext eq $toext) ) {
7827 $func_name = $try_func_name;
7828 }
7829 }
7830 if ($func_name) {
7831 my $PAnew_cmd = ['do_cusdep', $func_name];
7832 # Set source file as non-existent.
7833 # If it existed on last run, it will be in later
7834 # lines of the fdb file
7835 rdb_create_rule( $rule, 'cusdep', '', $PAnew_cmd, 1,
7836 $source, $dest, $base, 0, $run_time, $check_time, 1 );
7837 }
7838 else {
7839 warn "$My_name: In file-database '$in_name', the custom-dependency rule\n",
7840 " '$rule' is not available in this session.\n",
7841 " Presumably it's no longer in your configuration for latexmk.\n";
7842 $state = 10;
7843 next LINE;
7844 }
7845 }
7846 elsif ( $rule =~ /^(makeindex|bibtex|biber)\s*(.*)$/ ) {
7847 my $PA_extra_gen = [];
7848 my $rule_generic = $1;
7849 my $int_cmd = '';
7850 if ( ! $source ) {
7851 # If fdb_file was old-style (v. 1)
7852 $source = $2;
7853 my $path = '';
7854 my $ext = '';
7855 ($base, $path, $ext) = fileparseA( $source );
7856 $base = $path.$base;
7857 if ($rule_generic eq 'makeindex') {
7858 $dest = "$base.ind";
7859 }
7860 elsif ($rule_generic eq 'bibtex') {
7861 $dest = "$base.bbl";
7862 $source = "$base.aux";
7863 }
7864 elsif ($rule_generic eq 'biber') {
7865 $dest = "$base.bbl";
7866 $source = "$base.bcf";
7867 }
7868 }
7869 if ($rule =~ /^makeindex/) { $PA_extra_gen = [ "$base.ilg" ]; }
7870 if ($rule =~ /^(bibtex|biber)/) { $PA_extra_gen = [ "$base.blg" ]; }
7871 if ($rule =~ /^bibtex/) { $int_cmd = "run_bibtex"; }
7872 if ($rule =~ /^makeindex/) { $int_cmd = "run_makeindex"; }
7873 print "$My_name: File-database '$in_name': setting rule '$rule'\n"
7874 if $diagnostics;
7875 my $cmd_type = 'external';
7876 no strict "refs";
7877 my $ext_cmd = ${$rule_generic};
7878 print " Rule kind = '$rule_generic'; ext_cmd = '$ext_cmd';\n",
7879 " int_cmd = '$int_cmd';\n",
7880 " source = '$source'; dest = '$dest'; base = '$base';\n"
7881 if $diagnostics;
7882 # Set source file as non-existent.
7883 # If it existed on last run, it will be in later
7884 # lines of the fdb file
7885 rdb_create_rule( $rule, $cmd_type, $ext_cmd, $int_cmd, 1,
7886 $source, $dest, $base, 0, $run_time, $check_time, 1, $PA_extra_gen );
7887 }
7888 else {
7889 if ($diagnostics) {
7890 print "$My_name: In file-database '$in_name' rule '$rule'\n",
7891 " is not in use in this session\n";
7892 }
7893 $new_source = undef;
7894 $state = 10;
7895 next LINE;
7896 }
7897 if ( rdb_rule_exists( $rule ) ) {
7898 rdb_one_rule( $rule, \&rdb_read_set_rule );
7899 }
7900 $new_source = $new_sources{$rule} = {};
7901 $state = 1; #Reading a section, source part
7902 }
7903 elsif ( ($state <=0) || ($state >= 4) ) {
7904 next LINE;
7905 }
7906 elsif ( /^\(source\)/ ) { $state = 1; next LINE; }
7907 elsif ( /^\(generated\)/ ) { $state = 2; next LINE; }
7908 elsif ( /^\(rewritten before read\)/ ) { $state = 3; next LINE; }
7909 elsif ( ($state == 1) && /^\"([^\"]*)\"\s+(\S+)\s+(\S+)\s+(\S+)\s+\"([^\"]*)\"/ ) {
7910 # Source file line
7911 my $file = $1;
7912 my $time = $2;
7913 my $size = $3;
7914 my $md5 = $4;
7915 my $from_rule = $5;
7916 if ($state != 1) {
7917 warn "$My_name: In file-database '$in_name' ",
7918 "line $. is outside a section:\n '$_'\n";
7919 $errors++;
7920 next LINE;
7921 }
7922 # Set file in database. But ensure we don't do an unnecessary
7923 # fdb_get, which can trigger a new MD5 calculation, which is
7924 # lengthy for a big file. Ininitially flagging the file
7925 # as non-existent solves the problem:
7926 rdb_ensure_file( $rule, $file, undef, 1 );
7927 rdb_set_file1( $rule, $file, $time, $size, $md5 );
7928 fdb_set( $file, $time, $size, $md5 );
7929 # Save the rest of the data, especially the from_rule until we know all
7930 # the rules, otherwise the from_rule may not exist.
7931 # Also we'll have a better chance of looping through files.
7932 ${$new_source}{$file} = [ $time, $size, $md5, $from_rule ];
7933 }
7934 elsif ( ($state == 2) && /^\"([^\"]*)\"/ ) {
7935 my $file = $1;
7936 rdb_one_rule( $rule, sub{ rdb_add_generated($file); } );
7937 }
7938 elsif ( ($state == 3) && /^\"([^\"]*)\"/ ) {
7939 my $file = $1;
7940 rdb_one_rule( $rule, sub{ rdb_add_rewritten_before_read($file); } );
7941 }
7942 else {
7943 warn "$My_name: In file-database '$in_name' ",
7944 "line $. is of wrong format:\n '$_'\n";
7945 $errors++;
7946 next LINE;
7947 }
7948 }
7949 close $in_handle;
7950 # Get state of dependencies, including creating cus deps if needed
7951 # !!!??? This doesn't match definition of rdb_set_dependents
7952 &rdb_set_dependents( keys %rule_db );
7953 &rdb_set_rule_net;
7954
7955 return $errors;
7956 } # END rdb_read
7957
7958 #************************************************************
7959
7960 sub rdb_read_set_rule {
7961 # Makes some settings for rule from data as read from .fdb_latexmk.
7962 # Rule context assumed. Implicit passing of $dest, $run_time, $check_time,
7963 # $inhibit_output_switch, $last_result used as local variables in calling
7964 # routine rdb_read.
7965 #
7966 our ( $dest, $run_time, $check_time, $inhibit_output_switch, $last_result );
7967 $$Pno_history = 0;
7968 $$Prun_time = $run_time;
7969 $$Pcheck_time = $check_time;
7970 $$Plast_result = $last_result;
7971 $$Plast_result_info = 'CACHE';
7972
7973 # Deal with possibility that destination file in fdb_latexmk from
7974 # run differs from what is currently set. Often that just reflects a
7975 # difference between the end result of the last run and what the user
7976 # has requested for this run.
7977 # 1. Diagnostics are given, in case that matters.
7978 # 2. Generally it's only needed to keep the current destination, and to
7979 # flag the rule as out-of-date.
7980 # 3. But special treatmen is needed when the rule is a primary rule and
7981 # only the extension of the destination file has changed.
7982 if ($dest eq $$Pdest) { return; }
7983 if ( ! rdb_is_active($rule) ) {
7984 # A common cause: Change of requested files.
7985 # No other causes known.
7986 # So just do nothing.
7987 return;
7988 }
7989 # Arrive here if rule is active and previous dest differs from current.
7990 my ($oldbase, $oldpath, $oldext) = fileparseA( $dest );
7991 my ($newbase, $newpath, $newext) = fileparseA( $$Pdest );
7992 if ( ($oldext ne $newext)
7993 && $possible_primaries{$rule}
7994 && exists( $allowed_output_ext{$oldext} )
7995 && ( $oldpath.$oldbase eq $newpath.$newbase )
7996 && ( ! $inhibit_output_switch )
7997 )
7998 {
7999 # Change only in extension: A common cause: use of \pdfoutput in tex
8000 # file, with conflict with requested compilation type. The old
8001 # extension wins.
8002 warn "$My_name: In reading the fdb_latexmk file for the previous run of latexmk, I\n",
8003 " found that the output extension for '$rule' was '$oldext', but requests for\n",
8004 " this run of latexmk give '$newext'. Probably that was due to a specific\n",
8005 " request by the .tex document for output to '$oldext'.\n",
8006 " So (if possible) I'll reset the output extension back to '$oldext', which\n",
8007 " will be correct on the assumption that the old extension still reflects the\n",
8008 " situation with the .tex document. If the assumption is wrong, I'll correct\n",
8009 " that after the next run of '$rule'.\n";
8010 my $switch_error = switch_output( $rule, $oldext, $newext );
8011 if ($switch_error) {
8012 warn " I could not accommodate the changed output extension.\n",
8013 " That is either because the configuration does not allow it\n",
8014 " or because there is a conflict with implicit or explicit requested filetypes.\n",
8015 " (Typically that is about .dvi and/or .ps filetypes.)\n",
8016 "===> There may be subsequent warnings, which may or may not be ignorable.\n",
8017 "===> If necessary, clean out generated files and try again\n";
8018 }
8019 return;
8020 }
8021 # All special cases now dealt with.
8022 } #END rdb_read_set_rule
8023
8024 #************************************************************
8025
8026 sub rdb_write {
8027 # Call: rdb_write( $out_name )
8028 # Writes to the given file name the database of file and rule data
8029 # for all rules needed to make final output
8030 # Returns 1 on success, 0 if file couldn't be opened.
8031 my $out_name = $_[0];
8032
8033 my $out_handle;
8034 if ( ($out_name eq "") || ($out_name eq "-") ) {
8035 # Open STDOUT
8036 open( $out_handle, '>-' );
8037 }
8038 else {
8039 open( $out_handle, '>', $out_name );
8040 }
8041 if (!$out_handle) { return 0; }
8042
8043 # ??? For safety?
8044 &rdb_set_rule_net;
8045
8046 fprint8( $out_handle, "# Fdb version $fdb_ver\n" );
8047 my @rules = sort &rdb_accessible;
8048 rdb_for_some(
8049 \@rules,
8050 sub {
8051 # Omit data on a unused and never-run primary rule:
8052 if ( ($$Prun_time == 0)
8053 && exists( $possible_primaries{$rule} )
8054 && ($rule ne $current_primary )
8055 )
8056 {
8057 return;
8058 }
8059 fprint8( $out_handle, "[\"$rule\"] $$Prun_time \"$$Psource\" \"$$Pdest\" \"$$Pbase\" $$Pcheck_time $$Plast_result\n" );
8060 rdb_do_files(
8061 sub { my $from_rule = $from_rules{$file} || '';
8062 fprint8( $out_handle, " \"$file\" $$Ptime $$Psize $$Pmd5 \"$from_rule\"\n" );
8063 }
8064 );
8065 fprint8( $out_handle, " (generated)\n" );
8066 foreach (sort keys %$PHdest) {
8067 fprint8( $out_handle, " \"$_\"\n" );
8068 }
8069 fprint8( $out_handle, " (rewritten before read)\n" );
8070 foreach (sort keys %$PHrewritten_before_read) {
8071 fprint8( $out_handle, " \"$_\"\n" );
8072 }
8073 }
8074 );
8075 close $out_handle;
8076 return 1;
8077 } #END rdb_write
8078
8079 #************************************************************
8080
8081 sub rdb_set_latex_deps {
8082 # Call: rdb_set_latex_deps( [inhibit_output_switch] )
8083 # Assume primary rule context.
8084 # This is intended to be applied only for a primary (LaTeX-like) rule.
8085 # Set its dependents etc, using information from log, aux, and fls files.
8086 # Use fls file only if $recorder is set, and the fls file was generated
8087 # on this run.
8088 # Return: An array: ( Whether there are missing directories,
8089 # reference to array of missing directories,
8090 # whether there are bad warnings
8091 # )
8092 # (Missing directories are those for aux files in aux_dir.)
8093
8094 # N.B. A complication which we try and handle in determining
8095 # dependent files is that there may be aliasing of file names,
8096 # especially when characters are used in file and directory
8097 # names that are not pure 7-bit-ASCII. Here is a list of some
8098 # of the difficulties that do arise, between, on the one hand,
8099 # the filenames specified on latexmk's and the cwd found by
8100 # latexmk from the system, and, on the other hand, the filenames
8101 # and their components reported by *latex in the fls and log
8102 # files:
8103 # 1. Whether the separator of path components is / or \ in
8104 # MSWin.
8105 # 2. Whether the LFN or the SFN is provided.
8106 # 3. Whether the filenames include the cwd or whether they
8107 # are relative to the current directory.
8108 # 4. Under cygwin, whether the absolute filenames are
8109 # specified by UNIX or native MSWin conventions.
8110 # (With cygin, the programs used, including the Perl that
8111 # executes latexmk, can be any combination of native MSWin
8112 # programs and cygwin programs with their UNIX-like
8113 # behavior.)
8114 # 5. Whether UTF-8 or some other coding is used, and under
8115 # which circumstances: e.g., in calls to the OS to access
8116 # files, in files output by programs, on latexmk's command
8117 # line, on other programs' command lines, by the command
8118 # interpreterS.
8119 # 6. If UTF-8 is used, what kind of canonicalization is used,
8120 # if any. (This is a particular bugbear when files are
8121 # transferred between different OSes.)
8122 # 7. Whether the name of a file in the current directory is
8123 # reported as the simple filename or whether it is
8124 # preceeded by ".\" or "./".
8125 # 8. How is it determined whether a pathname is absolute or
8126 # relative? An absolute pathname in MSWin may start with
8127 # a drive letter and a colon, but under UNIX-type systems,
8128 # the colon is an ordinary character.
8129 # 9. Whether a filename reported in an fls or log file can be
8130 # used as is by perl to access a file, or on the command
8131 # line to invoke another program, and whether the use on a
8132 # command line depends on whether the command line is
8133 # executed by a CLI, and by which CLI. (E.g., cmd.exe,
8134 # v. sh v. tcsh, etc.)
8135 # 10. Whether such a filename for the filename on *latex's
8136 # file agrees with the one on the command line.
8137 # The above questions have arisen from actual experiences and
8138 # tests.
8139 #
8140 # In any case, when determining dependent files, we will try to
8141 # remove an initial directory string from filenames found in the
8142 # fls and log files, whenever it denotes the current
8143 # directory. The directory string may be an absolute pathname,
8144 # such as MiKTeX writes in both fls and log files, or it may be
8145 # simply "./" as given by TeXLive in its log file. There are
8146 # several reasons for removing a directory string when possible:
8147 #
8148 # 1. To avoid having multiple names referring to the same
8149 # file in the list of dependents.
8150 # 2. Because the name may be in a different coding. Thus
8151 # under MSWin 7, cmd.exe and perl (by default) work in an
8152 # "ANSI" coding with some code page, but the filenames
8153 # written by MiKTeX are UTF-8 coded (and if they are non-ASCII
8154 # can't be used for file-processing by Perl without some
8155 # trouble). This is a particular problem if the pathname
8156 # contains non-ASCII characters; the directory names may not
8157 # even be under the user's control, unlike typical filenames.
8158 # 3. When it comes to filenames that are then used in calls to
8159 # bibtex and makeindex, it is bad to use absolute pathnames
8160 # instead of clearly relative pathnames, because the default
8161 # security settings are to prohibit writing files to the
8162 # corresponding directories, which makes the calls to these
8163 # programs unnecessarily fail.
8164 #
8165 # In removing unnecessary directory-specifying strings, to
8166 # convert a filename to a simple specification relative to the
8167 # current directory, it will be important to preferentially use
8168 # a determination of the current directory from the file being
8169 # processed. In the fls file, there is normally a PWD line. In
8170 # the log file, if *latex is started with a filename instead
8171 # of a command-executing first line, then this can be determined
8172 # from the first few lines of the log file -- see parse_log.
8173 # This gives a more reliable determination of the relevant path
8174 # string; this is especially important in cases where there is a
8175 # mismatch of coding of the current directory, particularly
8176 # notable in the above-mentioned case of non-ASCII characters
8177 # under MSWin. Other inconsistencies happen when there is a
8178 # mixure of cygwin and native MSWin software. There can also be
8179 # inconsistencies between whether the separator of pathname
8180 # components is "/" or "\". So we will allow for this. The
8181 # necessary normalizations of filenames are handled by the
8182 # subroutines normalize_filename and normalize_clean_filename.
8183 #
8184 # I have not tried to handle the (currently rare) cases that the
8185 # OS is neither UNIX-like nor MSWin-like.
8186 #
8187 # Assumption: the list of generated files in %PHdest was already initialized earlier.
8188 # In principle, I should do it here, but useful possibilities (e.g.,
8189 # see pythontex-latexmk) for subroutine called to process a .tex to add items to
8190 # %PHdest. So initializing here is too late.
8191
8192 my ($inhibit_output_switch) = @_;
8193 if ( $$Pcmd_type ne 'primary' ) {
8194 warn "\n$My_name: ==========$My_name: Probable BUG======= \n ",
8195 " rdb_set_latex_deps called to set files ",
8196 "for non-latex-like rule '$rule'\n\n";
8197 return;
8198 }
8199
8200 #?? # We'll prune this by all files determined to be needed for source files.
8201 #?? my %unneeded_source = %$PHsource;
8202
8203 # Parse fls and log files to find relevant filenames
8204 # See parse_log for the definition of %dependents.
8205 # Results in the following variables:
8206 our ( %dependents, @bbl_files, %idx_files, %generated_log, %generated_fls,
8207 %source_fls, %first_read_after_write, %log_info, $pwd_latex, $primary_out,
8208 @missing_subdirs, %conversions );
8209 local %dependents = (); # Maps files to status
8210 local @bbl_files = ();
8211 local %idx_files = (); # Maps idx_file to (ind_file, base)
8212 local %generated_log = (); # Lists generated files found in log file
8213 local %generated_fls = (); # Lists generated files found in fls file
8214 local %source_fls = (); # Lists source files found in fls file
8215 local %first_read_after_write = (); # Lists source files that are only read
8216 # after being written (so are not true
8217 # source files).
8218 local $primary_out = $$Pdest; # output file (dvi or pdf)
8219 local %conversions = (); # *latex-performed conversions.
8220 # Maps output file created and read by *latex
8221 # to source file of conversion.
8222 local @missing_subdirs = (); # Missing subdirectories in aux_dir
8223
8224 local $pwd_latex = undef; # Cwd as reported in fls file by *latex
8225
8226 my %created_rules = (); # Maps files to rules existing or created to
8227 # make them. Use to avoid misunderstood
8228 # dependencies when a package creates a
8229 # missing file during *latex compliation
8230 # instead of just allowing to be made later
8231 # by another rule.
8232
8233 # Give a quick way of looking up custom-dependency extensions
8234 my %cusdep_from = (); # Map source extension to ref to array of
8235 # [dest ext, cusdep, name]
8236 # ext is **without** period.
8237 foreach ( @cus_dep_list ) {
8238 my ($from_ext, $to_ext, $must, $func_name) = split;
8239 push @{$cusdep_from{$from_ext}}, [ $to_ext, $_, $func_name ];
8240 }
8241
8242 # The following are also returned by parsing routines, but are global,
8243 # to be used by caller:
8244 # $reference_changed, $bad_reference, $bad_character, $bad_citation, $mult_defined
8245
8246 # Do I have my own eps-to-pdf conversion?
8247 my $epspdf_cusdep = 0;
8248 foreach (@cus_dep_list) {
8249 if ( /^eps pdf / ) { $epspdf_cusdep = 1; last; }
8250 }
8251
8252
8253 # Settings to be found by reading log file:
8254 our $engine = ''; # Which tex program? (Use of $latex v. ... no good, since
8255 # can be set to use another program.)
8256 our $tex_distribution = '';
8257 local %log_info = (); # Info. returned by get_log_file
8258 my @log_lines = (); # Lines in log file after unwrapping and converting
8259 # to use my internal CS.
8260 # Get lines from log file now, with side effect of setting $engine and
8261 # $tex_distribution, so parse_fls can adjust its behavior if necessary).
8262 my $read_log_file = get_log_file( $log_name, \@log_lines, \%log_info );
8263 if (! $read_log_file ) {
8264 warn "$My_name: Couldn't read log file '$log_name':\n $!\n";
8265 }
8266 else {
8267 $engine = $log_info{engine};
8268 $tex_distribution = $log_info{distribution};
8269 }
8270
8271
8272 # Analyze fls file first. It tells us the working directory as seen by *latex
8273 # But we'll use the results later, so that they take priority over the findings
8274 # from the log file.
8275 our $fls_file_analyzed;
8276 local $fls_file_analyzed = 0;
8277 if ($recorder && test_gen_file_time($fls_name) ) {
8278 $fls_file_analyzed =
8279 (0== parse_fls( $fls_name, \%source_fls, \%generated_fls, \%first_read_after_write, \$pwd_latex ));
8280 if (! $fls_file_analyzed ) {
8281 warn "$My_name: fls file '$fls_name' appears to have been made but it couldn't be opened.\n";
8282 }
8283 }
8284
8285 if ($read_log_file) { parse_log( $log_name, \@log_lines, \%log_info ); }
8286
8287 my $missing_dirs = 'none'; # Status of missing directories
8288 if (@missing_subdirs) {
8289 $missing_dirs = 'success';
8290 if ($allow_subdir_creation) {
8291 foreach my $dir ( uniqs( @missing_subdirs ) ) {
8292 if ( -d $dir ) {
8293 $missing_dirs = 'failure';
8294 warn "$My_name: ==== Directory '$dir' is said to be missing\n",
8295 " But it exists!\n";
8296 }
8297 elsif ( (-e $dir) && (!-d $dir) ) {
8298 $missing_dirs = 'failure';
8299 warn "$My_name: ==== Directory '$dir' is said to be missing\n",
8300 " But a non-directory file of this name exists!\n";
8301 }
8302 else {
8303 if (make_path_mod($dir)) {
8304 print "$My_name: Directory '$dir' created\n";
8305 }
8306 else {
8307 $missing_dirs = 'failure';
8308 warn "$My_name: Couldn't create directory '$dir'.\n",
8309 " System error: '$!'\n";
8310 }
8311 }
8312 }
8313 }
8314 else {
8315 $missing_dirs = 'not allowed';
8316 warn_array( "$My_name: There are missing subdirectories, but their creation\n".
8317 " is not allowed. The subdirectories are:",
8318 uniqs(@missing_subdirs) );
8319 }
8320 }
8321 # Use results from fls file. (N.B. The hashes will be empty if the fls file
8322 # wasn't used/analyzed, so we don't need a test as to whether the fls file was
8323 # used.
8324 foreach (keys %source_fls) {
8325 if (! -e ) {
8326 # File is listed in .fls file as read, but doesn't exist now.
8327 # Therefore it is not a true source file, surely.
8328 # Sometimes this is caused by a bug (e.g., lualatex in TeXLive 2016,
8329 # 2017) when there is an incorrect line in .fls file. (This
8330 # would deserve a warning.)
8331 # But sometimes (e.g., with minted package), the file could be
8332 # created during a run, read, and then deleted.
8333 next;
8334 }
8335 $dependents{$_} = 4;
8336 if ( /\.bbl$/ ) { push @bbl_files, $_; }
8337 }
8338 foreach (keys %generated_fls) {
8339 if (! -e ) {
8340 # File is listed in .fls file as written, but doesn't exist now.
8341 # Therefore it is not a true externally visible generated file.
8342 # (Typically, e.g., with the minted package, it is a temporary
8343 # file created during a run and then deleted during the run.)
8344 next;
8345 }
8346 rdb_add_generated( $_ );
8347 if ( exists($dependents{$_}) ) {
8348 $dependents{$_} = 6;
8349 }
8350 }
8351
8352 for my $conv (sort keys %conversions) {
8353 my $conv_source = $conversions{$conv};
8354 if ( $conv =~ /^(.*)-eps-converted-to\.pdf$/ ) {
8355 # Check all the conditions for pdflatex's conversion eps to pdf
8356 # are valid; if they are, treat the converted file as not a
8357 # source file.
8358 my $base = $1;
8359 if ( (-e $conv_source) && (-e $conv) && ( $conv_source eq "$base.eps" ) ) {
8360 # $conv isn't a real source of *latex
8361 rdb_remove_files( $rule, $conv );
8362 delete $dependents{$conv};
8363 if ($epspdf_cusdep) {
8364 $dependents{"$base.pdf"} = ((-e "$base.pdf") ? 4 : 0 );
8365 }
8366 }
8367 }
8368 }
8369
8370
8371
8372 # ?? !! Should also deal with .run.xml file
8373
8374 # Handle result on output file:
8375 # 1. Non-existent output file, which is because of no content.
8376 # This could either be because the source file has genuinely
8377 # no content, or because of a missing input file. Since a
8378 # missing input file might be correctable by a run of some
8379 # other program whose running is provoked AFTER a run of
8380 # *latex, we'll set a diagnostic and leave it to the
8381 # rdb_make to handle after all circular dependencies are
8382 # resolved.
8383 # 2. The output file might be of a different kind than expected
8384 # (i.e., dvi instead of pdf, or vv). This could
8385 # legitimately occur when the source file (or an invoked
8386 # package or class) sets \pdfoutput.
8387 $missing_dvi_pdf = '';
8388 if ($primary_out eq '') {
8389 print "$My_name: For rule '$rule', no output was made\n";
8390 $missing_dvi_pdf = $$Pdest;
8391 }
8392 elsif ($primary_out ne normalize_filename($$Pdest) ) {
8393 my ($actual_base, $actual_path, $actual_ext) = fileparseA( $primary_out );
8394 my ($intended_base, $intended_path, $intended_ext) = fileparseA( $$Pdest );
8395 if ( ($actual_ext ne $intended_ext) && (!$inhibit_output_switch) ) {
8396 warn "$My_name: ===For rule '$rule', the extensions differ between the\n",
8397 " actual output file '$primary_out',\n",
8398 " and the expected output '$$Pdest'.\n";
8399 if ( ! exists $allowed_output_ext{$actual_ext} ) {
8400 warn " Actual output file has an extension '$actual_ext' that\n",
8401 " is not one I know about. I cannot handle this\n";
8402 }
8403 else {
8404 my $switch_error = switch_output( $rule, $actual_ext, $intended_ext );
8405 if ( $switch_error ) {
8406 warn " I could not accommodate the changed output extension\n",
8407 " (either because the configuration does not allow it\n",
8408 " or because there is a conflict with requested filetypes).\n";
8409 $failure = 1;
8410 $failure_msg = 'Could not handle change of output extension';
8411 }
8412 else {
8413 print " Rule structure will be changed suitably.\n";
8414 }
8415 }
8416 }
8417 }
8418
8419 foreach my $file ( keys %generated_fls ) {
8420 if ( $file =~ /^(.*)\.idx$/ ) {
8421 $idx_files{$file} = [];
8422 }
8423 }
8424 IDX_FILE:
8425 foreach my $idx_file ( keys %idx_files ) {
8426 print "$My_name: Index file '$idx_file' was written\n"
8427 unless $silent;
8428 my ($idx_base, $idx_path, $idx_ext) = fileparseA( $idx_file );
8429 $idx_base = $idx_path.$idx_base;
8430 $idx_file = $idx_base.$idx_ext;
8431 my $idx_ext1 = $idx_ext;
8432 $idx_ext1 =~ s/^\.//;
8433 my $ind_file = '';
8434 # Whether we are to have standard idx to ind processing by makeindex:
8435 my $standard_index = 0;
8436 my $from_rule = '';
8437 if ( $idx_ext eq '.idx' ) {
8438 $ind_file = "$idx_base.ind";
8439 $standard_index = 1;
8440 $from_rule = "makeindex $idx_file";
8441 }
8442 elsif ( exists $cusdep_from{$idx_ext1} ) {
8443 # At this point, we know an index file was written with an extension other.
8444 # than .idx, and it may be possible to use a custom dependency to make
8445 # the corresponding ind-type file. Work out as much as
8446 # possible here.
8447
8448 # Does there exist a unique relevant cus dep that's already in use?
8449 my @possible_makers = ();
8450 foreach my $try_rule ( keys %rule_db ) {
8451 if ($try_rule =~ /^cusdep $idx_ext1 ([^ ]+) (.+)$/) {
8452 my @sources = rdb_get_source( $try_rule );
8453 foreach my $s (@sources) {
8454 if ($s eq $idx_file) {
8455 push @possible_makers, $try_rule;
8456 }
8457 }
8458 }
8459 }
8460 if ($#possible_makers < 0) {
8461 # Nothing found
8462 }
8463 elsif ($#possible_makers == 0) {
8464 my $from_rule = $possible_makers[0];
8465 print " Have relevant rule '$from_rule'.\n"
8466 if ($diagnostics);
8467 $ind_file = rdb_get_dest( $from_rule );
8468 }
8469 else {
8470 # Too many possibilities. That's not normal.
8471 # It could arise if there's both a cus dep to make the
8472 # .ind-type file, and some other cus dep to make an
8473 # unusual other file. I give up here.
8474 }
8475 if ( ! $ind_file ) {
8476 # If not, try to find a cus dep pattern that could be used:
8477 my @cusdeps = @{$cusdep_from{$idx_ext1}};
8478 if ($#cusdeps > 0) {
8479 print
8480 "$My_name: I have more than one possibility making .ind type file from\n",
8481 " '$idx_file' by a custom dependency. I can't currently resolve the\n",
8482 " ambiguity, now during the analysis of results of the *latex run, but it\n",
8483 " will normally be resolved elsewhere in my workings.\n";
8484 next IDX_FILE;
8485 }
8486 my ($ind_ext, $spec, $func_name) = @{$cusdeps[0]};
8487 $ind_file = "$idx_base.$ind_ext";
8488 if ( !$silent ) {
8489 print " It corresponds to ind-type file '$ind_file',\n",
8490 " and cusdep '$spec' '$func_name' should be set up make it.\n";
8491 }
8492 # I'll delegate the setting up of the rule to the general
8493 # purpose code for setting up cus deps. The general setting
8494 # below that there's a definite dependence is enough to
8495 # provoke the appropriate behavior.
8496 }
8497 }
8498 else {
8499 warn "$My_name: Index file '$idx_file' written\n",
8500 " ==> but it has an extension I do not know how to handle <==\n";
8501 next IDX_FILE;
8502 }
8503
8504 if ( $standard_index && ! rdb_rule_exists( $from_rule ) ){
8505 print "!!!===Creating rule '$from_rule': '$ind_file' from '$idx_file'\n"
8506 if ($diagnostics);
8507 rdb_create_rule( $from_rule, 'external', $makeindex, 'run_makeindex', 1,
8508 $idx_file, $ind_file, $idx_base, 1, 0, 0, 1, [ "$idx_base.ilg" ] );
8509 print " ===Source file '$ind_file' for '$rule'\n"
8510 if ($diagnostics);
8511 rdb_ensure_file( $rule, $ind_file, $from_rule );
8512 }
8513 if ($ind_file) {
8514 # Make sure the .ind file of the appropriate location
8515 # (directory) and name is definitively treated as a
8516 # source file for the current rule (for *latex). Otherwise:
8517 # (a) If the log file has it under a different name (as
8518 # with MiKTeX, which gives full directory
8519 # information), there will be problems with the
8520 # clean-up of the rules concerning no-longer-in-use
8521 # source files.
8522 # (b) When a cus dep is to be used, it ensures that a cus
8523 # dep rule with the correct dest file is created, even
8524 # if the dest file doesn't yet exist in the correct
8525 # directory. This solves the problem that if an old
8526 # version of the dest file exists in another directory,
8527 # and if it is read during compilation, then there is
8528 # no relevant missing-file message in the .log file to
8529 # trigger creation of the correct cus dep rule.
8530 $dependents{$ind_file} = 4;
8531 if ( ! -e $ind_file ) {
8532 # Failure of *latex was non-existence of makable file
8533 # Leave failure issue to other rules.
8534 $failure = 0;
8535 }
8536 if ($from_rule) { $created_rules{$ind_file} = $from_rule; }
8537 }
8538
8539 } # end IDX_FILE
8540
8541 # ==========================================================
8542 # .bbl files, biber and bibtex.
8543 # Situations where .bbl file is used:
8544 # 1. Under document control, bibtex is for generating .bbl files, and
8545 # one or more .bbl files is to be used, each for a specific
8546 # bibliography. Critical: Each .bbl file is generated by bibtex
8547 # from a corresponding .aux file in the same directory, **and** the
8548 # .aux file is a generated file of *latex.
8549 # 2. Under document control, biber is used to generated a single,
8550 # document-wide .bbl file. It is a single .bbl file, even if
8551 # multiple bibliographies appear in the document. Critical: The
8552 # (single) .bbl file is generated by biber from the corresponding
8553 # .bcf file in the same directory, **and** the .bcf file is a
8554 # generated file of *latex.
8555 # 3. A .bbl file is read that was generated on a **previous** run of
8556 # *latex plus associated use of bibtex or biber, in which a
8557 # different aux dir was used. (I think the only realistic situation
8558 # is where that previous run's aux dir was the cwd, i.e., './'.)
8559 # There is then a corresponding .aux or .bcf file (unless it has
8560 # been deleted), but the file was not generated by the current run
8561 # of *latex.
8562 # This is an anomalous situation, which can cause errors (e.g., if a
8563 # .bbl file corresponds to a different state of the document). But
8564 # *latex will read a .bbl file of a relevant name, if present, in ./
8565 # if it doesn't exist in the aux dir. In this case, bibtex rule(s)
8566 # or a biber rule must be generated for the correct source files, so
8567 # that .bbl file(s) are generated in the aux dir (or relative to
8568 # it).
8569 # 4. A "foreign" .bbl file is read that was generated in the
8570 # compilation of a different document. This is a **rare**
8571 # situation, but is conceivable. In this case, the current document
8572 # should not be using its default bibtex and/or biber templates
8573 # (almost surely), and the making of it is to be delegated to the
8574 # other document. It is conceivable to use a rule to generate it
8575 # under the control of latexmk working on the current document, but
8576 # that would need something like a custom dependency adapted to this
8577 # special situation, not the normal bibtex/biber template.
8578 #
8579 # KEY: Always, for normal document bibliographies, a .bbl file is
8580 # generated by bibtex or biber from a corresponding unique source
8581 # file of the same name and directory that differs in having an
8582 # extension .aux or .bcf (as appropriate), and that source file was
8583 # generated in the current run of *latex.
8584 # Always if a .bcf file is generated, then there is to be a single
8585 # biber rule to make a corresponding .bbl file, and no bibtex rules
8586 # at all.
8587 #
8588 my %processed_aux_files = ();
8589 my $bib_program = 'bibtex';
8590
8591 if ( test_gen_file( $bcf_name ) ) {
8592 # then biblatex + biber is currently in use (with single .bbl file).
8593 warn "$My_name: Using biber to make bibliography file(s).\n";
8594 $bib_program = 'biber';
8595
8596 my $bbl_base = ($bcf_name =~ s/\.bcf$//r);
8597 my $bbl_name = "$bbl_base.bbl";
8598 my $from_rule = "biber $bbl_base";
8599
8600 rdb_ensure_file( $rule, $bbl_name, $from_rule );
8601 # Flag bbl file status as definite dependence. Otherwise it may get
8602 # removed from source list when it is cleaned up at end of this
8603 # subroutine. Situation that causes trouble: .bbl file of correct
8604 # name read from wrong directory (e.g., in ./ from earlier compilation
8605 # w/o aux_dir), but doesn't exist in aux_dir, so there's no previous
8606 # setting for the correct .bbl file in %dependents.
8607 $dependents{$bbl_name} = 4;
8608 $created_rules{$bbl_name} = $from_rule;
8609 print " ===Source file '$bbl_name' for '$rule'\n"
8610 if ($diagnostics);
8611 # Remove OPPOSITE kind of bbl generation:
8612 rdb_remove_rule( "bibtex $bbl_base" );
8613 # Get information from .bcf file:
8614 my $bcf_status = 0;
8615 my %bib_files = ();
8616 my @found = ();
8617 my @not_found = ();
8618 my @remote = ();
8619 parse_bcf( $bcf_name, \$bcf_status, \%bib_files,
8620 \@found, \@not_found, \@remote );
8621 my @new_sources = (@found, @not_found);
8622 push @new_sources, $bcf_name;
8623 show_array( 'Sources for biber', @new_sources );
8624 if ( ! rdb_rule_exists( $from_rule ) ){
8625 print " ===Creating rule '$from_rule'\n" if ($diagnostics);
8626 rdb_create_rule( $from_rule, 'external', $biber, '', 1,
8627 $bcf_name, $bbl_name, $bbl_base,
8628 1, 0, 0, 1, [ "$bbl_base.blg" ] );
8629 # Since the rule is new, populate it with the best information
8630 # that we have;
8631 rdb_ensure_file_multi( $from_rule, @new_sources );
8632 }
8633 # Cache the information about source files from .bcf file, for use
8634 # when biber terminates earlier:
8635 rdb_set_extra( $from_rule, 'bcf_datasources', [@new_sources] );
8636 if ($bcf_status >= 100 ) {
8637 my $save_bcf = "$bcf_name$save_error_suffix";
8638 my $save_bbl = "$bbl_name$save_error_suffix";
8639 warn "$My_name: ========== Incomplete .bcf file '$bcf_name'.\n",
8640 " I'll rename the file to '$save_bcf'.\n";
8641 rename $bcf_name, $save_bcf;
8642 if ($bibtex_use) {
8643 warn " I'll rename the bbl file to '$save_bbl',\n",
8644 " in case the incomplete bcf file was a result of error in\n",
8645 " '$rule' caused by an error in the bbl file.\n";
8646 rename $bbl_name, $save_bbl;
8647 }
8648 }
8649 if ( ($bibtex_use == 1) || ($bibtex_use == 1.5) ) {
8650 # Conditional use of biber => we'll make decisions on
8651 # whether to run biber according to whether all bib files
8652 # exist. That's on the basis of the source list of the
8653 # biber rule. So if the latest information from .bcf file
8654 # is that a previously listed but non-existent bib file is
8655 # not in the list from the .bcf file, then we remove it
8656 # from the source list of biber.
8657 # AND I must add any files listed in .bcf that are
8658 # non-existent.
8659 my @bib_to_remove = ();
8660 foreach (rdb_get_source( $from_rule ) ) {
8661 if ( ( /\.bib$/ ) && ( ! -e $_ ) && ( ! exists $bib_files{$_} ) ) {
8662 push @bib_to_remove, $_;
8663 }
8664 }
8665 show_array( "Bib files to remove from source list of '$from_rule'",
8666 @bib_to_remove
8667 ) if $diagnostics;
8668 rdb_remove_files( $from_rule, @bib_to_remove );
8669 show_array( "Bib files to add to source list of '$from_rule'",
8670 @not_found
8671 ) if $diagnostics;
8672 rdb_ensure_file_multi( $from_rule, @not_found );
8673 }
8674 } # end biber setup
8675 elsif ( $log_info{biber} ) {
8676 # biblatex gave a symptom that it is using biber, but a .bcf file
8677 # wasn't generated on this run; any .bcf is a relic from previous
8678 # runs. This situation can occur even if biblatex gave a warning
8679 # in the .log file about a need to (re)run biber. An example is
8680 # when beamer is used with its 'show only notes' option, and
8681 # biblatex is used. The 'rerun biber' message occurs even if there
8682 # is no .bcf file, so that running biber would fail.
8683 #
8684 # But in this situation we definitely don't want to run bibtex to
8685 # make any missing .bbl file. So we must not go the to the bibtex
8686 # section just below.
8687 $bib_program = 'biber';
8688 }
8689 else {
8690 $bib_program = 'bibtex';
8691 warn "$My_name: Using bibtex to make bibliography file(s).\n";
8692
8693 # Remove OPPOSITE kind of bbl generation:
8694 rdb_remove_rule( "biber $aux_dir1$$Pbase" );
8695
8696 # Maps bbl files for bibtex rules to basename (incl. path):
8697 my %good_bbl = ();
8698
8699 # Check detected bbl_files/candidates for those that are suitable
8700 # for bibtex: They correspond to .aux files generated on this run.
8701 # Special cases:
8702 # 1. .bbl file read but from wrong directory (because .bbl file
8703 # in correct directory doesn't (yet) exist). I must look in
8704 # aux_dir. (Typical case: aux_dir ne './' but previous run
8705 # without aux_dir generated .bbl file in ./.)
8706 # 2. I'm on first run of *latex, .aux file was created by
8707 # set_trivial_aux_fdb, *latex didn't create .aux file, but
8708 # test_gen_file reports it did, because not enough time
8709 # elapsed after creation of file for test_gen_file to give
8710 # correct result.
8711 foreach my $bbl_file ( uniqs( @bbl_files ) ) {
8712 # say "===== BBL candidate file '$bbl_file'";
8713 my ($bbl_base, $bbl_path, $bbl_ext) = fileparseA( $bbl_file );
8714 $bbl_base = $bbl_path.$bbl_base;
8715 my $aux_file = "$bbl_base.aux";
8716 if (test_gen_file($aux_file)) {
8717 $good_bbl{$bbl_file} = $bbl_base;
8718 }
8719 else {
8720 # .bbl file corresponds to .aux file that wasn't from this run"
8721 # So look in aux_dir to check for relevant .aux file
8722 # that corresponds to the .bbl file.
8723 # Case not covered: chapter bib with subdirectory for chapter.
8724 # .bbl file generated in subdirectory on run w/o aux_dir.
8725 # Run with aux_dir picks up old .bbl file from subdirectory.
8726 # But the code below assumes .aux file (and corresponding
8727 # correct .bbl file) is in aux_dir itself.
8728 # I could try searching list of generated .aux files for
8729 # .aux file with the correct basename?
8730 my $try_base = "$aux_dir1$bbl_base";
8731 my $try_bbl = "$aux_dir1$bbl_base.bbl";
8732 if (test_gen_file( "$try_base.aux" )) {
8733 $good_bbl{$try_bbl} = "$try_base";
8734 $dependents{$try_bbl} = 4;
8735 }
8736 else {
8737 warn "$My_name: Foreign .bbl file, '$bbl_file',\n",
8738 "appears **not** to be associated with .aux file from this run.\n";
8739 }
8740 }
8741 }
8742 foreach my $bbl_file ( sort keys %good_bbl ) {
8743 my $bbl_base = $good_bbl{$bbl_file};
8744 my $aux_file = "$bbl_base.aux";
8745 my $from_rule = "$bib_program $bbl_base";
8746 $created_rules{$bbl_file} = $from_rule;
8747 print " ===Source file '$bbl_file' for '$rule'\n"
8748 if ($diagnostics ||1);
8749 rdb_ensure_file( $rule, $bbl_file, $from_rule );
8750
8751 if ( ! rdb_rule_exists( $from_rule ) ){
8752 say "Create $from_rule";
8753 rdb_create_rule( $from_rule, 'external', $bibtex, 'run_bibtex', 1,
8754 "$bbl_base.aux", $bbl_file, $bbl_base,
8755 1, 0, 0, 1, [ "$bbl_base.blg" ] );
8756 }
8757 my @new_bib_files = ();
8758 my @new_aux_files = ();
8759 my @new_bst_files = ();
8760 parse_aux( "$bbl_base.aux",
8761 \@new_bib_files, \@new_aux_files, \@new_bst_files );
8762 foreach ( @new_aux_files ) { $processed_aux_files{$_} = 1; }
8763 rdb_set_source( $from_rule,
8764 @new_bib_files, @new_aux_files, @new_bst_files );
8765 } # end BBL_FILE
8766 } # end bibtex setup
8767
8768 if ( ($#aux_hooks > -1) && ! exists $processed_aux_files{$aux_main} ) {
8769 my @new_bib_files = ();
8770 my @new_aux_files = ();
8771 my @new_bst_files = ();
8772 parse_aux( $aux_main, \@new_bib_files, \@new_aux_files, \@new_bst_files );
8773 foreach my $source ( @new_aux_files ) {
8774 $processed_aux_files{$source} = 1;
8775 }
8776 }
8777
8778 NEW_SOURCE:
8779 foreach my $new_source (keys %dependents) {
8780 print " ===Source file for rule '$rule': '$new_source'\n"
8781 if ($diagnostics);
8782 if ( exists $first_read_after_write{$new_source} ) {
8783 if ( dep_at_start($new_source) ) {
8784 $dependents{$new_source} = 8;
8785 }
8786 else {
8787 $dependents{$new_source} = 6;
8788 }
8789 }
8790 if ( ($dependents{$new_source} == 5)
8791 || ($dependents{$new_source} == 6)
8792 ) {
8793 # (a) File was detected in "No file..." line in log file.
8794 # Typically file was searched for early in run of
8795 # latex/pdflatex, was not found, and then was written
8796 # later in run.
8797 # or (b) File was written during run.
8798 # In both cases, if file doesn't already exist in database, we
8799 # don't know its previous status. Therefore we tell
8800 # rdb_ensure_file that if it needs to add the file to its
8801 # database, then the previous version of the file should be
8802 # treated as non-existent, to ensure another run is forced.
8803 rdb_ensure_file( $rule, $new_source, undef, 1 );
8804 }
8805 elsif ( $dependents{$new_source} == 7 ) {
8806 # File was result of conversion by *latex.
8807 # start of run. S
8808 my $cnv_source = $conversions{$new_source};
8809 rdb_ensure_file( $rule, $new_source );
8810 # if ($cnv_source && ($cnv_source !~ /\"/ ) ) {
8811 if ($cnv_source ) {
8812 # Conversion from $cnv_source to $new_source
8813 # implies that effectively $cnv_source is a source
8814 # of the *latex run.
8815 rdb_ensure_file( $rule, $cnv_source );
8816 }
8817 # Flag that changes of the generated file during a run
8818 # do not require a rerun:
8819 rdb_one_file( $new_source, sub{ $$Pcorrect_after_primary = 1; } );
8820 }
8821 elsif ( $dependents{$new_source} == 8 ) {
8822 # File was read only after being written
8823 # and the file existed at the beginning of the run
8824 rdb_ensure_file( $rule, $new_source );
8825 rdb_add_generated( $new_source );
8826 rdb_add_rewritten_before_read( $new_source );
8827 }
8828 else {
8829 # But we don't need special precautions for ordinary user files
8830 # (or for files that are generated outside of latex/pdflatex).
8831 rdb_ensure_file( $rule, $new_source );
8832 }
8833 if ( ($dependents{$new_source} == 6)
8834 || ($dependents{$new_source} == 7)
8835 ) {
8836 rdb_add_generated($new_source);
8837 }
8838 }
8839
8840 run_hooks( 'latex_file_hooks' );
8841
8842 # Some packages (e.g., bibtopic) generate a dummy error-message-providing
8843 # bbl file when a bbl file does not exist. Then the fls and log files
8844 # show the bbl file as created by the primary run and hence as a
8845 # generated file. Since we now have a rule to create a real bbl file,
8846 # the information in the fls and log files no longer represents a
8847 # correct dependency, so the bbl file is to be removed from the
8848 # generated files.
8849 foreach (keys %created_rules) { rdb_remove_generated( $_ ); }
8850
8851 my @more_sources = &rdb_set_dependents( $rule );
8852 my $num_new = $#more_sources + 1;
8853 foreach (@more_sources) {
8854 $dependents{$_} = 4;
8855 if ( ! -e $_ ) {
8856 # Failure was non-existence of makable file
8857 # Leave failure issue to other rules.
8858 $failure = 0;
8859 $$Pchanged = 1; # New files can be made. Ignore error.
8860 }
8861 }
8862 if ($diagnostics) {
8863 if ($num_new > 0 ) {
8864 show_array( "$num_new new source files for rule '$rule':", @more_sources );
8865 }
8866 else {
8867 print "No new source files for rule '$rule':\n";
8868 }
8869 my @first_read_after_write = sort keys %first_read_after_write;
8870 if ($#first_read_after_write >= 0) {
8871 show_array( "The following files were only read after being written:", @first_read_after_write );
8872 }
8873 }
8874 my @files_not_needed = ();
8875 foreach (keys %$PHsource) {
8876 if ( ! exists $dependents{$_} ) {
8877 print "Removing no-longer-needed dependent '$_' from rule '$rule'\n"
8878 if $diagnostics;
8879 push @files_not_needed, $_;
8880 }
8881 }
8882 rdb_remove_files( $rule, @files_not_needed );
8883
8884 return ($missing_dirs, [@missing_subdirs],
8885 ( $log_info{bad_warning} ? 1 : 0 ),
8886 );
8887
8888 } # END rdb_set_latex_deps
8889
8890 #************************************************************
8891
8892 sub switch_output {
8893 # Usage: switch_output( primary_rule, actual_ext, intended_ext )
8894 # Rearrange rules to deal with changed extension of output file of
8895 # the specified primary rule (one of *latex).
8896 # The switching only works if no request was made for dvi, ps or xdv
8897 # files, but only if the requested file was pdf.
8898 # Return 0 on success, non-zero error code on failure.
8899
8900 my ( $rule, $actual_ext, $intended_ext ) = @_;
8901 if ( $actual_ext eq $intended_ext ) { return 0; }
8902 if ( ! $can_switch ) { return 1; }
8903
8904 if (! defined $possible_primaries{$rule} ) {
8905 warn "$My_name: BUG: subroutine switch_output called with non-primary rule '$rule'\n";
8906 return 1;
8907 }
8908
8909 # Turn off all pdf producers and all primaries (pdf producing or not).
8910 # Then reactivate what we need: current rule and whatever else is needed
8911 # to produce a pdf file.
8912 # Given that we get here if the rule is not producing the intended kind
8913 # of output file, it's best to turn off all primaries, so as to make the
8914 # primary in use unambiguous.
8915 rdb_deactivate_derequest( 'dvipdf', 'pspdf', 'xdvipdfmx', keys %possible_primaries );
8916
8917 rdb_activate_request( $rule );
8918
8919 if ( $actual_ext eq '.dvi' ) {
8920 rdb_activate_request( 'dvipdf' );
8921 $input_extensions{$rule} = $standard_input_extensions{latex};
8922 }
8923 elsif ( $actual_ext eq '.xdv' ) {
8924 rdb_activate_request( 'xdvipdfmx' );
8925 $input_extensions{$rule} = $standard_input_extensions{xelatex};
8926 }
8927 else {
8928 $input_extensions{$rule} = $standard_input_extensions{pdflatex};
8929 }
8930
8931 my $old_dest = $$Pdest;
8932 my $new_dest = $$Pdest;
8933 $new_dest =~ s/$intended_ext$/$actual_ext/;
8934 # Compensate for MiKTeX's behavior: dvi and pdf are put in out_dir, but xdv is put in aux_dir:
8935 if ( ($actual_ext eq '.xdv') && ($out_dir ne $aux_dir) ){ $new_dest =~ s/^$out_dir1/$aux_dir1/; }
8936 if ( ($intended_ext eq '.xdv') && ($out_dir ne $aux_dir) ){ $new_dest =~ s/^$aux_dir1/$out_dir1/; }
8937
8938 rdb_remove_generated( $old_dest );
8939 rdb_add_generated( $new_dest );
8940 $$Pdest = $new_dest;
8941
8942 &rdb_set_rule_net;
8943
8944 # Some fixes to avoid spurious error conditions:
8945 $switched_primary_output = 1;
8946 if (-e $$Pdest) {
8947 $missing_dvi_pdf = '';
8948 if ($$Plast_result == 1 ) { $$Plast_result = 0; }
8949 }
8950 else { $missing_dvi_pdf = $$Pdest; }
8951
8952 return 0;
8953 } #END switch_output
8954
8955 #************************************************************
8956
8957 sub test_gen_file {
8958 # Usage: test_gen_file( filename )
8959 # Tests whether a file of given name was generated during current run
8960 # of *latex, with override of comparison of file and run time by
8961 # file being listed in %generated_log or %generated_fls
8962 # Assumes context for primary rule.
8963 my $file = shift;
8964 if ($file eq $aux_main ) {
8965 # Do I need special treatment here, if I make aux file just before run?
8966 }
8967 our ( %generated_fls, %generated_log );
8968 return exists $generated_log{$file} || $generated_fls{$file}
8969 || test_gen_file_time($file);
8970 }
8971
8972 #************************************************************
8973
8974 sub test_gen_file_time {
8975 # Usage: test_gen_file_time( filename )
8976 # Tests whether a file of given name exists and was generated during
8977 # current run of *latex. Comparison of file and run time used for
8978 # testing whether file was generated or is left over from a previous run.
8979 #
8980 my $file = shift;
8981 if (! -e $file) { return 0; }
8982 my $new_time = get_mtime( $file );
8983 # If file's mtime is later than at beginning of this pass, it was certainly made.
8984 # But unless hires time is available, the time of a new file may equal that for the old file.
8985 if ( (exists $fdb_current{$file}) && ($new_time > ${$fdb_current{$file}}[0] ) ) {
8986 return 1;
8987 }
8988 # Fall back on mtime relative to run time, with allowance for imprecisioni.
8989 return ( $new_time >= $$Prun_time + $filetime_offset - $filetime_causality_threshold );
8990 }
8991
8992 #************************************************************
8993
8994 sub dep_at_start {
8995 # Usage: dep_at_start( filename )
8996 # Tests whether the file was source file and existed at start of run.
8997 # Assumes context for primary rule.
8998 my $time = undef;
8999 rdb_one_file( shift, sub{ $time = $$Ptime; } );
9000 return (defined $time) && ($time != 0);
9001 }
9002
9003 #************************************************************
9004
9005 sub rdb_find_new_files {
9006 # Call: rdb_find_new_files
9007 # Assumes rule context for primary rule.
9008 # Deal with files which were missing and for which a method
9009 # of finding them has become available:
9010 # (a) A newly available source file for a custom dependency.
9011 # (b) When there was no extension, a file with appropriate
9012 # extension
9013 # (c) When there was no extension, and a newly available source
9014 # file for a custom dependency can make it.
9015
9016 my %new_includes = ();
9017
9018 MISSING_FILE:
9019 foreach my $missing ( keys %$PHsource ) {
9020 next if ( $$PHsource{$missing} != 0 );
9021 my ($base, $path, $ext) = fileparseA( $missing );
9022 $ext =~ s/^\.//;
9023 if ( -e "$missing.tex" ) {
9024 $new_includes{"$missing.tex"} = 1;
9025 }
9026 elsif ( -e $missing ) {
9027 $new_includes{$missing} = 1;
9028 }
9029 elsif ( $ext ne "" ) {
9030 foreach my $dep (@cus_dep_list){
9031 my ($fromext,$toext) = split('\s+',$dep);
9032 if ( ( "$ext" eq "$toext" )
9033 && ( -f "$path$base.$fromext" )
9034 ) {
9035 # Source file for the missing file exists
9036 # So we have a real include file, and it will be made
9037 # next time by rdb_set_dependents
9038 $new_includes{$missing} = 1;
9039 }
9040 else {
9041 # no point testing the $toext if the file doesn't exist.
9042 }
9043 next MISSING_FILE;
9044 }
9045 }
9046 else {
9047 # $_ doesn't exist, $_.tex doesn't exist,
9048 # and $_ doesn't have an extension
9049 foreach my $dep (@cus_dep_list){
9050 my ($fromext,$toext) = split('\s+',$dep);
9051 if ( -f "$path$base.$fromext" ) {
9052 # Source file for the missing file exists
9053 # So we have a real include file, and it will be made
9054 # next time by &rdb__dependents
9055 $new_includes{"$path$base.$toext"} = 1;
9056 # next MISSING_FILE;
9057 }
9058 if ( -f "$path$base.$toext" ) {
9059 # We've found the extension for the missing file,
9060 # and the file exists
9061 $new_includes{"$path$base.$toext"} = 1;
9062 # next MISSING_FILE;
9063 }
9064 }
9065 }
9066 } # end MISSING_FILES
9067
9068 # Sometimes bad line-breaks in log file (etc) create the
9069 # impression of a missing file e.g., ./file, but with an incorrect
9070 # extension. The above tests find the file with an extension,
9071 # e.g., ./file.tex, but it is already in the list. So now I will
9072 # remove files in the new_include list that are already in the
9073 # include list. Also handle aliasing of file.tex and ./file.tex.
9074 # For example, I once found:
9075 # (./qcdbook.aux (./to-do.aux) (./ideas.aux) (./intro.aux) (./why.aux) (./basics
9076 #.aux) (./classics.aux)
9077
9078 my $found = 0;
9079 foreach my $file (keys %new_includes) {
9080 # if ( $file =~ /\"/ ) {next; }
9081 my $stripped = $file;
9082 $stripped =~ s{^\./}{};
9083 if ( exists $$PHsource{$file} ) {
9084 delete $new_includes{$file};
9085 }
9086 else {
9087 $found ++;
9088 rdb_ensure_file( $rule, $file );
9089 }
9090 }
9091
9092 if ( $diagnostics && ( $found > 0 ) ) {
9093 show_array( "$My_name: Detected previously missing files:", sort keys %new_includes );
9094 }
9095 return $found;
9096 } # END rdb_find_new_files
9097
9098 #************************************************************
9099
9100 sub rdb_set_dependents {
9101 # Call rdb_set_dependents( rules ...)
9102 # Returns array (sorted), of new source files for the given rules.
9103 our ( @new_sources, @deletions );
9104 local @new_sources = ();
9105 local @deletions = ();
9106
9107 rdb_for_some( [@_], 0, \&rdb_one_dep );
9108 foreach (@deletions) {
9109 my ($rule, $file) = @$_;
9110 rdb_remove_files( $rule, $file );
9111 }
9112 return uniqs( @new_sources );
9113 } #END rdb_set_dependents
9114
9115 #************************************************************
9116
9117 sub rdb_find_source_file {
9118 # Helper for searching dependencies in all paths inside the TEXINPUTS
9119 # environment variable.
9120 my $test = "$_[0].$_[1]";
9121 if ( -e $test ) {
9122 return $_[0];
9123 }
9124 if ( exists $ENV{TEXINPUTS} ) {
9125 foreach my $searchpath (split $search_path_separator, $ENV{TEXINPUTS}) {
9126 my $file = catfileA($searchpath,$_[0]);
9127 if ( $file =~ /\\/ ) { print "====== '$file'\n"; die; }
9128 my $test = "$file.$_[1]";
9129 if ( -e $test ) {
9130 return $file;
9131 }
9132 }
9133 }
9134 return "$_[0]";
9135 }
9136
9137 #************************************************************
9138
9139 sub rdb_one_dep {
9140 # Helper for finding dependencies. One case, $rule and $file given
9141 # Assume file (and rule) context for DESTINATION file.
9142
9143 # Only look for dependency if $rule is primary rule (i.e., latex
9144 # or pdflatex) or is a custom dependency: ???WHY???!!!
9145 if ( (! exists $possible_primaries{$rule}) && ($rule !~ /^cusdep/) ) {
9146 return;
9147 }
9148 our ( @new_sources, @deletions );
9149 my $new_dest = $file;
9150 if ($$PHdest{$new_dest} ) {
9151 # We already have a way of making the file.
9152 # No need to find another one.
9153 return;
9154 }
9155 my ($base_name, $path, $toext) = fileparseA( $new_dest );
9156 $base_name = $path.$base_name;
9157 $toext =~ s/^\.//;
9158 my $Pinput_extensions = $input_extensions{$rule};
9159 DEP:
9160 foreach my $dep ( @cus_dep_list ) {
9161 my ($fromext,$proptoext,$must,$func_name) = split('\s+',$dep);
9162 if ( $toext eq $proptoext ) {
9163 # Look in search path for file of correct name:
9164 $base_name = rdb_find_source_file($base_name, $fromext);
9165 my $source = "$base_name.$fromext";
9166 # Found match of rule
9167 if ($diagnostics) {
9168 print "Found cusdep: $source to make $rule:$new_dest ====\n";
9169 }
9170 if ( -e $source ) {
9171 my $from_rule = "cusdep $fromext $toext $base_name";
9172 my $new_new_dest = "$base_name.$toext";
9173 if ($$PHdest{$new_new_dest} ) {
9174 # We already have a way of making the file.
9175 # No need to find another one.
9176 return;
9177 }
9178 if ($new_new_dest ne $new_dest) {
9179 rdb_ensure_file( $rule, $new_new_dest );
9180 $new_dest = $new_new_dest;
9181 }
9182 my @Anew_cmd = ( 'do_cusdep', $func_name );
9183 if ( !-e $new_dest ) {
9184 push @new_sources, $new_dest;
9185 }
9186 if (! rdb_rule_exists( $from_rule ) ) {
9187 print "$My_name: === Creating rule '$from_rule'\n" if $diagnostics;
9188 rdb_create_rule( $from_rule, 'cusdep', '', \@Anew_cmd, 3,
9189 $source, $new_dest, $base_name, 0 );
9190 }
9191 return;
9192 }
9193 else {
9194 # Source file does not exist
9195 if ( !$force_mode && ( $must != 0 ) ) {
9196 # But it is required that the source exist ($must !=0)
9197 $failure = 1;
9198 $failure_msg = "File '$base_name.$fromext' does not exist ".
9199 "to build '$base_name.$toext'";
9200 return;
9201 }
9202 elsif ( $from_rules{$file} && ($from_rules{$file} =~ /^cusdep $fromext $toext / ) ) {
9203 # Source file does not exist, destination has the rule set.
9204 # So turn the from_rule off
9205 delete $from_rules{$file};
9206 }
9207 else {
9208 }
9209 }
9210 }
9211 elsif ( ($toext eq '')
9212 && (! -e $file )
9213 && (! -e "$base_name.$proptoext" )
9214 && exists $$Pinput_extensions{$proptoext}
9215 ) {
9216 # Empty extension and non-existent destination
9217 # This normally results from \includegraphics{A}
9218 # without graphics extension for file, when file does
9219 # not exist. So we will try to find something to make it.
9220 $base_name = rdb_find_source_file($base_name, $fromext);
9221 my $source = "$base_name.$fromext";
9222 if ( -e $source ) {
9223 $new_dest = "$base_name.$proptoext";
9224 my $from_rule = "cusdep $fromext $proptoext $base_name";
9225 if ( $$PHdest{$new_dest} ) {
9226 # We already have a way of making the file.
9227 # No need to find another one.
9228 return;
9229 }
9230 push @new_sources, $new_dest;
9231 print "$My_name: Ensuring rule for '$from_rule', to make '$new_dest'\n"
9232 if $diagnostics > -1;
9233 my @Anew_cmd = ( 'do_cusdep', $func_name );
9234 if (! rdb_rule_exists( $from_rule ) ) {
9235 print "$My_name: === Creating rule '$from_rule'\n" if $diagnostics;
9236 rdb_create_rule( $from_rule, 'cusdep', '', \@Anew_cmd, 3,
9237 $source, $new_dest, $base_name, 0 );
9238 }
9239 rdb_ensure_file( $rule, $new_dest, $from_rule );
9240 # We've now got a spurious file in our rule. But don't mess
9241 # with deleting an item we are in the middle of!
9242 push @deletions, [$rule, $file];
9243 return;
9244 }
9245 } # End of Rule found
9246 } # End DEP
9247 if ( (! -e $file) && $use_make_for_missing_files ) {
9248 # Try to make the missing file
9249 #Set character to surround filenames in commands:
9250 if ( $toext ne '' ) {
9251 print "$My_name: '$rule': source file '$file' doesn't exist. I'll try making it...\n";
9252 &Run_subst( "$make $quote$file$quote" );
9253 if ( -e $file ) {
9254 return;
9255 }
9256 }
9257 else {
9258 print "$My_name: '$rule': source '$file' doesn't exist.\n",
9259 " I'll try making it with allowed extensions \n";
9260 foreach my $try_ext ( keys %$Pinput_extensions ) {
9261 my $new_dest = "$file.$try_ext";
9262 if (-e $new_dest) {
9263 # A file that exists cannot have been the missing file.
9264 next;
9265 }
9266 &Run_subst( "$make $quote$new_dest$quote" );
9267 if ( -e $new_dest ) {
9268 print "SUCCESS in making '$new_dest'\n",
9269 "I'll ensure '$rule' is rerun.\n";
9270 # Put file in rule, without a from_rule, but
9271 # set its state as non-existent, to correspond
9272 # to file's state before the file was made
9273 # This ensures a rerun of *latex is provoked.
9274 rdb_ensure_file( $rule, $new_dest, undef, 1 );
9275 push @new_sources, $new_dest;
9276 push @deletions, [$rule, $file];
9277 # Flag need for a new run of *latex despite
9278 # the error due to a missing file.
9279 $$Pout_of_date_user = "Missing file '$new_dest' now exists";
9280 return;
9281 }
9282 }
9283 }
9284 }
9285 } #END rdb_one_dep
9286
9287 #************************************************************
9288
9289 sub rdb_list {
9290 # Call: rdb_list()
9291 # List rules and their source files
9292 print "===Rules:\n";
9293 my $count_rules = 0;
9294 my @accessible_all = &rdb_accessible;
9295 rdb_for_some(
9296 \@accessible_all,
9297 sub{ $count_rules++;
9298 print "Rule '$rule' depends on:\n";
9299 },
9300 sub{ print " '$file'\n"; },
9301 sub{ print " and generates:\n";
9302 foreach (keys %$PHdest) { print " '$_'\n"; }
9303 # print " default_extra_generated:\n";
9304 # foreach (@$PA_extra_gen) { print " '$_'\n"; }
9305 },
9306 );
9307 if ($count_rules <= 0) {
9308 print " ---No rules defined\n";
9309 }
9310 } #END rdb_list
9311
9312 #************************************************************
9313
9314 sub deps_list {
9315 # Call: deps_list(fh)
9316 # List dependent files to file open on fh
9317 my $fh = $_[0];
9318 fprint8( $fh, "#===Dependents, and related info, for $filename:\n" );
9319 my @dest_exts = ();
9320 if ($pdf_mode) {push @dest_exts, '.pdf';}
9321 if ($dvi_mode) {push @dest_exts, '.dvi';}
9322 if ($hnt_mode) {push @dest_exts, '.hnt';}
9323 if ($postscript_mode) {push @dest_exts, '.ps';}
9324
9325 my $deps_space = ' ';
9326 if ($deps_escape eq 'unix' ) { $deps_space = '\ '; }
9327 elsif ($deps_escape eq 'nmake' ) { $deps_space = '^ '; }
9328 my $Pescape = sub {
9329 my $name = shift;
9330 $name =~ s/ /$deps_space/g;
9331 return $name;
9332 };
9333
9334 my %source = ( $texfile_name => 1 );
9335 my @accessible_all = &rdb_accessible;
9336 rdb_for_some(
9337 \@accessible_all,
9338 sub{},
9339 sub{ $source{$file} = 1; }
9340 );
9341 foreach (keys %from_rules) {
9342 # Remove known generated files from list of source files.
9343 delete $source{$_};
9344 }
9345
9346 show_array( "Sources:", sort keys %source ) if $diagnostics;
9347
9348 foreach my $ext (@dest_exts) {
9349 # Don't insert name of deps file in targets.
9350 # The previous behavior of inserting the name of the deps file
9351 # matched the method recommended by GNU make for automatically
9352 # generated prerequisites -- see Sec. "Generating Prerequisites
9353 # Automatically" of GNU make manual (v. 4.2). But this can
9354 # cause problems in complicated cases, and as far as I can see,
9355 # it doesn't actually help, despite the reasoning given.
9356 # The only purpose of the deps file is to to determine source
9357 # files for a particular rule. The files whose changes make the
9358 # deps file out-of-date are the same as those that make the real
9359 # target file (e.g., .pdf) out-of-date. So the GNU method seems
9360 # completely unnecessary.
9361 fprint8( $fh, &$Pescape(${out_dir1}.${root_filename}.${ext}), " :" );
9362 foreach (sort keys %source) {
9363 fprint8( $fh, "\\\n ", &$Pescape($_) );
9364 }
9365 fprint8( $fh, "\n" );
9366 }
9367 fprint8( $fh, "#===End dependents for $filename:\n" );
9368 if ($dependents_phony) {
9369 fprint8( $fh, "\n#===Phony rules for $filename:\n\n" );
9370 foreach (sort keys %source) {
9371 fprint8( $fh, "$_ :\n\n" );
9372 }
9373 fprint8( $fh, "#===End phony rules for $filename:\n" );
9374 }
9375 } #END deps_list
9376
9377 #************************************************************
9378
9379 sub rdb_show {
9380 # Call: rdb_show()
9381 # Displays contents of rule data base.
9382 # Side effect: Exercises access routines!
9383 print "===Rules:\n";
9384 my $count_rules = 0;
9385 rdb_for_actives(
9386 sub{ $count_rules++;
9387 my @int_cmd = @$PAint_cmd;
9388 foreach (@int_cmd) {
9389 if ( !defined($_) ) { $_='undef';}
9390 }
9391 print " [$rule]: '$$Pcmd_type' '$$Pext_cmd' '@int_cmd' $$Pno_history ",
9392 "'$$Psource' '$$Pdest' '$$Pbase' $$Pout_of_date $$Pout_of_date_user\n";
9393 },
9394 sub{ print " '$file': $$Ptime $$Psize $$Pmd5 '", ($from_rules{$file} || ''), "'\n"; }
9395 );
9396 if ($count_rules <= 0) {
9397 print " ---No rules defined\n";
9398 }
9399 } #END rdb_show
9400
9401 #************************************************************
9402
9403 sub rdb_target_array {
9404 # Returns array of all rules implicated by %target_rules and %target_files
9405 my %rules = &rdb_target_hash;
9406 return keys %rules;
9407 } # End rdb_target_array
9408
9409 #************************************************************
9410
9411 sub rdb_target_hash {
9412 # Returns hash mapping to 1 all rules implicated by %target_rules and %target_files
9413 my %rules = %target_rules;
9414 foreach (keys %target_files) {
9415 if (exists $from_rules{$_}) { $rules{$from_rules{$_}} = 1; }
9416 }
9417 # show_array( 'target_hash', sort keys %rules );
9418 # &traceback;
9419 return %rules;
9420 } # End rdb_target_hash
9421
9422 #************************************************************
9423
9424 sub rdb_accessible {
9425 # Call: &rdb_accessible
9426 # Returns array of rules accessible from target rules and rules to make target files
9427
9428 my %accessible_rules = &rdb_target_hash;
9429 rdb_recurse( [keys %accessible_rules], sub{ $accessible_rules{$rule} = 1; } );
9430 return keys %accessible_rules;
9431 } #END rdb_accessible
9432
9433 #************************************************************
9434 #************************************************************
9435 #************************************************************
9436
9437 sub rdb_make {
9438 # Call: &rdb_make
9439 # Makes the targets and prerequisites.
9440 # Leaves one-time rules to last.
9441 # Does appropriate repeated makes to resolve dependency loops
9442
9443 # Returns 0 on success, nonzero on failure.
9444
9445 # General method: Find all accessible rules, then repeatedly make
9446 # them until all accessible rules are up-to-date and the source
9447 # files are unchanged between runs. On termination, all
9448 # accessible rules have stable source files.
9449 #
9450 # One-time rules are view and print rules that should not be
9451 # repeated in an algorithm that repeats rules until the source
9452 # files are stable. It is the calling routine's responsibility to
9453 # arrange to call them, or to use them here with caution.
9454 #
9455 # Note that an update-viewer rule need not be considered
9456 # one-time. It can be legitimately applied everytime the viewed
9457 # file changes.
9458 #
9459 # Note also that the criterion of stability is to be applied to
9460 # source files, not to output files. Repeated application of a
9461 # rule to IDENTICALLY CONSTANT source files may produce different
9462 # output files. This may be for a trivial reason (e.g., the
9463 # output file contains a time stamp, as in the header comments for
9464 # a typical postscript file), or for a non-trivial reason (e.g., a
9465 # stochastic algorithm, as in abcm2ps).
9466 #
9467 # This caused me some actual trouble in certain cases, with circular
9468 # dependencies causing non-termination when the standard
9469 # stability-of-source-file algorithm is applied, together with
9470 # non-optimality if the depedence isn't actually circular: e.g., from a
9471 # rerun of X-to-pdf cusdep, where the pdf file is unchanged from
9472 # previous one aside from a time of generation comment. The following
9473 # situation is an example of a generic situation where a change from
9474 # the standard stability-of-input-files criterion must be modified in
9475 # order to obtain proper results:
9476 # 1. A/the latex source file contains specifications for
9477 # certain postprocessing operations. Standard *latex
9478 # already has this, for indexing and bibliography.
9479 # 2. In the case in point that caused me trouble, the
9480 # specification was for musical tunes that were contained
9481 # in external source files not directly input to
9482 # *latex. But in the original version, there was a
9483 # style file (abc.sty) that caused latex itself to call
9484 # abcm2ps **un**conditionally to make .eps files for each tune
9485 # that was to be read in on the next run of latex.
9486 # 3. Thus the specification can cause a non-terminating loop
9487 # for latexmk, because the output files of abcm2ps changed
9488 # on every run, even with identical input.
9489 # 4. The solution was to
9490 # a. Use a style file abc_get.sty that simply wrote the
9491 # specification on the tunes to the .aux file in a
9492 # completely deterministic fashion.
9493 # b. Instead of latex, use a script abclatex.pl that runs
9494 # latex and then extracts the abc contents for each tune
9495 # from the source abc file. This is also
9496 # deterministic.
9497 # c. Use a cusdep rule in latexmk to convert the tune abc
9498 # files to eps. This is non-deterministic, but only
9499 # gets called when the (deterministic) source file
9500 # changes.
9501 # This solves the problem. Latexmk works. Also, it is no
9502 # longer necessary to enable write18 in latex, and multiple
9503 # unnecessary runs of abcm2ps are no longer used.
9504
9505 # [**N.B.** Other sty files have similar problems, of
9506 # unconditional write18s to make eps, pdf or other files. That's
9507 # always non-optimal, often highly so --- see at least one of
9508 # the example_latexmkrc files for real cases. But work is needed
9509 # on the package to do better, which has been done in some
9510 # packages. It is also possible to do better with a suitable
9511 # configuration of latexmk with write18 turned off. E,g,,
9512 # perhaps a cusdep, or a fancy used of a subroutine for *latex
9513 # --- see the example_latexmkrc files for examples.]
9514 #
9515 # The method used is conditioned on:
9516 # 1. The network of active rules is constructed, with dependencies
9517 # linking the rules. The network may change during the
9518 # make. Notably, dependency information can be discovered from
9519 # the results of runs of rules, especially *latex. This involves
9520 # addition (and deletion) of items in the source-file list of a
9521 # rule. It also involves addition (or deletion) of rule-nodes
9522 # for e.g., cusdeps, bibtex, makeindex. Bigger changes
9523 # sometimes occur --- e.g., when a .tex document chooses a
9524 # kind of output file from the expected one: e.g., pdf to dvi or
9525 # vice versa.
9526 # 2. The *latex rules are called primary rules, and are the core
9527 # source of dependency information (as ultimately determined by
9528 # the .tex file(s). Only one primary rule is active. That was
9529 # enforced by initialization.
9530 # 3. There are generally loops of dependencies. The overall aim is
9531 # to keep looping through rules until the content of the source
9532 # files for each rule is unchanged from the previous run. Given
9533 # the basic assumption that it is the content of these files
9534 # that determines the output, stability of input files gives
9535 # stability of output.
9536 # 4. During the loop, the main criterion for running a rule is
9537 # that the current contents of the source files are changed
9538 # compared with the state saved in the rule. This is
9539 # supplemented by the condition that a rule not previously run
9540 # (under latexmk control) is to be run unconditionally.
9541 # 5. In addition, there are specified dependencies not going via a
9542 # set of files not known to latexmk as source files of the
9543 # target rule. The primary examples are dvips, dvipdf, etc,
9544 # which use graphics files; these are specified to have a dvi
9545 # producing fule (e.g., latex) as a source rule. Such a rule is
9546 # to be run after the source rule has been run.
9547 # 6. There are special cases, coded in rdb_rerun_needed and
9548 # rdb_file_change1.
9549 # 7. Immediately before running a rule, the saved state of its
9550 # source files is updated to their current state. If there is
9551 # no error in the run, the source-file-state is **not** updated
9552 # after the rule is run. Then on a subsequent pass through
9553 # rdb_make's main loop, when the rule is tested for a rerun, any
9554 # change in source file contents since the start of the previous
9555 # run is cause for running the rule again.
9556 # 8. When there is an error, and force_mode is off, processing of
9557 # all further rules is terminated. A problem is then caused for
9558 # a later invocation of latexmk (or, in -pvc mode, the next
9559 # scanning of source-file status): It may be that a generated
9560 # file from a run of some rule changed compared with its status
9561 # before the run. Because of the termination of processing
9562 # there was no rerun of the rule. New runs should only be made
9563 # after a change in the user-written files, which give the
9564 # possibility of correcting the error. But on a subsequent
9565 # invocation of latexmk it could appear that some rule(s) is/are
9566 # out-of-date because of the changed generated files, which
9567 # would result in unneeded extra runs, which will tend to
9568 # pollute the screen output with misleading downstream
9569 # consequences of the original error.
9570 # To avoid this problem, after an error-generating round of
9571 # compilations, the cached state of generated files is updated
9572 # to their state after the compilations. Then only user-caused
9573 # file changes will be cause for new runs.
9574 # 9. With circular dependencies, there is a choice of which order
9575 # to examine the rules. Generally, primary rules are more
9576 # time-consuming than most others, so the choice of the order of
9577 # examination of rules to check out-of-dateness is to try to
9578 # minimize the number of primary runs. The other time-consuming
9579 # rules are things like xdvipdfmx in documents with much
9580 # graphics. These are normally outside a dependency loop, so
9581 # those are left to last. Even if they are inside a dependency
9582 # loop, they need the primary rule to have been run first.
9583 # 10. After rdb_make is run, all non-user source files are updated
9584 # to their current state. Rules are considered up-to-date
9585 # here. On a subsequent call to rdb_make, subsequent changes are
9586 # relevant to what is to be done. Note: the states of user
9587 # files aren't updated. This guards against user caused changes
9588 # that are made between the start of the run of a rule and the
9589 # end of rdb_make.
9590 #
9591 # [Comment: Possible scenario for dvips, xdvipdfmx etc in loop:
9592 # Document is documentation for viewer. At some page, the result
9593 # in the viewer is to be displayed, with the display in the
9594 # viewer being a neighboring page of the document, so the
9595 # relevant page is extracted from the pdf file (or ...), and
9596 # then processed into a graphics file to be included in the
9597 # document.]
9598 #
9599 # This leads to the following approach:
9600 # 1. Classify accessible rules as: primary, pre-primary
9601 # (typically cusdep, bibtex, makeindex, etc), post-primary
9602 # (typically dvips, etc), and one-time.
9603 # This step is the start of rdb_make's main "PASS" loop.
9604 # 2. Go over the pre-primaries, the primary and the
9605 # post-primaries. Examine each rule for out-of-dateness; if
9606 # out-of-date run it.
9607 # 3. Just before a run of a rule, update its source file state to
9608 # the current state of the files.
9609 # 4. After the rule is run, at least after a primary rule is run,
9610 # examine the dependency information available (.fls, .log, .aux
9611 # files) and updated the rule configuration. This can involve
9612 # radical changes in the rule network: E.g., a newly found use
9613 # of bibtex or makeindex, or even more radical rearrangements,
9614 # if for example (under document control) *latex produces a .dvi
9615 # file instead of an expected .pdf file.
9616 # 5. If in any pass through the loop one (or more) of the
9617 # pre-primary and primary rules is run, don't go on to examine
9618 # the post-primaries. Not only are these are sometimes
9619 # time-consuming and are almost always outside the dependency
9620 # loops involving the primary, but, most importantly, dealing
9621 # with the dependency information from a primary rule can change
9622 # the rule network a lot.
9623 # Instead go back to step 1.
9624 # 6. Once visiting the pre-primaries and primaries no longer
9625 # triggers any run, i.e., those rules are all stable, go on to
9626 # the post-primaries.
9627 # 7. If one or more of the post-primaries has been run, go back to
9628 # 1. This allows for the possibility that a post-primary rule is
9629 # part of a dependency loop. This is highly unusual for a
9630 # normal document, but not impossible in principle. See earlier
9631 # for a conceivable example.
9632 # 10. Thus we finish the looping when no further run has been
9633 # triggered by an examination of all of the pre-primary,
9634 # primary, post-primary rules.
9635 # 11. In addition, the loop is terminated if the number of
9636 # applications of a rule exceeds a configured maximum. This
9637 # guards agains the possibility that it may never be possible to
9638 # get stable output, i.e., there is an infinite loop. It is
9639 # impossible for an algorithm to determine in general whether
9640 # there is an infinite loop. (An example of the Turing halting
9641 # theorem.) But normal documents need a decidable modest number
9642 # of passes through the loop. Any exceeding of the limit on the
9643 # number of passes needs examination.
9644 # 12. Finally apply one-time rules. These are rules that by their
9645 # nature are both outside of any dependency a loop and are ones
9646 # that should be applied last. Standard ones including running
9647 # a viewer or causing it to be updated. The standard ones are
9648 # not actually in the class of rules that rdb_make runs. Instead
9649 # they are run by the calling routines, since the needs may be
9650 # quite special.
9651
9652 if ($compiling_cmd) { Run_subst( $compiling_cmd ); }
9653 # ???!!! Overkill? No. $compiling_cmd might have injected something.
9654 &rdb_set_rule_net;
9655
9656 our %pass;
9657 local %pass = (); # Counts runs on each rule: Used for testing for
9658 # exceeding maximum runs and for determining
9659 # whether to run rules that have a list of source
9660 # rules. (E.g., dvips, which is to be run
9661 # whenever latex has been run to make a dvi
9662 # file. This because the list of source files of
9663 # dvips misses all graphics files, and so the
9664 # source file method is insufficient for deciding
9665 # on a rerun.)
9666 rdb_for_some( [keys %rule_db],
9667 sub{ $pass{$rule} = 0;
9668 foreach (keys %$PHsource_rules) {
9669 $$PHsource_rules{$_} = 0;
9670 }
9671 }
9672 );
9673
9674 our ($runs, $runs_total, $too_many_passes, $newrule_nofile);
9675 local $failure = 0; # General accumulated error flag
9676 local $missing_dvi_pdf = ''; # Did primary run fail to make its output file?
9677 local $runs = 0;
9678 local $runs_total = 0;
9679 local $too_many_passes = 0;
9680 local $switched_primary_output = 0;
9681 our @warning_list;
9682 local @warning_list = (); # Undef refs etc reported in last primary run
9683 my $retry_msg = 0; # Did I earlier say I was going to attempt
9684 # another pass after a failure?
9685 my %changes = (); # For reporting of changes
9686 PASS:
9687 while (1==1) {
9688 # Exit condition at end of body of loop.
9689 $runs = 0;
9690 $switched_primary_output = 0;
9691 my $previous_failure = $failure;
9692 $failure = 0;
9693 local $newrule_nofile = 0; # Flags whether rule created for
9694 # making currently non-existent file, which
9695 # could become a needed source file for a run
9696 # and therefore undo an error condition
9697 foreach my $rule (keys %rule_db) {
9698 # Update %pass in case new rules have been created
9699 if (! exists $pass{$rule} ) { $pass{$rule} = 0; }
9700 }
9701 if ($diagnostics) {
9702 print "Make: doing pre_primary and primary...\n";
9703 }
9704 # Do the primary run preceeded by pre_primary runs, all only if needed.
9705 # On return, $runs == 0 signals that nothing was run (and hence
9706 # no output files changed), either because no input files
9707 # changed and no run was needed, or because the
9708 # number of passes through the rule exceeded the
9709 # limit. In the second case $too_many_passes was set.
9710 rdb_for_some( [@pre_primary, $current_primary], \&rdb_make1 );
9711 if ($switched_primary_output) {
9712 print "=========SWITCH OF OUTPUT WAS DONE.\n";
9713 next PASS;
9714 }
9715
9716 if ( ($runs > 0) && ! $too_many_passes ) {
9717 $retry_msg = 0;
9718 if ( $force_mode || (! $failure) ) {
9719 next PASS;
9720 }
9721 # Get here on failure, without being in force_mode
9722 if ( $newrule_nofile ) {
9723 $retry_msg = 1;
9724 print "$My_name: Error on run, but found possibility to ",
9725 "make new source files\n";
9726 next PASS;
9727 }
9728 elsif ( rdb_user_changes( \%changes, @pre_primary, $current_primary )) {
9729 print "$My_name: Some rule(s) failed, but user file(s) changed ",
9730 "so keep trying\n";
9731 rdb_diagnose_changes2( \%changes, "", 1 ) if (!$silent);
9732 next PASS;
9733 }
9734 else { last PASS; }
9735 }
9736 if ( ($runs == 0) && (! $too_many_passes) && (! $failure) ) {
9737 # $failure not set on this pass, so use value from previous pass:
9738 $failure = $previous_failure;
9739 if ($retry_msg) {
9740 print "But in fact no new files made\n";
9741 }
9742 if ($failure && !$force_mode ) { last PASS; }
9743 }
9744 if ( $missing_dvi_pdf ) {
9745 # No output from primary, after completing circular dependence
9746 warn "Failure to make '$missing_dvi_pdf'\n";
9747 $failure = 1;
9748 last PASS;
9749 }
9750 if ($diagnostics) {
9751 print "Make: doing post_primary...\n";
9752 }
9753 rdb_for_some( [@post_primary], \&rdb_make1 );
9754 if ( ($runs == 0) || $too_many_passes ) {
9755 # Either nothing needed to be done,
9756 # and/or a rule needed to be run more than the allowed count.
9757 last PASS;
9758 }
9759 }
9760 continue {
9761 # Re-evaluate rule classification and accessibility,
9762 # but do not change primaries.
9763 # Problem is that $current_primary gets altered
9764 &rdb_set_rule_net;
9765 } #End PASS
9766
9767 if ($failure ) {
9768 # Update state of generated source files, but not non-generated,
9769 # i.e., user source files. Without that, when there was a termination of
9770 # processing because of an error, it could be some generated files changed
9771 # without reruns of the relevant rule(s) being triggered; that's because
9772 # with an error and with force_mode off, the reruns are blocked.
9773 # But that situation would cause reruns either when latexmk is reinvoked
9774 # or at the next examination of file state (in -pvc mode). But those runs
9775 # (almost certainly) won't improve the error situation in the absence of
9776 # a change in user files, since the error is ultimately due to a problem
9777 # with a user file.
9778 # By updating the state of generated source files, reruns are not
9779 # triggered until a user file is changed.
9780 # Also turn $$Pout_of_date off for the rules. It may have been set
9781 # at some point to trigger a rerun, but that information is now
9782 # out-of-date, given that an error occurred.
9783 rdb_for_some( [&rdb_accessible()],
9784 sub{
9785 &rdb_update_gen_files;
9786 $$Pout_of_date = 0;
9787 }
9788 );
9789 }
9790 rdb_for_some( [@unusual_one_time], \&rdb_make1 );
9791 if ( ($out2_dir_requested ne '') && ($out_dir ne $out2_dir) ) {
9792 do_copies_out_to_out2( $out_dir1, $out2_dir1 );
9793 }
9794
9795
9796 #---------------------------------------
9797 # All of make done. Finish book-keeping:
9798 # 1. Update state of source files suitably.
9799 # 2. Update fdb_latexmk file, if needed.
9800 # 3. Diagnostics.
9801 # 4. Other book-keeping and clean up.
9802
9803 ############ Update state of source files. Complications:
9804 # **Either** success. Then the algorithms arrange that the contents of
9805 # source files have stabilized between start and end of run of rule,
9806 # so that output files have also stabilized.
9807 # **or** failure. Then processing is normally aborted, so source files
9808 # that are generated may not have stabilized, e.g., .aux file.
9809 # At the next round of compilation (or test for a need for a rerun, as in
9810 # make_preview_continuous), the criterion for a rerun of a rule is that
9811 # source file(s) have changed relative to the saved state.
9812 # At this point the saved file state for each rule is the state just
9813 # before its last run. After a successful make, that gives correct
9814 # behavior, including for user files (i.e., non-generated files). But
9815 # not always after a failure.
9816 #
9817 # **So at this point we set state of generated source files to current
9818 # state.**
9819 #
9820 # Normally there are no further changes in generated files, so they
9821 # won't trigger reruns, only changes in user files will do that.
9822 # That's correct behavior.
9823 # But occasionally generated files have errors that block further
9824 # processing, as is known for .aux and .bbl files. Then user can
9825 # delete .aux and .bbl and thereby trigger a rerun. It also optimizes
9826 # testing for changes, since, e.g., an .aux file of the same content but
9827 # a different time than the current file will have its md5 signature
9828 # recomputed during a check for a rerun. But when both time and size
9829 # are unchanged, the test is optimized by assuming no change, and it
9830 # doesn't do the md5 calculation.
9831 #
9832 # **However**, we will not update the state of the user files (i.e.,
9833 # the non-generated files). This is because when the user notices an
9834 # error during a run, they may correct the error in a .tex file say,
9835 # but both too late to trigger a *latex and too early to be a post-make
9836 # changed. Then it is correct to compare the current state of a user
9837 # source file with its state just before the last run.
9838 #
9839 # In addition, we only update the file state for active rules, i.e.,
9840 # those that the current use of make is supposed to have made
9841 # up-to-date.
9842 # Only do file-state update if something was run, otherwise it's work
9843 # for nothing.
9844
9845 if ($runs_total > 0) {
9846 rdb_for_some( [rdb_accessible()], \&rdb_update_gen_files );
9847 rdb_write( $fdb_name );
9848 }
9849 else { print "$My_name: Nothing to do for '$texfile_name'.\n"; }
9850
9851 # Diagnostics
9852 my @missing_bib = ();
9853 my @bibx_vetoed = ();
9854 rdb_for_some( [rdb_accessible()],
9855 sub{ if ( $rule =~ /^(biber|bibtex)/ ) {
9856 my $veto = $$PHextra{bibx_vetoed};
9857 if ( $veto ) {
9858 push @bibx_vetoed, $rule;
9859 if ( (ref($veto) eq 'ARRAY') && (@$veto) ) { push @missing_bib, @$veto; }
9860 }
9861 }
9862 }
9863 );
9864 if (@bibx_vetoed && ! $silent) {
9865 show_array(
9866 "\n$My_name: The following rule(s) were vetoed from being run, because of\n".
9867 "the setting for the non-use/conditional use of bibtex/biber:",
9868 sort( @bibx_vetoed )
9869 );
9870 if ($bibtex_use == 0) { print "Reason: I am configured not to use bibtex/biber\n"; }
9871 elsif (@missing_bib) {
9872 show_array(
9873 "Reason: I am configured only to use bibtex/biber if all .bib files exist,\n".
9874 "but the following didn't:",
9875 uniqs( @missing_bib )
9876 );
9877 }
9878 }
9879 if ($#primary_warning_summary > -1) {
9880 # N.B. $mult_defined, $bad_reference, $bad_character, $bad_citation also available here.
9881 show_array( "$My_name: Summary of warnings from last run of *latex:",
9882 @primary_warning_summary );
9883 }
9884 if ( ($#warning_list >= 0) && !$silence_logfile_warnings ) {
9885 warn "$My_name: ====Undefined refs and citations with line #s in .tex file:\n";
9886 for (my $i = 0; $i <= $#warning_list; $i++) {
9887 if ($i >= $max_logfile_warnings ) {
9888 warn " And ", $#warning_list + 1 - $i, " more --- see log file '$log_name'\n";
9889 last;
9890 }
9891 warn " $warning_list[$i]\n";
9892 }
9893 }
9894
9895 if (! $silent) {
9896 if ($failure && $force_mode) {
9897 print "$My_name: Errors, in force_mode: so I tried finishing targets\n";
9898 }
9899 elsif ($failure) {
9900 print "$My_name: Errors, so I did not complete making targets\n";
9901 }
9902 else {
9903 # local @dests = ( $current_primary, @pre_primary, @post_primary, @unusual_one_time );
9904 my @rules = ( $current_primary, @post_primary, @unusual_one_time );
9905 my @dests = ();
9906 rdb_for_some( [@rules], sub{ push @dests, $$Pdest if ($$Pdest); } );
9907 print "$My_name: All targets (@dests) are up-to-date\n";
9908 }
9909 }
9910
9911 rdb_for_some( [keys %rule_db],
9912 sub{
9913 foreach my $s_rule (keys %$PHsource_rules) {
9914 $$PHsource_rules{$s_rule} = $pass{$s_rule};
9915 }
9916 }
9917 );
9918 return $failure;
9919 } #END rdb_make
9920
9921 #-------------------
9922
9923 sub rdb_show_rule_errors {
9924 my @errors = ();
9925 my @warnings = ();
9926 rdb_for_actives(
9927 sub {
9928 my $message_tail = "";
9929 if ( $$Plast_result_info eq 'PREV' ) {
9930 $message_tail = " in previous round of document compilation.";
9931 }
9932 elsif ( $$Plast_result_info eq 'CACHE' ) {
9933 $message_tail = " in previous invocation of $my_name.";
9934 }
9935 if ($$Plast_message ne '') {
9936 if ($$Plast_result == 200) {
9937 push @warnings, "$rule: $$Plast_message";
9938 }
9939 else {
9940 push @errors, "$rule: $$Plast_message";
9941 }
9942 }
9943 elsif ($$Plast_result == 1) {
9944 push @errors, "$rule: failed to create output file$message_tail";
9945 }
9946 elsif ($$Plast_result == 2) {
9947 push @errors, "$rule: gave an error$message_tail";
9948 }
9949 elsif ($$Prun_time == 0) {
9950 # This can have innocuous causes. So don't report
9951 }
9952 }
9953 );
9954 if ($#warnings > -1) {
9955 show_array( "Collected warning summary (may duplicate other messages):". @warnings );
9956 }
9957 if ($#errors > -1) {
9958 show_array( "Collected error summary (may duplicate other messages):", @errors );
9959 }
9960 return $#errors+1;
9961 }
9962
9963 #-------------------
9964
9965 sub rdb_make1 {
9966 # ???!!! Rethink how $$Pout_of_date is reset at end.
9967 # Call: rdb_make1
9968 # Helper routine for rdb_make.
9969 # Carries out make at level of given rule (all data available).
9970 # Assumes contexts for recursion, make, and rule, and
9971 # assumes that source files for the rule are to be considered
9972 # up-to-date.
9973 our ($rule, %pass, $runs, $runs_total, $too_many_passes, $newrule_nofile);
9974
9975 if ($diagnostics) { print " Make for rule '$rule'\n"; }
9976 # Is this needed? Yes; rdb_make1 is called on a sequence of rules and
9977 # if one gives an error, then it provides source files directly or
9978 # indirectly to later rules, which should not be run.
9979 if ($failure && ! $force_mode) {return;}
9980
9981 # Rule may have been created since last run. Just in case we didn't,
9982 # define $pass{$rule} elsewhere, do it here:
9983 if ( ! defined $pass{$rule} ) {$pass{$rule} = 0; }
9984
9985 my %changes = ();
9986 if ( ! rdb_rerun_needed(\%changes, 0) ) {
9987 my $veto = $$PHextra{bibx_vetoed};
9988 if ($veto && ! $silent ) {
9989 warn "$My_name: Veto of running of '$rule' (\$bibtex_use=$bibtex_use)\n";
9990 }
9991 return;
9992 }
9993
9994 if (!$silent) {
9995 print "$My_name: applying rule '$rule'...\n";
9996 &rdb_diagnose_changes2( \%changes, "Rule '$rule': ", 0 );
9997 }
9998
9999 # Set this in case of early exit:
10000 # ???!!! Check I am setting $missing_dvi_pdf correctly.
10001 if ( $$Pdest && (! -e $$Pdest) && ( $$Pcmd_type eq 'primary' ) ) {
10002 $missing_dvi_pdf = $$Pdest;
10003 }
10004 # We are applying the rule, so its source file state for when it was
10005 # last made should be as of now. This is done in the subroutines that
10006 # do the actual run, to allow for possible calls to them from other
10007 # places. (Actually only rdb_run1, now.)
10008
10009 # The actual run
10010 my $return = 0; # Return code from called routine
10011
10012 if ( $pass{$rule} >= $max_repeat ) {
10013 # Avoid infinite loop by having a maximum repeat count
10014 # Getting here represents some kind of weird error.
10015 warn "$My_name: Maximum runs of $rule reached ",
10016 "without getting stable files\n";
10017 $too_many_passes = 1;
10018 # Treat rule as completed, else in -pvc mode get infinite reruns:
10019 $$Pout_of_date = 0;
10020 $failure = 1;
10021 $failure_msg = "'$rule' needed too many passes";
10022 return;
10023 }
10024
10025 $runs++;
10026 $runs_total++;
10027
10028 $pass{$rule}++;
10029
10030 warn_running( "Run number $pass{$rule} of rule '$rule'" );
10031 $return = &rdb_run1;
10032
10033 if ($$Pchanged) {
10034 $newrule_nofile = 1;
10035 $return = 0;
10036 }
10037 elsif ( $$Pdest && ( !-e $$Pdest ) && (! $failure) ){
10038 # If there is a destination to make, but for some reason
10039 # it did not get made, and an error condition wasn't set already
10040 # in $failure, then a priori there appears to be an error
10041 # condition, i.e., the run failed. But there are some important
10042 # cases in which this is a wrong diagnosis.
10043 if ( ( $$Pcmd_type eq 'cusdep') && $$Psource && (! -e $$Psource) ) {
10044 # However, if the rule is a custom dependency, this is not by
10045 # itself an error, if also the source file does not exist. In
10046 # that case, we may have the situation that (1) the dest file is no
10047 # longer needed by the tex file, and (2) therefore the user
10048 # has deleted the source and dest files. After the next
10049 # latex run and the consequent analysis of the log file, the
10050 # cusdep rule will no longer be needed, and will be removed.
10051
10052 # So in this case, do NOT report an error
10053 $$Pout_of_date = 0;
10054 }
10055 elsif ($$Pcmd_type eq 'primary' ) {
10056 # For a primary rule, i.e., *latex, not to produce the
10057 # expected output file may not be an error condition.
10058 # Diagnostics were handled in parsing the log file.
10059 # Special action in main loop in rdb_make
10060 $missing_dvi_pdf = $$Pdest;
10061 }
10062 elsif ($return == -2) {
10063 # Missing output file was reported to be NOT an error
10064 $$Pout_of_date = 0;
10065 }
10066 else {
10067 $failure = 1;
10068 }
10069 }
10070 if ( ($return != 0) && ($return != -2) ) {
10071 $failure = 1;
10072 $$Plast_result = 2;
10073 if ( !$$Plast_message ) {
10074 $$Plast_message = "Run of rule '$rule' gave a non-zero error code";
10075 }
10076 }
10077 foreach ( keys %$PHsource_rules ) {
10078 $$PHsource_rules{$_} = $pass{$_};
10079 }
10080 } #END rdb_make1
10081
10082 #************************************************************
10083
10084 sub rdb_run1 {
10085 # Assumes context for: rule.
10086 # Unconditionally apply the rule
10087 # Returns return code from applying the rule.
10088 # Otherwise: 0 on other kind of success,
10089 # -1 on error,
10090 # -2 when missing dest_file is to be ignored
10091 # -3 for situation like biber with malformed bcf file:
10092 # missing dest_file that can't be made without
10093 # change of source file
10094 # error is to be reported
10095 # corrupt source file has been deleted/renamed.
10096
10097 # Defaults for summary of results of run.
10098 $$Prun_time = time();
10099
10100 $$Pchanged = 0; # No special changes in files
10101 $$Plast_result = 0;
10102 $$Plast_result_info = 'CURR';
10103 $$Plast_message = '';
10104 my $latex_like = ($$Pcmd_type eq 'primary');
10105
10106 # Return value for external command:
10107 my $return = 0;
10108
10109 # Source file data, by definition, correspond to the file state just
10110 # before the latest run, and the run_time to the time just before the run:
10111 if ($latex_like) {
10112 # For *latex, we will generate the list of generated files from the
10113 # analysis of the results of the run. So before the run we must
10114 # reset the list of generated files saved in the rule data. Otherwise
10115 # it can continue to contain out-of-date items left from the previous
10116 # run. (Think bibtopic, which writes bbl files!)
10117 #
10118 # This reset is not used/needed for other rules, since normally no
10119 # analysis of a log file (or similar) is made to find generated
10120 # files. The set of extra generated files beyond the main
10121 # destination file is hard wired into the rule definition.
10122 #
10123 &rdb_initialize_generated;
10124 }
10125 # Now set the current state of the files
10126 &rdb_update_files;
10127
10128 # Find any internal command
10129 my @int_args = @$PAint_cmd;
10130 my $int_cmd = shift @int_args;
10131 my @int_args_for_printing = @int_args;
10132 foreach (@int_args_for_printing) {
10133 if ( ! defined $_ ) { $_ = 'undef'; }
10134 }
10135
10136 # ========== Now the actual run of the command or ... for the rule ==========
10137 # But first save current total processing time for the process, so that after
10138 # the run of the command for the rule we can measure the processing time of
10139 # the rule (without overhead from other work latexmk does):
10140
10141 if ($latex_like) { run_hooks( 'before_xlatex' ); }
10142
10143 my $time_start = processing_time();
10144
10145 if ($int_cmd) {
10146 print "For rule '$rule', use internal command '\&$int_cmd( @int_args_for_printing )' ...\n"
10147 if $diagnostics;
10148 no strict "refs";
10149 $return = &$int_cmd( @int_args );
10150 }
10151 elsif ($$Pext_cmd) {
10152 $return = &Run_subst() / 256;
10153 }
10154 else {
10155 warn "$My_name: Either a bug OR a configuration error:\n",
10156 " No command provided for '$rule'\n";
10157 traceback();
10158 $return = -1;
10159 $$Plast_result = 2;
10160 $$Plast_message = "Bug or configuration error; incorrect command type";
10161 }
10162 add_timing( processing_time() - $time_start, $rule );
10163
10164 #============================================================================
10165
10166
10167 # Analyze the results of the run, the first step of which is highly rule
10168 # dependent, and may reassess the return code in $return.
10169 # ????? Probably it would be best at a later revision to have analysis
10170 # subroutines for each special case instead of in-line code here; there
10171 # could possibly a user-configurable per-rulehook.
10172 #
10173 $$Pout_of_date = $$Pout_of_date_user = 0;
10174 if ($latex_like) {
10175 correct_locations();
10176 run_hooks( 'after_xlatex' );
10177 $return = analyze_latex_run( $return );
10178 run_hooks( 'after_xlatex_analysis' );
10179 }
10180 elsif ( $rule =~ /^biber/ ) {
10181 after_biber( \$return );
10182 }
10183 elsif ( $rule =~ /^bibtex/ ) {
10184 after_bibtex( \$return );
10185 }
10186 else {
10187 # No special analysis for other rules
10188 }
10189 if ($$Pdest eq $pdf_final) {
10190 if ( run_hooks( 'after_main_pdf' ) ) {
10191 warn "$My_name: ======Some hook failed.\n";
10192 $return = -1;
10193 }
10194 }
10195
10196 # General
10197 $updated = 1;
10198 if ( ($$Plast_result == 0) && ($return != 0) && ($return != -2) ) {
10199 $$Plast_result = 2;
10200 if ($$Plast_message eq '') {
10201 $$Plast_message = "Command for '$rule' gave return code $return";
10202 if ($rule =~ /^(pdf|lua|xe|)latex/) {
10203 if ( test_gen_file($log_name) ) {
10204 $$Plast_message .=
10205 "\n Refer to '$log_name' and/or above output for details";
10206 }
10207 else {
10208 $$Plast_message .=
10209 "\n Serious error that appeared not to generate a log file.";
10210 }
10211 }
10212 elsif ($rule =~ /^makeindex/) {
10213 $$Plast_message .= "\n Refer to '${aux_dir1}${root_filename}.ilg' for details";
10214 }
10215 }
10216 }
10217 elsif ( $$Pdest && (! -e $$Pdest) && ($return != -2) ) {
10218 $$Plast_result = 1;
10219 }
10220 return $return;
10221 } # END rdb_run1
10222
10223 #-----------------
10224
10225 sub Run_subst {
10226 # Call: Run_subst( cmd, msg, options, source, dest, base )
10227 # Runs command with substitutions.
10228 # If an argument is omitted or undefined, it is replaced by a default:
10229 # cmd is the command to execute
10230 # msg is whether to print a message:
10231 # 0 for not, 1 according to $silent setting, 2 always
10232 # options, source, dest, base: correspond to placeholders.
10233 # Substitutions:
10234 # %S=source, %D=dest, %B=base, %R=root=base for latex, %O=options,
10235 # %T=texfile,
10236 # %V=$aux_dir, %W=$out_dir, %Y=$aux_dir1, %Z=$out_dir1
10237 # This is a globally usable subroutine, and works in a rule context,
10238 # and outside.
10239 # Defaults:
10240 # cmd: $$Pext_cmd if defined, else '';
10241 # msg: 1
10242 # options: ''
10243 # source: $$Psource if defined, else $texfile_name;
10244 # dest: $$Pdest if defined, else $view_file, else '';
10245 # base: $$Pbase if defined, else $root_filename;
10246
10247 my ($ext_cmd, $msg, $options, $source, $dest, $base ) = @_;
10248
10249 $ext_cmd ||= ( $Pext_cmd ? $$Pext_cmd : '' );
10250 $msg = ( defined $msg ? $msg : 1 );
10251 $options ||= '';
10252 $source ||= ( $Psource ? $$Psource : $texfile_name );
10253 $dest ||= ( $Pdest ? $$Pdest : ( $view_file || '' ) );
10254 $base ||= ( $Pbase ? $$Pbase : $root_filename );
10255
10256 if ( $ext_cmd eq '' ) {
10257 return 0;
10258 }
10259
10260 #Set character to surround filenames:
10261 my %subst = (
10262 '%A' => $quote.$tex_basename.$quote,
10263 '%B' => $quote.$base.$quote,
10264 '%D' => $quote.$dest.$quote,
10265 '%O' => $options,
10266 '%S' => $quote.$source.$quote,
10267 '%R' => $quote.$root_filename.$quote,
10268 '%S' => $quote.$source.$quote,
10269 '%T' => $quote.$texfile_name.$quote,
10270 '%V' => $quote.$aux_dir.$quote,
10271 '%W' => $quote.$out_dir.$quote,
10272 '%Y' => $quote.$aux_dir1.$quote,
10273 '%Z' => $quote.$out_dir1.$quote,
10274 '%%' => '%' # To allow literal %B, %R, etc, by %%B.
10275 );
10276 if ($pre_tex_code) {
10277 $subst{'%U'} = $quote.$pre_tex_code.$quote;
10278 $subst{'%P'} = "$quote$pre_tex_code\\input{$source}$quote";
10279 }
10280 else {
10281 $subst{'%U'} = '';
10282 $subst{'%P'} = $subst{'%S'};
10283 }
10284 if ( ($^O eq "MSWin32" ) && $MSWin_back_slash ) {
10285 foreach ( '%R', '%B', '%T', '%S', '%D', '%Y', '%Z' ) {
10286 $subst{$_} =~ s(/)(\\)g;
10287 }
10288 }
10289
10290 my @tokens = split /(%.)/, $ext_cmd;
10291 foreach (@tokens) {
10292 if (exists($subst{$_})) { $_ = $subst{$_}; }
10293 }
10294 $ext_cmd = join '', @tokens;
10295 my ($pid, $return) =
10296 ( ($msg == 0) || ( ($msg == 1) && $silent ) )
10297 ? &Run($ext_cmd)
10298 : &Run_msg($ext_cmd);
10299 return $return;
10300 } #END Run_subst
10301
10302
10303 #************************************************************
10304
10305 sub analyze_latex_run {
10306 # Call: analyze_latex_run(old_ret_code)
10307 # Analyze results of run of *latex (or whatever was run instead) from
10308 # fls, log and aux files, and certain other information.
10309 # It also deals with (a) Change of main output file from one allowed
10310 # extension to another (e.g., dvi -> pdf). (b) Failure of *latex to
10311 # handle -aux-directory option, as with TeXLive.
10312 #
10313 # The argument is the return code as obtained from the run of *latex
10314 # and the returned value is either the original return code or an adjusted
10315 # value depending on the conditions found (e.g., missing file(s) that
10316 # latexmk know how to create).
10317 #
10318 # Assumes contexts for: recursion, make, & rule.
10319 # Assumes (a) the rule is a primary,
10320 # (b) a run has been made,
10321
10322 my $return_latex = shift;
10323 my $return = $return_latex;
10324
10325 # Need to worry about changed directory, changed output extension
10326 # Where else is $missing_dvi_pdf set? Was it initialized?
10327 if (-e $$Pdest) { $missing_dvi_pdf = '';}
10328
10329 # Find current set of source files:
10330 my ($missing_dirs, $PA_missing_subdirs, $bad_warnings) = rdb_set_latex_deps();
10331 if ($bad_warning_is_error && $bad_warnings) {
10332 warn "$My_name: Serious warnings in .log configured to be errors\n";
10333 $return ||= $bad_warnings;
10334 }
10335
10336 # For each file of the kind made by epstopdf.sty during a run,
10337 # if the file has changed during a run, then the new version of
10338 # the file will have been read during the run. Unlike the usual
10339 # case, we will NOT need to redo the primary run because of the
10340 # change of this file during the run. Therefore set the file as
10341 # up-to-date:
10342 rdb_do_files( sub { if ($$Pcorrect_after_primary) {&rdb_update1;} } );
10343
10344 $updated = 1; # Flag that some dependent file has been remade
10345
10346 if ( $diagnostics ) {
10347 print "$My_name: Rules after run: \n";
10348 rdb_show();
10349 }
10350
10351 if ($return_latex && ($missing_dirs ne 'none') ) {
10352 print "Error in *LaTeX, but needed subdirectories in output directory\n",
10353 " were missing and successfully created, so try again.\n"
10354 if (! $silent);
10355 $return = 0;
10356 }
10357 # Summarize issues that may have escaped notice:
10358 @primary_warning_summary = ();
10359 if ($bad_reference) {
10360 push @primary_warning_summary,
10361 "Latex failed to resolve $bad_reference reference(s)";
10362 }
10363 if ($mult_defined) {
10364 push @primary_warning_summary,
10365 "Latex found $mult_defined multiply defined reference(s)";
10366 }
10367 if ($bad_character) {
10368 push @primary_warning_summary,
10369 "=====Latex reported missing or unavailable character(s).\n".
10370 "=====See log file for details.";
10371 }
10372 if ($bad_citation) {
10373 push @primary_warning_summary,
10374 "Latex failed to resolve $bad_citation citation(s)";
10375 }
10376 if ( $diagnostics && ($#primary_warning_summary > -1) ) {
10377 show_array( "$My_name: Summary of warnings:", @primary_warning_summary );
10378 }
10379
10380 return $return;
10381
10382 } #END analyze_latex_run
10383
10384 #************************************************************
10385
10386 sub rdb_remake_needed {
10387 # Usage: rdb_remake_needed( \%change_record, outside-make-loop, rules ...)
10388 # Determine whether one or more of the rules needs to be rerun, and
10389 # return corresponding value.
10390 #
10391 # Report diagnostics (reasons for remake) in the hash referenced by the
10392 # first argument (the hash maps kinds of reason to refs to arrays).
10393 #
10394 # If second argument is true, use rerun criterion suitable to e.g.,
10395 # initial tests in rdb_make, rerun test in
10396 # make_preview_continuous. Otherwise use rerun criterion suitable for
10397 # with rdb_make's looping through rules.
10398 # In the first case, the file state recorded in each rule corresponds
10399 # to the files **after** the of the previous invocation of rdb_make. In
10400 # the second case it corresponds to the state immediately **before**
10401 # the latest run of the rule.
10402
10403 my $PHchanges = shift;
10404 my $outside_make_loop = shift;
10405
10406 my $remake_needed = 0;
10407
10408 %$PHchanges = ();
10409
10410 # ???!!! Need fancier tests: SEE NOTES.
10411
10412 rdb_recurse( [@_],
10413 sub {
10414 my %changes_rule = ();
10415 if( rdb_rerun_needed(\%changes_rule, $outside_make_loop)) {
10416 $remake_needed = 1;
10417 foreach my $kind (keys %changes_rule ) {
10418 push @{$$PHchanges{$kind}}, @{$changes_rule{$kind}};
10419 }
10420 }
10421 }
10422 );
10423
10424 return $remake_needed;
10425 } #END rdb_remake_needed
10426
10427 #************************************************************
10428
10429 sub rdb_user_changes {
10430 # Usage: rdb_user_changes( \%change_record, rules ...)
10431 # Return value: whether any user files changed.
10432 # Report changes in hash pointed to by first argument.
10433 # Side effect: out-of-date rules flagged in $$Pout_of_date.
10434 #
10435 # ???!!!
10436 # Ideally, need specialized versions of rdb_rerun_needed and
10437 # rdb_file_change1 (or special option to those), to restrict attention
10438 # to user_changed files. But for now, fudge our way around that.
10439
10440 my $PHchanges = shift;
10441 my $user_changes = 0;
10442 %$PHchanges = ( 'changed_user' => [],
10443 'rules_to_apply' => []
10444 );
10445
10446 rdb_recurse(
10447 [@_],
10448 sub {
10449 my %changes_rule = ( 'changed_user' => [] );
10450 if ( rdb_rerun_needed(\%changes_rule, 0 )
10451 && @{$changes_rule{changed_user}}
10452 ) {
10453 push @{$$PHchanges{changed_user}},
10454 @{$changes_rule{changed_user}};
10455 push @{$$PHchanges{rules_to_apply}}, $rule;
10456 $user_changes = 1;
10457 if ($user_changes) { $$Pout_of_date = $$Pout_of_date_user = 'Changed user file'; }
10458 else { $$Pout_of_date = $$Pout_of_date_user = 0; }
10459 }
10460 }
10461 );
10462
10463 return $user_changes;
10464 } #END rdb_user_changes
10465
10466 #************************************************************
10467
10468 sub rdb_rerun_needed {
10469 # Usage: rdb_rerun_needed( \%change_record, outside-make-loop )
10470 # Rule context assumed.
10471 # Determines whether a rerun of the rule is needed.
10472 # Return value is whether a rerun is needed.
10473 #
10474 # Report diagnostics (reasons for remake) in the hash referenced by the
10475 # first argument (the hash maps kinds of reason to refs to arrays).
10476 #
10477 # If second argument is true, use rerun criterion suitable to e.g.,
10478 # initial tests in rdb_make, rerun test in
10479 # make_preview_continuous. Otherwise use rerun criterion suitable for
10480 # with rdb_make's looping through rules.
10481 #
10482 our ($rule, %pass);
10483
10484 local our $PHchanges = shift;
10485 local our $outside_make_loop = shift;
10486
10487 my $bibx_rule = ( $rule =~ /^(biber|bibtex)/ );
10488
10489 # File level routine reports its results in %$PHchanges: maps kind of
10490 # change to ref to array of files with that kind of change.
10491 %$PHchanges = ();
10492 foreach ('changed', 'changed_source_rules', 'changed_user',
10493 'disappeared_gen_other', 'disappeared_gen_this',
10494 'disappeared_user', 'no_dest', 'other', 'rules_to_apply' )
10495 { $$PHchanges{$_} = []; }
10496
10497 my $rerun_needed = $$Pout_of_date;
10498 if ($rerun_needed) {
10499 push @{$$PHchanges{other}},
10500 "Rerun of '$rule' forced or previously required:\n Reason or flag: '$rerun_needed'";
10501 goto rdb_rerun_needed_CLEAN_UP;
10502 }
10503
10504 my $user_deleted_is_changed =
10505 ( ($user_deleted_file_treated_as_changed == 1)
10506 && (! $preview_continuous_mode)
10507 )
10508 || ($user_deleted_file_treated_as_changed == 2);
10509
10510 $$Pcheck_time = time();
10511
10512 our $dest_mtime;
10513 local $dest_mtime = 0;
10514 $dest_mtime = get_mtime($$Pdest) if ($$Pdest);
10515
10516 rdb_do_files( \&rdb_file_change1);
10517 if (! $outside_make_loop) {
10518 while ( my ($s_rule, $l_pass) = each %$PHsource_rules ) {
10519 # %$PHsource_rules is about rules on which the current rule
10520 # depends, but for which this dependence is not determined by
10521 # the source rules of the set of known source files.
10522 # Use pass-count criterion to determine out-of-dateness for these.
10523 #
10524 if ( defined $pass{$s_rule}
10525 && ($pass{$s_rule} > $l_pass)
10526 )
10527 {
10528 push @{$$PHchanges{changed_source_rules}}, $s_rule;
10529 $rerun_needed = 1;
10530 }
10531 }
10532 }
10533
10534 # ???!!!: Comments about disappeared files.
10535 # Relevant situations I know of:
10536 # a. \input (or c.) of a file, and file deleted. No other version.
10537 # b. Like a., but file of the correct name exists in
10538 # source-file-search path; the earlier source file version may for
10539 # example have been an override for a standard file.
10540 # c. There's a chain of input-if-file-exists cases, where the first
10541 # file found in a list of files is used. Then deleting the file
10542 # found on the previous run merely results in the next run using
10543 # the next file in the list (if there is one, else the situation
10544 # is as at a..
10545 # d. File was deleted, either by user or automatically by something,
10546 # and the file can be regenerated. (Note: If an aux or bbl file
10547 # (etc) persistently causes errors, then after correcting, e.g., a
10548 # relevant .tex file, then a clean rerun can be triggered by
10549 # deleting the offending file.)
10550 # Need tests: Has the file a from rule? If so it can be made, and
10551 # current rule shouldn't be rerun now.
10552 # **But** it's different if the rule that makes in
10553 # Is the file the main source file? If so problems will
10554 # normally happen when trying to run rule.
10555 # Can the file be found by kpsewhich? If so, is it the
10556 # main source of the rule?
10557 # Need to mention missing files at end of run.
10558
10559 foreach my $kind (keys %$PHchanges) {
10560 if (($kind eq 'disappeared_user') && !$user_deleted_is_changed)
10561 { #???!!! Delete entry, as it is no longer a reason for rerun.
10562 $$PHchanges{$kind} = [];
10563 }
10564 elsif ($kind eq 'disappeared_gen_other') {
10565 # It's the generating rule of the file that needs to be run,
10566 # not this rule, to remake the missing file. So we should not
10567 # set the current rule to be rerun. A rerun of the current rule
10568 # will be triggered once the file-generating rule has generates
10569 # the file, unless, of course, the generated file is identical
10570 # to the version that got deleted.
10571 # ????!!! should the disappeared_gen_other item in the hash be
10572 # emptied out?
10573 }
10574 elsif ( @{$$PHchanges{$kind}} ) {
10575 $rerun_needed = 1;
10576 }
10577 }
10578
10579 # Non-source-file-change reasons for rerun:
10580 if ( ( ($$Prun_time == 0) || ( $$Plast_result =~ /^-1/ ) )
10581 && ( $$Pcmd_type eq 'primary' ) )
10582 {
10583 # Never run. Only use this test with primary, so we can get
10584 # dependency information, which is essential to latexmk's
10585 # functioning. Other rules: there appears to be danger
10586 # of, e.g., rerunning many cusdeps when their destinations have
10587 # already been made and we used time criterion for deciding whether
10588 # to run the rule.
10589 push @{$$PHchanges{never_run}}, $rule;
10590 $rerun_needed = $rule;
10591 }
10592 if ( $$Pdest && (! -e $$Pdest) && ( $$Plast_result <= 0 ) ) {
10593 # No dest. But not if last run gave error, for then we should not
10594 # rerun rule until there's a change in source file(s), which
10595 # presumably contain the cause of the error.
10596 # But there are other reasons for not rerunning:
10597 if ( $$Pcmd_type eq 'delegated' ) {
10598 # Delegate to destination rule
10599 }
10600 elsif ( $$PHextra{bibx_vetoed} ) {
10601 # Previous attempt at a run of biber/bibtex was vetoed
10602 # So it's pointless to rerun it unless there was some
10603 # other change, which will have been detected.
10604 }
10605 else {
10606 $rerun_needed = 1;
10607 push @{$$PHchanges{no_dest}}, $rule;
10608 }
10609 }
10610
10611 rdb_rerun_needed_CLEAN_UP:
10612 if ( $$Psource && (! -e $$Psource) && ( $$Pcmd_type ne 'primary' ) ) {
10613 # Main source file doesn't exist, and rule is NOT primary.
10614 # No action, since a run is pointless. Primary is different:
10615 # file might be found elsewhere (by kpsearch from *latex),
10616 # while non-existence of main source file is a clear error.
10617 $rerun_needed = 0;
10618 }
10619 foreach my $file ( @{$$PHchanges{changed}} ) {
10620 if ( ! $from_rules{$file} ) {
10621 push @{$$PHchanges{changed_user}}, $file;
10622 }
10623 }
10624 $$Pno_history = 0; # See comments in definition of %rule_db.
10625 if ( $bibx_rule ) {
10626 # Check whether run of biber/bibtex rule is to be vetoed.
10627 # Default to no veto:
10628 $$PHextra{bibx_vetoed} = 0;
10629 if ($rerun_needed) {
10630 if ($bibtex_use == 0) {
10631 # Do not use biber/bibtex at all
10632 $rerun_needed = 0;
10633 $$PHextra{bibx_vetoed} = 1;
10634 }
10635 elsif ($bibtex_use < 1.9) {
10636 # Conditional bibtex/biber use, if all .bib files exist
10637 my @missing_bib_files = ();
10638 foreach ( keys %$PHsource ) {
10639 if ( ( /\.bib$/ ) && (! -e $_) ) {
10640 push @missing_bib_files, $_;
10641 }
10642 }
10643 if ( @missing_bib_files ) {
10644 $rerun_needed = 0;
10645 $$PHextra{bibx_vetoed} = [ sort @missing_bib_files ];
10646 }
10647 }
10648 if ($$PHextra{bibx_vetoed}) {
10649 # Avoid propagating error state from previous invocations,
10650 # since things might have changed if I did a run instead of
10651 # vetoing it. A saved non-zero error state tends to stop
10652 # certain things from being run.
10653 $$Plast_result = 0;
10654 }
10655
10656 }
10657 }
10658 if ($rerun_needed) {
10659 push @{$$PHchanges{rules_to_apply}}, $rule;
10660 }
10661 return $rerun_needed;
10662 } #END rdb_rerun_needed
10663
10664 #************************************************************
10665
10666 sub rdb_file_change1 {
10667 # Call: &rdb_file_change1
10668 # Assumes rule and file context. Assumes $dest_mtime set.
10669 # Flag whether $file in $rule has changed or disappeared.
10670 our ($rule, $file, $PHchanges, $outside_make_loop, $dest_mtime);
10671
10672 my $check_time_argument =
10673 ($outside_make_loop ? 0 : max($$Pcheck_time, $$Prun_time) );
10674
10675
10676 # For files that won't be read until after they are written, ignore any changes:
10677 if (exists $$PHrewritten_before_read{$file}) {
10678 return;
10679 }
10680 my ($new_time, $new_size, $new_md5) = fdb_get($file, $check_time_argument );
10681 my $ext_no_period = ext_no_period( $file );
10682
10683 my $generated = 0;
10684 if (exists $from_rules{$file}) {
10685 if ($from_rules{$file} eq $rule) { $generated = 1; }
10686 else { $generated = 2; }
10687 }
10688
10689 if ( ($new_size < 0) && ($$Psize < 0) ) {
10690 return;
10691 }
10692
10693 if ( ($new_size < 0) && ($$Psize >= 0) ) {
10694 if ($generated == 2) {
10695 # Non-existent file generated by another rule. It's up to that
10696 # rule to remake it.
10697 push @{$$PHchanges{disappeared_gen_other}}, $file;
10698 }
10699 elsif ($generated == 1) {
10700 # Non-existent file generated by this rule.
10701 push @{$$PHchanges{disappeared_gen_this}}, $file;
10702 }
10703 # ???!!! Keep this, or only for primary, or not?
10704 # elsif ( my @kpse = kpsewhich( $file ) ) {
10705 # print "After '$file' disappeared for '$rule', kpsewhich found it at\n:",
10706 # " '$kpse[0]'.\n";
10707 # push @{$$PHchanges{changed}}, $file;
10708 # }
10709 else {
10710 push @{$$PHchanges{disappeared_user}}, $file;
10711 }
10712 }
10713 # For other kinds of file change, primarily use md5 signature to
10714 # determine whether file contents have changed.
10715 # Backup by file size change, but only in the case where there is
10716 # no pattern of lines to ignore in testing for a change
10717 elsif ( ($new_md5 ne $$Pmd5)
10718 || (
10719 (! exists $hash_calc_ignore_pattern{$ext_no_period})
10720 && ($new_size != $$Psize)
10721 )
10722 ) {
10723 push @{$$PHchanges{changed}}, $file;
10724 }
10725 elsif ( $new_time != $$Ptime ) {
10726 $$Ptime = $new_time;
10727 }
10728 # If there's no history, supplement by file-time criterion, i.e., is
10729 # this source file time later than destination file file
10730 if ( $$Pno_history && ( $new_time > $dest_mtime ) ) {
10731 push @{$$PHchanges{changed}}, $file;
10732 }
10733
10734 } #END rdb_file_change1
10735
10736 #************************************************************
10737
10738 sub rdb_diagnose_changes2 {
10739 # Call: rdb_diagnose_changes2( \%changes, heading, show_out_of_date_rules )
10740
10741 my ($PHchanges, $heading, $show_out_of_date_rules) = @_;
10742
10743 my %labels = (
10744 'changed' => 'Changed files or newly in use/created',
10745 );
10746
10747 print "$heading Reasons for rerun\n";
10748 foreach my $kind (sort keys %$PHchanges) {
10749 if ( (! $show_out_of_date_rules) && ($kind eq 'rules_to_apply' ) )
10750 { next; }
10751 my $label = $labels{$kind} || "Category '$kind'";
10752 if ( @{$$PHchanges{$kind}} ) {
10753 show_array( "$label:",
10754 uniqs( @{$$PHchanges{$kind}} ) );
10755 }
10756 }
10757 print "\n";
10758 } #END rdb_diagnose_changes2
10759
10760 #************************************************************
10761 #************************************************************
10762 #************************************************************
10763 #************************************************************
10764
10765 #************************************************************
10766 #************************************************************
10767 #************************************************************
10768 #************************************************************
10769
10770 # Routines for convenient looping and recursion through rule database
10771 # ================= NEW VERSION ================
10772
10773 # There are several places where we need to loop through or recurse
10774 # through rules and files. This tends to involve repeated, tedious
10775 # and error-prone coding of much book-keeping detail. In particular,
10776 # working on files and rules needs access to the variables involved,
10777 # which either involves direct access to the elements of the database,
10778 # and consequent fragility against changes and upgrades in the
10779 # database structure, or involves lots of routines for reading and
10780 # writing data in the database, then with lots of repetitious
10781 # house-keeping code.
10782 #
10783 # The routines below provide a solution. Looping and recursion
10784 # through the database are provided by a set of basic routines where
10785 # each necessary kind of looping and iteration is coded once. The
10786 # actual actions are provided as references to action subroutines.
10787 # (These can be either actual references, as in \&routine, or
10788 # anonymous subroutines, as in sub{...}, or aas a zero value 0 or an
10789 # omitted argument, to indicate that no action is to be performed.)
10790 #
10791 # When the action subroutine(s) are actually called, a context for the
10792 # rule and/or file (as appropriate) is given by setting named
10793 # variables to REFERENCES to the relevant data values. These can be
10794 # used to retrieve and set the data values. As a convention,
10795 # references to scalars are given by variables named start with "$P",
10796 # as in "$Pdest", while references to arrays start with "$PA", as in
10797 # "$PAint_cmd", and references to hashes with "$PH", as in "$PHsource".
10798 # After the action subroutine has finished, checks for data
10799 # consistency may be made.
10800 #
10801 # The only routines that actually use the database structure and need
10802 # to be changed if that is changed are: (a) the routines rdb_one_rule
10803 # and rdb_one_file that implement the calling of the action subroutines,
10804 # (b) routines for creation of single rules and file items, and (c) to
10805 # a lesser extent, the routine for destroying a file item.
10806 #
10807 # Note that no routine is provided for destroying a rule. During a
10808 # run, a rule, with its source files, may become inaccessible or
10809 # unused. This happens dynamically, depending on the dependencies
10810 # caused by changes in the source file or by error conditions that
10811 # cause the computation of dependencies, particular of latex files, to
10812 # become wrong. In that situation the files certainly come and go in
10813 # the database, but subsidiary rules, with their content information
10814 # on their source files, need to be retained so that their use can be
10815 # reinstated later depending on dynamic changes in other files.
10816 #
10817 # However, there is a potential memory leak unless some pruning is
10818 # done in what is written to the fdb file. (Probably only accessible
10819 # rules and those for which source files exist. Other cases have no
10820 # relevant information that needs to be preserved between runs.)
10821
10822 #
10823 #
10824
10825
10826 #************************************************************
10827
10828 # First the top level routines for recursion and iteration
10829
10830 #************************************************************
10831
10832 sub rdb_recurse {
10833 # Call: rdb_recurse( rule | [ rules],
10834 # \&rule_act1, \&file_act1, \&file_act2,
10835 # \&rule_act2 )
10836 # The actions are pointers to subroutines, and may be null (0, or
10837 # undefined) to indicate no action to be applied.
10838 # Recursively acts on the given rules and all ancestors:
10839 # foreach rule found:
10840 # apply rule_act1
10841 # loop through its files:
10842 # apply file_act1
10843 # act on its ancestor rule, if any
10844 # apply file_act2
10845 # apply rule_act2
10846 # Guards against loops.
10847 # Access to the rule and file data by local variables, only
10848 # for getting and setting.
10849
10850 # This routine sets a context for anything recursive, with @heads,
10851 # %visited and $depth being set as local variables.
10852
10853 our ($depth, @heads, %visited);
10854 local @heads = ();
10855 my $rules = shift;
10856
10857 # Distinguish between single rule (a string) and a reference to an
10858 # array of rules:
10859 if ( ref $rules eq 'ARRAY' ) { @heads = @$rules; }
10860 else { @heads = ( $rules ); }
10861
10862 # Keep a list of visited rules, used to block loops in recursion:
10863 local %visited = ();
10864 local $depth = 0;
10865
10866 foreach $rule ( @heads ) {
10867 if ( rdb_is_active($rule) ) { rdb_recurse_rule( $rule, @_ ); }
10868 }
10869
10870 } #END rdb_recurse
10871
10872 #************************************************************
10873
10874 sub rdb_for_actives {
10875 # Call: rdb_for_actives( \&rule_act1, \&file_act, \&rule_act2 )
10876 # Loops through all rules and their source files, using the
10877 # specified set of actions, which are pointers to subroutines.
10878 # Sorts rules alphabetically.
10879 # See rdb_for_some for details.
10880 # rdb_for_some( [ sort keys %rule_db ], @_);
10881 rdb_for_some( [ sort &rdb_actives ], @_);
10882 } #END rdb_for_actives
10883
10884 #************************************************************
10885
10886 sub rdb_for_some {
10887 # Call: rdb_for_some( rule | [ rules],
10888 # \&rule_act1, \&file_act, \&rule_act2)
10889 # Actions can be zero, and rules at tail of argument list can be
10890 # omitted. E.g. rdb_for_some( rule, 0, \&file_act ).
10891 # Anonymous subroutines can be used, e.g., rdb_for_some( rule, sub{...} ).
10892 #
10893 # Loops through rules and their source files, using the
10894 # specified set of rules:
10895 # foreach rule:
10896 # apply rule_act1
10897 # loop through its files:
10898 # apply file_act
10899 # apply rule_act2
10900 #
10901 # Rule data and file data are made available in local variables
10902 # for access by the subroutines.
10903
10904 our (@heads);
10905 local @heads = ();
10906 my $rules = shift;
10907 # Distinguish between single rule (a string) and a reference to an
10908 # array of rules:
10909 if ( ref $rules eq 'ARRAY' ) { @heads = @$rules; }
10910 else { @heads = ( $rules ); }
10911
10912 foreach $rule ( @heads ) {
10913 # $rule is implicitly local
10914 &rdb_one_rule( $rule, @_ );
10915 }
10916 } #END rdb_for_some
10917
10918 #************************************************************
10919
10920 # Routines for inner part of recursion and iterations
10921
10922 #************************************************************
10923
10924 sub rdb_recurse_rule {
10925 # Call: rdb_recurse_rule($rule, \&rule_act1, \&file_act1, \&file_act2,
10926 # \&rule_act2 )
10927 # to do the work for one rule, recurisvely called source_rules for
10928 # the sources of the rules.
10929 # Assumes recursion context, i.e. that %visited, @heads, $depth.
10930 # We are overriding actions:
10931 our (%visited, @heads, $depth);
10932 our ($rule, $rule_act1, $new_file_act1, $new_file_act2, $rule_act2);
10933 local ($rule, $rule_act1, $new_file_act1, $new_file_act2, $rule_act2)
10934 = @_;
10935 if (! rdb_is_active($rule)) { return; }
10936 # and must propagate the file actions:
10937 our ( $file_act1, $file_act2 );
10938 local $file_act1 = $new_file_act1;
10939 local $file_act2 = $new_file_act2;
10940 # Prevent loops:
10941 if ( (! $rule) || exists $visited{$rule} ) { return; }
10942 $visited{$rule} = 1;
10943 # Recursion depth
10944 $depth++;
10945 # We may need to repeat actions on dependent rules, without being
10946 # blocked by the test on visited files. So save %visited:
10947 # NOT CURRENTLY USED!! local %visited_at_rule_start = %visited;
10948 # At end, the last value set for %visited wins.
10949 rdb_one_rule( $rule, $rule_act1, \&rdb_recurse_file, $rule_act2 );
10950 $depth--;
10951 } #END rdb_recurse_rule
10952
10953 #************************************************************
10954
10955 sub rdb_recurse_file {
10956 # Call: rdb_recurse_file to do the work for one file.
10957 # This has no arguments, since it is used as an action subroutine,
10958 # passed as a reference in calls in higher-level subroutine.
10959 # Assumes contexts set for: Recursion, rule, and file
10960 our ( $file_act1, $file_act2, $rule_act1, $rule_act2 );
10961 &$file_act1 if $file_act1;
10962 my $from_rule = $from_rules{$file} || '';
10963 rdb_recurse_rule( $from_rule, $rule_act1, $file_act1, $file_act2,
10964 $rule_act2 )
10965 if $from_rule;
10966 &$file_act2 if $file_act2;
10967 } #END rdb_recurse_file
10968
10969 #************************************************************
10970
10971 sub rdb_do_files {
10972 # Assumes rule context, including $PHsource.
10973 # Applies an action to all the source files of the rule.
10974 my $file_act = shift;
10975 my @file_list = sort keys %$PHsource;
10976 foreach my $file ( @file_list ) {
10977 rdb_one_file( $file, $file_act );
10978 }
10979 } #END rdb_do_files
10980
10981 #************************************************************
10982
10983 # Routines for action on one rule and one file. These are the main
10984 # places (in addition to creation and destruction routines for rules
10985 # and files) where the database structure is accessed.
10986
10987 #************************************************************
10988
10989 sub rdb_one_rule {
10990 # Call: rdb_one_rule( $rule, $rule_act1, $file_act, $rule_act2 )
10991 # Sets context for rule and carries out the actions.
10992 #===== Accesses rule part of database structure =======
10993
10994 local $rule = shift;
10995 my ( $rule_act1, $file_act, $rule_act2 ) = @_;
10996 if ( (! $rule) || ! rdb_rule_exists($rule) ) {
10997 die_trace( "$My_name: BUG in call to rdb_one_rule: non-existent rule '$rule'" );
10998 }
10999
11000 local ( $PArule_data, $PHsource, $PHdest, $PHrewritten_before_read,
11001 $PHsource_rules, $PHextra )
11002 = @{$rule_db{$rule}};
11003 local ($Pcmd_type, $Pext_cmd, $PAint_cmd, $Pno_history,
11004 $Psource, $Pdest, $Pbase,
11005 $Pout_of_date, $Pout_of_date_user, $Prun_time, $Pcheck_time,
11006 $Pchanged,
11007 $Plast_result, $Plast_result_info, $Plast_message, $PA_extra_gen )
11008 = Parray( $PArule_data );
11009
11010 &$rule_act1 if $rule_act1;
11011 &rdb_do_files( $file_act ) if $file_act;
11012 &$rule_act2 if $rule_act2;
11013 } #END rdb_one_rule
11014
11015 #************************************************************
11016
11017 sub rdb_activate {
11018 # Usage rdb_activate( rule_names )
11019 # Turns on active flag for the rules
11020 foreach ( @_ ) {
11021 if ( rdb_rule_exists($_) ) { $actives{$_} = 1; }
11022 }
11023 }
11024
11025 #--------------------------------------------------
11026
11027 sub rdb_deactivate {
11028 # Usage rdb_deactivate( rule_names )
11029 # Turns off active flag for the rules
11030 foreach ( @_ ) { delete $actives{$_}; }
11031 }
11032
11033 #--------------------------------------------------
11034
11035 sub rdb_activate_request {
11036 # Usage rdb_activate_request( rule_names )
11037 # Turns on active flag for the rules.
11038 # Adds rules to target_rules list
11039 foreach ( @_ ) {
11040 if ( rdb_rule_exists($_) ) { $actives{$_} = 1; $target_rules{$_} = 1; }
11041 }
11042 }
11043
11044 #--------------------------------------------------
11045
11046 sub rdb_deactivate_derequest {
11047 # Usage rdb_deactivate_derequest( rule_names )
11048 # Turns off active flag for the rules
11049 # Removes rules from target_rules list
11050 foreach ( @_ ) { delete $actives{$_}; delete $target_rules{$_}; }
11051 }
11052
11053 #--------------------------------------------------
11054 sub rdb_is_active {
11055 # Usage rdb_is_active( rule_name )
11056 if ( (exists $actives{$_[0]}) && rdb_rule_exists($_[0]) ) { return 1; }
11057 else { return 0; }
11058 }
11059
11060 #--------------------------------------------------
11061
11062 sub rdb_actives {
11063 # Returns array of active rules
11064 return keys %actives;
11065 }
11066
11067 #************************************************************
11068
11069 sub rdb_one_file {
11070 # Call: rdb_one_file($file, $file_act)
11071 # Sets context for file and carries out the action.
11072 # Assumes $rule context set.
11073 #===== Accesses file part of database structure =======
11074 our $file_act;
11075 local ($file, $file_act) = @_;
11076 if ( (!$file) ||(!exists ${$PHsource}{$file}) ) { return; }
11077 local $PAfile_data = ${$PHsource}{$file};
11078 our $DUMMY; # Fudge until fix rule_db
11079 local ($Ptime, $Psize, $Pmd5, $DUMMY, $Pcorrect_after_primary )
11080 = Parray( $PAfile_data );
11081 &$file_act() if $file_act;
11082 } #END rdb_one_file
11083
11084 #************************************************************
11085
11086 # Routines for creation of rules and file items, and for removing file
11087 # items.
11088
11089 #************************************************************
11090
11091 sub rdb_remove_rule {
11092 # rdb_remove_rule( rule, ... )
11093 foreach my $key (@_) {
11094 delete $rule_db{$key};
11095 delete $actives{$key};
11096 }
11097 }
11098
11099 #************************************************************
11100
11101 sub rdb_create_rule {
11102 # rdb_create_rule( rule, command_type, ext_cmd, int_cmd, DUMMY,
11103 # source, dest, base,
11104 # needs_making, run_time, check_time, set_file_not_exists,
11105 # ref_to_array_of_specs_of_extra_generated_files,
11106 # ref_to_array_of_specs_of_extra_source_files )
11107 # int_cmd is either a string naming a perl subroutine or it is a
11108 # reference to an array containing the subroutine name and its
11109 # arguments.
11110 # Makes rule. Update rule if it already exists.
11111 # Omitted arguments: replaced by 0, '', or [] as needed.
11112 # Rule is made active
11113 # 5th argument DUMMY is argument that used to be used (test_kind), but
11114 # is not used any more. But I keep it there to avoid having to change
11115 # calls, which are not only in the latexmk code itself, but may be in
11116 # latexmkrc files created by others.
11117
11118 # ==== Set rule data from arguments ====
11119 my ( $rule, $cmd_type, $ext_cmd, $PAint_cmd, $DUMMY,
11120 $source, $dest, $base,
11121 $needs_making, $run_time, $check_time, $set_file_not_exists,
11122 $PAextra_gen, $PAextra_source ) = @_;
11123 # Set defaults for undefined arguments
11124 foreach ( $needs_making, $run_time, $check_time, $DUMMY ) {
11125 if (! defined $_) { $_ = 0; }
11126 }
11127 if ($needs_making) {$needs_making = 'Initial set up of rule'; }
11128 foreach ( $cmd_type, $ext_cmd, $PAint_cmd, $source, $dest, $base,
11129 $set_file_not_exists ) {
11130 if (! defined $_) { $_ = ''; }
11131 }
11132 foreach ( $PAextra_gen, $PAextra_source ) {
11133 if (! defined $_) { $_ = []; }
11134 }
11135
11136 my $last_result = -1;
11137 my $last_result_info = '';
11138 my $no_history = ($run_time <= 0);
11139 my $active = 1;
11140 my $changed = 0;
11141
11142 if ( ($source =~ /\"/) || ($dest =~ /\"/) || ($base =~ /\"/) ) {
11143 die "$My_name: Error. In rdb_create_rule to create rule\n",
11144 " '$rule',\n",
11145 " there is a double quote in one of source, destination or base parameters:\n",
11146 " '$source'\n",
11147 " '$dest'\n",
11148 " '$base'\n",
11149 " I cannot handle this. Cause is probably a latexmk bug. Please report it.\n";
11150 }
11151 if ( ref( $PAint_cmd ) eq '' ) {
11152 # It is a single command. Convert to array reference:
11153 $PAint_cmd = [ $PAint_cmd ];
11154 }
11155 else {
11156 # COPY the referenced array:
11157 $PAint_cmd = [ @$PAint_cmd ];
11158 }
11159 $rule_db{$rule} =
11160 [ [$cmd_type, $ext_cmd, $PAint_cmd, $no_history,
11161 $source, $dest, $base,
11162 $needs_making, 0, $run_time, $check_time, $changed,
11163 $last_result, $last_result_info, '', $PAextra_gen ],
11164 {},
11165 {},
11166 {},
11167 {},
11168 {}
11169 ];
11170 foreach my $file ($source, @$PAextra_source ) {
11171 if ($file) { rdb_ensure_file( $rule, $file, undef, $set_file_not_exists ); }
11172 }
11173 rdb_one_rule( $rule, \&rdb_initialize_generated );
11174 if ($active) { rdb_activate($rule); }
11175 else { rdb_deactivate($rule); }
11176 } #END rdb_create_rule
11177
11178 #************************************************************
11179
11180 sub rdb_initialize_generated {
11181 # Assume rule context.
11182 # Initialize hashes of generated files, and of files rewritten before read
11183 %$PHdest = ();
11184 if ($$Pdest) { rdb_add_generated($$Pdest); }
11185 rdb_add_generated(@$PA_extra_gen);
11186
11187 %$PHrewritten_before_read = ();
11188 } #END rdb_initialize_generated
11189
11190 #************************************************************
11191
11192 sub rdb_add_generated {
11193 # Assume rule context.
11194 # Add arguments to hash of generated files, and to global cache
11195 foreach (@_) {
11196 $$PHdest{$_} = 1;
11197 $from_rules{$_} = $rule;
11198 }
11199 } #END rdb_add_generated
11200
11201 #************************************************************
11202
11203 sub rdb_add_rewritten_before_read {
11204 # Assume rule context.
11205 # Add arguments to hash of files rewritten before being read
11206 foreach (@_) { $$PHrewritten_before_read{$_} = 1; }
11207 } #END rdb_add_rewritten_before_read
11208
11209 #************************************************************
11210
11211 sub rdb_remove_generated {
11212 # Assume rule context.
11213 # Remove arguments from hash of generated files
11214 foreach (@_) { delete $$PHdest{$_}; }
11215 } #END rdb_remove_generated
11216
11217 #************************************************************
11218
11219 sub rdb_remove_rewritten_before_read {
11220 # Assume rule context.
11221 # Remove arguments from hash of files rewritten before being read
11222 foreach (@_) { delete $$PHrewritten_before_read{$_}; }
11223 } #END rdb_add_rewritten_before_read
11224
11225 #************************************************************
11226
11227 sub rdb_ensure_file {
11228 # rdb_ensure_file( rule, file[, fromrule[, set_not_exists]] )
11229 # Ensures the source file item exists in the given rule.
11230 # Then if the fromrule is specified, set it for the file item.
11231 # If the item is created, then:
11232 # (a) by default initialize it to current file state.
11233 # (b) but if the fourth argument, set_not_exists, is true,
11234 # initialize the item as if the file does not exist.
11235 # This case is typically used
11236 # (1) when the log file for a run of latex/pdflatex claims
11237 # that the file was non-existent at the beginning of a
11238 # run.
11239 # (2) When initializing rules, when there is no previous
11240 # known run under the control of latexmk.
11241 #============ NOTE: rule and file data set here ===============================
11242 my ( $rule, $new_file, $new_from_rule, $set_not_exists ) = @_;
11243 if ( ! rdb_rule_exists( $rule ) ) {
11244 die_trace( "$My_name: BUG in call to rdb_ensure_file: non-existent rule '$rule'" );
11245 }
11246 if ( ! defined $new_file ) {
11247 die_trace( "$My_name: BUG in call to rdb_ensure_file: undefined file for '$rule'" );
11248 }
11249 if ( ! defined $set_not_exists ) { $set_not_exists = 0; }
11250 rdb_one_rule(
11251 $rule, sub{ if ($set_not_exists) { rdb_ensure_new_files_here($new_file); }
11252 else { rdb_ensure_files_here($new_file); }
11253 }
11254 );
11255 if (defined $new_from_rule ) { $from_rules{$new_file} = $new_from_rule; }
11256 } #END rdb_ensure_file
11257
11258 #************************************************************
11259
11260 sub rdb_ensure_file_multi {
11261 # rdb_ensure_file( rule, file ... )
11262 # Ensures the source files exist in the given rule.
11263 # Like rdb_ensure_file, but without the possible setting of a from rule
11264 # or of the initialization to non-existent file
11265 #============ NOTE: rule and file data set here ===============================
11266 use strict;
11267 my $rule = shift;
11268 my @files = @_;
11269 rdb_one_rule( $rule, sub { rdb_ensure_files_here( @files ); } );
11270 } #END rdb_ensure_file_multi
11271
11272 #************************************************************
11273
11274 sub rdb_ensure_files_here {
11275 # rdb_ensure_files_here( file, ...)
11276 # Assumes rule context
11277 # Ensures the given files are in the source file list.
11278 # For added files, initialize state to current of file,
11279 # as is appropriate if the file was read in latest run of rule
11280 use strict;
11281 our ($rule, $My_name, $PHsource, $Prun_time);
11282 foreach my $file (@_) {
11283 # Use $file, not $_, since called subroutine may change it!
11284 if ( $file =~ /\"/ ) {
11285 warn "$My_name: in rdb_ensure_files_here for rule '$rule', there\n",
11286 " is a double quote in the filename: '$file'.\n",
11287 " I cannot handle this, will ignore this file.\n";
11288 next;
11289 }
11290 if (! exists ${$PHsource}{$file} ) {
11291 ${$PHsource}{$file} = [fdb_get($file, $$Prun_time), '', 0];
11292 }
11293 }
11294 } #END rdb_ensure_files_here
11295
11296 #************************************************************
11297
11298 sub rdb_ensure_new_files_here {
11299 # rdb_ensure_new_files_here( file, ...)
11300 # Assumes rule context
11301 # Ensures the given files are in the source file list.
11302 # For added files, initialize state to non-existent,
11303 # as is appropriate if the file is new to the rule
11304 use strict;
11305 our ($rule, $My_name, $PHsource, @nofile);
11306 foreach my $file (@_) {
11307 if ( $file =~ /\"/ ) {
11308 warn "$My_name: in rdb_ensure_new_files_here for rule '$rule', there\n",
11309 " is a double quote in the filename: '$file'.\n",
11310 " I cannot handle this, will ignore this file.\n";
11311 next;
11312 }
11313 if (! exists ${$PHsource}{$file} ) {
11314 ${$PHsource}{$file} = [@nofile, '', 0];
11315 }
11316 }
11317 } #END rdb_ensure_new_files_here
11318
11319 #************************************************************
11320
11321 sub rdb_remove_files {
11322 # rdb_remove_file( rule, file, ... )
11323 # Removes file(s) for the rule.
11324 my $rule = shift;
11325 if (!$rule) { return; }
11326 my @files = @_;
11327 rdb_one_rule( $rule,
11328 sub{ foreach (@files) { delete ${$PHsource}{$_}; } }
11329 );
11330 } #END rdb_remove_files
11331
11332 #************************************************************
11333
11334 sub rdb_get_extra {
11335 # rdb_get_extra( rule, key )
11336 # Returns value pointed to by key in the rule's extra hash.
11337 # Mostly for use when not in context of the given rule
11338 # or from user code.
11339 use strict;
11340 our $PHextra;
11341 my ($rule, $key) = @_;
11342 my $info = undef;
11343 rdb_one_rule( $rule, sub{ $info = $$PHextra{$key}; } );
11344 return $info;
11345 } #END rdb_get_extra
11346
11347 #************************************************************
11348
11349 sub rdb_get_dest {
11350 # rdb_get_dest( rule )
11351 # Returns destination for the rule.
11352 use strict;
11353 my $rule = $_[0];
11354 my $dest = undef;
11355 rdb_one_rule( $rule, sub{ $dest = $$Pdest; } );
11356 return $dest;
11357 } #END rdb_get_dest
11358
11359 #************************************************************
11360
11361 sub rdb_set_extra {
11362 # rdb_set_extra( rule, key, value )
11363 # Set value pointed to by key in the rule's extra hash.
11364 # Mostly for use when not in context of the given rule,
11365 # or from user code.
11366 use strict;
11367 our $PHextra;
11368 my ($rule, $key, $value) = @_;
11369 rdb_one_rule( $rule, sub{ $$PHextra{$key} = $value; } );
11370 } #END rdb_set_extra
11371
11372 #************************************************************
11373
11374 sub rdb_get_source {
11375 # rdb_get_source( rule )
11376 # Return array of source files for rule.
11377 use strict;
11378 our $PHsource;
11379 my $rule = $_[0];
11380 my @files = ();
11381 rdb_one_rule( $rule, sub{ @files = keys %$PHsource; } );
11382 return @files;
11383 } #END rdb_get_source
11384
11385 #************************************************************
11386
11387 sub rdb_show_source {
11388 # rdb_show_source( rule[, msg] )
11389 # Display sorted source files for rule, preceeded by optional message
11390 use strict;
11391 my ($rule, $msg) = @_;
11392 print( $msg ) if $msg;
11393 show_array( "Source files for '$rule'", sort( rdb_get_source($rule) ));
11394 } #END rdb_show_source
11395
11396 #************************************************************
11397
11398 sub rdb_set_source {
11399 # rdb_set_source( rule, file, ... )
11400 # Set the source file list for rule to given files
11401 use strict;
11402 my $rule = shift;
11403 my @files = @_;
11404 rdb_one_rule( $rule, sub { rdb_set_source_here( @files ); } );
11405 } #END rdb_set_source
11406
11407 #************************************************************
11408
11409 sub rdb_set_source_here {
11410 # rdb_set_source_here( file, ... )
11411 # Set the source file list for current rule to given files
11412 # Rule context assumed.
11413 use strict;
11414 our ( $rule, $PHsource, $Psource );
11415 my @files = @_;
11416 push( @files, $$Psource)
11417 if ($$Psource);
11418 my %deletions = %$PHsource;
11419 foreach (@files) { delete $deletions{$_}; }
11420 rdb_remove_files( $rule, keys %deletions );
11421 rdb_ensure_files_here( @files );
11422 } #END rdb_set_source
11423
11424 #************************************************************
11425
11426 sub rdb_rule_exists {
11427 # Call rdb_rule_exists($rule): Returns whether rule exists.
11428 my $rule = shift;
11429 if (! $rule ) { return 0; }
11430 return exists $rule_db{$rule};
11431 } #END rdb_rule_exists
11432
11433 #************************************************************
11434
11435 sub rdb_file_exists {
11436 # Call rdb_file_exists($rule, $file):
11437 # Returns whether source file item in rule exists.
11438 local ( $rule, $file ) = @_;
11439 my $exists = 0;
11440 rdb_one_rule( $rule,
11441 sub{ $exists = exists( ${$PHsource}{$file} ) ? 1:0; }
11442 );
11443 return $exists;
11444 } #END rdb_file_exists
11445
11446 #************************************************************
11447
11448 sub rdb_update_gen_files {
11449 # Assumes rule context. Update source files of rule to current state,
11450 # but only for source files that are generated by this or another rule.
11451 if ($$PHextra{bibx_vetoed} ) {
11452 # I will NOT update generated source files for vetoed rule, so that
11453 # source file state for the rule corresponds to last actual run of rule
11454 return;
11455 }
11456 rdb_do_files(
11457 sub{ if ( exists $from_rules{$file} ) { &rdb_update1; } }
11458 );
11459 } #END rdb_update_gen_files
11460
11461 #************************************************************
11462
11463 sub rdb_update_files {
11464 # Call: rdb_update_files
11465 # Assumes rule context. Update all source files of rule to current state.
11466 rdb_do_files( \&rdb_update1 );
11467 }
11468
11469 #************************************************************
11470
11471 sub rdb_update1 {
11472 # Call: rdb_update1.
11473 # Assumes file context. Updates file data to correspond to
11474 # current file state on disk
11475 ($$Ptime, $$Psize, $$Pmd5) = fdb_get($file);
11476 }
11477
11478 #************************************************************
11479
11480 sub rdb_set_file1 {
11481 # Call: rdb_set_file1(rule, file, new_time, new_size, new_md5)
11482 # Sets file time, size and md5, in rule data.
11483 my ( $rule, $file, @new_file_data ) = @_;
11484 rdb_for_some( $rule,
11485 sub{ rdb_one_file($file, sub{ ($$Ptime,$$Psize,$$Pmd5)=@new_file_data; } ); }
11486 );
11487 }
11488
11489 #************************************************************
11490
11491 sub rdb_dummy_file {
11492 # Returns file data for non-existent file
11493 # ==== Uses rule_db structure ====
11494 return (0, -1, 0, '');
11495 }
11496
11497 #************************************************************
11498 #************************************************************
11499
11500 # Predefined subroutines for custom dependency
11501
11502 sub cus_dep_delete_dest {
11503 # This subroutine is used for situations like epstopdf.sty, when
11504 # the destination (target) of the custom dependency invoking
11505 # this subroutine will be made by the primary run provided the
11506 # file (destination of the custom dependency, source of the
11507 # primary run) doesn't exist.
11508 # It is assumed that the resulting file will be read by the
11509 # primary run.
11510 # N.B.
11511 # The subroutine is not used by latexmk itself. It is here to support
11512 # a need in TeXShop's pdflatexmk engine as the subroutine for a cusdep
11513 # to work with the epspdf package.
11514
11515 print "I am delegating making of '$$Pdest' to *latex (e.g., by epspdf).\n",
11516 " So I'll delete '$$Pdest' to flag it needs to be remade,\n",
11517 " and flagging the rules using it to be rerun\n"
11518 if (!$silent);
11519 # Remove the destination file, to indicate it needs to be remade:
11520 unlink_or_move( $$Pdest );
11521 # Arrange that the non-existent destination file is not treated as
11522 # an error. The variable changed here is a bit misnamed.
11523 $$Pchanged = 1;
11524 # Ensure a primary run is done
11525 &cus_dep_require_primary_run;
11526 # Return success:
11527 return 0;
11528 }
11529
11530 #************************************************************
11531
11532 sub cus_dep_require_primary_run {
11533 # This subroutine is used for situations like epstopdf.sty, when
11534 # the destination (target) of the custom dependency invoking
11535 # this subroutine will be made by the primary run provided the
11536 # file (destination of the custom dependency, source of the
11537 # primary run) doesn't exist.
11538 # It is assumed that the resulting file will be read by the
11539 # primary run.
11540
11541 my $cus_dep_target = $$Pdest;
11542 # Loop over all active rules and source files:
11543 rdb_for_actives( 0,
11544 sub { if ($file eq $cus_dep_target) {
11545 $$Pout_of_date = "A new file has been made";
11546 $$Pcorrect_after_primary = 1;
11547 }
11548 }
11549 );
11550 # Return success:
11551 return 0;
11552 }
11553
11554
11555 #************************************************************
11556 #************************************************************
11557 #************************************************************
11558 #
11559 # UTILITIES:
11560 #
11561
11562 #************************************************************
11563 # Miscellaneous
11564
11565 sub show_array {
11566 # For use in diagnostics and debugging.
11567 # On stdout, print line with $_[0] = label.
11568 # Then print rest of @_, one item per line preceeded by some space
11569 print "$_[0]\n";
11570 shift;
11571 if ($#_ >= 0) {
11572 foreach (@_){
11573 if (defined $_ ) { print " $_\n"; }
11574 else { print " UNDEF\n"; }
11575 }
11576 }
11577 else { print " NONE\n"; }
11578 }
11579
11580 #************************************************************
11581
11582 sub show_hash {
11583 my ($msg, $PH) = @_;
11584 print "$msg\n";
11585 if (! %$PH ) {
11586 print " NONE\n";
11587 }
11588 else {
11589 while ( my ($key, $value) = each %$PH ) {
11590 if (defined $value) { print " '$key' => '$value'\n"; }
11591 else { print " '$key' => UNDEF\n"; }
11592 }
11593 }
11594 }
11595
11596 #************************************************************
11597
11598 sub warn_array {
11599 # For use in error messages etc.
11600 # On stderr, print line with $_[0] = label.
11601 # Then print rest of @_, one item per line preceeded by some space
11602 warn "$_[0]\n";
11603 shift;
11604 if ($#_ >= 0) {
11605 foreach (@_){
11606 if (defined $_ ) { warn " $_\n"; }
11607 else { warn " undef\n"; }
11608 }
11609 }
11610 else { warn " NONE\n"; }
11611 }
11612
11613
11614 #************************************************************
11615
11616 sub array_to_hash {
11617 # Call: array_to_hash( items )
11618 # Returns: hash mapping items to 1
11619 my %hash = ();
11620 foreach (@_) {$hash{$_} = 1; }
11621 return %hash;
11622 }
11623
11624 #************************************************************
11625
11626 sub Parray {
11627 # Call: Parray( \@A )
11628 # Returns array of references to the elements of @A
11629 # But if an element of @A is already a reference, the
11630 # reference will be returned in the output array, not a
11631 # reference to the reference.
11632 my $PA = shift;
11633 my @P = (undef) x (1+$#$PA);
11634 foreach my $i (0..$#$PA) {
11635 $P[$i] = (ref $$PA[$i]) ? ($$PA[$i]) : (\$$PA[$i]);
11636 }
11637 return @P;
11638 }
11639
11640 #************************************************************
11641
11642 sub glob_list1 {
11643 # Glob a collection of filenames.
11644 # But no sorting or elimination of duplicates
11645 # Usage: e.g., @globbed = glob_list1(string, ...);
11646 # Since perl's glob appears to use space as separator, I'll do a special check
11647 # for existence of non-globbed file (assumed to be tex like)
11648
11649 my @globbed = ();
11650 foreach my $file_spec (@_) {
11651 # Problem, when the PATTERN contains spaces, the space(s) are
11652 # treated as pattern separaters.
11653 # Solution: I now the glob from use File::Glob.
11654 # The following hack avoids issues with glob in the case that a file exists
11655 # with the specified name (possibly with extension .tex):
11656 if ( -e $file_spec || -e "$file_spec.tex" ) {
11657 # Non-globbed file exists, return the file_spec.
11658 # Return $file_spec only because this is not a file-finding subroutine, but
11659 # only a globber
11660 push @globbed, $file_spec;
11661 }
11662 else {
11663 push @globbed, my_glob( "$file_spec" );
11664 }
11665 }
11666 return @globbed;
11667 } #END glob_list1
11668
11669 #************************************************************
11670 # Miscellaneous
11671
11672 sub prefix {
11673 #Usage: prefix( string, prefix );
11674 #Return string with prefix inserted at the front of each line
11675 my @line = split( /\n/, $_[0] );
11676 my $prefix = $_[1];
11677 for (my $i = 0; $i <= $#line; $i++ ) {
11678 $line[$i] = $prefix.$line[$i]."\n";
11679 }
11680 return join( "", @line );
11681 } #END prefix
11682
11683
11684 #===============================
11685
11686 sub parse_quotes {
11687 # Split string into words.
11688 # Words are delimited by space, except that strings
11689 # quoted all stay inside a word. E.g.,
11690 # 'asdf B" df "d "jkl"'
11691 # is split to ( 'asdf', 'B df d', 'jkl').
11692 # An array is returned.
11693 my @results = ();
11694 my $item = '';
11695 local $_ = shift;
11696 pos($_) = 0;
11697 ITEM:
11698 while() {
11699 /\G\s*/gc;
11700 if ( /\G$/ ) {
11701 last ITEM;
11702 }
11703 # Now pos (and \G) is at start of item:
11704 PART:
11705 while () {
11706 if (/\G([^\s\"]*)/gc) {
11707 $item .= $1;
11708 }
11709 if ( /\G\"([^\"]*)\"/gc ) {
11710 # Match balanced quotes
11711 $item .= $1;
11712 next PART;
11713 }
11714 elsif ( /\G\"(.*)$/gc ) {
11715 # Match unbalanced quote
11716 $item .= $1;
11717 warn "====Non-matching quotes in\n '$_'\n";
11718 }
11719 push @results, $item;
11720 $item = '';
11721 last PART;
11722 }
11723 }
11724 return @results;
11725 } #END parse_quotes
11726
11727 #************************************************************
11728 #************************************************************
11729 # File handling utilities:
11730
11731
11732 #************************************************************
11733
11734 sub get_latest_mtime
11735 # - arguments: each is a filename.
11736 # - returns most recent modify time.
11737 {
11738 my $return_mtime = 0;
11739 foreach my $include (@_)
11740 {
11741 my $include_mtime = get_mtime($include);
11742 # The file $include may not exist. If so ignore it, otherwise
11743 # we'll get an undefined variable warning.
11744 if ( ($include_mtime) && ($include_mtime > $return_mtime) )
11745 {
11746 $return_mtime = $include_mtime;
11747 }
11748 }
11749 return $return_mtime;
11750 }
11751
11752 #************************************************************
11753
11754 sub get_mtime {
11755 # Return mtime of file if it exists, otherwise 0.
11756 #
11757 # stat returns an empty array for a non-existent file, and then
11758 # accessing an element of the array gives undef. Use || 0 to replace it
11759 # by the desired 0.
11760 return ( stat($_[0]) )[9] || 0;
11761 }
11762
11763 #************************************************************
11764
11765 sub get_time_size {
11766 # Return time and size of file named in argument
11767 # If file does not exist, return (0,-1);
11768 # Argument _ to stat: use values from previous call, to save disk access.
11769 my @result = stat($_[0]);
11770 if (@result) { return ($result[9], $result[7]); }
11771 else { return (0,-1); }
11772 }
11773
11774 #************************************************************
11775
11776 sub processing_time {
11777 # Return time used.
11778 # Either total processing time of process and child processes as reported
11779 # in pieces by times(), or time since Epoch depending on setting of
11780 # $times_are_clock.
11781 # That variable is to be set on OSs (MSWin32) where times() does not
11782 # include time for subprocesses.
11783 if ($times_are_clock) {
11784 return time();
11785 }
11786 my ($user, $system, $cuser, $csystem) = times();
11787 return $user + $system + $cuser + $csystem;
11788 }
11789
11790 #************************************************************
11791
11792 sub get_checksum_md5 {
11793 my $source = shift;
11794 my $input;
11795 my $md5 = Digest::MD5->new;
11796 my $ignore_pattern = undef;
11797 if ( -d $source ) {
11798 # We won't use checksum for directory
11799 return 0;
11800 }
11801 open( $input, '<:bytes', $source )
11802 or return 0;
11803 my ($base, $path, $ext) = fileparseA( $source );
11804 $ext =~ s/^\.//;
11805 if ( exists $hash_calc_ignore_pattern{$ext} ) {
11806 $ignore_pattern = $hash_calc_ignore_pattern{$ext};
11807 }
11808 eval {
11809 # Trap any errors that occur during reading, even though the file
11810 # was successfully opened.
11811 # Such errors have been known to occur under OneDrive on macOS.
11812 if ( defined $ignore_pattern ) {
11813 while (local $_ = <$input>) {
11814 if ( ! /$ignore_pattern/ ){
11815 $md5->add($_);
11816 }
11817 }
11818 }
11819 else {
11820 $md5->addfile($input);
11821 }
11822 };
11823 if ($@) {
11824 warn "$My_name: Attempt to get md5 of '$source' failed. Error=\n$@";
11825 }
11826 close $input;
11827 return $md5->hexdigest();
11828 }
11829
11830 #************************************************************
11831 #************************************************************
11832
11833 sub create_empty_file {
11834 my $name = shift;
11835 open( my $h, ">", $name )
11836 or return 1;
11837 close ($h);
11838 return 0;
11839 }
11840
11841 #************************************************************
11842 #************************************************************
11843
11844 sub find_files {
11845 # Usage: find_files( \%files, format, default_ext, \@files, \@not_found )
11846 # ???!!! This may be too elaborate. The hash is there to have all the
11847 # necessary information, but I don't actually use it.
11848 # The files hash, referred to by the 1st argument, has as its keys
11849 # specified file names, as specified for example in \bibliography.
11850 # The values are to be the names of the corresponding actual files,
11851 # as found by kpsewhich, or '' if kpsewhich doesn't find a file.
11852 # The format is used in a -format=... option to kpsewhich, e.g., 'bib'
11853 # for bib files, 'bst' for bst files.
11854 # The 3rd argument contains the default extension to use for not-found files.
11855 # The array @files, referred to by the 4th argument, contains the
11856 # sorted names of the found files, and then the specifications of the
11857 # not-found files.
11858 # But
11859 # The array @not_found, referred to by the 5th argument, contains the
11860 # sorted names of the specified names for the not-found files.
11861 # The value of each item in the hash is set to the found filename
11862 # corresponding to the key, if a file is found; otherwise it is set to
11863 # the empty string.
11864 # Return number of files not found.
11865 #
11866 # ???!!! Ideally use only 1 call to kpsewhich. But KISS for now. The
11867 # main use of this subroutine is for bib, bst files (and maybe index
11868 # files), which are few in number. Only likely conceivable case for
11869 # having many files is with a big document, for which *latex running
11870 # time is large, so almost certainly that dwarfs run time for several
11871 # runs of kpsewhich.
11872
11873 my ($PHfiles, $format, $ext, $PAfiles, $PAnot_found) = @_;
11874 @$PAfiles = @$PAnot_found = ();
11875 foreach my $name (keys %$PHfiles) {
11876 if (my @lines = kpsewhich( "-format=$format", $name ) ) {
11877 $$PHfiles{$name} = $lines[0];
11878 push @$PAfiles, $lines[0];
11879 }
11880 else {
11881 $$PHfiles{$name} = '';
11882 push @$PAnot_found, $name;
11883 }
11884 }
11885 @$PAnot_found = sort @$PAnot_found;
11886 @$PAfiles = sort @$PAfiles;
11887 foreach (@$PAnot_found) {
11888 if ( ! /\..*$/ ) { $_ .= ".$ext"; }
11889 push @$PAfiles, $_;
11890 }
11891
11892 return 1 + $#{$PAnot_found};
11893 } #END find_files
11894
11895 #************************************************************
11896 #************************************************************
11897
11898 sub unlink_or_move {
11899 if ( $del_dir eq '' ) {
11900 foreach (@_) {
11901 if (!-e) {next;}
11902 if (-d) {
11903 if (!rmdir) {
11904 warn "$My_name: Cannot remove directory '$_'\n",
11905 " Error message = '$!'\n";
11906 }
11907 }
11908 else {
11909 if (!unlink) {
11910 warn "$My_name: Cannot remove file '$_'\n",
11911 " Error message = '$!'\n";
11912 }
11913 }
11914 }
11915 }
11916 else {
11917 foreach (@_) {
11918 if (-e $_ && ! move $_, "$del_dir/$_" ) {
11919 warn "$My_name: Cannot move '$_' to '$del_dir/$_'\n",
11920 " Error message = '$!'\n";
11921 }
11922 }
11923 }
11924 }
11925
11926 #************************************************************
11927
11928 sub make_path_mod {
11929 # Ensures directory given in $_[0] exists, with error checking
11930 my $dir = $_[0];
11931 my $title = $_[1];
11932 my $ret = 0;
11933 if ( -d $dir ) {}
11934 elsif ( (! -e $dir) && (! -l $dir) ) {
11935 # N.B. A link pointing to a non-existing target
11936 # returns false for -e, so we must also check -l
11937 print "$My_name: making $title directory '$dir'\n"
11938 if ! $silent;
11939 # Error handling from File::Path documentation:
11940 make_path( $dir, {error => \my $err} );
11941 if ($err && @$err) {
11942 for my $diag (@$err) {
11943 my ($file, $message) = %$diag;
11944 if ($file eq '') {
11945 print "general error in making dir: $message\n";
11946 }
11947 else {
11948 print "problem making path $file: $message\n";
11949 }
11950 }
11951 $ret = 1;
11952 }
11953 }
11954 else {
11955 $ret = 2;
11956 warn "$My_name: you requested $title directory '$dir',\n",
11957 " but a non-directory file/symlink of the same name exists.\n";
11958 }
11959 return $ret;
11960 }
11961
11962 #************************************************************
11963
11964 sub kpsewhich {
11965 # Usage: kpsewhich( [options, ] filespec, ...)
11966 # The arguments are the command line arguments to kpsewhich, and the
11967 # return value is the array of filenames that are returned by
11968 # kpsewhich.
11969 # N.B. kpsewhich returns one line per found file; this routine removes
11970 # trailing line ends (\r\n or \n) before putting the line in the
11971 # returned array.
11972 # The arguments can just be names: e.g.,
11973 # kpsewhich( 'try.sty', 'jcc.bib' );
11974 # or can include options, e.g.,
11975 # kpsewhich( '-format=bib', 'trial.bib', 'file with spaces');
11976 # With standard use of kpsewhich (i.e., without -all option), the array
11977 # has either 0 or 1 element for each filespec argument.
11978
11979 my $cmd = $kpsewhich;
11980 my @args = @_;
11981 if ( ($cmd eq '') || ( $cmd =~ /^NONE($| )/ ) ) {
11982 # Kpsewhich not set up.
11983 warn "$My_name: Kpsewhich command needed but not set up\n";
11984 return ();
11985 }
11986 foreach (@args) {
11987 if ( ! /^-/ ) {
11988 $_ = "\"$_\"";
11989 }
11990 }
11991 $cmd =~ s/%[RBTDO]//g;
11992 $cmd =~ s/%S/@args/g;
11993 my @found = ();
11994 my $fh;
11995 if ( $kpsewhich_show || $diagnostics ) {
11996 print "$My_name.kpsewhich: Running '$cmd'...\n";
11997 }
11998 open $fh, "$cmd|"
11999 or die "Cannot open pipe for \"$cmd\"\n";
12000 while (local $_ = <$fh>) {
12001 s/\r?\n$//;
12002 push @found, $_;
12003 }
12004 close $fh;
12005 if ( $kpsewhich_show || $diagnostics ) {
12006 show_array( "$My_name.kpsewhich: '$cmd' ==>", @found );
12007 }
12008 return @found;
12009 }
12010
12011 ####################################################
12012
12013 sub add_cus_dep {
12014 # Usage: add_cus_dep( from_ext, to_ext, flag, sub_name )
12015 # Add cus_dep after removing old versions
12016 my ($from_ext, $to_ext, $must, $sub_name) = @_;
12017 remove_cus_dep( $from_ext, $to_ext );
12018 push @cus_dep_list, "$from_ext $to_ext $must $sub_name";
12019 }
12020
12021 ####################################################
12022
12023 sub remove_cus_dep {
12024 # Usage: remove_cus_dep( from_ext, to_ext )
12025 my ($from_ext, $to_ext) = @_;
12026 my $i = 0;
12027 while ($i <= $#cus_dep_list) {
12028 # Use \Q and \E round directory name in regex to avoid interpretation
12029 # of metacharacters in directory name:
12030 if ( $cus_dep_list[$i] =~ /^\Q$from_ext $to_ext \E/ ) {
12031 splice @cus_dep_list, $i, 1;
12032 }
12033 else {
12034 $i++;
12035 }
12036 }
12037 }
12038
12039 ####################################################
12040
12041 sub show_cus_dep {
12042 show_array( "Custom dependency list:", @cus_dep_list );
12043 }
12044
12045 ####################################################
12046
12047 sub find_cus_dep {
12048 # Usage find_cus_dep( dest, source )
12049 # Given dest, if a cus_dep to make it is found, set source.
12050 # Return 1 or 0 on success or failure.
12051 #
12052 my $dest = $_[0];
12053 my ($base, $path, $ext) = fileparseB( $dest );
12054 $ext =~ s/^\.//;
12055 if (! $ext ) { return 0; }
12056 foreach my $dep ( @cus_dep_list ) {
12057 my ($fromext, $toext) = split( '\s+', $dep );
12058 if ( ( "$ext" eq "$toext" ) && ( -f "$path$base.$fromext" ) ) {
12059 # We have a way of making $dest
12060 $_[1] = "$path$base.$fromext";
12061 return 1
12062 }
12063 }
12064 return 0;
12065 }
12066
12067 ####################################################
12068 ####################################################
12069
12070 sub add_hook {
12071 # Usage: add_book( name of stack, name of or pointer to subroutine )
12072 # Return 1 for success, 0 for failure.
12073 no strict "refs";
12074 our %hooks;
12075 my ($stack, $routine ) = @_;
12076 unless ( exists $hooks{$stack} ) {
12077 warn "In add_hook, request to add hook to non-existent stack '$stack'.\n";
12078 return 0;
12079 }
12080 print "============== ADDING HOOK to $stack\n";
12081
12082 my $ref;
12083 if ( ref $routine ) {
12084 $ref = $routine
12085 }
12086 elsif ( defined &$routine ) {
12087 $ref = \&$routine;
12088 }
12089 else {
12090 warn "In add_hook, no subroutine '$routine' to add to stack '$stack'.\n";
12091 return 0;
12092 }
12093 push @{$hooks{$stack}}, $ref;
12094 return 1;
12095 }
12096
12097 #****************************************************
12098
12099 sub run_hooks {
12100 # Usage: run_hooks( stackname, ... )
12101 # Call the subroutines whose references on on the named stack.
12102 # They are given arguments as follows
12103 # a. If arguments follow the stackname in the call to run_hooks, these
12104 # are given to the called subroutines.
12105 # b. Otherwise a hash of information is given to the called subroutines.
12106 # Each has a return value, which like from system, is 0 for success.
12107 # Return 0 for success, non-zero for failure.
12108 my $name = shift;
12109 my $Pstack = $hooks{$name};
12110 my @args = @_;
12111 if (!@args) { @args = &info_make; }
12112 # else { print "Have args\n"; }
12113
12114 if ( ! defined $Pstack ) {
12115 warn "run_hooks: No stack named '$name'\n";
12116 # But I'll not treat this as an error. Is that appropriate?
12117 return 0;
12118 }
12119 elsif (! @$Pstack) {
12120 # Nothing to do
12121 return 0;
12122 }
12123 else {
12124 # print "$My_name: ====Running hooks in stack $name\n";
12125 my $fail = 0;
12126 # Do NOT use default $_, as in "for (...) {...}":
12127 # The called subroutine may change $_, which is a global variable
12128 # (although localized to the for loop and called subroutines).
12129 for my $Psub ( @$Pstack) {
12130 if ( &$Psub(@args) ) {
12131 $fail = 1;
12132 }
12133 }
12134 return $fail;
12135 }
12136 }
12137
12138 #-------------------------------------
12139
12140 sub info_make {
12141 my %info_make = (
12142 'aux_main' => $aux_main,
12143 'fls_file' => $fls_name,
12144 'log_file' => $log_name,
12145 'root_name' => $root_filename,
12146 'tex_file' => $texfile_name,
12147
12148 'aux_dir' => $aux_dir,
12149 'aux_dir1' => $aux_dir1,
12150 'out_dir' => $out_dir,
12151 'out_dir1' => $out_dir1,
12152 );
12153 # Rule data, if in rule context:
12154 if ($rule) { $info_make{rule} = $rule; }
12155 if ($Pbase) { $info_make{base} = $$Pbase; }
12156 if ($Psource) { $info_make{source} = $$Psource; }
12157 if ($Pdest) { $info_make{dest} = $$Pdest; }
12158 return %info_make;
12159 }
12160
12161 ####################################################
12162
12163 sub set_input_ext {
12164 # Usage: set_input_ext( rule, ext, ... )
12165 # Set list of extension(s) (specified without a leading period)
12166 # for the given rule ('latex', 'pdflatex', etc).
12167 # These extensions are used when an input
12168 # file without an extension is found by *latex, as in
12169 # \input{file} or \includegraphics{figure}. When latexmk searches
12170 # custom dependencies to make the missing file, it will assume that
12171 # the file has one of the specified extensions.
12172 my $rule = shift;
12173 $input_extensions{$rule} = { map { $_ => 1 } @_ };
12174 }
12175
12176 ####################################################
12177
12178 sub show_input_ext {
12179 # Usage: show_input_ext( rule )
12180 my $rule = shift;
12181 show_array ("Input extensions for rule '$rule': ",
12182 keys %{$input_extensions{$rule}} );
12183 }
12184
12185 ####################################################
12186
12187 sub find_dirs1 {
12188 # Same as find_dirs, but argument is single string with directories
12189 # separated by $search_path_separator
12190 # ???!!! WRONG DEFAULT?
12191 find_dirs( &split_search_path( $search_path_separator, ".", $_[0] ) );
12192 }
12193
12194
12195 #************************************************************
12196
12197 sub find_dirs {
12198 # @_ is list of directories
12199 # return: same list of directories, except that for each directory
12200 # name ending in //, a list of all subdirectories (recursive)
12201 # is added to the list.
12202 # Non-existent directories and non-directories are removed from the list
12203 # Trailing "/"s and "\"s are removed
12204 my @result = ();
12205 my $find_action
12206 = sub
12207 { ## Subroutine for use in File::find
12208 ## Check to see if we have a directory
12209 if (-d) { push @result, $File::Find::name; }
12210 };
12211 foreach my $directory (@_) {
12212 my $recurse = ( $directory =~ m[//$] );
12213 # Remove all trailing /s, since directory name with trailing /
12214 # is not always allowed:
12215 $directory =~ s[/+$][];
12216 # Similarly for MSWin reverse slash
12217 $directory =~ s[\\+$][];
12218 if ( ! -e $directory ){
12219 next;
12220 }
12221 elsif ( $recurse ){
12222 # Recursively search directory
12223 find( $find_action, $directory );
12224 }
12225 else {
12226 push @result, $directory;
12227 }
12228 }
12229 return @result;
12230 }
12231
12232 #************************************************************
12233
12234 # How I use the result of loading glob routines:
12235 sub my_glob {
12236 my @results = ();
12237 if ($have_bsd_glob) { @results = bsd_glob( $_[0] ); }
12238 else { @results = glob( $_[0] ); }
12239 return @results;
12240 }
12241
12242 #************************************************************
12243
12244 sub uniq
12245 # Read arguments, delete neighboring items that are identical,
12246 # return array of results
12247 {
12248 my @sort = ();
12249 my ($current, $prev);
12250 my $first = 1;
12251 while (@_)
12252 {
12253 $current = shift;
12254 if ($first || ($current ne $prev) )
12255 {
12256 push @sort, $current;
12257 $prev = $current;
12258 $first = 0;
12259 }
12260 }
12261 return @sort;
12262 }
12263
12264 #==================================================
12265
12266 sub uniq1 {
12267 # Usage: uniq1( strings )
12268 # Returns array of strings with duplicates later in list than
12269 # first occurence deleted. Otherwise preserves order.
12270
12271 my @strings = ();
12272 my %string_hash = ();
12273
12274 foreach my $string (@_) {
12275 if (!exists( $string_hash{$string} )) {
12276 $string_hash{$string} = 1;
12277 push @strings, $string;
12278 }
12279 }
12280 return @strings;
12281 }
12282
12283 #************************************************************
12284
12285 sub uniqs {
12286 # Usage: uniq2( strings )
12287 # Returns array of strings sorted and with duplicates deleted
12288 return uniq( sort @_ );
12289 }
12290
12291 #************************************************************
12292
12293 sub ext {
12294 # Return extension of filename. Extension includes the period
12295 my $file_name = $_[0];
12296 my ($base_name, $path, $ext) = fileparseA( $file_name );
12297 return $ext;
12298 }
12299
12300 #************************************************************
12301
12302 sub ext_no_period {
12303 # Return extension of filename. Extension excludes the period
12304 my $file_name = $_[0];
12305 my ($base_name, $path, $ext) = fileparseA( $file_name );
12306 $ext =~ s/^\.//;
12307 return $ext;
12308 }
12309
12310 #************************************************************
12311
12312 sub catfileA {
12313 # Like catfile, but change \ to / in result.
12314 my $file = catfile(@_);
12315 $file =~ s[\\][/]g;
12316 return $file;
12317 }
12318
12319 #************************************************************
12320
12321 sub fileparseA {
12322 # Like fileparse but replace $path for current dir ('./' or '.\') by ''
12323 # Also default second argument to get normal extension.
12324 # With msys, change all \ to / in given name since with msys, fileparse
12325 # doesn't recognize \ as directory separator.
12326 my $given = $_[0];
12327 if ( $^O eq 'msys' ) {
12328 $given =~ s[\\][/]g;
12329 }
12330 my $pattern = '\.[^\.]*';
12331 if ($#_ > 0 ) { $pattern = $_[1]; }
12332 my ($base_name, $path, $ext) = fileparse( $given, $pattern );
12333 if ( ($path eq './') || ($path eq '.\\') ) {
12334 $path = '';
12335 }
12336 return ($base_name, $path, $ext);
12337 }
12338
12339 #************************************************************
12340
12341 sub fileparseB {
12342 # Like fileparse but with default second argument for normal extension
12343 # With msys, change all \ to / in given name since with msys, fileparse
12344 # doesn't recognize \ as directory separator.
12345 my $given = $_[0];
12346 if ( $^O eq 'msys' ) {
12347 $given =~ s[\\][/]g;
12348 }
12349 my $pattern = '\.[^\.]*';
12350 if ($#_ > 0 ) { $pattern = $_[1]; }
12351 my ($base_name, $path, $ext) = fileparse( $given, $pattern );
12352 return ($base_name, $path, $ext);
12353 }
12354
12355 #************************************************************
12356
12357 sub split_search_path
12358 {
12359 # Usage: &split_search_path( separator, default, string )
12360 # Splits string by separator and returns array of the elements
12361 # Allow empty last component.
12362 # Replace empty terms by the default. ???!!! WRONG DEFAULT?
12363 my $separator = $_[0];
12364 my $default = $_[1];
12365 my $search_path = $_[2];
12366 my @list = split( /$separator/, $search_path);
12367 if ( $search_path =~ /$separator$/ ) {
12368 # If search path ends in a blank item, the split subroutine
12369 # won't have picked it up.
12370 # So add it to the list by hand:
12371 push @list, "";
12372 }
12373 # Replace each blank argument (default) by current directory:
12374 for (my $i = 0; $i <= $#list ; $i++ ) {
12375 if ($list[$i] eq "") {$list[$i] = $default;}
12376 }
12377 return @list;
12378 }
12379
12380 #################################
12381
12382 sub get_filetime_offset {
12383 # Usage: get_filetime_offset( prefix, [suffix] )
12384 # Measures offset between filetime in a directory and system time
12385 # Makes a temporary file of a unique name, and deletes in.
12386 # Filename is of form concatenation of prefix, an integer, suffix.
12387 # Prefix is normally of form dir/ or dir/tmp.
12388 # Default default suffix ".tmp".
12389 my $prefix = $_[0];
12390 my $suffix = $_[1] || '.tmp';
12391 my $tmp_file_count = 0;
12392 while (1==1) {
12393 # Find a new temporary file, and make it.
12394 $tmp_file_count++;
12395 my $tmp_file = "${prefix}${tmp_file_count}${suffix}";
12396 if ( ! -e $tmp_file ) {
12397 open( TMP, ">$tmp_file" )
12398 or die "$My_name.get_filetime_offset: In measuring filetime offset, couldn't write to\n",
12399 " temporary file '$tmp_file'\n";
12400 my $time = time();
12401 close(TMP);
12402 my $offset = get_mtime($tmp_file) - $time;
12403 unlink $tmp_file;
12404 return $offset;
12405 }
12406 }
12407 die "$My_name.get_filetime_offset: BUG TO ARRIVE HERE\n";
12408 }
12409
12410 #################################
12411
12412 sub tempfile1 {
12413 # Makes a temporary file of a unique name. I could use File::temp,
12414 # but it is not present in all versions of perl.
12415 # Filename is of form $tmpdir/$_[0]nnn$suffix, where nnn is an integer
12416 my $tmp_file_count = 0;
12417 my $prefix = $_[0];
12418 my $suffix = $_[1];
12419 while (1==1) {
12420 # Find a new temporary file, and make it.
12421 $tmp_file_count++;
12422 my $tmp_file = "${tmpdir}/${prefix}${tmp_file_count}${suffix}";
12423 if ( ! -e $tmp_file ) {
12424 open( my $tmp, ">$tmp_file" )
12425 or next;
12426 close($tmp);
12427 return $tmp_file;
12428 }
12429 }
12430 die "$My_name.tempfile1: BUG TO ARRIVE HERE\n";
12431 }
12432
12433 #################################
12434
12435 #************************************************************
12436 #************************************************************
12437 # Process/subprocess routines
12438
12439 sub Run_msg {
12440 # Same as Run, but give message about my running
12441 warn_running( "Running '$_[0]'" );
12442 return Run($_[0]);
12443 } #END Run_msg
12444
12445 #==================
12446
12447 sub Run {
12448 # Usage: Run_no_time ("command string");
12449 # or Run_no_time ("one-or-more keywords command string");
12450 # Possible keywords: internal, NONE, start, nostart.
12451 #
12452 # A command string not started by keywords just gives a call to system with
12453 # the specified string, I return after that has finished executing.
12454 # Exceptions to this behavior are triggered by keywords.
12455 # The general form of the string is
12456 # Zero or more occurences of the start keyword,
12457 # followed by at most one of the other key words (internal, nostart, NONE),
12458 # followed by (a) a command string to be executed by the systerm
12459 # or (b) if the command string is specified to be internal, then
12460 # it is of the form
12461 #
12462 # routine arguments
12463 #
12464 # which implies invocation of the named Perl subroutine
12465 # with the given arguments, which are obtained by splitting
12466 # the string into words, delimited by spaces, but with
12467 # allowance for double quotes.
12468 #
12469 # The meaning of the keywords is:
12470 #
12471 # start: The command line is to be running detached, as appropriate for
12472 # a previewer. The method is appropriate for the operating system
12473 # (and the keyword is inspired by the action of the start command
12474 # that implements in under MSWin).
12475 # HOWEVER: the start keyword is countermanded by the nostart,
12476 # internal, and NONE keywords. This allows rules that do
12477 # previewing to insert a start keyword to create a presumption
12478 # of detached running unless otherwise.
12479 # nostart: Countermands a previous start keyword; the following command
12480 # string is then to be obeyed by the system, and any necessary
12481 # detaching (as of a previewer) is done by the executed command(s).
12482 # internal: The following command string, of the form 'routine arguments'
12483 # specifies a call to the named Perl subroutine.
12484 # NONE: This does not run anything, but causes an error message to be
12485 # printed. This is provided to allow program names defined in the
12486 # configuration to flag themselves as unimplemented.
12487 # Note that if the word "start" is duplicated at the beginning, that is
12488 # equivalent to a single "start".
12489 #
12490 # Return value is a list (pid, exitcode):
12491 # If a process is spawned sucessfully, and I know the PID,
12492 # return (pid, 0),
12493 # else if process is spawned sucessfully, but I do not know the PID,
12494 # return (0, 0),
12495 # else if process is run,
12496 # return (0, exitcode of process)
12497 # else if I fail to run the requested process
12498 # return (0, suitable return code)
12499 # where return code is 1 if cmdline is null or begins with "NONE" (for
12500 # an unimplemented command)
12501 # or the return value of the Perl subroutine.
12502 my $cmd_line = $_[0];
12503 if ( $cmd_line eq '' ) {
12504 traceback( "$My_name: Bug OR configuration error\n".
12505 " In run of '$rule', attempt to run a null program" );
12506 return (0, 1);
12507 }
12508 # Deal with latexmk-defined pseudocommands 'start' and 'NONE'
12509 # at front of command line:
12510 my $detach = 0;
12511 while ( $cmd_line =~ s/^start +// ) {
12512 # But first remove extra starts (which may have been inserted
12513 # to force a command to be run detached, when the command
12514 # already contained a "start").
12515 $detach = 1;
12516 }
12517 if ( $cmd_line =~ s/^nostart +// ) {
12518 $detach = 0;
12519 }
12520 if ( $cmd_line =~ /^internal\s+([a-zA-Z_]\w*)\s+(.*)$/ ) {
12521 my $routine = $1;
12522 my @args = parse_quotes( $2 );
12523 print "$My_name: calling $routine( $2 )\n"
12524 if (! $silent);
12525 no strict "refs";
12526 return ( 0, &$routine( @args ) );
12527 }
12528 elsif ( $cmd_line =~ /^internal\s+([a-zA-Z_]\w*)\s*$/ ) {
12529 my $routine = $1;
12530 print "$My_name: calling $routine()\n"
12531 if (! $silent);
12532 no strict "refs";
12533 return ( 0, &$routine() );
12534 }
12535 elsif ( $cmd_line =~ /^NONE/ ) {
12536 warn "$My_name: ",
12537 "Program not implemented for this version. Command line:\n";
12538 warn " '$cmd_line'\n";
12539 return (0, 1);
12540 }
12541 elsif ($detach) {
12542 # Run detached. How to do this depends on the OS
12543 return &Run_Detached( $cmd_line );
12544 }
12545 else {
12546 # The command is given to system as a single argument, to force shell
12547 # metacharacters to be interpreted:
12548 return( 0, system( $cmd_line ) );
12549 }
12550 } #END Run
12551
12552 #************************************************************
12553
12554 sub Run_Detached {
12555 # Usage: Run_Detached ("program arguments ");
12556 # Runs program detached. Returns 0 on success, 1 on failure.
12557 # Under UNIX use a trick to avoid the program being killed when the
12558 # parent process, i.e., me, gets a ctrl/C, which is undesirable for pvc
12559 # mode. (The simplest method, system("program arguments &"), makes the
12560 # child process respond to the ctrl/C.)
12561 # Return value is a list (pid, exitcode):
12562 # If process is spawned sucessfully, and I know the PID,
12563 # return (pid, 0),
12564 # else if process is spawned sucessfully, but I do not know the PID,
12565 # return (0, 0),
12566 # else if I fail to spawn a process
12567 # return (0, 1)
12568
12569 my $cmd_line = $_[0];
12570
12571 ## print "Running '$cmd_line' detached...\n";
12572 if ( $cmd_line =~ /^NONE / ) {
12573 warn "$My_name: ",
12574 "Program not implemented for this version. Command line:\n";
12575 warn " '$cmd_line'\n";
12576 return (0, 1);
12577 }
12578
12579 if ( "$^O" eq "MSWin32" ){
12580 # Win95, WinNT, etc: Use MS's start command:
12581 # Need extra double quotes to deal with quoted filenames:
12582 # MSWin start takes first quoted argument to be a Window title.
12583 return( 0, system( "start \"\" $cmd_line" ) );
12584 } else {
12585 # Assume anything else is UNIX or clone
12586 # For this purpose cygwin behaves like UNIX.
12587 ## print "Run_Detached.UNIX: A\n";
12588 my $pid = fork();
12589 ## print "Run_Detached.UNIX: B pid=$pid\n";
12590 if ( ! defined $pid ) {
12591 ## print "Run_Detached.UNIX: C\n";
12592 warn "$My_name: Could not fork to run the following command:\n";
12593 warn " '$cmd_line'\n";
12594 return (0, 1);
12595 }
12596 elsif( $pid == 0 ){
12597 ## print "Run_Detached.UNIX: D\n";
12598 # Forked child process arrives here
12599 # Insulate child process from interruption by ctrl/C to kill parent:
12600 # setpgrp(0,0);
12601 # Perhaps this works if setpgrp doesn't exist
12602 # (and therefore gives fatal error):
12603 eval{ setpgrp(0,0);};
12604 exec( $cmd_line );
12605 # Exec never returns; it replaces current process by new process
12606 die "$My_name forked process: could not run the command\n",
12607 " '$cmd_line'\n";
12608 }
12609 ##print "Run_Detached.UNIX: E\n";
12610 # Original process arrives here
12611 return ($pid, 0);
12612 }
12613 # NEVER GET HERE.
12614 ##print "Run_Detached.UNIX: F\n";
12615 } #END Run_Detached
12616
12617 #************************************************************
12618
12619 sub find_process_id {
12620 # find_process_id(string) finds id of process containing string and
12621 # being run by the present user. In all the uses in latexmk, the string is
12622 # the name of a file that is expected to be on the command line.
12623 #
12624 # On success, this subroutine returns the process ID.
12625 # On failure, it returns 0.
12626 #
12627 # This subroutine only works on UNIX systems at the moment.
12628
12629 if ( $pid_position < 0 ) {
12630 # I cannot do a ps on this system
12631 return (0);
12632 }
12633
12634 my $looking_for = $_[0];
12635 my @ps_output = `$pscmd`;
12636 my @ps_lines = ();
12637
12638 # There may be multiple processes. Find only latest,
12639 # almost surely the one with the highest process number
12640 # This will deal with cases like xdvi where a script is used to
12641 # run the viewer and both the script and the actual viewer binary
12642 # have running processes.
12643 my @found = ();
12644
12645 shift(@ps_output); # Discard the header line from ps
12646 foreach (@ps_output) {
12647 next unless ( /$looking_for/ ) ;
12648 s/^\s*//;
12649 my @ps_line = split ('\s+');
12650 push @found, $ps_line[$pid_position];
12651 push @ps_lines, $_;
12652 }
12653
12654 if ($#found < 0) {
12655 # No luck in finding the specified process.
12656 return(0);
12657 }
12658 @found = reverse sort @found;
12659 if ($diagnostics) {
12660 print "Found the following processes concerning '$looking_for'\n",
12661 " @found\n",
12662 " I will use $found[0]\n";
12663 print " The relevant lines from '$pscmd' were:\n";
12664 foreach (@ps_lines) { print " $_"; }
12665 }
12666 return $found[0];
12667 }
12668
12669 #************************************************************
12670 #************************************************************
12671 #************************************************************
12672
12673 #============================================
12674
12675 sub cache_good_cwd {
12676 # Set cached value of cwd to current cwd.
12677 # Under cygwin, the cached value is converted to a native MSWin path so
12678 # that the result can be used for input to MSWin programs as well
12679 # as cygwin programs.
12680 # Similarly for msys.
12681 my $cwd = getcwd();
12682 if ( $^O eq "cygwin" ) {
12683 my $cmd = "cygpath -w \"$cwd\"";
12684 my $Win_cwd = `$cmd`;
12685 chomp $Win_cwd;
12686 if ( $Win_cwd ) {
12687 $cwd = $Win_cwd;
12688 }
12689 else {
12690 warn "$My_name: Could not correctly run command\n",
12691 " '$cmd'\n",
12692 " to get MSWin version of cygwin path\n",
12693 " '$cwd'\n",
12694 " The result was\n",
12695 " '$Win_cwd'\n";
12696 }
12697 }
12698 elsif ( $^O eq "msys" ) {
12699 $cwd =~ s[^/([a-z])/][\u$1:/];
12700 }
12701 # Normalized
12702 if ($normalize_names) {
12703 my $abs = abs_path($cwd);
12704 # It's conceivable that abs_path doesn't know how to convert to an
12705 # absolute path of a standard normalization. Then it returns undef.
12706 # In that case, it's probably good not to try normalizing $cwd.
12707 if (defined $abs) { $cwd = $abs; }
12708 }
12709 $cache{cwd} = $cwd;
12710 } # END cache_good_cwd
12711
12712 #============================================
12713
12714 sub good_cwd {
12715 # Return cwd, but under cygwin (or ...), convert to MSWin path.
12716 # Use cached result, to save a possible expensive computation (running
12717 # of extenal program under cygwin).
12718 return $cache{cwd};
12719 } # END good_cwd
12720
12721 #============================================
12722
12723 # Directory stack routines
12724
12725 sub pushd {
12726 push @dir_stack, [cwd(), $cache{cwd}];
12727 if ( $#_ > -1) {
12728 my $ret = 0;
12729 eval {
12730 if ( -d $_[0] ) {
12731 $ret = chdir dirname_no_tail( $_[0] );
12732 }
12733 else {
12734 print "$my_name: Can't change directory to '$_[0]'\n",
12735 " A directory of the same name does not exist.\n";
12736 }
12737 };
12738 if ( ($ret == 0) || $@ ) {
12739 if ($@) {
12740 print "Error:\n $@" ;
12741 }
12742 die "$My_name: Error in changing directory to '$_[0]'. I must stop\n";
12743 }
12744 &cache_good_cwd;
12745 }
12746 }
12747
12748 #************************************************************
12749
12750 sub popd {
12751 if ($#dir_stack > -1 ) {
12752 my $Parr = pop @dir_stack;
12753 chdir $$Parr[0];
12754 $cache{cwd} = $$Parr[1];
12755 }
12756 }
12757
12758 #************************************************************
12759
12760 sub ifcd_popd {
12761 if ( $do_cd ) {
12762 print "$My_name: Undoing directory change\n"
12763 if !$silent;
12764 &popd;
12765 }
12766 }
12767
12768 #************************************************************
12769
12770 sub finish_dir_stack {
12771 while ($#dir_stack > -1 ) { &popd; }
12772 }
12773
12774 #************************************************************
12775 #************************************************************
12776 # Break handling routines (for wait-loop in preview continuous)
12777
12778 sub end_wait {
12779 # Handler for break: Set global variable $have_break to 1.
12780 # Some systems (e.g., MSWin reset) appear to reset the handler.
12781 # So I'll re-enable it
12782 our $have_break;
12783 &catch_break;
12784 $have_break = 1;
12785 }
12786
12787 #========================
12788
12789 sub catch_break {
12790 # Capture ctrl/C and ctrl/break.
12791 # $SIG{INT} corresponds to ctrl/C on LINUX/?UNIX and MSWin
12792 # $SIG{BREAK} corresponds to ctrl/break on MSWin, doesn't exist on LINUX
12793 $SIG{INT} = \&end_wait;
12794 if ( exists $SIG{BREAK} ) {
12795 $SIG{BREAK} = \&end_wait;
12796 }
12797 }
12798
12799 #========================
12800
12801 sub default_break {
12802 # Arrange for ctrl/C and ctrl/break to give default behavior
12803 $SIG{INT} = 'DEFAULT';
12804 if ( exists $SIG{BREAK} ) {
12805 $SIG{BREAK} = 'DEFAULT';
12806 }
12807 }
12808
12809 #************************************************************
12810 #************************************************************
12811
12812 #************************************************************
12813 #************************************************************
12814 # Unicode manipuation and normalization
12815 # Notes about Perl strings:
12816 # 1. Strings have a flag utf8.
12817 # a. If the utf8 flag is on, the string is to be interpreted as a sequence
12818 # of code points.
12819 # When "use utf8;" is used, a string containing non-ASCII characters
12820 # has the utf8 flag set.
12821 # If 'no bytes;' is in effect, the ordinal value for each item in the
12822 # string is the Unicode code point value.
12823 # b. If the utf8 flag is off for a string, the string is a sequence of
12824 # bytes, to be interpreted according to whatever CS the user happens
12825 # to choose to use.
12826 # c. The utf8 flag is NOT to be interpreted as saying that the string is
12827 # encoded as UTF-8, even though under the hood that may be the case.
12828 # d. Indeed, setting 'use bytes;' appears to expose the internal
12829 # byte-level representation of a string with the utf8 flag set, and
12830 # that appears to be UTF-8.
12831 # 2. The utf8 flag is quite confusing in its meaning.
12832 # 3. When encode is applied to a string whose utf8 flag is on, the result
12833 # is a string with the utf8 flag off, and the result consists of a sequence
12834 # of bytes in the chosen encoding scheme, which may be chosen as UTF-8.
12835 # 4. Strings received from the command line have the utf8 flag off and are
12836 # encoded in whatever CS the OS/terminal is using.
12837 # 5. When a string is supplied to print (or c), by default:
12838 # a. If the utf8 flag is off or if 'use bytes;' is in effect, then the
12839 # string is sent as a sequence of bytes. They are UTF-8 coded if
12840 # the utf8 flag is on and 'use bytes;' is in effect.
12841 # b. If the utf8 flag is on and if 'no bytes;' is in effect, then mostly
12842 # garbage results for non-ASCII characters; the string must first be
12843 # encoded as a byte string, in the CS suitable for the OS.
12844 # c. Correct results are obtained when the utf8 flag is on and 'no bytes'
12845 # is used when the binmode for the file handle is set suitably.
12846 # 6. Generally OS calls and interactions with the OS need encoded byte strings.
12847 # 7. Even more generally, interaction with the external world, including file
12848 # contents is in terms of byte strings, with some CS chosen by default, by
12849 # the user, or the OS. Unix-like OSs: Default is UTF-8, but as much by
12850 # convention as by a requirement of the OS.
12851
12852 #-------------------------------------
12853
12854 sub utf8_to_mine {
12855 # Given string encoded in UTF-8, return encoded string in my current CS.
12856 # Don't use Encode::from_to, which does in-place conversion.
12857 if ($no_CP_conversions) { return $_[0]; }
12858 else { return encode( $CS_system, decode('UTF-8', $_[0])); }
12859 }
12860
12861 #-------------------------------------
12862
12863 sub utf8_to_mine_errors {
12864 # Given string encoded in UTF-8, return encoded string in my current CS.
12865 # Don't use Encode::from_to, which does in-place conversion.
12866 # Assume coding of input string is correctly UTF-8, but
12867 # check for correct encoding in CS_system.
12868 # Error message is returned in $@. No error => $@ is null string.
12869 # (Same style as eval!)
12870 $@ = '';
12871 if ($no_CP_conversions) { return $_[0]; }
12872 else {
12873 my $result = '';
12874 eval {
12875 $result = encode( $CS_system,
12876 decode('UTF-8', $_[0]),
12877 Encode::FB_CROAK | Encode::LEAVE_SRC
12878 );
12879 };
12880 return $result;
12881 }
12882 }
12883
12884 #-------------------------------------
12885
12886 sub config_to_mine {
12887 # Ensure that configuration strings about files and directories are
12888 # encoded in system CS.
12889 # Configuration strings set in an rc file SHOULD either be:
12890 # a. ASCII only, with Perl's utf8 flag off.
12891 # b. Containing non-ASCII characters, with utf8 flag on.
12892 # These need to be converted to encoded strings in system CS (and
12893 # hence with utf8 flag off).
12894 # Configuration variables set from the command line, e.g., from an
12895 # -outdir=... option, are already in the system CS, because that is
12896 # how strings are passed on the command line.
12897 # So we just need to do a conversion for strings with utf8 flag on:
12898 foreach ( $out_dir, $out2_dir, $aux_dir, @default_files, @default_excluded_files ) {
12899 if (utf8::is_utf8($_)) { $_ = encode( $CS_system, $_ ); }
12900 }
12901 } #END config_to_mine
12902
12903 #************************************************************
12904
12905 sub mine_to_utf8 {
12906 # Given string encoded in my current CS, return utf-8 encoded string.
12907 # Don't use Encode::from_to, which does in-place conversion.
12908 if ($no_CP_conversions) { return $_[0]; }
12909 else { return encode( 'UTF-8', decode($CS_system, $_[0])); }
12910 }
12911
12912 #-------------------------------------
12913
12914 sub is_valid_utf8 {
12915 eval { decode( 'UTF-8', $_[0], (Encode::FB_CROAK | Encode::LEAVE_SRC ) ); };
12916 if ($@) { return 0; }
12917 else { return 1; }
12918 }
12919
12920 #-------------------------------------
12921
12922 sub fprint8 {
12923 # Usage: fprint8( handle, data array)
12924 # Write to file converting from my CS to UTF-8
12925 my $fh = shift;
12926 print $fh mine_to_utf8( join( '', @_ ) );
12927 }
12928
12929 #-------------------------------------
12930
12931 ################################################################