Debian Codegraph @

texk/texlive/linked_scripts/memoize/memoize-extract.pl

raw
1 #!/usr/bin/env perl
2
3 # This file is a part of Memoize, a TeX package for externalization of
4 # graphics and memoization of compilation results in general, available at
5 # https://ctan.org/pkg/memoize and https://github.com/sasozivanovic/memoize.
6 #
7 # Copyright (c) 2020- Saso Zivanovic <[email protected]>
8 #
9 # This work may be distributed and/or modified under the conditions of the
10 # LaTeX Project Public License, either version 1.3c of this license or (at
11 # your option) any later version. The latest version of this license is in
12 # https://www.latex-project.org/lppl.txt and version 1.3c or later is part of
13 # all distributions of LaTeX version 2008 or later.
14 #
15 # This work has the LPPL maintenance status `maintained'.
16 # The Current Maintainer of this work is Saso Zivanovic.
17 #
18 # The files belonging to this work and covered by LPPL are listed in
19 # <texmf>/doc/generic/memoize/FILES.
20
21 my $PROG = 'memoize-extract.pl';
22 my $VERSION = '2024/12/02 v1.4.1';
23
24 use strict;
25 use File::Basename qw/basename/;
26 use Getopt::Long;
27 use File::Spec::Functions
28 qw/splitpath catpath splitdir rootdir file_name_is_absolute/;
29 use File::Path qw(make_path);
30 # We will only try to import the PDF processing library once we set up the error
31 # log.
32
33 # Declare variables for command-line arguments and for |kpathsea|
34 # variables. They are defined here so that they are global in the subs which use
35 # them.
36 our ($pdf_file, $prune, $keep, $format, $force, $quiet,
37 $pdf_library, $print_version, $mkdir, $help,
38 $openin_any, $openout_any, $texmfoutput, $texmf_output_directory);
39
40 # \paragraph{Messages}
41
42 # The messages are written both to the extraction log and the terminal (we
43 # output to stdout rather than stderr so that messages on the TeX terminal and
44 # document |.log| appear in chronological order). Messages are automatically
45 # adapted to the TeX |--format|.
46
47 # The format of the messages. It depends on the given |--format|; the last
48 # entry is for t the terminal output.
49
50 my %ERROR = (
51 latex => '\PackageError{memoize (perl-based extraction)}{$short}{$long}',
52 plain => '\errhelp{$long}\errmessage{memoize (perl-based extraction): $short}',
53 context => '\errhelp{$long}\errmessage{memoize (perl-based extraction): $short}',
54 '' => '$header$short. $long');
55
56 my %WARNING = (
57 latex => '\PackageWarning{memoize (perl-based extraction)}{$texindent$text}',
58 plain => '\message{memoize (perl-based extraction) Warning: $texindent$text}',
59 context => '\message{memoize (perl-based extraction) Warning: $texindent$text}',
60 '' => '$header$indent$text.');
61
62 my %INFO = (
63 latex => '\PackageInfo{memoize (perl-based extraction)}{$texindent$text}',
64 plain => '\message{memoize (perl-based extraction): $texindent$text}',
65 context => '\message{memoize (perl-based extraction): $texindent$text}',
66 '' => '$header$indent$text.');
67
68 # Some variables used in the message routines; note that |header| will be
69 # redefined once we parse the arguments.
70
71 my $exit_code = 0;
72 my $log;
73 my $header = '';
74 my $indent = '';
75 my $texindent = '';
76
77 # The message routines.
78
79 sub error {
80 my ($short, $long) = @_;
81 if (! $quiet) {
82 $_ = $ERROR{''};
83 s/\$header/$header/;
84 s/\$short/$short/;
85 s/\$long/$long/;
86 print(STDOUT "$_\n");
87 }
88 if ($log) {
89 $short =~ s/\\/\\string\\/g;
90 $long =~ s/\\/\\string\\/g;
91 $_ = $ERROR{$format};
92 s/\$short/$short/;
93 s/\$long/$long/;
94 print(LOG "$_\n");
95 }
96 $exit_code = 11;
97 endinput();
98 }
99
100 sub warning {
101 my $text = shift;
102 if (! $quiet) {
103 $_ = $WARNING{''};
104 s/\$header/$header/;
105 s/\$indent/$indent/;
106 s/\$text/$text/;
107 print(STDOUT "$_\n");
108 }
109 if ($log) {
110 $_ = $WARNING{$format};
111 $text =~ s/\\/\\string\\/g;
112 s/\$texindent/$texindent/;
113 s/\$text/$text/;
114 print(LOG "$_\n");
115 }
116 $exit_code = 10;
117 }
118
119 sub info {
120 my $text = shift;
121 if ($text && ! $quiet) {
122 $_ = $INFO{''};
123 s/\$header/$header/;
124 s/\$indent/$indent/;
125 s/\$text/$text/;
126 print(STDOUT "$_\n");
127 if ($log) {
128 $_ = $INFO{$format};
129 $text =~ s/\\/\\string\\/g;
130 s/\$texindent/$texindent/;
131 s/\$text/$text/;
132 print(LOG "$_\n");
133 }
134 }
135 }
136
137 # Mark the log as complete and exit.
138 sub endinput {
139 if ($log) {
140 print(LOG "\\endinput\n");
141 close(LOG);
142 }
143 exit $exit_code;
144 }
145
146 sub die_handler {
147 stderr_to_warning();
148 my $text = shift;
149 chomp($text);
150 error("Perl error: $text", '');
151 }
152
153 sub warn_handler {
154 my $text = shift;
155 chomp($text);
156 warning("Perl warning: $text");
157 }
158
159 # This is used to print warning messages from PDF::Builder, which are output to
160 # STDERR.
161 my $stderr;
162 sub stderr_to_warning {
163 if ($stderr) {
164 my $w = ' Perl info: ';
165 my $nl = '';
166 for (split(/\n/, $stderr)) {
167 /(^\s*)(.*?)(\s*)$/;
168 $w .= ($1 ? ' ' : $nl) . $2;
169 $nl = "\n";
170 }
171 warning("$w");
172 $stderr = '';
173 }
174 }
175
176 # \paragraph{Permission-related functions}
177
178 # We will need these variables below. Note that we only support Unix and
179 # Windows.
180 my $on_windows = $^O eq 'MSWin32';
181 my $dirsep = $on_windows ? '\\' : '/';
182
183 # |paranoia_in|/|out| should work exactly as
184 # |kpsewhich -safe-in-name|/|-safe-out-name|.
185 sub paranoia_in {
186 my ($f, $remark) = @_;
187 error("I'm not allowed to read from '$f' (openin_any = $openin_any)",
188 $remark) unless _paranoia($f, $openin_any);
189 }
190
191 sub paranoia_out {
192 my ($f, $remark) = @_;
193 error("I'm not allowed to write to '$f' (openin_any = $openout_any)",
194 $remark) unless _paranoia($f, $openout_any);
195 }
196
197 sub _paranoia {
198 # |f| is the path to the file (it should not be empty), and |mode| is the
199 # value of |openin_any| or |openout_any|.
200 my ($f, $mode) = @_;
201 return if (! $f);
202 # We split the filename into the directory and the basename part, and the
203 # directory into components.
204 my ($volume, $dir, $basename) = splitpath($f);
205 my @dir = splitdir($dir);
206 return (
207 # In mode `any' (|a|, |y| or |1|), we may access any file.
208 $mode =~ /^[ay1]$/
209 || (
210 # Otherwise, we are at least in the restricted mode, so we should
211 # not open dot files on Unix-like systems (except file called
212 # |.tex|).
213 ! (!$on_windows && $basename =~ /^\./ && !($basename =~ /^\.tex$/))
214 && (
215 # If we are precisely in the restricted mode (|r|, |n|, |0|),
216 # then there are no further restrictions.
217 $mode =~ /^[rn0]$/
218 # Otherwise, we are in the paranoid mode (officially |p|, but
219 # any other value is interpreted as |p| as well). There are
220 # two further restrictions in the paranoid mode.
221 || (
222 # We're not allowed to go to a parent directory.
223 ! grep(/^\.\.$/, @dir) && $basename ne '..'
224 &&
225 # If the given path is absolute, is should be a descendant
226 # of either |TEXMF_OUTPUT_DIRECTORY| or |TEXMFOUTPUT|.
227 (!file_name_is_absolute($f)
228 ||
229 is_ancestor($texmf_output_directory, $f)
230 ||
231 is_ancestor($texmfoutput, $f)
232 )))));
233 }
234
235 # Only removes final "/"s. This is unlike |File::Spec|'s |canonpath|, which also
236 # removes |.| components, collapses multiple |/| --- and unfortunately also goes
237 # up for |..| on Windows.
238 sub normalize_path {
239 my $path = shift;
240 my ($v, $d, $n) = splitpath($path);
241 if ($n eq '' && $d =~ /[^\Q$dirsep\E]\Q$dirsep\E+$/) {
242 $path =~ s/\Q$dirsep\E+$//;
243 }
244 return $path;
245 }
246
247 # On Windows, we disallow ``semi-absolute'' paths, i.e.\ paths starting with the
248 # |\| but lacking the drive. |File::Spec|'s function |file_name_is_absolute|
249 # returns 2 if the path is absolute with a volume, 1 if it's absolute with no
250 # volume, and 0 otherwise. After a path was sanitized using this function,
251 # |file_name_is_absolute| will work as we want it to.
252 sub sanitize_path {
253 my $f = normalize_path(shift);
254 my ($v, $d, $n) = splitpath($f);
255 if ($on_windows) {
256 my $a = file_name_is_absolute($f);
257 if ($a == 1 || ($a == 0 && $v) ) {
258 error("\"Semi-absolute\" paths are disallowed: " . $f,
259 "The path must either both contain the drive letter and " .
260 "start with '\\', or none of these; paths like 'C:foo\\bar' " .
261 "and '\\foo\\bar' are disallowed");
262 }
263 }
264 }
265
266 sub access_in {
267 return -r shift;
268 }
269
270 sub access_out {
271 my $f = shift;
272 my $exists;
273 eval { $exists = -e $f };
274 # Presumably, we get this error when the parent directory is not executable.
275 return if ($@);
276 if ($exists) {
277 # An existing file should be writable, and if it's a directory, it
278 # should also be executable.
279 my $rw = -w $f; my $rd = -d $f; my $rx = -x $f;
280 return -w $f && (! -d $f || -x $f);
281 } else {
282 # For a non-existing file, the parent directory should be writable.
283 # (This is the only place where function |parent| is used, so it's ok
284 # that it returns the logical parent.)
285 my $p = parent($f);
286 return -w $p;
287 }
288 }
289
290 # This function finds the location for an input file, respecting
291 # |TEXMF_OUTPUT_DIRECTORY| and |TEXMFOUTPUT|, and the permissions in the
292 # filesystem. It returns an absolute file as-is. For a relative file, it tries
293 # |TEXMF_OUTPUT_DIRECTORY| (if defined), the current directory (always), and
294 # |TEXMFOUTPUT| directory (if defined), in this order. The first readable file
295 # found is returned; if no readable file is found, the file in the current
296 # directory is returned.
297 sub find_in {
298 my $f = shift;
299 sanitize_path($f);
300 return $f if file_name_is_absolute($f);
301 for my $df (
302 $texmf_output_directory ? join_paths($texmf_output_directory, $f) : undef,
303 $f,
304 $texmfoutput ? join_paths($texmfoutput, $f) : undef) {
305 return $df if $df && -r $df;
306 }
307 return $f;
308 }
309
310 # This function finds the location for an output file, respecting
311 # |TEXMF_OUTPUT_DIRECTORY| and |TEXMFOUTPUT|, and the permissions in the
312 # filesystem. It returns an absolute file as-is. For a relative file, it tries
313 # |TEXMF_OUTPUT_DIRECTORY| (if defined), the current directory (unless
314 # |TEXMF_OUTPUT_DIRECTORY| is defined), and |TEXMFOUTPUT| directory (if
315 # defined), in this order. The first writable file found is returned; if no
316 # writable file is found, the file in either the current or the output directory
317 # is returned.
318 sub find_out {
319 my $f = shift;
320 sanitize_path($f);
321 return $f if file_name_is_absolute($f);
322 for my $df (
323 $texmf_output_directory ? join_paths($texmf_output_directory, $f) : undef,
324 $texmf_output_directory ? undef : $f,
325 $texmfoutput ? join_paths($texmfoutput, $f) : undef) {
326 return $df if $df && access_out($df);
327 }
328 return $texmf_output_directory ? join_paths($texmf_output_directory, $f) : $f;
329 }
330
331 # We next define some filename-related utilities matching what Python offers out
332 # of the box. We avoid using |File::Spec|'s |canonpath|, because on Windows,
333 # which has no concept of symlinks, this function resolves |..| to the parent.
334
335 sub name {
336 my $path = shift;
337 my ($volume, $dir, $filename) = splitpath($path);
338 return $filename;
339 }
340
341 sub suffix {
342 my $path = shift;
343 my ($volume, $dir, $filename) = splitpath($path);
344 $filename =~ /\.[^.]*$/;
345 return $&;
346 }
347
348 sub with_suffix {
349 my ($path, $suffix) = @_;
350 my ($volume, $dir, $filename) = splitpath($path);
351 if ($filename =~ s/\.[^.]*$/$suffix/) {
352 return catpath($volume, $dir, $filename);
353 } else {
354 return catpath($volume, $dir, $filename . $suffix);
355 }
356 }
357
358 sub with_name {
359 my ($path, $name) = @_;
360 my ($volume, $dir, $filename) = splitpath($path);
361 my ($v,$d,$f) = splitpath($name);
362 die "Runtime error in with_name: " .
363 "'$name' should not contain the directory component"
364 unless $v eq '' && $d eq '' && $f eq $name;
365 return catpath($volume, $dir, $name);
366 }
367
368 sub join_paths {
369 my $path1 = normalize_path(shift);
370 my $path2 = normalize_path(shift);
371 return $path2 if !$path1 || file_name_is_absolute($path2);
372 my ($volume1, $dir1, $filename1) = splitpath($path1, 'no_file');
373 my ($volume2, $dir2, $filename2) = splitpath($path2);
374 die if $volume2;
375 return catpath($volume1,
376 join($dirsep, ($dir1 eq $dirsep ? '' : $dir1, $dir2)),
377 $filename2);
378 }
379
380 # The logical parent. The same as |pathlib.parent| in Python.
381 sub parent {
382 my $f = normalize_path(shift);
383 my ($v, $dn, $_dummy) = splitpath($f, 1);
384 my $p_dn = $dn =~ s/[^\Q$dirsep\E]+$//r;
385 if ($p_dn eq '') {
386 $p_dn = $dn =~ /^\Q$dirsep\E/ ? $dirsep : '.';
387 }
388 my $p = catpath($v, $p_dn, '');
389 $p = normalize_path($p);
390 return $p;
391 }
392
393 # This function assumes that both paths are absolute; ancestor may be '',
394 # signaling a non-path.
395 sub is_ancestor {
396 my $ancestor = normalize_path(shift);
397 my $descendant = normalize_path(shift);
398 return if ! $ancestor;
399 $ancestor .= $dirsep unless $ancestor =~ /\Q$dirsep\E$/;
400 return $descendant =~ /^\Q$ancestor/;
401 }
402
403 # A paranoid |Path.mkdir|. The given folder is preprocessed by |find_out|.
404 sub make_directory {
405 my $folder = find_out(shift);
406 if (! -d $folder) {
407 paranoia_out($folder);
408 # Using |make_path| is fine because we know that
409 # |TEXMF_OUTPUT_DIRECTORY|/|TEXMFOUTPUT|, if given, exists, and that
410 # ``folder'' contains no |..|.
411 make_path($folder);
412 # This does not get logged when the function is invoked via |--mkdir|,
413 # as it is not clear what the log name should be.
414 info("Created directory $folder");
415 }
416 }
417
418 sub unquote {
419 shift =~ s/"(.*?)"/\1/rg;
420 }
421
422 # \paragraph{Kpathsea}
423
424 # Get the values of |openin_any|, |openout_any|, |TEXMFOUTPUT| and
425 # |TEXMF_OUTPUT_DIRECTORY|.
426
427 my $maybe_backslash = $on_windows ? '' : '\\';
428 my $query = 'kpsewhich -expand-var=' .
429 "openin_any=$maybe_backslash\$openin_any," .
430 "openout_any=$maybe_backslash\$openout_any," .
431 "TEXMFOUTPUT=$maybe_backslash\$TEXMFOUTPUT";
432 my $kpsewhich_output = `$query`;
433 if (! $kpsewhich_output) {
434 # No TeX? (Note that |kpsewhich| should exist in MiKTeX as well.) In
435 # absence of |kpathsea| information, we get very paranoid.
436 ($openin_any, $openout_any) = ('p', 'p');
437 ($texmfoutput, $texmf_output_directory) = ('', '');
438 # Unfortunately, this warning can't make it into the log. But then again,
439 # the chances of a missing |kpsewhich| are very slim, and its absence would
440 # show all over the place anyway.
441 warning('I failed to execute "kpsewhich", is there no TeX system installed? ' .
442 'Assuming openin_any = openout_any = "p" ' .
443 '(i.e. restricting all file operations to non-hidden files ' .
444 'in the current directory of its subdirectories).');
445 } else {
446 $kpsewhich_output =~ /^openin_any=(.*),openout_any=(.*),TEXMFOUTPUT=(.*)/;
447 ($openin_any, $openout_any, $texmfoutput) = @{^CAPTURE};
448 $texmf_output_directory = $ENV{'TEXMF_OUTPUT_DIRECTORY'};
449 if ($openin_any =~ '^\$openin_any') {
450 # When the |open*_any| variables are not expanded, we assume we're
451 # running MiKTeX. The two config settings below correspond to TeXLive's
452 # |openin_any| and |openout_any|; afaik, there is no analogue to
453 # |TEXMFOUTPUT|.
454 $query = 'initexmf --show-config-value=[Core]AllowUnsafeInputFiles ' .
455 '--show-config-value=[Core]AllowUnsafeOutputFiles';
456 my $initexmf_output = `$query`;
457 $initexmf_output =~ /^(.*)\n(.*)\n/m;
458 $openin_any = $1 eq 'true' ? 'a' : 'p';
459 $openout_any = $2 eq 'true' ? 'a' : 'p';
460 $texmfoutput = '';
461 $texmf_output_directory = '';
462 }
463 }
464
465 # An output directory should exist, and may not point to the root on Linux. On
466 # Windows, it may point to the root, because being absolute also implies
467 # containing the drive; see |sanitize_filename|.
468 sub sanitize_output_dir {
469 return unless my $d = shift;
470 sanitize_path($d);
471 # On Windows, |rootdir| returns |\|, so it cannot possibly match |$d|.
472 return $d if -d $d && $d ne rootdir();
473 }
474
475 $texmfoutput = sanitize_output_dir($texmfoutput);
476 $texmf_output_directory = sanitize_output_dir($texmf_output_directory);
477
478 # We don't delve into the real script when loaded from the testing code.
479 return 1 if caller;
480
481 # \paragraph{Arguments}
482
483 my $usage = "usage: $PROG [-h] [-P PDF] [-p] [-k] [-F {latex,plain,context}] [-f] " .
484 "[-L {PDF::API2,PDF::Builder}] [-q] [-m] [-V] mmz\n";
485 my $Help = <<END;
486 Extract extern pages produced by package Memoize out of the document PDF.
487
488 positional arguments:
489 mmz the record file produced by Memoize:
490 doc.mmz when compiling doc.tex
491 (doc and doc.tex are accepted as well)
492
493 options:
494 -h, --help show this help message and exit
495 -P PDF, --pdf PDF extract from file PDF
496 -p, --prune remove the extern pages after extraction
497 -k, --keep do not mark externs as extracted
498 -F, --format {latex,plain,context}
499 the format of the TeX document invoking extraction
500 -f, --force extract even if the size-check fails
501 -q, --quiet describe what's happening
502 -L, --library {PDF::API2, PDF::Builder}
503 which PDF library to use for extraction (default: PDF::API2)
504 -m, --mkdir create a directory (and exit);
505 mmz argument is interpreted as directory name
506 -V, --version show program's version number and exit
507
508 For details, see the man page or the Memoize documentation.
509 END
510
511 my @valid_libraries = ('PDF::API2', 'PDF::Builder');
512 Getopt::Long::Configure ("bundling");
513 GetOptions(
514 "pdf|P=s" => \$pdf_file,
515 "prune|p" => \$prune,
516 "keep|k" => \$keep,
517 "format|F=s" => \$format,
518 "force|f" => \$force,
519 "quiet|q" => \$quiet,
520 "library|L=s" => \$pdf_library,
521 "mkdir|m" => \$mkdir,
522 "version|V" => \$print_version,
523 "help|h|?" => \$help,
524 ) or die $usage;
525
526 if ($help) {print("$usage\n$Help"); exit 0}
527
528 if ($print_version) { print("$PROG of Memoize $VERSION\n"); exit 0 }
529
530 die "${usage}$PROG: error: the following arguments are required: mmz\n"
531 unless @ARGV == 1;
532
533 die "${usage}$PROG: error: argument -F/--format: invalid choice: '$format' " .
534 "(choose from 'latex', 'plain', 'context')\n"
535 unless grep $_ eq $format, ('', 'latex', 'plain', 'context');
536
537 die "${usage}$PROG: error: argument -L/--library: invalid choice: '$pdf_library' " .
538 "(choose from " . join(", ", @valid_libraries) . ")\n"
539 if $pdf_library && ! grep $_ eq $pdf_library, @valid_libraries;
540
541 $header = $format ? basename($0) . ': ' : '';
542
543 # start a new line in the TeX terminal output
544 print("\n") if $format;
545
546 # \paragraph{Initialization}
547
548 # With |--mkdir|, argument |mmz| is interpreted as the directory to create.
549 if ($mkdir) {
550 make_directory($ARGV[0]);
551 exit 0;
552 }
553
554 # Normalize the |mmz| argument into a |.mmz| filename.
555 my $mmz_file = $ARGV[0];
556 $mmz_file = with_suffix($mmz_file, '.mmz')
557 if suffix($mmz_file) eq '.tex';
558 $mmz_file = with_name($mmz_file, name($mmz_file) . '.mmz')
559 if suffix($mmz_file) ne '.mmz';
560
561 # Once we have the |.mmz| filename, we can open the log.
562 if ($format) {
563 my $_log = find_out(with_suffix($mmz_file, '.mmz.log'));
564 paranoia_out($_log);
565 info("Logging to '$_log'");
566 $log = $_log;
567 open LOG, ">$log";
568 }
569
570 # Now that we have opened the log file, we can try loading the PDF processing
571 # library.
572 if ($pdf_library) {
573 eval "use $pdf_library";
574 error("Perl module '$pdf_library' was not found",
575 'Have you followed the instructions is section 1.1 of the manual?')
576 if ($@);
577 } else {
578 for (@valid_libraries) {
579 eval "use $_";
580 if (!$@) {
581 $pdf_library = $_;
582 last;
583 }
584 }
585 if (!$pdf_library) {
586 error("No suitable Perl module for PDF processing was found, options are " .
587 join(", ", @valid_libraries),
588 'Have you followed the instructions is section 1.1 of the manual?');
589 }
590 }
591
592 # Catch any errors in the script and output them to the log.
593 $SIG{__DIE__} = \&die_handler;
594 $SIG{__WARN__} = \&warn_handler;
595 close(STDERR);
596 open(STDERR, ">", \$stderr);
597
598 # Find the |.mmz| file we will read, but retain the original filename in
599 # |$given_mmz_file|, as we will still need it.
600 my $given_mmz_file = $mmz_file;
601 $mmz_file = find_in($mmz_file, 1);
602 if (! -e $mmz_file) {
603 info("File '$given_mmz_file' does not exist, assuming there's nothing to do");
604 endinput();
605 }
606 paranoia_in($mmz_file);
607 paranoia_out($mmz_file,
608 'I would have to rewrite this file unless option --keep is given.')
609 unless $keep;
610
611 # Determine the PDF filename: it is either given via |--pdf|, or constructed
612 # from the |.mmz| filename.
613 $pdf_file = with_suffix($given_mmz_file, '.pdf') if !$pdf_file;
614 $pdf_file = find_in($pdf_file);
615 paranoia_in($pdf_file);
616 paranoia_out($pdf_file,
617 'I would have to rewrite this file because option --prune was given.')
618 if $prune;
619
620 # Various initializations.
621 my $pdf;
622 my %extern_pages;
623 my $new_mmz;
624 my $tolerance = 0.01;
625 info("Extracting new externs listed in '$mmz_file' " .
626 "from '$pdf_file' using Perl module $pdf_library");
627 my $done_message = "Done (there was nothing to extract)";
628 $indent = ' ';
629 $texindent = '\space\space ';
630 my $dir_to_make;
631
632 # \paragraph{Process \texttt{.mmz}}
633 #
634 # We cannot process the .mmz file using in-place editing. It would fail when
635 # the file is writable but its parent directory is not.
636
637 open (MMZ, $mmz_file);
638 while (<MMZ>) {
639 my $mmz_line = $_;
640 if (/^\\mmzPrefix *{(?P<prefix>)}/) {
641 # Found |\mmzPrefix|: create the extern directory, but only later, if an
642 # extern file is actually produced. We parse the prefix in two steps
643 # because we have to unquote the entire prefix.
644 my $prefix = unquote($+{prefix});
645 warning("Cannot parse line '$mmz_line'") unless
646 $prefix =~ /(?P<dir_prefix>.*\/)?(?P<name_prefix>.*?)/;
647 $dir_to_make = $+{dir_prefix};
648 } elsif (/^\\mmzNewExtern\ *{(?P<extern_path>.*?)}{(?P<page_n>[0-9]+)}#
649 {(?P<expected_width>[0-9.]*)pt}{(?P<expected_height>[0-9.]*)pt}/x) {
650 # Found |\mmzNewExtern|: extract the extern page into an extern file.
651 $done_message = "Done";
652 my $ok = 1;
653 my %m_ne = %+;
654 # The extern filename, as specified in |.mmz|:
655 my $extern_file = unquote($m_ne{extern_path});
656 # We parse the extern filename in a separate step because we have to
657 # unquote the entire path.
658 warning("Cannot parse line '$mmz_line'") unless
659 $extern_file =~ /(?P<dir_prefix>.*\/)?(?P<name_prefix>.*?)#
660 (?P<code_md5sum>[0-9A-F]{32})-#
661 (?P<context_md5sum>[0-9A-F]{32})(?:-[0-9]+)?.pdf/x;
662 # The actual extern filename:
663 my $extern_file_out = find_out($extern_file);
664 paranoia_out($extern_file_out);
665 my $page = $m_ne{page_n};
666 # Check whether c-memo and cc-memo exist (in any input directory).
667 my $c_memo = with_name($extern_file,
668 $+{name_prefix} . $+{code_md5sum} . '.memo');
669 my $cc_memo = with_name($extern_file,
670 $+{name_prefix} . $+{code_md5sum} .
671 '-' . $+{context_md5sum} . '.memo');
672 my $c_memo_in = find_in($c_memo);
673 my $cc_memo_in = find_in($cc_memo);
674 if ((! access_in($c_memo_in) || ! access_in($cc_memo_in)) && !$force) {
675 warning("I refuse to extract page $page into extern '$extern_file', " .
676 "because the associated c-memo '$c_memo' and/or " .
677 "cc-memo '$cc_memo' does not exist");
678 $ok = '';
679 }
680 # Load the PDF. We only do this now so that we don't load it if there
681 # is nothing to extract.
682 if ($ok && ! $pdf) {
683 if (!access_in($pdf_file)) {
684 warning("Cannot open '$pdf_file'", '');
685 endinput();
686 }
687 # Temporarily disable error handling, so that we can catch the error
688 # ourselves.
689 $SIG{__DIE__} = undef; $SIG{__WARN__} = undef;
690 # All safe, |paranoia_in| was already called above.
691 eval { $pdf = $pdf_library->open($pdf_file, msgver => 0) };
692 $SIG{__DIE__} = \&die_handler; $SIG{__WARN__} = \&warn_handler;
693 error("File '$pdf_file' seems corrupted. " .
694 "Perhaps you have to load Memoize earlier in the preamble",
695 "In particular, Memoize must be loaded before TikZ library " .
696 "'fadings' and any package deploying it, and in Beamer, " .
697 "load Memoize by writing \\RequirePackage{memoize} before " .
698 "\\documentclass{beamer}. " .
699 "This was the error thrown by Perl:" . "\n$@") if $@;
700 }
701 # Does the page exist?
702 if ($ok && $page > (my $n_pages = $pdf->page_count())) {
703 error("I cannot extract page $page from '$pdf_file', " .
704 "as it contains only $n_pages page" .
705 ($n_pages > 1 ? 's' : ''), '');
706 }
707 if ($ok) {
708 # Import the page into the extern PDF (no disk access yet).
709 my $extern = $pdf_library->new(outver => $pdf->version);
710 $extern->import_page($pdf, $page);
711 my $extern_page = $extern->open_page(1);
712 # Check whether the page size matches the |.mmz| expectations.
713 my ($x0, $y0, $x1, $y1) = $extern_page->get_mediabox();
714 my $width_pt = ($x1 - $x0) / 72 * 72.27;
715 my $height_pt = ($y1 - $y0) / 72 * 72.27;
716 my $expected_width_pt = $m_ne{expected_width};
717 my $expected_height_pt = $m_ne{expected_height};
718 if ((abs($width_pt - $expected_width_pt) > $tolerance
719 || abs($height_pt - $expected_height_pt) > $tolerance) && !$force) {
720 warning("I refuse to extract page $page from $pdf_file, " .
721 "because its size (${width_pt}pt x ${height_pt}pt) " .
722 "is not what I expected " .
723 "(${expected_width_pt}pt x ${expected_height_pt}pt)");
724 } else {
725 # All tests were successful, let's create the extern file.
726 # First, the containing directory, if necessary.
727 if ($dir_to_make) {
728 make_directory($dir_to_make);
729 $dir_to_make = undef;
730 }
731 # Now the extern file. Note that |paranoia_out| was already
732 # called above.
733 info("Page $page --> $extern_file_out");
734 $extern->saveas($extern_file_out);
735 # This page will get pruned.
736 $extern_pages{$page} = 1 if $prune;
737 # Comment out this |\mmzNewExtern|.
738 $new_mmz .= '%' unless $keep;
739 }
740 }
741 }
742 $new_mmz .= $mmz_line unless $keep;
743 stderr_to_warning();
744 }
745 close(MMZ);
746 $indent = '';
747 $texindent = '';
748 info($done_message);
749
750 # Write out the |.mmz| file with |\mmzNewExtern| lines commented out. (All safe,
751 # |paranoia_out| was already called above.)
752 if (!$keep) {
753 open(MMZ, ">", $mmz_file);
754 print MMZ $new_mmz;
755 close(MMZ);
756 }
757
758 # Remove the extracted pages from the original PDF. (All safe, |paranoia_out|
759 # was already called above.)
760 if ($prune and keys(%extern_pages) != 0) {
761 my $pruned_pdf = $pdf_library->new();
762 for (my $n = 1; $n <= $pdf->page_count(); $n++) {
763 if (! $extern_pages{$n}) {
764 $pruned_pdf->import_page($pdf, $n);
765 }
766 }
767 $pruned_pdf->save($pdf_file);
768 info("The following extern pages were pruned out of the PDF: " .
769 join(",", sort(keys(%extern_pages))));
770 }
771
772 endinput();
773
774 # Local Variables:
775 # fill-column: 79
776 # after-save-hook: pl2dtx
777 # End: