Debian Codegraph @

texk/texlive/linked_scripts/ltximg/ltximg.pl

raw
1 #!/usr/bin/env perl
2 use v5.26;
3
4 ############################# LICENCE ##################################
5 # This program is free software; you can redistribute it and/or modify #
6 # it under the terms of the GNU General Public License as published by #
7 # the Free Software Foundation; either version 3 of the License, or #
8 # (at your option) any later version. #
9 # #
10 # This program is distributed in the hope that it will be useful, but #
11 # WITHOUT ANY WARRANTY; without even the implied warranty of #
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU #
13 # General Public License for more details. #
14 ########################################################################
15
16 use Getopt::Long qw(:config bundling_values require_order no_ignore_case);
17 use File::Spec::Functions qw(catfile devnull);
18 use File::Basename;
19 use Archive::Tar;
20 use Data::Dumper;
21 use FileHandle;
22 use IO::Compress::Zip qw(:all);
23 use File::Path qw(remove_tree);
24 use File::Temp qw(tempdir);
25 use POSIX qw(strftime);
26 use File::Copy;
27 use File::Find;
28 use Env qw(PATH);
29 use autodie;
30 use Config;
31 use Cwd;
32 use if $^O eq 'MSWin32', 'Win32';
33 use if $^O eq 'MSWin32', 'Module::Load::Conditional' => qw(can_load check_install requires);
34 # Need for colors in Windows cmd, TeX Live not provide 'Win32::Console::ANSI'
35 if($^O eq 'MSWin32' && check_install( module => 'Win32::Console::ANSI')) {
36 require Win32::Console::ANSI;
37 }
38 use Term::ANSIColor;
39
40 ### Directory for work and temp files
41 my $tempDir = tempdir( CLEANUP => 1);
42 my $workdir = cwd;
43
44 ### Script identification
45 my $scriptname = 'ltximg';
46 my $program = 'LTXimg';
47 my $nv = 'v2.1';
48 my $date = '2021-05-21';
49 my $copyright = <<"END_COPYRIGHT" ;
50 [$date] - LaTeX environments to image and standalone files
51 END_COPYRIGHT
52
53 ### Standart info in terminal
54 my $title = "$program $nv $copyright";
55
56 ### Log vars
57 my $LogFile = "$scriptname.log";
58 my $LogWrite;
59 my $LogTime = strftime("%y-%m-%d %H:%M:%S", localtime);
60
61 ### Default values
62 my $skiptag = 'noltximg'; # internal tag for regex
63 my $extrtag = 'ltximg'; # internal tag for regex
64 my @extr_env_tmp; # save extract environments
65 my @skip_env_tmp; # save skip environments
66 my @verb_env_tmp; # save verbatim environments
67 my @verw_env_tmp; # save verbatim write environments
68 my @delt_env_tmp; # save delete environments in output file
69 my @clean; # clean document options
70 my $outfile = 0; # write output file
71 my $outsrc = 0; # write standalone files
72 my $PSTexa = 0; # run extract PSTexample environments
73 my $STDenv = 0; # run extract standart environments
74 my $verbose = 0; # verbose info
75 my $gscmd; # ghostscript executable name
76 my $write18; # storing write18 for compiler in TeXLive and MikTeX
77 my $log = 0; # log file
78 my @currentopt; # storing current options for log file
79
80 ### Hash to store options for Getopt::Long and log file
81 my %opts_cmd;
82 $opts_cmd{string}{prefix} = 'fig';
83 $opts_cmd{string}{dpi} = '150';
84 $opts_cmd{string}{runs} = '1';
85 $opts_cmd{string}{margin} = '0';
86 $opts_cmd{string}{imgdir} = 'images';
87 $opts_cmd{string}{myverb} = 'myverb';
88 $opts_cmd{clean} = 'doc';
89
90 ### Error in command line
91 sub errorUsage {
92 my $msg = shift;
93 die color('red').'* Error!!: '.color('reset').$msg.
94 " (run $scriptname --help for more information)\n";
95 return;
96 }
97
98 ### Extended error messages
99 sub exterr {
100 chomp(my $msg_errno = $!);
101 chomp(my $msg_extended_os_error = $^E);
102 if ($msg_errno eq $msg_extended_os_error) {
103 $msg_errno;
104 }
105 else {
106 "$msg_errno/$msg_extended_os_error";
107 }
108 }
109
110 ### Funtion uniq
111 sub uniq {
112 my %seen;
113 return grep !$seen{$_}++, @_;
114 }
115
116 ### Funtion array_minus
117 sub array_minus(\@\@) {
118 my %e = map{ $_ => undef } @{$_[1]};
119 return grep !exists $e{$_}, @{$_[0]};
120 }
121
122 ### Funtion to create hash begin -> BEGIN, end -> END
123 sub crearhash {
124 my %cambios;
125 for my $aentra(@_){
126 for my $initend (qw(begin end)) {
127 $cambios{"\\$initend\{$aentra"} = "\\\U$initend\E\{$aentra";
128 }
129 }
130 return %cambios;
131 }
132
133 ### Print colored info in screen
134 sub Infocolor {
135 my $type = shift;
136 my $info = shift;
137 if ($type eq 'Running') {
138 print color('cyan'), '* ', color('reset'), color('green'),
139 "$type: ", color('reset'), color('cyan'), "$info\r\n", color('reset');
140 }
141 if ($type eq 'Warning') {
142 print color('bold red'), "* $type: ", color('reset'),
143 color('yellow'), "$info\r\n", color('reset');
144 }
145 if ($type eq 'Finish') {
146 print color('cyan'), '* ', color('reset'), color('magenta'),
147 "$type!: ", color('reset'), color('green'), "$info\r\n",color('reset');
148 }
149 return;
150 }
151
152 ### Write Log line and print msg (common)
153 sub Infoline {
154 my $msg = shift;
155 my $now = strftime("%y-%m-%d %H:%M:%S", localtime);
156 if ($log) { $LogWrite->print(sprintf "[%s] * %s\n", $now, $msg); }
157 say $msg;
158 return;
159 }
160
161 ### Write Log line (no print msg and time stamp)
162 sub Logline {
163 my $msg = shift;
164 if ($log) { $LogWrite->print("$msg\n"); }
165 return;
166 }
167
168 ### Write Log line (time stamp)
169 sub Log {
170 my $msg = shift;
171 my $now = strftime("%y-%m-%d %H:%M:%S", localtime);
172 if ($log) { $LogWrite->print(sprintf "[%s] * %s\n", $now, $msg); }
173 return;
174 }
175
176 ### Write array env in Log
177 sub Logarray {
178 my ($env_ref) = @_;
179 my @env_tmp = @{ $env_ref }; # dereferencing and copying each array
180 if ($log) {
181 if (@env_tmp) {
182 my $tmp = join "\n", map { qq/* $_/ } @env_tmp;
183 print {$LogWrite} "$tmp\n";
184 }
185 else {
186 print {$LogWrite} "Not found\n";
187 }
188 }
189 return;
190 }
191
192 ### Extended print info for execute system commands using $ command
193 sub Logrun {
194 my $msg = shift;
195 my $now = strftime("%y-%m-%d %H:%M:%S", localtime);
196 if ($log) { $LogWrite->print(sprintf "[%s] \$ %s\n", $now, $msg); }
197 return;
198 }
199
200 ### Capture and execute system commands
201 sub RUNOSCMD {
202 my $cmdname = shift;
203 my $argcmd = shift;
204 my $showmsg = shift;
205 my $captured = "$cmdname $argcmd";
206 Logrun($captured);
207 if ($showmsg eq 'show') {
208 if ($verbose) {
209 Infocolor('Running', $captured);
210 }
211 else{ Infocolor('Running', $cmdname); }
212 }
213 if ($showmsg eq 'only' and $verbose) {
214 Infocolor('Running', $captured);
215 }
216 # Run system system command
217 $captured = qx{$captured};
218 if ($log) { $LogWrite->print($captured); }
219 if ($? == -1) {
220 my $errorlog = "* Error!!: ".$cmdname." failed to execute (%s)!\n";
221 my $errorprint = "* Error!!: ".color('reset').$cmdname." failed to execute (%s)!\n";
222 if ($log) { $LogWrite->print(sprintf $errorlog, exterr); }
223 print STDERR color('red');
224 die sprintf $errorprint, exterr;
225 } elsif ($? & 127) {
226 my $errorlog = "* Error!!: ".$cmdname." died with signal %d!\n";
227 my $errorprint = "* Error!!: ".color('reset').$cmdname." died with signal %d!\n";
228 if ($log) { $LogWrite->print(sprintf $errorlog, ($? & 127)); }
229 print STDERR color('red');
230 die sprintf $errorprint, ($? & 127);
231 } elsif ($? != 0 ) {
232 my $errorlog = "* Error!!: ".$cmdname." exited with error code %d!\n";
233 my $errorprint = "* Error!!: ".color('reset').$cmdname." exited with error code %d!\n";
234 if ($log) { $LogWrite->print(sprintf $errorlog, $? >> 8); }
235 print STDERR color('red');
236 die sprintf $errorprint, $? >> 8;
237 }
238 if ($verbose) { print $captured; }
239 return;
240 }
241
242 ### Help for command line
243 sub usage {
244 find_ghostscript();
245
246 my $usage = <<"END_OF_USAGE";
247 ${title}Syntax
248 \$ ltximg [<options>] [--] <filename>.<tex|ltx>
249
250 Description
251 ltximg is a "perl" script that automates the process of extracting and
252 converting "environments" provided by tikz, pstricks and other packages
253 from LaTeX file to image formats and "standalone" files using ghostscript
254 and poppler-utils. Generates a one file with only extracted environments
255 and other with all extracted environments converted to \\includegraphics.
256
257 By default the extracted environments are:
258
259 preview pspicture tikzpicture pgfpicture psgraph postscript PSTexample
260
261 Options
262 Options that accept a value require either a blank space or = between
263 the option and the value. Multiple short options can be bundling and
264 if the last option takes a comma separated list you need -- at the end.
265 Relative or absolute paths for directories and files is not supported.
266
267 If used without [<options>] the extracted environments are converted
268 to pdf image format and saved in "./images" directory using pdflatex
269 and preview package for process.
270
271 [default]
272 -h, --help Display command line help and exit [off]
273 -v, --version Display current version ($nv) and exit [off]
274 -V, --verbose Verbose printing information [off]
275 -l, --log Write .log file with debug information [off]
276 -t, --tif Create .tif files using ghostscript [$gscmd]
277 -b, --bmp Create .bmp files using ghostscript [$gscmd]
278 -j, --jpg Create .jpg files using ghostscript [$gscmd]
279 -p, --png Create .png files using ghostscript [$gscmd]
280 -e, --eps Create .eps files using poppler-utils [pdftops]
281 -s, --svg Create .svg files using poppler-utils [pdftocairo]
282 -P, --ppm Create .ppm files using poppler-utils [pdftoppm]
283 -g, --gray Gray scale for images using ghostscript [off]
284 -f, --force Capture "\\psset" and "\\tikzset" to extract [off]
285 -n, --noprew Create images files without "preview" package [off]
286 -r <integer>, --runs=<integer>
287 Set the number of times the compiler will run
288 on the input file for environment extraction [1]
289 -d <integer>, --dpi=<integer>
290 Dots per inch resolution for images [150]
291 -m <integer>, --margins=<integer>
292 Set margins in bp for pdfcrop [0]
293 -o <filename>, --output=<filename>
294 Create output file [off]
295 --imgdir=<dirname> Set name of directory to save images/files [images]
296 --prefix=<string> Set prefix append to each generated files [fig]
297 --myverb=<macroname> Add "\\macroname" to verbatim inline search [myverb]
298 --clean=doc|pst|tkz|all|off
299 Removes specific block text in output file [doc]
300 --zip Compress files generated in .zip [off]
301 --tar Compress files generated in .tar.gz [off]
302 --srcenv Create files with only code of environments [off]
303 --subenv Create standalone files for environments [off]
304 --shell Enable \\write18\{shell command\} [off]
305 --latex Using latex>dvips>ps2pdf for compiler input
306 and pdflatex for compiler output [off]
307 --dvips Using latex>dvips>ps2pdf for compiler input
308 and latex>dvips>ps2pdf for compiler output [off]
309 --dvilua Using dvilualatex>dvips>ps2pdf for compiler
310 input and lualatex for compiler output [off]
311 --dvipdf Using latex>dvipdfmx for compiler input and
312 latex>dvipdfmx for compiler output [off]
313 --xetex Using xelatex for compiler input and output [off]
314 --luatex Using lualatex for compiler input and output [off]
315 --arara Use arara for compiler input and output [off]
316 --latexmk Using latexmk for compiler output file [off]
317 --norun Run script, but no create images files [off]
318 --nopdf Don't create a ".pdf" image files [off]
319 --nocrop Don't run pdfcrop [off]
320 --extrenv=<env1,...> Add new environments to extract [empty]
321 --skipenv=<env1,...> Skip some default environments to extract [empty]
322 --verbenv=<env1,...> Add new verbatim environments [empty]
323 --writenv=<env1,...> Add new verbatim write environments [empty]
324 --deltenv=<env1,...> Delete environments in output file [empty]
325
326 Example
327 \$ ltximg --latex -e -p --subenv --imgdir mypics -o test-out.ltx test-in.ltx
328
329 Create a "./mypics" directory (if it doesn't exist) with all
330 extracted environments converted to ".pdf", ".eps", ".png" and
331 standalone files ".ltx", a file "test-in-fig-all.ltx" with all
332 extracted environments and the file "test-out.ltx" with all
333 environments converted to \\includegraphics using latex>dvips>ps2pdf
334 and preview package for <test-in.ltx> and pdflatex for
335 <test-out.ltx>.
336
337 Documentation
338 For full documentation use:
339 \$ texdoc ltximg
340
341 Issues and reports
342 Repository : https://github.com/pablgonz/ltximg
343 Bug tracker: https://github.com/pablgonz/ltximg/issues
344 Copyright(C) 2013-2021 by Pablo González, pablgonz<at>yahoo.com
345 END_OF_USAGE
346 print $usage;
347 exit 0;
348 }
349
350 ### Getopt configuration
351 my $result=GetOptions (
352 # image options
353 'b|bmp' => \$opts_cmd{image}{bmp}, # gs
354 't|tif' => \$opts_cmd{image}{tif}, # gs
355 'j|jpg' => \$opts_cmd{image}{jpg}, # gs
356 'p|png' => \$opts_cmd{image}{png}, # gs
357 's|svg' => \$opts_cmd{image}{svg}, # pdftocairo
358 'e|eps' => \$opts_cmd{image}{eps}, # pdftops
359 'P|ppm' => \$opts_cmd{image}{ppm}, # pdftoppm
360 # compilers
361 'arara' => \$opts_cmd{compiler}{arara}, # arara compiler
362 'xetex' => \$opts_cmd{compiler}{xetex}, # xelatex compiler
363 'latex' => \$opts_cmd{compiler}{latex}, # latex compiler
364 'latexmk' => \$opts_cmd{compiler}{latexmk}, # latex compiler
365 'dvips' => \$opts_cmd{compiler}{dvips}, # dvips compiler
366 'dvipdf' => \$opts_cmd{compiler}{dvipdf}, # dvipdfmx compiler
367 'dvilua' => \$opts_cmd{compiler}{dvilua}, # dvilualatex compiler
368 'luatex' => \$opts_cmd{compiler}{luatex}, # lualatex compiler
369 # boolean
370 'zip' => \$opts_cmd{boolean}{zip}, # zip images dir
371 'tar' => \$opts_cmd{boolean}{tar}, # tar images dir
372 'shell' => \$opts_cmd{boolean}{shell}, # set write18 for compiler
373 'nopdf' => \$opts_cmd{boolean}{nopdf}, # no pdf image format
374 'norun' => \$opts_cmd{boolean}{norun}, # no run compiler
375 'nocrop' => \$opts_cmd{boolean}{nocrop}, # no run pdfcrop
376 'subenv' => \$opts_cmd{boolean}{subenv}, # subfile environments (bolean)
377 'srcenv' => \$opts_cmd{boolean}{srcenv}, # source files (bolean)
378 'g|gray' => \$opts_cmd{boolean}{gray}, # gray (boolean)
379 'f|force' => \$opts_cmd{boolean}{force}, # force (boolean)
380 'n|noprew' => \$opts_cmd{boolean}{noprew}, # no preview (boolean)
381 # string
382 'd|dpi=i' => \$opts_cmd{string}{dpi}, # positive integer < 2500
383 'r|runs=i' => \$opts_cmd{string}{runs}, # positive integer 1,2,3
384 'm|margins=i' => \$opts_cmd{string}{margins}, # integer
385 'extrenv=s{1,9}' => \@extr_env_tmp, # extract environments
386 'skipenv=s{1,9}' => \@skip_env_tmp, # skip environments
387 'verbenv=s{1,9}' => \@verb_env_tmp, # verbatim environments
388 'writenv=s{1,9}' => \@verw_env_tmp, # verbatim write environments
389 'deltenv=s{1,9}' => \@delt_env_tmp, # delete environments
390 'o|output=s{1}' => \$opts_cmd{string}{output}, # output file name (string)
391 'imgdir=s{1}' => \$opts_cmd{string}{imgdir}, # images dir name
392 'myverb=s{1}' => \$opts_cmd{string}{myverb}, # \myverb inline (string)
393 'prefix=s{1}' => \$opts_cmd{string}{prefix}, # prefix
394 'clean=s{1}' => \$opts_cmd{clean}, # clean output file
395 # internal
396 'h|help' => \$opts_cmd{internal}{help}, # help
397 'v|version' => \$opts_cmd{internal}{version}, # version
398 'l|log' => \$log, # write log file
399 'V|verbose' => \$verbose, # verbose mode
400 ) or do { $log = 0 ; die usage(0); };
401
402 ### Open log file
403 if ($log) {
404 if (!defined $ARGV[0]) { errorUsage('Input filename missing'); }
405 my $tempname = $ARGV[0];
406 $tempname =~ s/\.(tex|ltx)$//;
407 if ($LogFile eq "$tempname.log") { $LogFile = "$scriptname-log.log"; }
408 $LogWrite = FileHandle->new("> $LogFile");
409 }
410
411 ### Init ltximg.log file
412 Log("The script $scriptname $nv was started in $workdir");
413 Log("Creating the temporary directory $tempDir");
414
415 ### Make ENV safer (perldoc perlsec)
416 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
417
418 ### The next code it's part of pdfcrop (adapted from TexLive 2014)
419 # Windows detection
420 my $Win = 0;
421 if ($^O =~ /mswin32/i) { $Win = 1; }
422
423 my $archname = $Config{'archname'};
424 $archname = 'unknown' unless defined $Config{'archname'};
425
426 # Get ghostscript command name
427 sub find_ghostscript {
428 if ($log) {
429 Log('General information about the Perl instalation and operating system');
430 print {$LogWrite} "* Perl executable: $^X\n";
431 if ($] < 5.006) {
432 print {$LogWrite} "* Perl version: $]\n";
433 }
434 else {
435 printf {$LogWrite} "* Perl version: v%vd\n", $^V;
436 }
437 if (defined &ActivePerl::BUILD) {
438 printf {$LogWrite} "* Perl product: ActivePerl, build %s\n", ActivePerl::BUILD();
439 }
440 printf {$LogWrite} "* Pointer size: $Config{'ptrsize'}\n";
441 printf {$LogWrite} "* Pipe support: %s\n",
442 (defined $Config{'d_pipe'} ? 'yes' : 'no');
443 printf {$LogWrite} "* Fork support: %s\n",
444 (defined $Config{'d_fork'} ? 'yes' : 'no');
445 }
446 my $system = 'unix';
447 $system = 'win' if $^O =~ /mswin32/i;
448 $system = 'msys' if $^O =~ /msys/i;
449 $system = 'cygwin' if $^O =~ /cygwin/i;
450 $system = 'miktex' if defined $ENV{'TEXSYSTEM'} and
451 $ENV{'TEXSYSTEM'} =~ /miktex/i;
452 if ($log) {
453 print {$LogWrite} "* OS name: $^O\n";
454 print {$LogWrite} "* Arch name: $archname\n";
455 if ($^O eq 'MSWin32') {
456 my $tmp = Win32::GetOSName();
457 print {$LogWrite} "* System: $tmp\n";
458 }
459 else { print {$LogWrite} "* System: $system\n"; }
460 }
461 Log('Trying to locate the executable for Ghostscript');
462 my %candidates = (
463 'unix' => [qw|gs|],
464 'win' => [qw|gswin32c|],
465 'msys' => [qw|gswin64c gswin32c|],
466 'cygwin' => [qw|gs|],
467 'miktex' => [qw|mgs gswin32c|],
468 );
469 if ($system eq 'win' or $system eq 'miktex') {
470 if ($archname =~ /mswin32-x64/i) {
471 my @a = ();
472 foreach my $name (@{$candidates{$system}}) {
473 push @a, 'gswin64c' if $name eq 'gswin32c';
474 push @a, $name;
475 }
476 $candidates{$system} = \@a;
477 }
478 }
479 my %exe = (
480 'unix' => q{},
481 'win' => '.exe',
482 'msys' => '.exe',
483 'cygwin' => '.exe',
484 'miktex' => '.exe',
485 );
486 my $candidates_ref = $candidates{$system};
487 my $exe = $Config{'_exe'};
488 $exe = $exe{$system} unless defined $exe;
489 my @path = File::Spec->path();
490 my $found = 0;
491 foreach my $candidate (@$candidates_ref) {
492 foreach my $dir (@path) {
493 my $file = File::Spec->catfile($dir, "$candidate$exe");
494 if (-x $file) {
495 $gscmd = $candidate;
496 $found = 1;
497 if ($log) { print {$LogWrite} "* Found ($candidate): $file\n"; }
498 last;
499 }
500 if ($log) { print {$LogWrite} "* Not found ($candidate): $file\n"; }
501 }
502 last if $found;
503 }
504 if (not $found and $Win and $system ne 'msys') {
505 $found = SearchRegistry();
506 }
507 if (not $found and $system eq 'msys') {
508 $found = Searchbyregquery();
509 }
510 if ($found) {
511 if ($log) { print {$LogWrite} "* Autodetected ghostscript command: $gscmd\n"; }
512 }
513 else {
514 $gscmd = $$candidates_ref[0];
515 if ($log) { print {$LogWrite} "* Default ghostscript command: $gscmd\n"; }
516 }
517 }
518
519 sub SearchRegistry {
520 my $found = 0;
521 # The module Win32::TieRegistry not aviable in cygwin/msys
522 eval 'use Win32::TieRegistry qw|KEY_READ REG_SZ|';
523 if ($@) {
524 if ($log) {
525 print {$LogWrite} "* Registry lookup for Ghostscript failed:\n";
526 my $msg = $@;
527 $msg =~ s/\s+$//;
528 foreach (split /\r?\n/, $msg) {
529 print {$LogWrite} " $_\n";
530 }
531 }
532 return $found;
533 }
534 my $open_params = {Access => KEY_READ(), Delimiter => q{/}};
535 my $key_name_software = 'HKEY_LOCAL_MACHINE/SOFTWARE/';
536 my $current_key = $key_name_software;
537 my $software = new Win32::TieRegistry $current_key, $open_params;
538 if (not $software) {
539 if ($log) {
540 print {$LogWrite} "* Cannot find or access registry key `$current_key'!\n";
541 }
542 return $found;
543 }
544 if ($log) { print {$LogWrite} "* Search registry at `$current_key'.\n"; }
545 my %list;
546 foreach my $key_name_gs (grep /Ghostscript/i, $software->SubKeyNames()) {
547 $current_key = "$key_name_software$key_name_gs/";
548 if ($log) { print {$LogWrite} "* Registry entry found: $current_key\n"; }
549 my $key_gs = $software->Open($key_name_gs, $open_params);
550 if (not $key_gs) {
551 if ($log) { print {$LogWrite} "* Cannot open registry key `$current_key'!\n"; }
552 next;
553 }
554 foreach my $key_name_version ($key_gs->SubKeyNames()) {
555 $current_key = "$key_name_software$key_name_gs/$key_name_version/";
556 if ($log) { print {$LogWrite} "* Registry entry found: $current_key\n"; }
557 if (not $key_name_version =~ /^(\d+)\.(\d+)$/) {
558 if ($log) { print {$LogWrite} " The sub key is not a version number!\n"; }
559 next;
560 }
561 my $version_main = $1;
562 my $version_sub = $2;
563 $current_key = "$key_name_software$key_name_gs/$key_name_version/";
564 my $key_version = $key_gs->Open($key_name_version, $open_params);
565 if (not $key_version) {
566 if ($log) { print {$LogWrite} "* Cannot open registry key `$current_key'!\n"; }
567 next;
568 }
569 $key_version->FixSzNulls(1);
570 my ($value, $type) = $key_version->GetValue('GS_DLL');
571 if ($value and $type == REG_SZ()) {
572 if ($log) { print {$LogWrite} " GS_DLL = $value\n"; }
573 $value =~ s|([\\/])([^\\/]+\.dll)$|$1gswin32c.exe|i;
574 my $value64 = $value;
575 $value64 =~ s/gswin32c\.exe$/gswin64c.exe/;
576 if ($archname =~ /mswin32-x64/i and -f $value64) {
577 $value = $value64;
578 }
579 if (-f $value) {
580 if ($log) { print {$LogWrite} "EXE found: $value\n"; }
581 }
582 else {
583 if ($log) { print {$LogWrite} "EXE not found!\n"; }
584 next;
585 }
586 my $sortkey = sprintf '%02d.%03d %s',
587 $version_main, $version_sub, $key_name_gs;
588 $list{$sortkey} = $value;
589 }
590 else {
591 if ($log) { print {$LogWrite} "Missing key `GS_DLL' with type `REG_SZ'!\n"; }
592 }
593 }
594 }
595 foreach my $entry (reverse sort keys %list) {
596 $gscmd = $list{$entry};
597 if ($log) { print {$LogWrite} "* Found (via registry): $gscmd\n"; }
598 $found = 1;
599 last;
600 }
601 return $found;
602 } # end GS search registry
603
604 ### This part is only necessary if you're using Git-bash on windows and don't
605 ### have gs configured in PATH. Git for windows don't have a Win32::TieRegistry
606 ### module for perl (is not supported in the current versions of msys).
607 sub Searchbyregquery {
608 my $found = 0;
609 my $gs_regkey;
610 my $opt_reg = '//s //v';
611 if ($log) { print {$LogWrite} "* Search Ghostscript in Windows registry under mingw/msys:\n";}
612 $gs_regkey = qx{reg query "HKLM\\Software\\GPL Ghostscript" $opt_reg GS_DLL};
613 if ($? == 0) {
614 if ($log) { print {$LogWrite} "* Registry entry found for GS_DLL (64 bits version)\n";}
615 }
616 else {
617 $gs_regkey = qx{reg query "HKLM\\Software\\Wow6432Node\\GPL Ghostscript" $opt_reg GS_DLL};
618 if ($? == 0) {
619 if ($log) { print {$LogWrite} "* Registry entry found for GS_DLL (32 bits version)\n";}
620 }
621 }
622 my ($gs_find) = $gs_regkey =~ m/(?:\s* GS_DLL \s* REG_SZ \s*) (.+?)(?:\.dll.+?\R)/s;
623 if ($gs_find) {
624 my ($gs_vol, $gs_path, $gs_ver) = $gs_find =~ m/
625 (\w{1})(?:\:) # volumen
626 (.+?) # path to executable
627 (?:\\gsdll) # LIB
628 (\d{2}) # Version
629 /xs;
630 # Adjust
631 $gs_vol = lc($gs_vol);
632 $gs_path = '/'.$gs_vol.$gs_path;
633 $gs_path =~ s|\\|/|gmsxi;
634 # Add to PATH
635 if ($log) { print {$LogWrite} "* Add $gs_path to PATH for current session\n"; }
636 $PATH .= ":$gs_path";
637 # Set executable
638 $gscmd = 'gswin'.$gs_ver.'c';
639 if ($log) { print {$LogWrite} "* Found (via reg query): $gscmd\n"; }
640 $found = 1;
641 }
642 if ($@) {
643 if ($log) {
644 print {$LogWrite} "* Registry lookup for Ghostscript by reg query failed:\n";
645 my $msg = $@;
646 $msg =~ s/\s+$//;
647 foreach (split /\r?\n/, $msg) {
648 print {$LogWrite} " $_\n";
649 }
650 }
651 return $found;
652 }
653 return $found;
654 }
655
656 ### Call GS
657 find_ghostscript();
658
659 ### Windows need suport space in path
660 if ($Win and $gscmd =~ /\s/) { $gscmd = "\"$gscmd\"";}
661
662 ### Help
663 if (defined $opts_cmd{internal}{help}) {
664 usage(1);
665 exit 0;
666 }
667
668 ### Version
669 if (defined $opts_cmd{internal}{version}) {
670 print $title;
671 exit 0;
672 }
673
674 ### Check <input file> from command line
675 @ARGV > 0 or errorUsage('Input filename missing');
676 @ARGV < 2 or errorUsage('Unknown option or too many input files');
677
678 ### Check <input file> extention
679 my @SuffixList = ('.tex', '.ltx');
680 my ($name, $path, $ext) = fileparse($ARGV[0], @SuffixList);
681 if ($ext eq '.tex' or $ext eq '.ltx') {
682 $ext = $ext;
683 }
684 else {
685 errorUsage('Invalid or empty extention for input file');
686 }
687
688 ### Read <input file> in memory, need [:crlf] for old windows files
689 Log("Read input file $name$ext in memory");
690 open my $INPUTfile, '<:crlf', "$name$ext";
691 my $ltxfile;
692 {
693 local $/;
694 $ltxfile = <$INPUTfile>;
695 }
696 close $INPUTfile;
697
698 ### Set tmp random number for <name-fig-tmp> and others
699 my $tmp = int(rand(10000));
700
701 ### Identification message in terminal
702 print $title;
703
704 ### Remove white space and '=' in array captured from command line
705 s/^\s*(\=):?|\s*//mg foreach @extr_env_tmp;
706 s/^\s*(\=):?|\s*//mg foreach @skip_env_tmp;
707 s/^\s*(\=):?|\s*//mg foreach @verb_env_tmp;
708 s/^\s*(\=):?|\s*//mg foreach @verw_env_tmp;
709 s/^\s*(\=):?|\s*//mg foreach @delt_env_tmp;
710
711 ### Split comma separte list options from command line
712 @extr_env_tmp = split /,/,join q{},@extr_env_tmp;
713 @skip_env_tmp = split /,/,join q{},@skip_env_tmp;
714 @verb_env_tmp = split /,/,join q{},@verb_env_tmp;
715 @verw_env_tmp = split /,/,join q{},@verw_env_tmp;
716 @delt_env_tmp = split /,/,join q{},@delt_env_tmp;
717
718 ### Validate environments options from comand line
719 if (grep /(^\-|^\.).*?/, @extr_env_tmp) {
720 Log('Error!!: Invalid argument for --extrenv, some argument from list begin with -');
721 errorUsage('Invalid argument for --extrenv option');
722 }
723 if (grep /(^\-|^\.).*?/, @skip_env_tmp) {
724 Log('Error!!: Invalid argument for --skipenv, some argument from list begin with -');
725 errorUsage('Invalid argument for --skipenv option');
726 }
727 if (grep /(^\-|^\.).*?/, @verb_env_tmp) {
728 Log('Error!!: Invalid argument for --verbenv, some argument from list begin with -');
729 errorUsage('Invalid argument for --verbenv option');
730 }
731 if (grep /(^\-|^\.).*?/, @verw_env_tmp) {
732 Log('Error!!: Invalid argument for --writenv, some argument from list begin with -');
733 errorUsage('Invalid argument for --writenv option');
734 }
735 if (grep /(^\-|^\.).*?/, @delt_env_tmp) {
736 Log('Error!!: Invalid argument for --deltenv, some argument from list begin with -');
737 errorUsage('Invalid argument for --deltenv option');
738 }
739
740 ### Default environment to extract
741 my @extr_tmp = qw (
742 preview postscript tikzpicture pgfpicture pspicture psgraph PSTexample
743 );
744 push @extr_env_tmp, @extr_tmp;
745
746 ### Default verbatim environment
747 my @verb_tmp = qw (
748 Example CenterExample SideBySideExample PCenterExample PSideBySideExample
749 verbatim Verbatim BVerbatim LVerbatim SaveVerbatim PSTcode
750 LTXexample tcblisting spverbatim minted listing lstlisting
751 alltt comment chklisting verbatimtab listingcont boxedverbatim
752 demo sourcecode xcomment pygmented pyglist program programl
753 programL programs programf programsc programt
754 );
755 push @verb_env_tmp, @verb_tmp;
756
757 ### Default verbatim write environment
758 my @verbw_tmp = qw (
759 scontents filecontents tcboutputlisting tcbexternal tcbwritetmp extcolorbox extikzpicture
760 VerbatimOut verbatimwrite filecontentsdef filecontentshere filecontentsdefmacro
761 filecontentsdefstarred filecontentsgdef filecontentsdefmacro filecontentsgdefmacro
762 );
763 push @verw_env_tmp, @verbw_tmp;
764
765 ########################################################################
766 # One problem that can arise is the filecontents environment, this can #
767 # contain a complete document and be anywhere, before dividing we will #
768 # make some replacements for this and comment lines #
769 ########################################################################
770
771 ### Create a Regex for verbatim write environment
772 @verw_env_tmp = uniq(@verw_env_tmp);
773 my $tmpverbw = join q{|}, map { quotemeta } sort { length $a <=> length $b } @verw_env_tmp;
774 $tmpverbw = qr/$tmpverbw/x;
775 my $tmp_verbw = qr {
776 (
777 (?:
778 \\begin\{$tmpverbw\*?\}
779 (?:
780 (?>[^\\]+)|
781 \\
782 (?!begin\{$tmpverbw\*?\})
783 (?!end\{$tmpverbw\*?\})|
784 (?-1)
785 )*
786 \\end\{$tmpverbw\*?\}
787 )
788 )
789 }x;
790
791 ### A pre-regex for comment lines
792 my $tmpcomment = qr/^ \s* \%+ .+? $ /mx;
793
794 ### Hash for replace in verbatim's and comment lines
795 my %document = (
796 '\begin{document}' => '\BEGIN{document}',
797 '\end{document}' => '\END{document}',
798 '\documentclass' => '\DOCUMENTCLASS',
799 '\pagestyle{' => '\PAGESTYLE{',
800 '\thispagestyle{' => '\THISPAGESTYLE{',
801 );
802
803 ### Changes in <input file> for verbatim write and comment lines
804 while ($ltxfile =~ / $tmp_verbw | $tmpcomment /pgmx) {
805 my ($pos_inicial, $pos_final) = ($-[0], $+[0]);
806 my $encontrado = ${^MATCH};
807 while (my($busco, $cambio) = each %document) {
808 $encontrado =~ s/\Q$busco\E/$cambio/g;
809 }
810 substr $ltxfile, $pos_inicial, $pos_final-$pos_inicial, $encontrado;
811 pos ($ltxfile) = $pos_inicial + length $encontrado;
812 }
813
814 ### Now, split input file in $atbegindoc and contain % ltximg : <argument>
815 my ($atbegindoc, $document) = $ltxfile =~ m/\A (\s* .*? \s*) (\\documentclass.*)\z/msx;
816
817 ### Capture options in preamble of <input file>
818 # % ltximg : extrenv : {extrenv1, extrenv2, ... , extrenvn}
819 # % ltximg : skipenv : {skipenv1, skipenv2, ... , skipenvn}
820 # % ltximg : verbenv : {verbwrt1, verbwrt2, ... , verbwrtn}
821 # % ltximg : writenv : {verbwrt1, verbwrt2, ... , verbwrtn}
822 # % ltximg : deltenv : {deltenv1, deltenv2, ... , deltenvn}
823 # % ltximg : options : {opt1=arg, opt2=arg, ... , booleans}
824
825 my $readoptfile = qr/
826 ^ %+ \s* ltximg (?&SEPARADOR) (?<clave>(?&CLAVE)) (?&SEPARADOR) \{ (?<argumentos>(?&ARGUMENTOS)) \}
827 (?(DEFINE)
828 (?<CLAVE> \w+ )
829 (?<ARGUMENTOS> .+? )
830 (?<SEPARADOR> \s* : \s* )
831 )
832 /mx;
833
834 ### Search options in <input file> and store in %opts_file
835 my %opts_file;
836 while ($atbegindoc =~ /$readoptfile/g) {
837 my ($clave, $argumentos) = @+{qw(clave argumentos)};
838 my @argumentos = split /\s*,\s*?/, $argumentos;
839 for (@argumentos) { s/^ \s* | \s* $//gx; }
840 if ($clave eq 'options') {
841 for my $argumento (@argumentos) {
842 if ($argumento =~ /(?<key>\S+) \s* = \s* (?<valor>\S+)/x) {
843 $opts_file{$clave}{$+{'key'}} = $+{'valor'};
844 }
845 else {
846 $opts_file{$clave}{$argumento} = 1;
847 }
848 }
849 }
850 else {
851 push @{ $opts_file{ $clave } }, @argumentos;
852 }
853 }
854
855 ### Process options from <input file>
856 if(%opts_file) {
857 Infocolor('Warning', "Found options for script in $name$ext");
858 # Search and extract options from <input file>
859 Log("Searching options for script in $name$ext");
860 if (exists $opts_file{extrenv}) {
861 Log("Found \% ltximg\: extrenv\: \{...\} in $name$ext");
862 if (grep /(^\-|^\.).*?/, @{$opts_file{extrenv}}) {
863 Log('Error!!: Invalid argument for % ltximg: extrenv: {...}, some argument from list begin with -');
864 errorUsage('Invalid argument in % ltximg: extrenv: {...}');
865 }
866 Logarray(\@{$opts_file{extrenv}});
867 push @extr_env_tmp, @{$opts_file{extrenv}};
868 }
869 # Add skipenv options from <input file>
870 if (exists $opts_file{skipenv}) {
871 Log("Found \% ltximg\: skipenv\: \{...\} in $name$ext");
872 if (grep /(^\-|^\.).*?/, @{$opts_file{skipenv}}) {
873 Log('Error!!: Invalid argument for % ltximg: skipenv: {...}, some argument from list begin with -');
874 errorUsage('Invalid argument in % ltximg: skipenv: {...}');
875 }
876 Logarray(\@{$opts_file{skipenv}});
877 push @skip_env_tmp, @{$opts_file{skipenv}};
878 }
879 # Add verbenv options from <input file>
880 if (exists $opts_file{verbenv}) {
881 Log("Found \% ltximg\: verbenv\: \{...} in $name$ext");
882 if (grep /(^\-|^\.).*?/, @{$opts_file{verbenv}}) {
883 Log('Error!!: Invalid argument for % ltximg: verbenv: {...}, some argument from list begin with -');
884 errorUsage('Invalid argument in % ltximg: verbenv: {...}');
885 }
886 Logarray(\@{ $opts_file{verbenv}});
887 push @verb_env_tmp, @{$opts_file{verbenv}};
888 }
889 # Add writenv options from <input file>
890 if (exists $opts_file{writenv}) {
891 Log("Found \% ltximg\: writenv\: \{...\} in $name$ext");
892 if (grep /(^\-|^\.).*?/, @{ $opts_file{writenv}}) {
893 Log('Error!!: Invalid argument for % ltximg: writenv: {...}, some argument from list begin with -');
894 errorUsage('Invalid argument in % ltximg: writenv: {...}');
895 }
896 Logarray(\@{ $opts_file{writenv}});
897 push @verw_env_tmp, @{$opts_file{writenv}};
898 }
899 # Add deltenv options from <input file>
900 if (exists $opts_file{deltenv}) {
901 Log("Found \% ltximg\: deltenv\: \{...\} in $name$ext");
902 if (grep /(^\-|^\.).*?/, @{$opts_file{deltenv}}) {
903 Log('Error!!: Invalid argument for % ltximg: deltenv: {...}, some argument from list begin with -');
904 errorUsage('Invalid argument in % ltximg: deltenv: {...}');
905 }
906 Logarray(\@{ $opts_file{deltenv}});
907 push @delt_env_tmp, @{$opts_file{deltenv}};
908 }
909 # Add all other options from <input file>
910 if (exists $opts_file{options}) {
911 Log("Found \% ltximg\: options\: \{...\} in $name$ext");
912 # Add compilers from <input file>
913 for my $opt (qw(arara xetex luatex latex dvips dvipdf dvilua latexmk)) {
914 if (exists $opts_file{options}{$opt}) {
915 Log("Found [$opt] compiler option in $name$ext");
916 $opts_cmd{compiler}{$opt} = 1;
917 }
918 }
919 # Add image options
920 for my $opt (qw(eps ppm svg png jpg bmp tif)) {
921 if (exists $opts_file{options}{$opt}) {
922 Log("Found [$opt] image option in $name$ext");
923 $opts_cmd{image}{$opt} = 1;
924 }
925 }
926 # Add boolean options
927 for my $opt (qw(shell nopdf norun nocrop srcenv subenv zip tar gray force noprew)) {
928 if (exists $opts_file{options}{$opt}) {
929 Log("Found [$opt] option in $name$ext");
930 $opts_cmd{boolean}{$opt} = 1;
931 }
932 }
933 # Add string options
934 for my $opt (qw(dpi myverb margins prefix imgdir output runs)) {
935 if (exists $opts_file{options}{$opt}) {
936 Log("Found [$opt = $opts_file{options}{$opt}] in $name$ext");
937 $opts_cmd{string}{$opt} = $opts_file{options}{$opt};
938 }
939 }
940 # Add clean option
941 for my $opt (qw(doc off pst tkz all)) {
942 if ($opts_file{options}{clean} eq "$opt" ) {
943 Log("Found [clean = $opt] in $name$ext");
944 $opts_cmd{clean} = $opt;
945 }
946 }
947 }
948 }
949
950 ### Validate --dpi
951 if( $opts_cmd{string}{dpi} <= 0 or $opts_cmd{string}{dpi} >= 2500) {
952 Log('Error!!: Invalid argument for --dpi, argument out of range');
953 errorUsage('Invalid argument for --dpi option');
954 }
955
956 ### Validate --runs
957 if( $opts_cmd{string}{runs} <= 0 or $opts_cmd{string}{runs} >= 3) {
958 Log('Error!!: Invalid argument for --runs, argument out of range');
959 errorUsage('Invalid argument for --runs option');
960 }
961
962 ### Check --arara and others compilers
963 if ($opts_cmd{compiler}{arara}) {
964 # Search others compilers options
965 for my $opt (qw(xetex luatex latex dvips dvipdf dvilua latexmk)) {
966 if (defined $opts_cmd{compiler}{$opt}) {
967 Log("Error!!: Options --arara and --$opt are mutually exclusive");
968 errorUsage("Options --arara and --$opt are mutually exclusive");
969 }
970 }
971 }
972
973 ### Check --srcenv and --subenv option
974 if ($opts_cmd{boolean}{srcenv} && $opts_cmd{boolean}{subenv}) {
975 Log('Error!!: Options --srcenv and --subenv are mutually exclusive');
976 errorUsage('Options --srcenv and --subenv are mutually exclusive');
977 }
978
979 ### If --srcenv or --subenv option are OK activate write <sub files>
980 if ($opts_cmd{boolean}{srcenv}) {
981 $outsrc = 1;
982 $opts_cmd{boolean}{subenv} = undef;
983 }
984 if ($opts_cmd{boolean}{subenv}) {
985 $outsrc = 1;
986 $opts_cmd{boolean}{srcenv} = undef;
987 }
988
989 ### Add pdf image format if --nopdf
990 if (!$opts_cmd{boolean}{nopdf}) {
991 $opts_cmd{image}{pdf} = 1;
992 }
993
994 ### Store defined image formats in $format
995 my $format = join q{, },grep { defined $opts_cmd{image}{$_} } keys %{$opts_cmd{image}};
996
997 ### Write defined image format in log file
998 if (!$opts_cmd{boolean}{norun}) {
999 Log("Defined image formats for creating: $format");
1000 }
1001
1002 ### Check --norun and no images type
1003 if (!$opts_cmd{boolean}{norun} and $format eq q{}) {
1004 Log('Error!!: Option --nopdf need --norun or an image option');
1005 errorUsage('Option --nopdf need --norun or an image option');
1006 }
1007
1008 ### Check --dvips and no eps image type
1009 if ($opts_cmd{compiler}{dvips} and !$opts_cmd{image}{eps} and !$opts_cmd{boolean}{norun}) {
1010 Log('Error!!: Option --dvips need --eps');
1011 errorUsage('Option --dvips need --eps');
1012 }
1013
1014 ### Validate myverb = macro option
1015 if (defined $opts_cmd{string}{myverb}) {
1016 if ($opts_cmd{string}{myverb} =~ /^(?:\\|\-).+?/) {
1017 Log('Error!!: Invalid argument for --myverb option, argument begin with - or \ ');
1018 errorUsage('Invalid argument for --myverb');
1019 }
1020 else { Log("Set myverb = $opts_cmd{string}{myverb}"); }
1021 }
1022
1023 ### Validate imgdir = string option
1024 if (defined $opts_cmd{string}{imgdir}) {
1025 if ($opts_cmd{string}{imgdir} =~ /^(?:\\|\-).+?/) {
1026 Log('Error!!: Invalid argument for --imgdir option, argument begin with -, \ or /');
1027 errorUsage('Invalid argument for --imgdir');
1028 }
1029 else { Log("Set imgdir = $opts_cmd{string}{imgdir}"); }
1030 }
1031
1032 ### Validate clean
1033 my %clean = map { $_ => 1 } @clean;
1034 $clean{doc} = 1; # by default clean = doc
1035
1036 ### Pass $opts_cmd{clean} to $clean{$opt}
1037 for my $opt (qw(doc off pst tkz all)) {
1038 if ($opts_cmd{clean} eq "$opt") {
1039 $clean{$opt} = 1;
1040 push @currentopt, "--clean=$opt";
1041 }
1042 }
1043
1044 ### Activate clean options for script
1045 if ($clean{pst} or $clean{tkz}) { $clean{doc} = 1; }
1046 if ($clean{all}) { @clean{qw(pst doc tkz)} = (1) x 3; }
1047 if ($clean{off}) { undef %clean; }
1048
1049 ### Validating the <output file> name and save extension
1050 my $outext;
1051 if (defined $opts_cmd{string}{output}) {
1052 Log('Validating name and extension for output file');
1053 # Capture and split
1054 my ($outname, $outpath, $tmpext) = fileparse($opts_cmd{string}{output}, @SuffixList);
1055 if ($outname =~ /(^\-|^\.).*?/) {
1056 Log('The name of output file begin with dash -');
1057 errorUsage("$opts_cmd{string}{output} it is not a valid name for output file");
1058 }
1059 if ($tmpext eq q{}) { # Check and set extension
1060 Log("Set extension for output file to $ext");
1061 $outext = $ext;
1062 }
1063 else {
1064 Log("Set extension for output file to $tmpext");
1065 $outext = $tmpext;
1066 }
1067 if ($outname eq $name) { # Check name
1068 Log("The name of the output file must be different that $name");
1069 Infoline("Changing the output file name to $name-out");
1070 $opts_cmd{string}{output} = "$name-out";
1071 }
1072 else {
1073 Log("Set name of the output file to $outname");
1074 $opts_cmd{string}{output} = $outname;
1075 }
1076 # If output name are ok, then $outfile = 1
1077 $outfile = 1;
1078 }
1079
1080 ### Storing the current options of script in array for ltximg.log file
1081 my @allopt = qw (arara xetex luatex latex dvips dvipdf dvilua latexmk
1082 shell nopdf norun nocrop srcenv subenv zip tar gray force
1083 noprew eps ppm svg png jpg bmp tif dpi myverb margins
1084 prefix imgdir output runs
1085 );
1086
1087 for my $opt (@allopt) {
1088 if (defined $opts_cmd{boolean}{$opt}) {
1089 push @currentopt, "--$opt";
1090 }
1091 if (defined $opts_cmd{compiler}{$opt}) {
1092 push @currentopt, "--$opt";
1093 }
1094 if (defined $opts_cmd{image}{$opt}) {
1095 push @currentopt, "--$opt";
1096 }
1097 if (defined $opts_cmd{string}{$opt}) {
1098 push @currentopt, "--$opt=$opts_cmd{string}{$opt}"
1099 }
1100 }
1101
1102 ### Write all options in ltximg.log file
1103 @currentopt = sort { length $a <=> length $b } @currentopt;
1104 Log('The script will execute the following options:');
1105 Logarray(\@currentopt);
1106
1107 ### Rules to capture for regex
1108 my $braces = qr/ (?:\{)(.+?)(?:\}) /msx;
1109 my $braquet = qr/ (?:\[)(.+?)(?:\]) /msx;
1110 my $no_corchete = qr/ (?:\[ .*? \])? /msx;
1111
1112 ### Array for capture new verbatim environments defined in input file
1113 my @new_verb = qw (
1114 newtcblisting DeclareTCBListing ProvideTCBListing NewTCBListing
1115 lstnewenvironment NewListingEnvironment NewProgram specialcomment
1116 includecomment DefineVerbatimEnvironment newverbatim newtabverbatim
1117 );
1118
1119 ### Regex to capture names for new verbatim environments from input file
1120 my $newverbenv = join q{|}, map { quotemeta} sort { length $a <=> length $b } @new_verb;
1121 $newverbenv = qr/\b(?:$newverbenv) $no_corchete $braces/msx;
1122
1123 ### Array for capture new verbatim write environments defined in input file
1124 my @new_verb_write = qw (
1125 renewtcbexternalizetcolorbox renewtcbexternalizeenvironment
1126 newtcbexternalizeenvironment newtcbexternalizetcolorbox newenvsc
1127 );
1128
1129 ### Regex to capture names for new verbatim write environments from input file
1130 my $newverbwrt = join q{|}, map { quotemeta} sort { length $a <=> length $b } @new_verb_write;
1131 $newverbwrt = qr/\b(?:$newverbwrt) $no_corchete $braces/msx;
1132
1133 ### Regex to capture MINTED related environments
1134 my $mintdenv = qr/\\ newminted $braces (?:\{.+?\}) /x;
1135 my $mintcenv = qr/\\ newminted $braquet (?:\{.+?\}) /x;
1136 my $mintdshrt = qr/\\ newmint $braces (?:\{.+?\}) /x;
1137 my $mintcshrt = qr/\\ newmint $braquet (?:\{.+?\}) /x;
1138 my $mintdline = qr/\\ newmintinline $braces (?:\{.+?\}) /x;
1139 my $mintcline = qr/\\ newmintinline $braquet (?:\{.+?\}) /x;
1140
1141 ### Filter input file, now $ltxfile is pass to $filecheck
1142 Log("Filter $name$ext \(remove % and comments\)");
1143 my @filecheck = $ltxfile;
1144 s/%.*\n//mg foreach @filecheck; # del comments
1145 s/^\s*|\s*//mg foreach @filecheck; # del white space
1146 my $filecheck = join q{}, @filecheck;
1147
1148 ### Search verbatim and verbatim write environments <input file>
1149 Log("Search verbatim and verbatim write environments in $name$ext");
1150
1151 ### Search new verbatim write names in <input file>
1152 my @newv_write = $filecheck =~ m/$newverbwrt/xg;
1153 if (@newv_write) {
1154 Log("Found new verbatim write environments in $name$ext");
1155 Logarray(\@newv_write);
1156 push @verw_env_tmp, @newv_write;
1157 }
1158
1159 ### Search new verbatim environments in <input file> (for)
1160 my @verb_input = $filecheck =~ m/$newverbenv/xg;
1161 if (@verb_input) {
1162 Log("Found new verbatim environments in $name$ext");
1163 Logarray(\@verb_input);
1164 push @verb_env_tmp, @verb_input;
1165 }
1166
1167 ### Search \newminted{$mintdenv}{options} in <input file>, need add "code" (for)
1168 my @mint_denv = $filecheck =~ m/$mintdenv/xg;
1169 if (@mint_denv) {
1170 Log("Found \\newminted\{envname\} in $name$ext");
1171 # Append "code"
1172 $mintdenv = join "\n", map { qq/$_\Qcode\E/ } @mint_denv;
1173 @mint_denv = split /\n/, $mintdenv;
1174 Logarray(\@mint_denv);
1175 push @verb_env_tmp, @mint_denv;
1176 }
1177
1178 ### Search \newminted[$mintcenv]{lang} in <input file> (for)
1179 my @mint_cenv = $filecheck =~ m/$mintcenv/xg;
1180 if (@mint_cenv) {
1181 Log("Found \\newminted\[envname\] in $name$ext");
1182 Logarray(\@mint_cenv);
1183 push @verb_env_tmp, @mint_cenv;
1184 }
1185
1186 ### Remove repetead again :)
1187 @verb_env_tmp = uniq(@verb_env_tmp);
1188
1189 ### Capture verbatim inline macros in input file
1190 Log("Search verbatim macros in $name$ext");
1191
1192 ### Store all minted inline/short in @mintline
1193 my @mintline;
1194
1195 ### Search \newmint{$mintdshrt}{options} in <input file> (while)
1196 my @mint_dshrt = $filecheck =~ m/$mintdshrt/xg;
1197 if (@mint_dshrt) {
1198 Log("Found \\newmint\{macroname\} (short) in $name$ext");
1199 Logarray(\@mint_dshrt);
1200 push @mintline, @mint_dshrt;
1201 }
1202
1203 ### Search \newmint[$mintcshrt]{lang}{options} in <input file> (while)
1204 my @mint_cshrt = $filecheck =~ m/$mintcshrt/xg;
1205 if (@mint_cshrt) {
1206 Log("Found \\newmint\[macroname\] (short) in $name$ext");
1207 Logarray(\@mint_cshrt);
1208 push @mintline, @mint_cshrt;
1209 }
1210
1211 ### Search \newmintinline{$mintdline}{options} in <input file> (while)
1212 my @mint_dline = $filecheck =~ m/$mintdline/xg;
1213 if (@mint_dline) {
1214 Log("Found \\newmintinline\{macroname\} in $name$ext");
1215 # Append "inline"
1216 $mintdline = join "\n", map { qq/$_\Qinline\E/ } @mint_dline;
1217 @mint_dline = split /\n/, $mintdline;
1218 Logarray(\@mint_dline);
1219 push @mintline, @mint_dline;
1220 }
1221
1222 ### Search \newmintinline[$mintcline]{lang}{options} in <input file> (while)
1223 my @mint_cline = $filecheck =~ m/$mintcline/xg;
1224 if (@mint_cline) {
1225 Log("Found \\newmintinline\[macroname\] in $name$ext");
1226 Logarray(\@mint_cline);
1227 push @mintline, @mint_cline;
1228 }
1229
1230 ### Add standart mint, mintinline and lstinline
1231 my @mint_tmp = qw(mint mintinline lstinline);
1232
1233 ### Join all inline verbatim macros captured
1234 push @mintline, @mint_tmp;
1235 @mintline = uniq(@mintline);
1236
1237 ### Create a regex using @mintline
1238 my $mintline = join q{|}, map { quotemeta } sort { length $a <=> length $b } @mintline;
1239 $mintline = qr/\b(?:$mintline)/x;
1240
1241 ### Reserved words in verbatim inline (while)
1242 my %changes_in = (
1243 '%<*ltximg>' => '%<*LTXIMG>',
1244 '%</ltximg>' => '%</LTXIMG>',
1245 '%<*noltximg>' => '%<*NOLTXIMG>',
1246 '%</noltximg>' => '%</NOLTXIMG>',
1247 '%<*remove>' => '%<*REMOVE>',
1248 '%</remove>' => '%</REMOVE>',
1249 '\psset' => '\PSSET',
1250 '\tikzset' => '\TIKZSET',
1251 '\pspicture' => '\TRICKS',
1252 '\endpspicture' => '\ENDTRICKS',
1253 '\pgfpicture' => '\PGFTRICKS',
1254 '\endpgfpicture' => '\ENDPGFTRICKS',
1255 '\tikzpicture' => '\TKZTRICKS',
1256 '\endtikzpicture' => '\ENDTKZTRICKS',
1257 '\psgraph' => '\PSGRAPHTRICKS',
1258 '\endpsgraph' => '\ENDPSGRAPHTRICKS',
1259 '\usepackage' => '\USEPACKAGE',
1260 '{graphicx}' => '{GRAPHICX}',
1261 '\graphicspath{' => '\GRAPHICSPATH{',
1262 );
1263
1264 ### Hash to replace \begin and \end in verbatim inline
1265 my %init_end = (
1266 '\begin{' => '\BEGIN{',
1267 '\end{' => '\END{',
1268 );
1269
1270 ### Join changes in new hash (while) for verbatim inline
1271 my %cambios = (%changes_in,%init_end);
1272
1273 ### Variables and constantes
1274 my $no_del = "\0";
1275 my $del = $no_del;
1276
1277 ### Rules
1278 my $llaves = qr/\{ .+? \} /x;
1279 my $no_llaves = qr/(?: $llaves )? /x;
1280 my $corchetes = qr/\[ .+? \] /x;
1281 my $delimitador = qr/\{ (?<del>.+?) \} /x;
1282 my $scontents = qr/Scontents [*]? $no_corchete /ix;
1283 my $verb = qr/(?:((spv|(?:q|f)?v|V)erb|$opts_cmd{string}{myverb})[*]?) /ix;
1284 my $lst = qr/(?:(lst|pyg)inline)(?!\*) $no_corchete /ix;
1285 my $mint = qr/(?: $mintline |SaveVerb) (?!\*) $no_corchete $no_llaves $llaves /ix;
1286 my $no_mint = qr/(?: $mintline) (?!\*) $no_corchete /ix;
1287 my $marca = qr/\\ (?:$verb | $lst |$scontents | $mint |$no_mint) (?:\s*)? (\S) .+? \g{-1} /sx;
1288 my $comentario = qr/^ \s* \%+ .+? $ /mx;
1289 my $definedel = qr/\\ (?: DefineShortVerb | lstMakeShortInline| MakeSpecialShortVerb ) [*]? $no_corchete $delimitador /ix;
1290 my $indefinedel = qr/\\ (?: (Undefine|Delete)ShortVerb | lstDeleteShortInline) $llaves /ix;
1291
1292 Log('Making changes to inline/multiline verbatim before extraction');
1293
1294 ### Changes in input file for verbatim inline/multiline
1295 while ($document =~
1296 / $marca
1297 | $comentario
1298 | $definedel
1299 | $indefinedel
1300 | $del .+? $del
1301 /pgmx) {
1302 my ($pos_inicial, $pos_final) = ($-[0], $+[0]);
1303 my $encontrado = ${^MATCH};
1304 if ($encontrado =~ /$definedel/) {
1305 $del = $+{del};
1306 $del = "\Q$+{del}" if substr($del,0,1) ne '\\';
1307 }
1308 elsif ($encontrado =~ /$indefinedel/) {
1309 $del = $no_del;
1310 }
1311 else {
1312 while (my($busco, $cambio) = each %cambios) {
1313 $encontrado =~ s/\Q$busco\E/$cambio/g;
1314 }
1315 substr $document, $pos_inicial, $pos_final-$pos_inicial, $encontrado;
1316 pos ($document) = $pos_inicial + length $encontrado;
1317 }
1318 }
1319
1320 ### Change "escaped braces" to <LTXSB.> (this label is not the one in the document)
1321 $document =~ s/\\[{]/<LTXSBO>/g;
1322 $document =~ s/\\[}]/<LTXSBC>/g;
1323
1324 ### Regex for verbatim inline/multiline with braces {...}
1325 my $nestedbr = qr / ( [{] (?: [^{}]++ | (?-1) )*+ [}] ) /x;
1326 my $fvextra = qr /\\ (?: (Save|Esc)Verb [*]?) $no_corchete /x;
1327 my $mintedbr = qr /\\ (?:$mintline|pygment) (?!\*) $no_corchete $no_llaves /x;
1328 my $tcbxverb = qr /\\ (?: tcboxverb [*]?| Scontents [*]? |$opts_cmd{string}{myverb} [*]?|lstinline) $no_corchete /x;
1329 my $verb_brace = qr / (?:$tcbxverb|$mintedbr|$fvextra) (?:\s*)? $nestedbr /x;
1330
1331 ### Change \verb*{code} for verbatim inline/multiline
1332 while ($document =~ /$verb_brace/pgmx) {
1333 my ($pos_inicial, $pos_final) = ($-[0], $+[0]);
1334 my $encontrado = ${^MATCH};
1335 while (my($busco, $cambio) = each %cambios) {
1336 $encontrado =~ s/\Q$busco\E/$cambio/g;
1337 }
1338 substr $document, $pos_inicial, $pos_final-$pos_inicial, $encontrado;
1339 pos ($document) = $pos_inicial + length $encontrado;
1340 }
1341
1342 ### We recovered the escaped braces
1343 $document =~ s/<LTXSBO>/\\{/g;
1344 $document =~ s/<LTXSBC>/\\}/g;
1345
1346 ### Reverse changes for extract and output file
1347 my %changes_out = (
1348 '\PSSET' => '\psset',
1349 '\TIKZSET' => '\tikzset',
1350 '\TRICKS' => '\pspicture',
1351 '\ENDTRICKS' => '\endpspicture',
1352 '\PGFTRICKS' => '\pgfpicture',
1353 '\ENDPGFTRICKS' => '\endpgfpicture',
1354 '\TKZTRICKS' => '\tikzpicture',
1355 '\ENDTKZTRICKS' => '\endtikzpicture',
1356 '\PSGRAPHTRICKS' => '\psgraph',
1357 '\ENDPSGRAPHTRICKS' => '\endpsgraph',
1358 '\USEPACKAGE' => '\usepackage',
1359 '{GRAPHICX}' => '{graphicx}',
1360 '\GRAPHICSPATH{' => '\graphicspath{',
1361 '\BEGIN{' => '\begin{',
1362 '\END{' => '\end{',
1363 '\DOCUMENTCLASS' => '\documentclass',
1364 '\PAGESTYLE{' => '\pagestyle{',
1365 '\THISPAGESTYLE{' => '\thispagestyle{',
1366 );
1367
1368 ### Reverse tags, need back in all file to extract
1369 my %reverse_tag = (
1370 '%<*LTXIMG>' => '%<*ltximg>',
1371 '%</LTXIMG>' => '%</ltximg>',
1372 '%<*NOLTXIMG>' => '%<*noltximg>',
1373 '%</NOLTXIMG>' => '%</noltximg>',
1374 '%<*REMOVE>' => '%<*remove>',
1375 '%</REMOVE>' => '%</remove>',
1376 );
1377
1378 ### First we do some security checks to ensure that they are verbatim and
1379 ### verbatim write environments are unique and disjointed
1380 @verb_env_tmp = array_minus(@verb_env_tmp, @verw_env_tmp); #disjointed
1381 my @verbatim = uniq(@verb_env_tmp);
1382 my %verbatim = crearhash(@verbatim);
1383
1384 Log('The environments that are considered verbatim:');
1385 Logarray(\@verbatim);
1386
1387 ### Create a Regex for verbatim standart environment
1388 my $verbatim = join q{|}, map { quotemeta } sort { length $a <=> length $b } @verbatim;
1389 $verbatim = qr/$verbatim/x;
1390 my $verb_std = qr {
1391 (
1392 (?:
1393 \\begin\{$verbatim\*?\}
1394 (?:
1395 (?>[^\\]+)|
1396 \\
1397 (?!begin\{$verbatim\*?\})
1398 (?!end\{$verbatim\*?\})|
1399 (?-1)
1400 )*
1401 \\end\{$verbatim\*?\}
1402 )
1403 )
1404 }x;
1405
1406 ### Verbatim write
1407 @verw_env_tmp = array_minus(@verw_env_tmp, @verb_env_tmp); #disjointed
1408 my @verbatim_w = uniq(@verw_env_tmp);
1409 my %verbatim_w = crearhash(@verbatim_w);
1410
1411 Log('The environments that are considered verbatim write:');
1412 Logarray(\@verbatim_w);
1413
1414 ### Create a Regex for verbatim write environment
1415 my $verbatim_w = join q{|}, map { quotemeta } sort { length $a <=> length $b } @verbatim_w;
1416 $verbatim_w = qr/$verbatim_w/x;
1417 my $verb_wrt = qr {
1418 (
1419 (?:
1420 \\begin\{$verbatim_w\*?\}
1421 (?:
1422 (?>[^\\]+)|
1423 \\
1424 (?!begin\{$verbatim_w\*?\})
1425 (?!end\{$verbatim_w\*?\})|
1426 (?-1)
1427 )*
1428 \\end\{$verbatim_w\*?\}
1429 )
1430 )
1431 }x;
1432
1433 ### Check skip environments
1434 my @skipped;
1435 if (@skip_env_tmp) {
1436 my %envcheck = map { $_ => 1 } @skip_env_tmp;
1437 if (exists $envcheck{PSTexample}) {
1438 Log('The [PSTexample] environment is not allowed for skipping');
1439 @skip_env_tmp = grep !/PSTexample/, @skip_env_tmp;
1440 }
1441 if (exists $envcheck{preview}) {
1442 Log('The [preview] environment is not allowed for skipping');
1443 @skip_env_tmp = grep !/preview/, @skip_env_tmp;
1444 }
1445 # Valid environments for skip
1446 for my $skip (qw(pspicture tikzpicture pgfpicture psgraph postscript)) {
1447 if (exists $envcheck{$skip}) {
1448 push @skipped,$skip;
1449 }
1450 }
1451 }
1452
1453 ### List of environments to be skiped from extraction
1454 @skipped = uniq(@skip_env_tmp);
1455 Log('The environments that will be skiped for extraction:');
1456 Logarray(\@skipped);
1457
1458 ### Create a Regex for skip environment
1459 my $skipenv = join q{|}, map { quotemeta } sort { length $a <=> length $b } @skipped;
1460 $skipenv = qr/$skipenv/x;
1461 my $skip_env = qr {
1462 (
1463 (?:
1464 \\begin\{$skipenv\*?\}
1465 (?:
1466 (?>[^\\]+)|
1467 \\
1468 (?!begin\{$skipenv\*?\})
1469 (?!end\{$skipenv\*?\})|
1470 (?-1)
1471 )*
1472 \\end\{$skipenv\*?\}
1473 )
1474 )
1475 }x;
1476
1477 ### Check reserved environments
1478 my %envcheck = map { $_ => 1 } @extr_env_tmp;
1479
1480 if (exists $envcheck{document}) {
1481 Log('The [document] environment is allowed for extraction');
1482 @extr_env_tmp = grep !/document/, @extr_env_tmp;
1483 }
1484 if (exists $envcheck{nopreview}) {
1485 Log('The [nopreview] environment is allowed for extraction');
1486 @extr_env_tmp = grep !/nopreview/, @extr_env_tmp;
1487 }
1488
1489 ### An array with all environments to extract, including nopreview
1490 my @extract_env = qw(nopreview);
1491 push @extract_env,@extr_env_tmp;
1492
1493 ### Some oprations for skip environments
1494 @extract_env = array_minus(@extract_env, @skip_env_tmp);
1495 @extract_env = uniq(@extract_env);
1496
1497 ### Hash for regex
1498 my %extract_env = crearhash(@extract_env);
1499
1500 Log('The environments that will be searched for extraction:');
1501 my @real_extract_env = grep !/nopreview/, @extract_env;
1502 Logarray(\@real_extract_env);
1503
1504 ### Create a regex to extract environments
1505 my $environ = join q{|}, map { quotemeta } sort { length $a <=> length $b } @extract_env;
1506 $environ = qr/$environ/x;
1507 my $extr_tmp = qr {
1508 (
1509 (?:
1510 \\begin\{$environ\*?\}
1511 (?:
1512 (?>[^\\]+)|
1513 \\
1514 (?!begin\{$environ\*?\})
1515 (?!end\{$environ\*?\})|
1516 (?-1)
1517 )*
1518 \\end\{$environ\*?\}
1519 )
1520 )
1521 }x;
1522
1523 ### Check delete environments
1524 if (@delt_env_tmp) {
1525 my %envcheck = map { $_ => 1 } @delt_env_tmp;
1526 if (exists $envcheck{document}) {
1527 Log('The [document] environment is not allowed for delete');
1528 @delt_env_tmp = grep !/document/, @delt_env_tmp;
1529 }
1530 }
1531
1532 ### An array of environments to be removed in <output file>
1533 my @delete_env = uniq(@delt_env_tmp);
1534 my %delete_env = crearhash(@delete_env);
1535
1536 Log('The environments that will be removed in output file:');
1537 Logarray(\@delete_env);
1538
1539 ### Create a Regex for delete environment in <output file>
1540 my $delenv = join q{|}, map { quotemeta } sort { length $a <=> length $b } @delete_env;
1541 $delenv = qr/$delenv/x;
1542 my $delt_env = qr {
1543 (
1544 (?:
1545 \\begin\{$delenv\*?\}
1546 (?:
1547 (?>[^\\]+)|
1548 \\
1549 (?!begin\{$delenv\*?\})
1550 (?!end\{$delenv\*?\})|
1551 (?-1)
1552 )*
1553 \\end\{$delenv\*?\}
1554 )
1555 )
1556 }x;
1557
1558 ########################################################################
1559 # In this first part the script only detects verbatim environments and #
1560 # verbatim write don't distinguish between which ones are extracted, #
1561 # that's done in a second pass. #
1562 ########################################################################
1563
1564 Log('Making changes to verbatim and verbatim write environments before extraction');
1565
1566 ### First, revert %<*TAGS> to %<*tags> in all document
1567 my $ltxtags = join q{|}, map { quotemeta } sort { length $a <=> length $b } keys %reverse_tag;
1568 $document =~ s/^($ltxtags)/$reverse_tag{$1}/gmsx;
1569
1570 ### Create an array with the temporary extraction list, no verbatim environments
1571 my @extract_tmp = array_minus(@extract_env, @verb_env_tmp);
1572 @extract_tmp = array_minus(@extract_tmp, @verw_env_tmp);
1573 @extract_tmp = uniq(@extract_tmp);
1574 my %extract_tmp = crearhash(@extract_tmp);
1575
1576 ### Hash and Regex for changes, this "regex" is re-used in ALL script
1577 my %replace = (%verbatim, %extract_tmp, %changes_in, %document); # revert tags again :)
1578 my $find = join q{|}, map { quotemeta } sort { length $a <=> length $b } keys %replace;
1579
1580 ### We go line by line and make the changes in verbatim's envoronments (/p for ${^MATCH})
1581 while ($document =~ /$verb_wrt | $verb_std /pgmx) {
1582 my ($pos_inicial, $pos_final) = ($-[0], $+[0]);
1583 my $encontrado = ${^MATCH};
1584 if ($encontrado =~ /$verb_wrt/) {
1585 $encontrado =~ s/($find)/$replace{$1}/g;
1586 substr $document, $pos_inicial, $pos_final-$pos_inicial, $encontrado;
1587 pos ($document) = $pos_inicial + length $encontrado;
1588 }
1589 if ($encontrado =~ /$verb_std/) {
1590 %replace = (%verbatim_w, %extract_tmp, %changes_in, %document);
1591 $find = join q{|}, map { quotemeta } sort { length $a <=> length $b } keys %replace;
1592 $encontrado =~ s/($find)/$replace{$1}/g;
1593 substr $document, $pos_inicial, $pos_final-$pos_inicial, $encontrado;
1594 pos ($document) = $pos_inicial + length $encontrado;
1595 }
1596 }
1597
1598 ### Now split document
1599 my ($preamble,$bodydoc,$enddoc) = $document =~ m/\A (.+?) (\\begin\{document\} .+?)(\\end\{document\}.*)\z/msx;
1600
1601 ### Internal <dtxtag> for mark verbatim and verbatim write environments
1602 my $dtxverb = "verbatim$tmp";
1603
1604 ### Match <dtxtags>, if they're matched, we turn them :)
1605 my @tag_extract = $bodydoc =~ m/(?:^\%<\*ltximg>.+?\%<\/ltximg>)/gmsx;
1606 my @tag_noextract = $bodydoc =~ m/(?:^\%<\*noltximg>.+?\%<\/noltximg>)/gmsx;
1607
1608 if (@tag_extract) {
1609 Log('Pass extract tags %<*ltximg> ... %</ltximg> to \begin{preview} ... \end{preview}');
1610 $bodydoc =~ s/\\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1611 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1612 ^\%<\*$extrtag>(.+?)\%<\/$extrtag>/\\begin\{preview\}$1\\end\{preview\}/gmsx;
1613 }
1614 if (@tag_noextract) {
1615 Log('Pass no extract tags %<*noltximg> ... %</noltximg> to \begin{nopreview} ... \end{nopreview}');
1616 $bodydoc =~ s/\\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1617 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1618 ^\%<\*$skiptag>(.+?)\%<\/$skiptag>/\\begin\{nopreview\}$1\\end\{nopreview\}/gmsx;
1619 }
1620
1621 ########################################################################
1622 # We now make the real changes for environment extraction. Since we #
1623 # don't know what kind of environments are passed, need to redefine #
1624 # all regex to make the changes. #
1625 ########################################################################
1626
1627 my @new_verb_tmp = array_minus(@verbatim, @extract_env);
1628 $verbatim = join q{|}, map { quotemeta } sort { length $a <=> length $b } @new_verb_tmp;
1629 $verbatim = qr/$verbatim/x;
1630 $verb_std = qr {
1631 (
1632 (?:
1633 \\begin\{$verbatim\*?\}
1634 (?:
1635 (?>[^\\]+)|
1636 \\
1637 (?!begin\{$verbatim\*?\})
1638 (?!end\{$verbatim\*?\})|
1639 (?-1)
1640 )*
1641 \\end\{$verbatim\*?\}
1642 )
1643 )
1644 }x;
1645
1646 my @new_verbw_tmp = array_minus(@verbatim_w, @extract_env);
1647 $verbatim_w = join q{|}, map { quotemeta } sort { length $a <=> length $b } @new_verbw_tmp;
1648 $verbatim_w = qr/$verbatim_w/x;
1649 $verb_wrt = qr {
1650 (
1651 (?:
1652 \\begin\{$verbatim_w\*?\}
1653 (?:
1654 (?>[^\\]+)|
1655 \\
1656 (?!begin\{$verbatim_w\*?\})
1657 (?!end\{$verbatim_w\*?\})|
1658 (?-1)
1659 )*
1660 \\end\{$verbatim_w\*?\}
1661 )
1662 )
1663 }x;
1664
1665 ### Regex using hash
1666 %replace = (%extract_env);
1667 $find = join q{|}, map { quotemeta } sort { length $a <=> length $b } keys %replace;
1668
1669 ### We go line by line and make the changes (/p for ${^MATCH})
1670 while ($bodydoc =~ /$verb_wrt | $verb_std /pgmx) {
1671 my ($pos_inicial, $pos_final) = ($-[0], $+[0]);
1672 my $encontrado = ${^MATCH};
1673 $encontrado =~ s/($find)/$replace{$1}/g;
1674 substr $bodydoc, $pos_inicial, $pos_final-$pos_inicial, $encontrado;
1675 pos ($bodydoc) = $pos_inicial + length $encontrado;
1676 }
1677
1678 ### Now put a internal dtxmark in no extraction/replace environments
1679 Log("Pass verbatim write environments to %<*$dtxverb> ... %</$dtxverb>");
1680 $bodydoc =~ s/\\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1681 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1682 ($verb_wrt)/\%<\*$dtxverb>$1\%<\/$dtxverb>/gmsx;
1683 $preamble =~ s/\\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1684 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1685 ($verb_wrt)/\%<\*$dtxverb>$1\%<\/$dtxverb>/gmsx;
1686 $atbegindoc =~ s/($verb_wrt)/\%<\*$dtxverb>$1\%<\/$dtxverb>/gmsx;
1687
1688 Log("Pass verbatim environments to %<*$dtxverb> ... %</$dtxverb>");
1689 $bodydoc =~ s/\\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1690 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1691 ($verb_std)/\%<\*$dtxverb>$1\%<\/$dtxverb>/gmsx;
1692 $preamble =~ s/\\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1693 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1694 ($verb_std)/\%<\*$dtxverb>$1\%<\/$dtxverb>/gmsx;
1695 $atbegindoc =~ s/($verb_std)/\%<\*$dtxverb>$1\%<\/$dtxverb>/gmsx;
1696
1697 ### Check plain TeX syntax
1698 my %plainsyntax = map { $_ => 1 } @extract_env; # anon hash
1699
1700 if (exists $plainsyntax{pspicture}) {
1701 Log('Convert plain \pspicture to LaTeX syntax [skip in PSTexample]');
1702 $bodydoc =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
1703 \\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1704 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1705 \\begin\{PSTexample\}.+?\\end\{PSTexample\}(*SKIP)(*F)|
1706 \\pspicture(\*)?(.+?)\\endpspicture/\\begin\{pspicture$1\}$2\\end\{pspicture$1\}/gmsx;
1707 }
1708
1709 if (exists $plainsyntax{psgraph}) {
1710 Log('Convert plain \psgraph to LaTeX syntax [skip in PSTexample]');
1711 $bodydoc =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
1712 \\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1713 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1714 \\begin\{PSTexample\}.+?\\end\{PSTexample\}(*SKIP)(*F)|
1715 \\psgraph(\*)?(.+?)\\endpsgraph/\\begin\{psgraph$1\}$2\\end\{psgraph$1\}/gmsx;
1716 }
1717
1718 if (exists $plainsyntax{tikzpicture}) {
1719 Log('Convert plain \tikzpicture to LaTeX syntax');
1720 $bodydoc =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
1721 \\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1722 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1723 \\tikzpicture(.+?)\\endtikzpicture/\\begin{tikzpicture}$1\\end{tikzpicture}/gmsx;
1724 }
1725
1726 if (exists $plainsyntax{pgfpicture}) {
1727 Log('Convert plain \pgfpicture to LaTeX syntax');
1728 $bodydoc =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
1729 \\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1730 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1731 \\pgfpicture(.+?)\\endpgfpicture/\\begin{pgfpicture}$1\\end{pgfpicture}/gmsx;
1732 }
1733
1734 ### Force mode for pstricks/psgraph/tikzpiture
1735 if ($opts_cmd{boolean}{force}) {
1736 if (exists $plainsyntax{pspicture} or exists $plainsyntax{psgraph}) {
1737 Log('Try to capture \psset{...} for pstricks environments [force mode]');
1738 $bodydoc =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
1739 \\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1740 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1741 \\begin\{PSTexample\}.+?\\end\{PSTexample\}(*SKIP)(*F)|
1742 \\begin\{postscript\}.+?\\end\{postscript\}(*SKIP)(*F)|
1743 (?<code>
1744 (?:\\psset\{(?:\{.*?\}|[^\{])*\}.+?)? # if exist ...save
1745 \\begin\{(?<env> pspicture\*?| psgraph)\} .+? \\end\{\k<env>\}
1746 )
1747 /\\begin\{preview\}$+{code}\\end\{preview\}/gmsx;
1748 }
1749 if (exists $plainsyntax{tikzpicture}) {
1750 Log('Try to capture \tikzset{...} for tikzpicture environments [force mode]');
1751 $bodydoc =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
1752 \\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1753 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1754 \\begin\{postscript\}.+?\\end\{postscript\}(*SKIP)(*F)|
1755 (?<code>
1756 (?:\\tikzset\{(?:\{.*?\}|[^\{])*\}.+?)? # if exist ...save
1757 \\begin\{(?<env> tikzpicture)\} .+? \\end\{\k<env>\}
1758 )
1759 /\\begin\{preview\}$+{code}\\end\{preview\}/gmsx;
1760 }
1761 }
1762
1763 Log('Pass skip environments to \begin{nopreview} ... \end{nopreview}');
1764 $bodydoc =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
1765 \\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1766 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1767 \\begin\{PSTexample\}.+?\\end\{PSTexample\}(*SKIP)(*F)|
1768 ($skip_env)/\\begin\{nopreview\}$1\\end\{nopreview\}/gmsx;
1769
1770 ### Pass all captured environments in body \begin{preview} ... \end{preview}
1771 Log('Pass all captured environments to \begin{preview} ... \end{preview}');
1772 $bodydoc =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
1773 \\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1774 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1775 ($extr_tmp)/\\begin\{preview\}$1\\end\{preview\}/gmsx;
1776
1777 ########################################################################
1778 # All environments are now classified: #
1779 # Extraction -> \begin{preview} ... \end{preview} #
1780 # No Extraction -> \begin{nopreview} ... \end{nopreview} #
1781 # Verbatim's -> %<\*$dtxverb> ... <\/$dtxverb> #
1782 ########################################################################
1783
1784 ### The %<*remove> ... %</remove> tags need a special treatment :)
1785 $bodydoc =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
1786 \\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1787 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1788 ^(\%<(?:\*|\/))(remove)(\>)/$1$2$tmp$3/gmsx;
1789 $preamble =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
1790 \\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1791 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1792 ^(\%<(?:\*|\/))(remove)(\>)/$1$2$tmp$3/gmsx;
1793 $atbegindoc =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
1794 \\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
1795 \\begin\{preview\}.+?\\end\{preview\}(*SKIP)(*F)|
1796 ^(\%<(?:\*|\/))(remove)(\>)/$1$2$tmp$3/gmsx;
1797
1798 ### Pass \begin{preview} ... \end{preview} to \START{preview} ... \STOP{preview}
1799 ### Pass \begin{nopreview} ... \end{nopreview} to \START{nopreview} ... \STOP{nopreview}
1800 $bodydoc =~ s/\\begin\{((no)?preview)\}/\\START\{$1\}/gmsx;
1801 $bodydoc =~ s/\\end\{((no)?preview)\}/\\STOP\{$1\}/gmsx;
1802
1803 ### We restore the changes of all environments in body
1804 my @lineas = split /\n/, $bodydoc;
1805 my $NEWDEL;
1806 for (@lineas) {
1807 %replace = (%changes_out);
1808 $find = join q{|}, map { quotemeta } sort { length $a <=> length $b } keys %replace;
1809 if (/\\START\{((no)?preview)(?{ $NEWDEL = "\Q$^N" })\}/ .. /\\STOP\{$NEWDEL\}/) {
1810 s/($find)/$replace{$1}/msgx;
1811 }
1812 if (/\%<\*($dtxverb)(?{ $NEWDEL = "\Q$^N" })>/ .. /\%<\/$NEWDEL>/) {
1813 s/($find)/$replace{$1}/msgx;
1814 }
1815 }
1816 $bodydoc = join "\n", @lineas;
1817
1818 ### We restore the changes of all environments in preamble
1819 while ($preamble =~ /\%<\*$dtxverb>(.+?)\%<\/$dtxverb>/pgmsx) {
1820 %cambios = (%changes_out);
1821 my ($pos_inicial, $pos_final) = ($-[0], $+[0]);
1822 my $encontrado = ${^MATCH};
1823 while (my($busco, $cambio) = each %cambios) {
1824 $encontrado =~ s/\Q$busco\E/$cambio/msxg;
1825 }
1826 substr $preamble, $pos_inicial, $pos_final-$pos_inicial, $encontrado;
1827 pos ($preamble) = $pos_inicial + length $encontrado;
1828 }
1829
1830 ### Set wrapped environments for extraction
1831 my $wrapping = "$scriptname$tmp";
1832 Log("Set up the environment [$wrapping] to encapsulate the extraction");
1833
1834 ### Set vars for match/regex
1835 my $BP = "\\\\begin\{$wrapping\}";
1836 my $EP = "\\\\end\{$wrapping\}";
1837 my $BE = '\\\\begin\{PSTexample\}';
1838 my $EE = '\\\\end\{PSTexample\}';
1839
1840 ### Wrap environments for extraction
1841 Log("Pass all captured environments to \\begin{$wrapping} ... \\end{$wrapping}");
1842 $bodydoc =~ s/\\START\{preview\}
1843 (?<code>.+? )
1844 \\STOP\{preview\}
1845 /\\begin\{$wrapping\}$+{code}\\end\{$wrapping\}/gmsx;
1846
1847 $bodydoc =~ s/\\START\{nopreview\}
1848 (?<code>.+? )
1849 \\STOP\{nopreview\}
1850 /\\begin\{nopreview\}\%$tmp$+{code}\\end\{nopreview\}\%$tmp/gmsx;
1851
1852 ### We put back ltximg tags :)
1853 $bodydoc =~ s/($ltxtags)/$reverse_tag{$1}/gmsx;
1854 $preamble =~ s/($ltxtags)/$reverse_tag{$1}/gmsx;
1855
1856 ### First search PSTexample environments for extract
1857 my @exa_extract = $bodydoc =~ m/(?:\\begin\{$wrapping\})($BE.+?$EE)(?:\\end\{$wrapping\})/gmsx;
1858 my $exaNo = scalar @exa_extract;
1859
1860 ### Set vars for log and print in terminal
1861 my $envEXA = $exaNo > 1 ? 'PSTexample environments' : 'PSTexample environment';
1862 my $fileEXA = $exaNo > 1 ? 'files' : 'file';
1863
1864 ### Check if PSTexample environment found
1865 if ($exaNo!=0) {
1866 $PSTexa = 1;
1867 Log("Found $exaNo $envEXA in $name$ext");
1868 my $figNo = 1;
1869 for my $item (@exa_extract) {
1870 Logline("%##### PSTexample environment captured number $figNo ######%");
1871 Logline($item);
1872 $figNo++;
1873 }
1874 # Add [graphic={[...]...}] to \begin{PSTexample}[...]
1875 Log('Append [graphic={[...]...}] to \begin{PSTexample}[...]');
1876 $figNo = 1;
1877 while ($bodydoc =~ /\\begin\{$wrapping\}(\s*)?\\begin\{PSTexample\}(\[.+?\])?/gsm) {
1878 my $swpl_grap = "graphic=\{\[scale=1\]$opts_cmd{string}{imgdir}/$name-$opts_cmd{string}{prefix}-exa";
1879 my $corchetes = $1;
1880 my ($pos_inicial, $pos_final) = ($-[1], $+[1]);
1881 if (not $corchetes) { $pos_inicial = $pos_final = $+[0]; }
1882 if (not $corchetes or $corchetes =~ /\[\s*\]/) {
1883 $corchetes = "[$swpl_grap-$figNo}]";
1884 }
1885 else { $corchetes =~ s/\]/,$swpl_grap-$figNo}]/; }
1886 substr($bodydoc, $pos_inicial, $pos_final - $pos_inicial) = $corchetes;
1887 pos($bodydoc) = $pos_inicial + length $corchetes;
1888 }
1889 continue { $figNo++; }
1890 Log('Pass PSTexample environments to \begin{nopreview} ... \end{nopreview}');
1891 $bodydoc =~ s/\\begin\{$wrapping\}
1892 (?<code>\\begin\{PSTexample\} .+? \\end\{PSTexample\})
1893 \\end\{$wrapping\}
1894 /\\begin\{nopreview\}\%$tmp$+{code}\\end\{nopreview\}\%$tmp/gmsx;
1895 }
1896
1897 ### Second search standart environments for extract
1898 my @env_extract = $bodydoc =~ m/(?<=$BP)(.+?)(?=$EP)/gms;
1899 my $envNo = scalar @env_extract;
1900
1901 ### Set vars for log and print in terminal
1902 my $envSTD = $envNo > 1 ? 'standard environments' : 'standard environment';
1903 my $fileSTD = $envNo > 1 ? 'files' : 'file';
1904
1905 ### If any standard environments found
1906 if ($envNo!=0) {
1907 $STDenv = 1;
1908 Log("Found $envNo $envSTD in $name$ext");
1909 my $figNo = 1;
1910 for my $item (@env_extract) {
1911 Logline("%##### Standard environment captured number $figNo ######%");
1912 Logline($item);
1913 $figNo++;
1914 }
1915 }
1916
1917 ### Run script process only if any enviroment found in <input file>
1918 if ($envNo == 0 and $exaNo == 0) {
1919 errorUsage("$scriptname can not find any environment to extract in $name$ext");
1920 }
1921
1922 ### Set directory to save generated files, need full path for goog log :)
1923 my $imgdirpath = File::Spec->rel2abs($opts_cmd{string}{imgdir});
1924
1925 if (-e $opts_cmd{string}{imgdir}) {
1926 Infoline("The generated files will be saved in $imgdirpath");
1927 }
1928 else {
1929 Infoline("Creating the directory $imgdirpath to save the generated files");
1930 Infocolor('Running', "mkdir $imgdirpath");
1931 Logline("[perl] mkdir($opts_cmd{string}{imgdir},0744)");
1932 mkdir $opts_cmd{string}{imgdir},0744 or errorUsage("Can't create the directory $opts_cmd{string}{imgdir}");
1933 }
1934
1935 ### Set compiler
1936 my $compiler = $opts_cmd{compiler}{xetex} ? 'xelatex'
1937 : $opts_cmd{compiler}{luatex} ? 'lualatex'
1938 : $opts_cmd{compiler}{latex} ? 'latex'
1939 : $opts_cmd{compiler}{dvips} ? 'latex'
1940 : $opts_cmd{compiler}{dvilua} ? 'dvilualatex'
1941 : $opts_cmd{compiler}{dvipdf} ? 'latex'
1942 : $opts_cmd{compiler}{arara} ? 'arara'
1943 : 'pdflatex'
1944 ;
1945
1946 if (!$opts_cmd{boolean}{norun}) {
1947 if ($compiler eq 'arara') {
1948 Log("The file will be processed using $compiler, no ducks will be harmed in this process");
1949 }
1950 else { Log("The file will be processed using $compiler"); }
1951 }
1952
1953 ### Set option for pdfcrop (last version of pdfcrop https://github.com/ho-tex/pdfcrop)
1954 my $opt_crop = $opts_cmd{compiler}{xetex} ? "--xetex --margins $opts_cmd{string}{margin}"
1955 : $opts_cmd{compiler}{luatex} ? "--luatex --margins $opts_cmd{string}{margin}"
1956 : $opts_cmd{compiler}{latex} ? "--margins $opts_cmd{string}{margin}"
1957 : "--pdftex --margins $opts_cmd{string}{margin}"
1958 ;
1959
1960 ### Set options for preview packpage
1961 my $opt_prew = $opts_cmd{compiler}{xetex} ? 'xetex,'
1962 : $opts_cmd{compiler}{latex} ? q{}
1963 : $opts_cmd{compiler}{dvipdf} ? q{}
1964 : $opts_cmd{compiler}{dvips} ? q{}
1965 : $opts_cmd{compiler}{dvilua} ? q{}
1966 : 'pdftex,'
1967 ;
1968
1969 ########################################################################
1970 # One problem with using arara is that we don't know what the file is #
1971 # really compiled with, this affects [preview] and [pdfcrop]. #
1972 ########################################################################
1973
1974 ### Try to capture arara:compiler in preamble of <input file>
1975 my @arara_engines = qw (latex pdflatex lualatex xelatex luahbtex);
1976 my $arara_engines = join q{|}, map { quotemeta} sort { length $a <=> length $b } @arara_engines;
1977 $arara_engines = qr/\b(?:$arara_engines)/x;
1978 my $arara_rule = qr /^(?:\%\s{1}arara[:]\s{1}) ($arara_engines) /msx;
1979
1980 ### Set options for [compiler], [preview] and [pdfcrop]
1981 if ($compiler eq 'arara') {
1982 Log('Trying to detect some suported [engine] in the rules of arara');
1983 my @engine = $atbegindoc =~ m/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|$arara_rule/msx;
1984 my %engine = map { $_ => 1 } @engine; # anon hash
1985 if (exists $engine{latex}) {
1986 Log('The [latex] engine was found in arara rule');
1987 # Set options for [preview] and [pdfcrop]
1988 $opt_crop = "--margins $opts_cmd{string}{margin}";
1989 $opt_prew = q{};
1990 }
1991 elsif (exists $engine{lualatex} or exists $engine{luahbtex}) {
1992 Log('The [lualatex] engine was found in arara rule');
1993 # Set options for [preview] and [pdfcrop]
1994 $opt_crop = "--luatex --margins $opts_cmd{string}{margin}";
1995 $opt_prew = 'pdftex,';
1996 }
1997 elsif (exists $engine{xelatex}) {
1998 Log('The [xelatex] engine was found in arara rule');
1999 # Set options for [preview] and [pdfcrop]
2000 $opt_crop = "--xetex --margins $opts_cmd{string}{margin}";
2001 $opt_prew = 'xetex,';
2002 }
2003 elsif (exists($engine{pdflatex})) {
2004 Log('The [pdflatex] engine was found in arara rule');
2005 # Set options for [preview] and [pdfcrop]
2006 $opt_crop = "--pdftex --margins $opts_cmd{string}{margin}";
2007 $opt_prew = 'pdftex,';
2008 }
2009 else {
2010 Log('No supported [engine] could be detected, default values will be used');
2011 # Set options for [preview] and [pdfcrop]
2012 $opt_crop = "--pdftex --margins $opts_cmd{string}{margin}";
2013 $opt_prew = 'pdftex,';
2014 }
2015 }
2016
2017 ### Message in command line for compiler
2018 my $msg_compiler = $opts_cmd{compiler}{xetex} ? 'xelatex'
2019 : $opts_cmd{compiler}{luatex} ? 'lualatex'
2020 : $opts_cmd{compiler}{latex} ? 'latex>dvips>ps2pdf'
2021 : $opts_cmd{compiler}{dvips} ? 'latex>dvips>ps2pdf'
2022 : $opts_cmd{compiler}{dvilua} ? 'dvilualatex>dvips>ps2pdf'
2023 : $opts_cmd{compiler}{dvipdf} ? 'latex>dvipdfmx'
2024 : $opts_cmd{compiler}{arara} ? 'arara'
2025 : 'pdflatex'
2026 ;
2027
2028 ### Set write18 for compiler
2029 if ($opts_cmd{boolean}{shell}) {
2030 $write18 = '-shell-escape';
2031 $write18 = '--enable-write18' if defined $ENV{'TEXSYSTEM'} and $ENV{'TEXSYSTEM'} =~ /miktex/i;
2032 }
2033 else {
2034 $write18 = '-no-shell-escape';
2035 $write18 = '--disable-write18' if defined $ENV{'TEXSYSTEM'} and $ENV{'TEXSYSTEM'} =~ /miktex/i;
2036 }
2037
2038 ### Set options for compiler
2039 my $opt_compiler = $opts_cmd{compiler}{arara} ? '--log'
2040 : $opts_cmd{compiler}{xetex} ? "$write18 -interaction=nonstopmode -recorder -no-pdf"
2041 : "$write18 -interaction=nonstopmode -recorder"
2042 ;
2043
2044 if (!$opts_cmd{boolean}{norun}) {
2045 Log("The options '$opt_compiler' will be passed to [$compiler]");
2046 }
2047
2048 ### Set -q for system command line (gs, poppler-utils, dvips, dvipdfmx)
2049 my $quiet = $verbose ? q{}
2050 : '-q'
2051 ;
2052
2053 ### Set options for ghostscript in command line
2054 my %opt_gs_dev = (
2055 pdf => '-dNOSAFER -dBATCH -dNOPAUSE -sDEVICE=pdfwrite',
2056 gray => '-dNOSAFER -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sColorConversionStrategy=Gray -sProcessColorModel=DeviceGray',
2057 png => "-dNOSAFER -dBATCH -dNOPAUSE -sDEVICE=pngalpha -r$opts_cmd{string}{dpi}",
2058 bmp => "-dNOSAFER -dBATCH -dNOPAUSE -sDEVICE=bmp32b -r$opts_cmd{string}{dpi}",
2059 jpg => "-dNOSAFER -dBATCH -dNOPAUSE -sDEVICE=jpeg -r$opts_cmd{string}{dpi} -dJPEGQ=100 -dGraphicsAlphaBits=4 -dTextAlphaBits=4",
2060 tif => "-dNOSAFER -dBATCH -dNOPAUSE -sDEVICE=tiff32nc -r$opts_cmd{string}{dpi}",
2061 );
2062
2063 ### Set executable from poppler-utils
2064 my %cmd_poppler = (
2065 eps => "pdftops",
2066 ppm => "pdftoppm",
2067 svg => "pdftocairo",
2068 );
2069
2070 ### Set options for poppler-utils
2071 my %opt_poppler = (
2072 eps => "$quiet -eps",
2073 ppm => "$quiet -r $opts_cmd{string}{dpi}",
2074 svg => "$quiet -svg",
2075 );
2076
2077 ### Copy preamble and body for temp file with all environments
2078 my $atbeginout = $atbegindoc;
2079 my $preamout = $preamble;
2080 my $tmpbodydoc = $bodydoc;
2081
2082 ### Match \pagestyle and \thispagestyle in preamble
2083 my $style_page = qr /(?:\\)(?:this)?(?:pagestyle\{) (.+?) (?:\})/x;
2084 my @style_page = $preamout =~ m/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)| $style_page/gmsx;
2085 my %style_page = map { $_ => 1 } @style_page; # anon hash
2086
2087 ### Seting \pagestyle{empty} for subfiles and process
2088 if (@style_page) {
2089 if (!exists $style_page{empty}) {
2090 Log("Replacing page style for generated files");
2091 $preamout =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
2092 (\\(this)?pagestyle)(?:\{.+?\})/$1\{empty\}/gmsx;
2093 }
2094 }
2095 else {
2096 Log('Add \pagestyle{empty} for generated files');
2097 $preamout = $preamout."\\pagestyle\{empty\}\n";
2098 }
2099
2100 #### Remove wraped postscript environments provide by pst-pdf, auto-pst-pdf, auto-pst-pdf-lua pkgs
2101 Log("Convert postscript environments to \\begin\{$wrapping\} ... \\end\{$wrapping\} for standalone files");
2102 $tmpbodydoc =~ s/(?:$BP)(?:\\begin\{postscript\})(?:\s*\[ [^]]*? \])?
2103 (?<code>.+?)
2104 (?:\\end\{postscript\})
2105 (?:$EP)
2106 /\\begin\{$wrapping\}$+{code}\\end\{$wrapping\}/gmsx;
2107
2108 ### We created a preamble for standalone files
2109 my $sub_prea = "$atbeginout$preamout".'\begin{document}';
2110
2111 ### Revert changes
2112 $sub_prea =~ s/\%<\*$dtxverb>\s*(.+?)\s*\%<\/$dtxverb>/$1/gmsx;
2113 %replace = (%changes_out);
2114 $find = join q{|}, map { quotemeta } sort { length $a <=> length $b } keys %replace;
2115 $sub_prea =~ s/($find)/$replace{$1}/g;
2116 $sub_prea =~ s/(remove$tmp)/remove/g;
2117
2118 ### Write standalone files for environments
2119 if ($outsrc) {
2120 my $src_name = "$name-$opts_cmd{string}{prefix}-";
2121 my $srcNo = 1;
2122 if ($opts_cmd{boolean}{srcenv}) {
2123 Log('Extract source code of all captured environments without preamble');
2124 if ($STDenv) {
2125 if (-e "$opts_cmd{string}{imgdir}/$name-$opts_cmd{string}{prefix}-1$ext") {
2126 Log("Recreating $envNo $fileSTD [$ext] with source code for $envSTD in $imgdirpath");
2127 print "Recreating $envNo $fileSTD ", color('magenta'), "[$ext]",
2128 color('reset'), " with source code for $envSTD\r\n";
2129 }
2130 else {
2131 Log("Creating $envNo $fileSTD [$ext] with source code for $envSTD in $imgdirpath");
2132 print "Creating $envNo $fileSTD ", color('magenta'), "[$ext]",
2133 color('reset'), " with source code for $envSTD\r\n";
2134 }
2135 # Write files
2136 while ($tmpbodydoc =~ m/$BP\s*(?<env_src>.+?)\s*$EP/gms) {
2137 open my $outexasrc, '>', "$opts_cmd{string}{imgdir}/$src_name$srcNo$ext";
2138 print {$outexasrc} $+{'env_src'};
2139 close $outexasrc;
2140 }
2141 continue { $srcNo++; }
2142 }
2143 if ($PSTexa) {
2144 if (-e "$opts_cmd{string}{imgdir}/$name-$opts_cmd{string}{prefix}-exa-1$ext") {
2145 Log("Recreating $exaNo $fileEXA [$ext] with source code for $envEXA in $imgdirpath");
2146 print "Recreating $exaNo $fileEXA ", color('magenta'), "[$ext]",
2147 color('reset'), " with source code for $envEXA\r\n";
2148 }
2149 else {
2150 Log("Creating $exaNo $fileEXA [$ext] with source code for $envEXA in $imgdirpath");
2151 print "Creating $exaNo $fileEXA ", color('magenta'), "[$ext]",
2152 color('reset'), " with source code for $envEXA\r\n";
2153 }
2154 # Write files
2155 while ($tmpbodydoc =~ m/$BE\[.+?(?<pst_exa_name>$opts_cmd{string}{imgdir}\/.+?-\d+)\}\]\s*(?<exa_src>.+?)\s*$EE/gms) {
2156 open my $outstdsrc, '>', "$+{'pst_exa_name'}$ext";
2157 print {$outstdsrc} $+{'exa_src'};
2158 close $outstdsrc;
2159 }
2160 }
2161 }
2162 if ($opts_cmd{boolean}{subenv}) {
2163 Log('Extract source code of all captured environments with preamble');
2164 if ($STDenv) {
2165 if (-e "$opts_cmd{string}{imgdir}/$name-$opts_cmd{string}{prefix}-1$ext") {
2166 Log("Recreating a $envNo standalone $fileSTD [$ext] for $envSTD in $imgdirpath");
2167 print "Recreating a $envNo standalone $fileSTD ", color('magenta'), "[$ext]",
2168 color('reset'), " for $envSTD\r\n";
2169 }
2170 else {
2171 Log("Creating a $envNo standalone $fileSTD [$ext] for $envSTD in $imgdirpath");
2172 print "Creating a $envNo standalone $fileSTD ", color('magenta'), "[$ext]",
2173 color('reset'), " for $envSTD\r\n";
2174 }
2175 # Write files
2176 while ($tmpbodydoc =~ m/$BP(?:\s*)?(?<env_src>.+?)(?:\s*)?$EP/gms) {
2177 open my $outstdfile, '>', "$opts_cmd{string}{imgdir}/$src_name$srcNo$ext";
2178 print {$outstdfile} "$sub_prea\n$+{'env_src'}\n\\end\{document\}";
2179 close $outstdfile;
2180 }
2181 continue { $srcNo++; }
2182 }
2183 if ($PSTexa) {
2184 if (-e "$opts_cmd{string}{imgdir}/$name-$opts_cmd{string}{prefix}-exa-1$ext") {
2185 Log("Recreating a $exaNo standalone $fileEXA [$ext] for $envEXA in $imgdirpath");
2186 print "Recreating a $exaNo standalone $fileEXA ", color('magenta'), "[$ext]",
2187 color('reset'), " for $envEXA\r\n";
2188 }
2189 else {
2190 Log("Creating a $exaNo standalone $fileEXA [$ext] for $envEXA in $imgdirpath");
2191 print "Creating a $exaNo standalone $fileEXA ", color('magenta'), "[$ext]",
2192 color('reset'), " for $envEXA\r\n";
2193 }
2194 # Write files
2195 while ($tmpbodydoc =~ m/$BE\[.+?(?<pst_exa_name>$opts_cmd{string}{imgdir}\/.+?-\d+)\}\]\s*(?<exa_src>.+?)\s*$EE/gms) {
2196 open my $outexafile, '>', "$+{'pst_exa_name'}$ext";
2197 print {$outexafile} "$sub_prea\n$+{'exa_src'}\n\\end\{document\}";
2198 close $outexafile;
2199 }
2200 }
2201 }
2202 }
2203
2204 ### Store options for preview and pst-pdf (add at begin document)
2205 my $previewpkg = <<"EXTRA";
2206 \\PassOptionsToPackage\{inactive\}\{pst-pdf\}%
2207 \\AtBeginDocument\{%
2208 \\RequirePackage\[inactive\]\{pst-pdf\}%
2209 \\RequirePackage\[${opt_prew}active,tightpage\]\{preview\}%
2210 \\renewcommand\\PreviewBbAdjust\{-60pt -60pt 60pt 60pt\}\}%
2211 EXTRA
2212
2213 ### Store options for pst-pdf (add at begin document)
2214 my $pstpdfpkg = <<'EXTRA';
2215 \PassOptionsToPackage{inactive}{pst-pdf}
2216 \AtBeginDocument{%
2217 \RequirePackage[inactive]{pst-pdf}}%
2218 EXTRA
2219
2220 ### First match preview package in preamble (prevent option clash)
2221 my $REQPACK = quotemeta'\RequirePackage';
2222 my $USEPACK = quotemeta'\usepackage';
2223 my $CORCHETES = qr/\[ [^]]*? \]/x;
2224
2225 my $PALABRAS = qr/\b (?: preview )/x;
2226 my $FAMILIA = qr/\{ \s* $PALABRAS (?: \s* [,] \s* $PALABRAS )* \s* \}(\%*)?/x;
2227
2228 Log('Remove preview package (if found) in preamble [memory]');
2229 $preamout =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
2230 ^ $USEPACK (?: $CORCHETES )? $FAMILIA \s*//msxg;
2231 $preamout =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
2232 (?: ^ $USEPACK \{ | \G) [^}]*? \K (,?) \s* $PALABRAS (\s*) (,?) /$1 and $3 ? ',' : $1 ? $2 : ''/gemsx;
2233 $preamout =~ s/^\\usepackage\{\}(?:[\t ]*(?:\r?\n|\r))+/\n/gmsx;
2234
2235 ### Remove %<*$dtxverb> ... %</$dtxverb> in tmpbodydoc and preamout
2236 $tmpbodydoc =~ s/\%<\*$dtxverb>(.+?)\%<\/$dtxverb>/$1/gmsx;
2237 $preamout =~ s/\%<\*$dtxverb>(.+?)\%<\/$dtxverb>/$1/gmsx;
2238 $atbeginout =~ s/\%<\*$dtxverb>(.+?)\%<\/$dtxverb>/$1/gmsx;
2239
2240 ### Adjust nopreview environments
2241 $tmpbodydoc =~ s/\\begin\{nopreview\}\%$tmp
2242 (?<code> .+?)
2243 \\end\{nopreview\}\%$tmp
2244 /\\begin\{nopreview\}\n$+{code}\n\\end\{nopreview\}\n/gmsx;
2245
2246 ### Adjust $wrapping environments (need \n after close for some environments, like a Verbatim)
2247 $tmpbodydoc =~ s/\\begin\{$wrapping\}
2248 (?<code>.+?)
2249 \\end\{$wrapping\}
2250 /\\begin\{$wrapping\}\n$+{code}\n\\end\{$wrapping\}/gmsx;
2251
2252 ### Reverse changes for temporary file with all env (no in -exa file)
2253 $tmpbodydoc =~ s/($find)/$replace{$1}/g;
2254 $tmpbodydoc =~ s/(\%$tmp)//g;
2255 $tmpbodydoc =~ s/(remove$tmp)/remove/g;
2256 $preamout =~ s/($find)/$replace{$1}/g;
2257 $atbeginout =~ s/(remove$tmp)/remove/g;
2258 $atbeginout =~ s/($find)/$replace{$1}/g;
2259
2260 ### We created a preamble for individual files with all environments
2261 $sub_prea = $opts_cmd{boolean}{noprew} ? "$atbeginout$pstpdfpkg$preamout".'\begin{document}'
2262 : "$atbeginout$previewpkg$preamout"
2263 ;
2264
2265 ### Create a one file with "all" PSTexample environments extracted
2266 if ($PSTexa) {
2267 @exa_extract = undef;
2268 Log("Adding packages to $name-$opts_cmd{string}{prefix}-exa-$tmp$ext");
2269 Logline($pstpdfpkg);
2270 Log('Convert plain Tex syntax for pspicture and psgraph to LaTeX syntax in PSTexample environments');
2271 while ($tmpbodydoc =~ m/$BE\[.+? $opts_cmd{string}{imgdir}\/.+?-\d+\}\] .+?$EE/pgsmx ) { # search
2272 my ($pos_inicial, $pos_final) = ($-[0], $+[0]);
2273 my $encontrado = ${^MATCH};
2274 $encontrado =~ s/\\pspicture(\*)?(.+?)\\endpspicture/\\begin\{pspicture$1\}$2\\end\{pspicture$1\}/gmsx;
2275 $encontrado =~ s/\\psgraph(\*)?(.+?)\\endpsgraph/\\begin\{psgraph$1\}$2\\end\{psgraph$1\}/gmsx;
2276 substr $tmpbodydoc, $pos_inicial, $pos_final-$pos_inicial, $encontrado;
2277 pos ($tmpbodydoc) = $pos_inicial + length $encontrado;
2278 }
2279 # Write files
2280 Infoline("Creating $name-$opts_cmd{string}{prefix}-exa-$tmp$ext with $exaNo $envEXA extracted");
2281 while ($tmpbodydoc =~ m/$BE\[.+? $opts_cmd{string}{imgdir}\/.+?-\d+\}\](?<exa_src>.+?)$EE/gmsx ) { # search
2282 push @exa_extract, $+{'exa_src'}."\\newpage\n";
2283 open my $allexaenv, '>', "$name-$opts_cmd{string}{prefix}-exa-$tmp$ext";
2284 print {$allexaenv} "$atbeginout$pstpdfpkg$preamout".'\begin{document}'."@exa_extract"."\\end\{document\}";
2285 close $allexaenv;
2286 }
2287 # Remove [graphic={...}] in PSTexample example environments
2288 $tmpbodydoc =~ s/($BE)(?:\[graphic=\{\[scale=1\]$opts_cmd{string}{imgdir}\/.+?-\d+\}\])/$1/gmsx;
2289 $tmpbodydoc =~ s/($BE\[.+?)(?:,graphic=\{\[scale=1\]$opts_cmd{string}{imgdir}\/.+?-\d+\})(\])/$1$2/gmsx;
2290 # Moving and renaming
2291 if ($opts_cmd{boolean}{norun}) {
2292 Infoline("Moving and renaming $name-$opts_cmd{string}{prefix}-exa-$tmp$ext to $name-$opts_cmd{string}{prefix}-exa-all$ext");
2293 if (-e "$opts_cmd{string}{imgdir}/$name-$opts_cmd{string}{prefix}-exa-all$ext") {
2294 Infocolor('Warning', "The file [$name-$opts_cmd{string}{prefix}-exa-all$ext] already exists and will be rewritten");
2295 Log("Rewriting the file $name-$opts_cmd{string}{prefix}-exa-all$ext in $imgdirpath");
2296 }
2297 else {
2298 Log("Writing the file $name-$opts_cmd{string}{prefix}-exa-all$ext in $imgdirpath");
2299 }
2300 if ($verbose) {
2301 Infocolor('Running', "mv $workdir/$name-$opts_cmd{string}{prefix}-exa-$tmp$ext $imgdirpath/$name-$opts_cmd{string}{prefix}-exa-all$ext");
2302 }
2303 else {
2304 Infocolor('Running', "mv $name-$opts_cmd{string}{prefix}-exa-$tmp$ext ./$opts_cmd{string}{imgdir}/$name-$opts_cmd{string}{prefix}-exa-all$ext");
2305 }
2306 Logline("[perl] move($workdir/$name-$opts_cmd{string}{prefix}-exa-$tmp$ext, $imgdirpath/$name-$opts_cmd{string}{prefix}-exa-all$ext)");
2307 move("$workdir/$name-$opts_cmd{string}{prefix}-exa-$tmp$ext", "$opts_cmd{string}{imgdir}/$name-$opts_cmd{string}{prefix}-exa-all$ext")
2308 or die "* Error!!: Couldn't be renamed $name-$opts_cmd{string}{prefix}-exa-$tmp$ext to ./$opts_cmd{string}{imgdir}/$name-$opts_cmd{string}{prefix}-exa-all$ext";
2309 }
2310 }
2311
2312 ### Create a one file with "all" standard environments extracted
2313 if ($STDenv) {
2314 if ($opts_cmd{boolean}{noprew}) {
2315 Log("Creating $name-$opts_cmd{string}{prefix}-$tmp$ext with $envNo $envSTD extracted [no preview]");
2316 print "Creating $name-$opts_cmd{string}{prefix}-$tmp$ext with $envNo $envSTD extracted",
2317 color('magenta'), " [no preview]\r\n",color('reset');
2318 }
2319 else {
2320 Log("Creating $name-$opts_cmd{string}{prefix}-$tmp$ext with $envNo $envSTD extracted [preview]");
2321 print "Creating $name-$opts_cmd{string}{prefix}-$tmp$ext with $envNo $envSTD extracted",
2322 color('magenta'), " [preview]\r\n",color('reset');
2323 }
2324 open my $allstdenv, '>', "$name-$opts_cmd{string}{prefix}-$tmp$ext";
2325 if ($opts_cmd{boolean}{noprew}) {
2326 my @env_extract;
2327 while ($tmpbodydoc =~ m/(?:$BP)(?<env_src>.+?)(?:$EP)/gms) {
2328 push @env_extract, $+{'env_src'}."\\newpage\n";
2329 }
2330 Log("Adding packages to $name-$opts_cmd{string}{prefix}-$tmp$ext");
2331 Logline($pstpdfpkg);
2332 print {$allstdenv} $sub_prea."@env_extract"."\\end{document}";
2333 }
2334 else {
2335 Log("Adding packages to $name-$opts_cmd{string}{prefix}-$tmp$ext");
2336 Logline($previewpkg);
2337 Log("Convert $wrapping to preview environments in $name-$opts_cmd{string}{prefix}-$tmp$ext");
2338 # Convert $wrapping to preview environments
2339 $tmpbodydoc =~ s/\\begin\{$wrapping\}(?<code>.+?)\\end\{$wrapping\}
2340 /\\begin\{preview\}$+{code}\\end\{preview\}\n/gmsx;
2341 print {$allstdenv} $sub_prea.$tmpbodydoc."\n\\end{document}";
2342 }
2343 close $allstdenv;
2344 if ($opts_cmd{boolean}{norun}) {
2345 # Moving and renaming
2346 Infoline("Moving and renaming $name-$opts_cmd{string}{prefix}-$tmp$ext to $name-$opts_cmd{string}{prefix}-all$ext");
2347 if (-e "$opts_cmd{string}{imgdir}/$name-$opts_cmd{string}{prefix}-all$ext") {
2348 Infocolor('Warning', "The file [$name-$opts_cmd{string}{prefix}-all$ext] already exists and will be rewritten");
2349 Log("Rewriting the file $name-$opts_cmd{string}{prefix}-all$ext in $imgdirpath");
2350 }
2351 else {
2352 Log("Writing the file $name-$opts_cmd{string}{prefix}-all$ext in $imgdirpath");
2353 }
2354 if ($verbose) {
2355 Infocolor('Running', "mv $workdir/$name-$opts_cmd{string}{prefix}-$tmp$ext $imgdirpath/$name-$opts_cmd{string}{prefix}-all$ext");
2356 }
2357 else {
2358 Infocolor('Running', "mv $name-$opts_cmd{string}{prefix}-$tmp$ext ./$opts_cmd{string}{imgdir}/$name-$opts_cmd{string}{prefix}-all$ext");
2359 }
2360 Logline("[perl] move($workdir/$name-$opts_cmd{string}{prefix}-$tmp$ext, $imgdirpath/$name-$opts_cmd{string}{prefix}-all$ext)");
2361 move("$workdir/$name-$opts_cmd{string}{prefix}-$tmp$ext", "$opts_cmd{string}{imgdir}/$name-$opts_cmd{string}{prefix}-all$ext")
2362 or die "* Error!!: Couldn't be renamed $name-$opts_cmd{string}{prefix}-$tmp$ext to ./$opts_cmd{string}{imgdir}/$name-$opts_cmd{string}{prefix}-all$ext";
2363 }
2364 }
2365
2366 ### Compiler and generate PDF files -dALLOWPSTRANSPARENCY
2367 if (!$opts_cmd{boolean}{norun}) {
2368 Log('Generate a PDF file with all captured environments');
2369 my @compiler = (1..$opts_cmd{string}{runs});
2370 opendir (my $DIR, $workdir);
2371 while (readdir $DIR) {
2372 if (/(?<name>$name-$opts_cmd{string}{prefix}(-exa)?)(?<type>-$tmp$ext)/) {
2373 Log("Compiling the file $+{name}$+{type} using [$msg_compiler]");
2374 print "Compiling the file $+{name}$+{type} using ", color('magenta'), "[$msg_compiler]\r\n",color('reset');
2375 for (@compiler){
2376 RUNOSCMD("$compiler $opt_compiler","$+{name}$+{type}",'show');
2377 }
2378 # Using xdvipdfmx
2379 if ($compiler eq 'xelatex') {
2380 RUNOSCMD("xdvipdfmx $quiet -E", "-o $+{name}-$tmp.pdf $+{name}-$tmp.xdv",'show');
2381 }
2382 # Compiling file using latex>dvips>ps2pdf
2383 if ($compiler eq 'dvips' or $compiler eq 'latex' or $compiler eq 'dvilualatex') {
2384 RUNOSCMD("dvips $quiet -Ppdf", "-o $+{name}-$tmp.ps $+{name}-$tmp.dvi",'show');
2385 RUNOSCMD("ps2pdf -sPDFSETTINGS=prepress -sAutoRotatePages=None -dALLOWPSTRANSPARENCY", "$+{name}-$tmp.ps $+{name}-$tmp.pdf",'show');
2386 }
2387 # Compiling file using latex>dvipdfmx
2388 if ($compiler eq 'dvipdf') {
2389 RUNOSCMD("dvipdfmx $quiet", "$+{name}-$tmp.dvi",'show');
2390 }
2391 # Moving and renaming temp files with source code
2392 Infoline("Moving and renaming $+{name}$+{type} to $+{name}-all$ext");
2393 if (-e "$opts_cmd{string}{imgdir}/$+{name}-all$ext") {
2394 Infocolor('Warning', "The file [$+{name}-all$ext] already exists and will be rewritten");
2395 Log("Rewriting the file $+{name}-all$ext with all source for environments in $imgdirpath");
2396 }
2397 else {
2398 Log("Writing the file $+{name}-all$ext with all source for environments in $imgdirpath");
2399 }
2400 if ($verbose){
2401 Infocolor('Running', "mv $workdir/$+{name}$+{type} $imgdirpath/$+{name}-all$ext");
2402 }
2403 else {
2404 Infocolor('Running', "mv $+{name}$+{type} ./$opts_cmd{string}{imgdir}/$+{name}-all$ext");
2405 }
2406 Logline("[perl] move($workdir/$+{name}$+{type}, $imgdirpath/$+{name}-all$ext)");
2407 move("$workdir/$+{name}$+{type}", "$opts_cmd{string}{imgdir}/$+{name}-all$ext")
2408 or die "* Error!!: Couldn't be renamed $+{name}$+{type} to $opts_cmd{string}{imgdir}/$+{name}-all$ext";
2409 # pdfcrop
2410 if (!$opts_cmd{boolean}{nocrop}) {
2411 Infoline("Cropping the file $+{name}-$tmp.pdf");
2412 RUNOSCMD("pdfcrop $opt_crop", "$+{name}-$tmp.pdf $+{name}-$tmp.pdf",'show');
2413 }
2414 # gray
2415 if ($opts_cmd{boolean}{gray}) {
2416 Infoline("Creating the file $+{name}-all.pdf [gray] in $tempDir");
2417 RUNOSCMD("$gscmd $quiet $opt_gs_dev{gray} ","-o $tempDir/$+{name}-all.pdf $workdir/$+{name}-$tmp.pdf",'show');
2418 }
2419 else {
2420 Infoline("Creating the file $+{name}-all.pdf in $tempDir");
2421 if ($verbose){
2422 Infocolor('Running', "mv $workdir/$+{name}-$tmp.pdf $tempDir/$+{name}-all.pdf");
2423 }
2424 else { Infocolor('Running', "mv $+{name}-$tmp.pdf $tempDir/$+{name}-all.pdf"); }
2425 # Renaming pdf file
2426 Logline("[perl] move($workdir/$+{name}-$tmp.pdf, $tempDir/$+{name}-all.pdf)");
2427 move("$workdir/$+{name}-$tmp.pdf", "$tempDir/$+{name}-all.pdf")
2428 or die "* Error!!: Couldn't be renamed $+{name}-$tmp.pdf to $tempDir/$+{name}-all.pdf";
2429 }
2430 }
2431 }
2432 closedir $DIR;
2433 }
2434
2435 ### Create image formats in separate files
2436 if (!$opts_cmd{boolean}{norun}) {
2437 Log("Creating the image formats: $format, working on $tempDir");
2438 opendir(my $DIR, $tempDir);
2439 while (readdir $DIR) {
2440 # PDF/PNG/JPG/BMP/TIFF format suported by ghostscript
2441 if (/(?<name>$name-$opts_cmd{string}{prefix}(-exa)?)(?<type>-all\.pdf)/) {
2442 for my $var (qw(pdf png jpg bmp tif)) {
2443 if (defined $opts_cmd{image}{$var}) {
2444 Log("Generating format [$var] from file $+{name}$+{type} in $imgdirpath using $gscmd");
2445 print 'Generating format', color('blue'), " [$var] ", color('reset'),"from file $+{name}$+{type}\r\n";
2446 RUNOSCMD("$gscmd $quiet $opt_gs_dev{$var} ", "-o $workdir/$opts_cmd{string}{imgdir}/$+{name}-%1d.$var $tempDir/$+{name}$+{type}",'show');
2447 }
2448 }
2449 }
2450 # EPS/PPM/SVG format suported by poppler-utils
2451 if (/(?<name>$name-$opts_cmd{string}{prefix}-exa)(?<type>-all\.pdf)/) { # pst-exa package
2452 for my $var (qw(eps ppm svg)) {
2453 if (defined $opts_cmd{image}{$var}) {
2454 Log("Generating format [$var] from file $+{name}$+{type} in $imgdirpath using $cmd_poppler{$var}");
2455 print 'Generating format', color('blue'), " [$var] ", color('reset'),"from file $+{name}$+{type}\r\n";
2456 if (!$verbose){
2457 Infocolor('Running', "$cmd_poppler{$var} $opt_poppler{$var}");
2458 }
2459 for (my $epsNo = 1; $epsNo <= $exaNo; $epsNo++) {
2460 RUNOSCMD("$cmd_poppler{$var} $opt_poppler{$var}", "-f $epsNo -l $epsNo $tempDir/$+{name}$+{type} $workdir/$opts_cmd{string}{imgdir}/$+{name}-$epsNo.$var",'only');
2461 }
2462 }
2463 }
2464 }
2465 if (/(?<name>$name-$opts_cmd{string}{prefix})(?<type>-all\.pdf)/) {
2466 for my $var (qw(eps ppm svg)) {
2467 if (defined $opts_cmd{image}{$var}) {
2468 Log("Generating format [$var] from file $+{name}$+{type} in $imgdirpath using $cmd_poppler{$var}");
2469 print 'Generating format', color('blue'), " [$var] ", color('reset'),"from file $+{name}$+{type}\r\n";
2470 if (!$verbose){
2471 Infocolor('Running', "$cmd_poppler{$var} $opt_poppler{$var}");
2472 }
2473 for (my $epsNo = 1; $epsNo <= $envNo; $epsNo++) {
2474 RUNOSCMD("$cmd_poppler{$var} $opt_poppler{$var}", "-f $epsNo -l $epsNo $tempDir/$+{name}$+{type} $workdir/$opts_cmd{string}{imgdir}/$+{name}-$epsNo.$var",'only');
2475 }
2476 }
2477 }
2478 }
2479 } # close while
2480 closedir $DIR;
2481 # Renaming PPM image files
2482 if (defined $opts_cmd{image}{ppm}) {
2483 Log("Renaming [ppm] images in $imgdirpath");
2484 if ($verbose){
2485 print 'Renaming', color('blue'), " [ppm] ", color('reset'),"images in $imgdirpath\r\n";
2486 }
2487 opendir(my $DIR, $opts_cmd{string}{imgdir});
2488 while (readdir $DIR) {
2489 if (/(?<name>$name-$opts_cmd{string}{prefix}(-exa)?-\d+\.ppm)(?<sep>-\d+)(?<ppm>\.ppm)/) {
2490 if ($verbose){
2491 Infocolor('Running', "mv $+{name}$+{sep}$+{ppm} $+{name}");
2492 }
2493 Logline("[perl] move($imgdirpath/$+{name}$+{sep}$+{ppm}, $imgdirpath/$+{name})");
2494 move("$opts_cmd{string}{imgdir}/$+{name}$+{sep}$+{ppm}", "$opts_cmd{string}{imgdir}/$+{name}")
2495 or die "* Error!!: Couldn't be renamed $+{name}$+{sep}$+{ppm} to $+{name}";
2496 }
2497 }
2498 closedir $DIR;
2499 }
2500 } # close run
2501
2502 ### Constant
2503 my $findgraphicx = 'true';
2504
2505 ### Add $atbegindoc to $preamble
2506 $preamble = "$atbegindoc$preamble";
2507
2508 ### Replacing the extracted environments with \\includegraphics
2509 if ($outfile) {
2510 my @tag_remove_preamble = $preamble =~ m/(?:^\%<\*remove$tmp>.+?\%<\/remove$tmp>)/gmsx;
2511 if (@tag_remove_preamble) {
2512 Log("Removing the content between <*remove> ... </remove> tags in preamble for $opts_cmd{string}{output}$outext");
2513 $preamble =~ s/^\%<\*remove$tmp>\s*(.+?)\s*\%<\/remove$tmp>(?:[\t ]*(?:\r?\n|\r))?+//gmsx;
2514 }
2515 Log("Convert standard extracted environments to \\includegraphics for $opts_cmd{string}{output}$outext");
2516 my $grap = "\\includegraphics[scale=1]{$name-$opts_cmd{string}{prefix}-";
2517 my $close = '}';
2518 my $imgNo = 1;
2519 $bodydoc =~ s/$BP.+?$EP/$grap@{[$imgNo++]}$close/msg;
2520 }
2521
2522 ### pst-exa package
2523 my $pstexa = qr/(?:\\ usepackage) \[\s*(.+?)\s*\] (?:\{\s*(pst-exa)\s*\} ) /x;
2524 my @pst_exa;
2525 my %pst_exa;
2526
2527 ### Search pst-exa package
2528 @pst_exa = $preamble =~ m/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|$pstexa/gmsx;
2529 %pst_exa = map { $_ => 1 } @pst_exa;
2530
2531 ### If found comment and adjust path for graphic files
2532 if (@pst_exa and $outfile) {
2533 Log("Comment pst-exa package in preamble for $opts_cmd{string}{output}$outext");
2534 $findgraphicx = 'false';
2535 $preamble =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
2536 (\\usepackage\[)\s*(swpl|tcb)\s*(\]\{pst-exa\})/\%$1$2,pdf$3/msxg;
2537 if (exists $pst_exa{tcb}) {
2538 Log("Suport for \\usepackage[tcb,pdf]\{pst-exa\} for $opts_cmd{string}{output}$outext");
2539 $bodydoc =~ s/(graphic=\{)\[(scale=\d*)\]($opts_cmd{string}{imgdir}\/$name-$opts_cmd{string}{prefix}-exa-\d*)\}/$1$2\}\{$3\}/gsmx;
2540 }
2541 }
2542
2543 ### Regex for clean file (pst) in preamble
2544 $PALABRAS = qr/\b (?: pst-\w+ | pstricks (?: -add | -pdf )? | psfrag |psgo |vaucanson-g| auto-pst-pdf(?: -lua )? )/x;
2545 $FAMILIA = qr/\{ \s* $PALABRAS (?: \s* [,] \s* $PALABRAS )* \s* \}(\%*)?/x;
2546
2547 ### Clean PSTricks content in preamble
2548 if ($clean{pst} and $outfile) {
2549 Log("Remove pstricks packages in preamble for $opts_cmd{string}{output}$outext");
2550 $preamble =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
2551 ^ $USEPACK (?: $CORCHETES )? $FAMILIA \s*//msxg;
2552 $preamble =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
2553 (?: ^ $USEPACK \{ | \G) [^}]*? \K (,?) \s* $PALABRAS (\s*) (,?) /$1 and $3 ? ',' : $1 ? $2 : ''/gemsx;
2554 Log("Remove \\psset\{...\} in preamble for $opts_cmd{string}{output}$outext");
2555 $preamble =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
2556 \\psset\{(?:\{.*?\}|[^\{])*\}(?:[\t ]*(?:\r?\n|\r))+//gmsx;
2557 Log("Remove \\SpecialCoor in preamble for $opts_cmd{string}{output}$outext");
2558 $preamble =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
2559 \\SpecialCoor(?:[\t ]*(?:\r?\n|\r))+//gmsx;
2560 Log("Remove empty lines in preamble for $opts_cmd{string}{output}$outext");
2561 $preamble =~ s/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|
2562 ^\\usepackage\{\}(?:[\t ]*(?:\r?\n|\r))+/\n/gmsx;
2563 }
2564
2565 ### Uncomment pst-exa package
2566 if (@pst_exa and $outfile) {
2567 Log("Uncomment pst-exa package in preamble for $opts_cmd{string}{output}$outext");
2568 $preamble =~ s/(?:\%)(\\usepackage\[\s*)(swpl|tcb)(,pdf\s*\]\{pst-exa\})/$1$2$3/msxg;
2569 }
2570
2571 ### To be sure that the package graphicx and \graphicspath is in the main
2572 ### document and not in a verbatim write environment we make the changes
2573 my %tmpreplace = (
2574 'graphicx' => 'TMPGRAPHICXTMP',
2575 'graphicspath' => 'TMPGRAPHICSPATHTMP',
2576 );
2577 my $findtmp = join q{|}, map { quotemeta } sort { length $a <=> length $b } keys %tmpreplace;
2578
2579 ### We go line by line and make the changes [need /p for ${^MATCH}]
2580 while ($preamble =~ /\%<\*$dtxverb>(.+?)\%<\/$dtxverb> | $tmpcomment /pgmsx) {
2581 my ($pos_inicial, $pos_final) = ($-[0], $+[0]);
2582 my $encontrado = ${^MATCH};
2583 $encontrado =~ s/($findtmp)/$tmpreplace{$1}/g;
2584 substr $preamble, $pos_inicial, $pos_final-$pos_inicial, $encontrado;
2585 pos ($preamble) = $pos_inicial + length $encontrado;
2586 }
2587
2588 ### Now we're trying to capture \graphicspath{...}
2589 my $graphicspath= qr/\\ graphicspath \{ ((?: $llaves )+) \}/ix;
2590 my @graphicspath;
2591 @graphicspath = $preamble =~ m/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|($graphicspath)/gmsx;
2592
2593 if (@graphicspath and $outfile) {
2594 Log("Found \\graphicspath in preamble for $opts_cmd{string}{output}$outext");
2595 $findgraphicx = 'false';
2596 while ($preamble =~ /$graphicspath /pgmx) {
2597 my ($pos_inicial, $pos_final) = ($-[0], $+[0]);
2598 my $encontrado = ${^MATCH};
2599 if ($encontrado =~ /$graphicspath/) {
2600 my $argumento = $1;
2601 if ($argumento !~ /\{$opts_cmd{string}{imgdir}\/\}/) {
2602 $argumento .= "\{$opts_cmd{string}{imgdir}/\}";
2603 my $cambio = "\\graphicspath{$argumento}";
2604 substr $preamble, $pos_inicial, $pos_final-$pos_inicial, $cambio;
2605 pos($preamble) = $pos_inicial + length $cambio;
2606 }
2607 }
2608 }
2609 }
2610
2611 ### Possible packages that load graphicx
2612 my @pkgcandidates = qw (
2613 rotating epsfig lyluatex xunicode parsa xepersian-hm gregoriotex teixmlslides
2614 teixml fotex hvfloat pgfplots grfpaste gmbase hep-paper postage schulealt
2615 schule utfsym cachepic abc doclicense rotating epsfig semtrans mgltex
2616 graphviz revquantum mpostinl cmpj cmpj2 cmpj3 chemschemex register papercdcase
2617 flipbook wallpaper asyprocess draftwatermark rutitlepage dccpaper-base
2618 nbwp-manual mandi fmp toptesi isorot pinlabel cmll graphicx-psmin ptmxcomp
2619 countriesofeurope iodhbwm-templates fgruler combinedgraphics pax pdfpagediff
2620 psfragx epsdice perfectcut upmethodology-fmt ftc-notebook tabvar vtable
2621 teubner pas-cv gcard table-fct pdfpages keyfloat pdfscreen showexpl simplecd
2622 ifmslide grffile reflectgraphics markdown bclogo tikz-page pst-uml realboxes
2623 musikui csbulobalka lwarp mathtools sympytex mpgraphics miniplot.sty:77
2624 dottex pdftricks2 feupphdteses tex4ebook axodraw2 hagenberg-thesis dlfltxb
2625 hu-berlin-bundle draftfigure quicktype endofproofwd euflag othelloboard
2626 pdftricks unswcover breqn pdfswitch latex-make figlatex repltext etsvthor
2627 cyber xcookybooky xfrac mercatormap chs-physics-report tikzscale ditaa
2628 pst-poker gmp CJKvert asypictureb hletter tikz-network powerdot-fuberlin
2629 skeyval gnuplottex plantslabels fancytooltips ieeepes pst-vectorian
2630 phfnote overpic xtuformat stubs graphbox ucs pdfwin metalogo mwe
2631 inline-images asymptote UNAMThesis authorarchive amscdx pst-pdf adjustbox
2632 trimclip fixmetodonotes incgraph scanpages pst-layout alertmessage
2633 svg quiz2socrative realhats autopdf egplot decorule figsize tikzexternal
2634 pgfcore frontespizio textglos graphicx tikz tcolorbox pst-exa
2635 );
2636
2637 my $pkgcandidates = join q{|}, map { quotemeta } sort { length $a <=> length $b } @pkgcandidates;
2638 $pkgcandidates = qr/$pkgcandidates/x;
2639 my @graphicxpkg;
2640
2641 ### Now we're trying to capture graphicx package
2642 @graphicxpkg = $preamble =~ m/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|($pkgcandidates)/gmsx;
2643 if (@graphicxpkg and $outfile and $findgraphicx ne 'false') {
2644 Log("Found graphicx package in preamble for $opts_cmd{string}{output}$outext");
2645 $findgraphicx = 'false';
2646 }
2647
2648 ### Revert changes in preamble for temp <output file>
2649 my %tmpoutreplace = (
2650 'TMPGRAPHICXTMP' => 'graphicx',
2651 'TMPGRAPHICSPATHTMP' => 'graphicspath',
2652 );
2653
2654 %replace = (%changes_out,%tmpoutreplace);
2655 $find = join q{|}, map {quotemeta} sort { length $a <=> length $b } keys %replace;
2656
2657 ### Capture graphicx.sty in .log of LaTeX file
2658 if ($findgraphicx ne 'false' and $outfile) {
2659 Log("Couldn't capture the graphicx package for $opts_cmd{string}{output}$ext in preamble");
2660 my $ltxlog;
2661 my @graphicx;
2662 my $null = devnull();
2663 # Copy preamble and revert changes
2664 my $preambletmp = $preamble;
2665 $preambletmp =~ s/($find)/$replace{$1}/g;
2666 $preambletmp =~ s/\%<\*$dtxverb>(.+?)\%<\/$dtxverb>/$1/gmsx;
2667 Log("Creating $name-$opts_cmd{string}{prefix}-$tmp$ext [only preamble]");
2668 if ($verbose) { say "Creating [$name-$opts_cmd{string}{prefix}-$tmp$ext] with only preamble"; }
2669 open my $OUTfile, '>', "$name-$opts_cmd{string}{prefix}-$tmp$ext";
2670 print {$OUTfile} "$preambletmp\n\\stop";
2671 close $OUTfile;
2672 # Set compiler
2673 if ($opts_cmd{compiler}{arara}) {
2674 my @engine = $atbegindoc =~ m/\%<\*$dtxverb> .+?\%<\/$dtxverb>(*SKIP)(*F)|$arara_rule/msx;
2675 my %engine = map { $_ => 1 } @engine;
2676 if (%engine) {
2677 for my $var (@arara_engines) {
2678 if (defined $engine{$var}) {
2679 Log("Found engine [$var] for arara");
2680 $compiler = $var;
2681 }
2682 }
2683 }
2684 else {
2685 Log("Not detected engine for arara, use default [pdflatex]");
2686 $compiler = 'pdflatex';
2687 }
2688 }
2689 if ($opts_cmd{compiler}{latex}) { $compiler = 'pdflatex'; }
2690 if ($opts_cmd{compiler}{dvilua}) { $compiler = 'lualatex'; }
2691 # Compiling file
2692 RUNOSCMD("$compiler $write18 -interaction=batchmode", "$name-$opts_cmd{string}{prefix}-$tmp$ext >$null", 'only');
2693 # Restore arara compiler
2694 if ($opts_cmd{compiler}{arara}) { $compiler = 'arara'; }
2695 Log("Search graphicx package in $name-$opts_cmd{string}{prefix}-$tmp.log");
2696 open my $LaTeXlog, '<', "$name-$opts_cmd{string}{prefix}-$tmp.log";
2697 {
2698 local $/;
2699 $ltxlog = <$LaTeXlog>;
2700 }
2701 close $LaTeXlog;
2702 # Try to capture graphicx
2703 @graphicx = $ltxlog =~ m/.+? (graphicx\.sty)/xg;
2704 if (@graphicx) {
2705 Log("Found graphicx package in $name-$opts_cmd{string}{prefix}-$tmp.log");
2706 }
2707 else {
2708 Log("Not found graphicx package in $name-$opts_cmd{string}{prefix}-$tmp.log");
2709 Log("Add \\usepackage\{graphicx\} to preamble of $opts_cmd{string}{output}$outext");
2710 $preamble= "$preamble\\usepackage\{graphicx\}\n";
2711 }
2712 }
2713
2714 ### Add last lines
2715 if ($outfile) {
2716 if (!@graphicspath) {
2717 Log("Not found \\graphicspath in preamble for $opts_cmd{string}{output}$outext");
2718 Log("Add \\graphicspath\{\{$opts_cmd{string}{imgdir}/\}\} to preamble for $opts_cmd{string}{output}$ext");
2719 $preamble= "$preamble\\graphicspath\{\{$opts_cmd{string}{imgdir}/\}\}\n";
2720 }
2721 Log("Add \\usepackage\{grfext\} to preamble for $opts_cmd{string}{output}$ext");
2722 $preamble = "$preamble\\usepackage\{grfext\}\n";
2723 Log("Add \\PrependGraphicsExtensions\*\{\.pdf\} to preamble for $opts_cmd{string}{output}$ext");
2724 $preamble = "$preamble\\PrependGraphicsExtensions\*\{\.pdf\}";
2725 $preamble =~ s/\%<\*$dtxverb>\s*(.+?)\s*\%<\/$dtxverb>/$1/gmsx;
2726 $preamble =~ s/^\\usepackage\{\}(?:[\t ]*(?:\r?\n|\r))+/\n/gmsx;
2727 $preamble =~ s/^(?:[\t ]*(?:\r?\n|\r))?+//gmsx;
2728 }
2729
2730 ### We remove environments from the <output file>
2731 if (%delete_env and $outfile) {
2732 Log("Remove environments in body of $opts_cmd{string}{output}$ext");
2733 %replace = (%delete_env);
2734 $find = join q{|}, map { quotemeta } sort { length $a <=> length $b } keys %replace;
2735 # We must prevent eliminating somewhere wrong
2736 # We re-create the regular expressions to make the changes
2737 my @new_verb_tmp = array_minus(@verbatim, @delete_env);
2738 $verbatim = join q{|}, map { quotemeta } sort { length $a <=> length $b } @new_verb_tmp;
2739 $verbatim = qr/$verbatim/x;
2740 $verb_std = qr {
2741 (
2742 (?:
2743 \\begin\{$verbatim\*?\}
2744 (?:
2745 (?>[^\\]+)|
2746 \\
2747 (?!begin\{$verbatim\*?\})
2748 (?!end\{$verbatim\*?\})|
2749 (?-1)
2750 )*
2751 \\end\{$verbatim\*?\}
2752 )
2753 )
2754 }x;
2755
2756 my @new_verbw_tmp = array_minus(@verbatim_w, @delete_env);
2757 $verbatim_w = join q{|}, map { quotemeta } sort { length $a <=> length $b } @new_verbw_tmp;
2758 $verbatim_w = qr/$verbatim_w/x;
2759 $verb_wrt = qr {
2760 (
2761 (?:
2762 \\begin\{$verbatim_w\*?\}
2763 (?:
2764 (?>[^\\]+)|
2765 \\
2766 (?!begin\{$verbatim_w\*?\})
2767 (?!end\{$verbatim_w\*?\})|
2768 (?-1)
2769 )*
2770 \\end\{$verbatim_w\*?\}
2771 )
2772 )
2773 }x;
2774 while ($bodydoc =~ /$verb_wrt | $verb_std /pgmx) {
2775 my ($pos_inicial, $pos_final) = ($-[0], $+[0]);
2776 my $encontrado = ${^MATCH};
2777 $encontrado =~ s/($find)/$replace{$1}/g;
2778 substr $bodydoc, $pos_inicial, $pos_final-$pos_inicial, $encontrado;
2779 pos ($bodydoc) = $pos_inicial + length $encontrado;
2780 }
2781 # Now remove
2782 $bodydoc =~ s/($delt_env)(?:[\t ]*(?:\r?\n|\r))?+//gmsx;
2783 }
2784
2785 ### Create a <output file>
2786 if ($outfile) {
2787 # Options for out_file (add $end to outfile)
2788 my $out_file = $clean{doc} ? "$preamble\n$bodydoc\n\\end\{document\}"
2789 : "$preamble\n$bodydoc\n$enddoc"
2790 ;
2791 # Clean \psset{...} content in <output file>
2792 if ($clean{pst}) {
2793 $out_file =~ s/\\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
2794 \%<\*$dtxverb> .+? \%<\/$dtxverb>(*SKIP)(*F)|
2795 \\psset\{(?:\{.*?\}|[^\{])*\}(?:[\t ]*(?:\r?\n|\r))?+//gmsx;
2796 }
2797 # Clean \tikzset{...} content in <output file>
2798 if ($clean{tkz}) {
2799 $out_file =~ s/\\begin\{nopreview\}.+?\\end\{nopreview\}(*SKIP)(*F)|
2800 \%<\*$dtxverb> .+? \%<\/$dtxverb>(*SKIP)(*F)|
2801 \\tikzset\{(?:\{.*?\}|[^\{])*\}(?:[\t ]*(?:\r?\n|\r))?+//gmsx;
2802 }
2803 # Revert all changes in outfile
2804 $out_file =~ s/\\begin\{nopreview\}\%$tmp\s*(.+?)\s*\\end\{nopreview\}\%$tmp/$1/gmsx;
2805 my @tag_remove_outfile = $out_file =~ m/(?:^\%<\*remove$tmp>.+?\%<\/remove$tmp>)/gmsx;
2806 if (@tag_remove_outfile) {
2807 Log("Removing the content between <*remove> ... </remove> tags in all $opts_cmd{string}{output}$outext");
2808 $out_file =~ s/^\%<\*remove$tmp>\s*(.+?)\s*\%<\/remove$tmp>(?:[\t ]*(?:\r?\n|\r))?+//gmsx;
2809 }
2810 # Remove internal mark for verbatim and verbatim write environments
2811 $out_file =~ s/\%<\*$dtxverb>\s*(.+?)\s*\%<\/$dtxverb>/$1/gmsx;
2812 %replace = (%changes_out,%tmpoutreplace);
2813 $find = join q{|}, map {quotemeta} sort { length $a <=> length $b } keys %replace;
2814 $out_file =~ s/($find)/$replace{$1}/g;
2815 # Write <output file>
2816 if (-e "$opts_cmd{string}{output}$outext") {
2817 Log("Rewriting the file $opts_cmd{string}{output}$outext in $workdir");
2818 Infocolor('Warning', "The file [$opts_cmd{string}{output}$outext] already exists and will be rewritten");
2819 }
2820 else{
2821 Infoline("Creating the file $opts_cmd{string}{output}$outext");
2822 Log("Write the file $opts_cmd{string}{output}$outext in $workdir");
2823 }
2824 open my $OUTfile, '>', "$opts_cmd{string}{output}$outext";
2825 print {$OUTfile} $out_file;
2826 close $OUTfile;
2827 }
2828
2829 ### Set compiler for process <output file>
2830 $compiler = $opts_cmd{compiler}{xetex} ? 'xelatex'
2831 : $opts_cmd{compiler}{luatex} ? 'lualatex'
2832 : $opts_cmd{compiler}{dvips} ? 'latex'
2833 : $opts_cmd{compiler}{dvilua} ? 'lualatex'
2834 : $opts_cmd{compiler}{dvipdf} ? 'latex'
2835 : $opts_cmd{compiler}{arara} ? 'arara'
2836 : $opts_cmd{compiler}{latexmk} ? 'latexmk'
2837 : 'pdflatex'
2838 ;
2839
2840 ### Set options for latexmk
2841 my $ltxmkopt = $opts_cmd{compiler}{xetex} ? "-pdfxe -silent -xelatex=\"xelatex $write18 -recorder %O %S\""
2842 : $opts_cmd{compiler}{luatex} ? "-pdflua -silent -lualatex=\"lualatex $write18 -recorder %O %S\""
2843 : $opts_cmd{compiler}{dvilua} ? "-pdflua -silent -lualatex=\"lualatex $write18 -recorder %O %S\""
2844 : $opts_cmd{compiler}{dvips} ? "-pdfps -silent -latex=\"latex $write18 -recorder %O %S\""
2845 : $opts_cmd{compiler}{dvipdf} ? "-pdfdvi -silent -latex=\"latex $write18 -recorder %O %S\""
2846 : "-pdf -silent -pdflatex=\"pdflatex $write18 -recorder %O %S\""
2847 ;
2848
2849 ### Set options for compiler <output file>
2850 $opt_compiler = $opts_cmd{compiler}{arara} ? '--log'
2851 : $opts_cmd{compiler}{latexmk} ? "$ltxmkopt"
2852 : "$write18 -interaction=nonstopmode -recorder"
2853 ;
2854
2855 ### Message in command line for compiler
2856 $msg_compiler = $opts_cmd{compiler}{xetex} ? 'xelatex'
2857 : $opts_cmd{compiler}{luatex} ? 'lualatex'
2858 : $opts_cmd{compiler}{latex} ? 'pdflatex'
2859 : $opts_cmd{compiler}{dvips} ? 'latex>dvips>ps2pdf'
2860 : $opts_cmd{compiler}{dvilua} ? 'lualatex'
2861 : $opts_cmd{compiler}{dvipdf} ? 'latex>dvipdfmx'
2862 : $opts_cmd{compiler}{arara} ? 'arara'
2863 : 'latexmk'
2864 ;
2865
2866 ### Now set message for latexmk
2867 if ($opts_cmd{compiler}{latexmk}) {
2868 $msg_compiler = 'latexmk';
2869 }
2870
2871 ### Compiling <output file>
2872 if (!$opts_cmd{boolean}{norun} and $outfile) {
2873 Log("Compiling the file $opts_cmd{string}{output}$outext using [$msg_compiler]");
2874 print "Compiling the file $opts_cmd{string}{output}$outext using ", color('magenta'), "[$msg_compiler]\r\n",color('reset');
2875 RUNOSCMD("$compiler $opt_compiler", "$opts_cmd{string}{output}$outext",'show');
2876 # Compiling <output file> using dvips>ps2pdf
2877 if ($opts_cmd{compiler}{dvips}) {
2878 RUNOSCMD("dvips $quiet -Ppdf", "$opts_cmd{string}{output}.dvi",'show');
2879 RUNOSCMD("ps2pdf -sPDFSETTINGS=prepress -sAutoRotatePages=None", "$opts_cmd{string}{output}.ps $opts_cmd{string}{output}.pdf", 'show');
2880 }
2881 # Compiling <output file> using latex>dvipdfmx
2882 if ($opts_cmd{compiler}{dvipdf}) {
2883 RUNOSCMD("dvipdfmx $quiet", "$opts_cmd{string}{output}.dvi", 'show');
2884 }
2885 }
2886
2887 ### Remove temporary files
2888 my @tmpfiles;
2889 my @protected = qw();
2890 my $flsline = 'OUTPUT';
2891 my @flsfile;
2892
2893 ### Protect generated files
2894 if (defined $opts_cmd{string}{output}) {
2895 push @protected, "$opts_cmd{string}{output}$outext", "$opts_cmd{string}{output}.pdf";
2896 }
2897
2898 ### Find files
2899 find(\&aux_files, $workdir);
2900 sub aux_files{
2901 my $findtmpfiles = $_;
2902 if (-f $findtmpfiles && $findtmpfiles =~ m/$name-$opts_cmd{string}{prefix}(-exa)?-$tmp.+?$/) { # search
2903 push @tmpfiles, $_;
2904 }
2905 return;
2906 }
2907
2908 ### Add if exists
2909 if (-e 'arara.log') {
2910 push @flsfile, 'arara.log';
2911 }
2912 if (-e "$name-$opts_cmd{string}{prefix}-$tmp.fls") {
2913 push @flsfile, "$name-$opts_cmd{string}{prefix}-$tmp.fls";
2914 }
2915 if (-e "$name-$opts_cmd{string}{prefix}-exa-$tmp.fls") {
2916 push @flsfile, "$name-$opts_cmd{string}{prefix}-exa-$tmp.fls";
2917 }
2918 if (-e "$opts_cmd{string}{output}.fls") {
2919 push @flsfile, "$opts_cmd{string}{output}.fls";
2920 }
2921
2922 ### Read .fls file
2923 for my $filename(@flsfile){
2924 open my $RECtmp, '<', $filename;
2925 push @tmpfiles, grep /^$flsline/,<$RECtmp>;
2926 close $RECtmp;
2927 }
2928 foreach (@tmpfiles) { s/^$flsline\s+|\s+$//g; }
2929 push @tmpfiles, @flsfile;
2930 @tmpfiles = uniq(@tmpfiles);
2931 @tmpfiles = array_minus(@tmpfiles, @protected);
2932
2933 Log('The files that will be deleted are:');
2934 Logarray(\@tmpfiles);
2935
2936 ### Remove only if exist
2937 if (@tmpfiles) {
2938 Infoline("Remove temporary files created in $workdir");
2939 foreach my $tmpfiles (@tmpfiles) {
2940 move($tmpfiles, $tempDir);
2941 }
2942 }
2943
2944 ### Find dirs created by minted
2945 my @deldirs;
2946 my $mintdir = "\_minted\-$name-$opts_cmd{string}{prefix}-$tmp";
2947 my $mintdirexa = "\_minted\-$name-$opts_cmd{string}{prefix}-exa-$tmp";
2948 if (-e $mintdir) { push @deldirs, $mintdir; }
2949 if (-e $mintdirexa) { push @deldirs, $mintdirexa; }
2950
2951 Log('The directory that will be deleted are:');
2952 Logarray(\@deldirs);
2953
2954 ### Remove only if exist
2955 if (@deldirs) {
2956 Infoline("Remove temporary directories created by minted in $workdir");
2957 foreach my $deldirs (@deldirs) {
2958 remove_tree($deldirs);
2959 }
2960 }
2961
2962 ### Compress ./images with all generated files
2963 my $archivetar;
2964 if ($opts_cmd{boolean}{zip} or $opts_cmd{boolean}{tar}) {
2965 my $stamp = strftime("%Y-%m-%d", localtime);
2966 $archivetar = "$opts_cmd{string}{imgdir}-$stamp";
2967
2968 my @savetozt;
2969 find(\&zip_tar, $opts_cmd{string}{imgdir});
2970 sub zip_tar{
2971 my $filesto = $_;
2972 if (-f $filesto && $filesto =~ m/$name-$opts_cmd{string}{prefix}-.+?$/) { # search
2973 push @savetozt, $File::Find::name;
2974 }
2975 return;
2976 }
2977 Log("The files are compress found in $imgdirpath are:");
2978 Logarray(\@savetozt);
2979 if ($opts_cmd{boolean}{zip}) {
2980 if (-e "$archivetar.zip") {
2981 Infocolor('Warning', "The file [$archivetar.zip] already exists and will be rewritten");
2982 Log("Rewriting the file $archivetar.zip in $workdir");
2983 }
2984 else{
2985 print "Creating the file ", color('magenta'), "[$archivetar.zip]",
2986 color('reset'), " with generate files in ./$opts_cmd{string}{imgdir}\r\n";
2987 Log("Writen the file $archivetar.tar.gz in $workdir");
2988 }
2989 zip \@savetozt => "$archivetar.zip";
2990 }
2991 if ($opts_cmd{boolean}{tar}) {
2992 if (-e "$archivetar.tar.gz") {
2993 Infocolor('Warning', "The file [$archivetar.tar.gz] already exists and will be rewritten");
2994 Log("Rewriting the file $archivetar.tar.gz in $workdir");
2995 }
2996 else{
2997 print "Creating the file ", color('magenta'), "[$archivetar.tar.gz]",
2998 color('reset'), " with generate files in ./$opts_cmd{string}{imgdir}\r\n";
2999 Log("Writen the file $archivetar.tar.gz in $workdir");
3000 }
3001 my $imgdirtar = Archive::Tar->new();
3002 $imgdirtar->add_files(@savetozt);
3003 $imgdirtar->write("$archivetar.tar.gz", 9);
3004 }
3005 }
3006
3007 ### End script process
3008 if (!$opts_cmd{boolean}{norun} and ($opts_cmd{boolean}{srcenv} or $opts_cmd{boolean}{subenv})) {
3009 Log("The image files: $format and generated files are in $imgdirpath");
3010 }
3011 if (!$opts_cmd{boolean}{norun} and (!$opts_cmd{boolean}{srcenv} and !$opts_cmd{boolean}{subenv})) {
3012 Log("The image files: $format are in $imgdirpath");
3013 }
3014 if ($opts_cmd{boolean}{norun} and ($opts_cmd{boolean}{srcenv} or $opts_cmd{boolean}{subenv})) {
3015 Log("The generated files are in $imgdirpath");
3016 }
3017 if ($outfile) { Log("The file $opts_cmd{string}{output}$ext are in $workdir"); }
3018
3019 Infocolor('Finish', "The execution of $scriptname has been successfully completed");
3020
3021 Log("The execution of $scriptname has been successfully completed");
3022
3023 __END__
3024 =encoding UTF-8
3025
3026 =head1 NAME
3027
3028 ltximg - LaTeX environments to image and standalone files
3029
3030 =head1 SYNOPSIS
3031
3032 B<ltximg> [E<lt>I<options>E<gt>] [S<-->] E<lt>I<filename>E<gt>.E<lt>I<tex>|I<ltx>E<gt>
3033
3034 =head1 DESCRIPTION
3035
3036 B<ltximg> automates the process of extracting and converting
3037 environments from LaTeX file to image formats and I<standalone> files
3038 using I<ghostscript> and I<poppler-utils>. Generates a one file with
3039 only extracted environments and other with all extracted environments
3040 converted to C<\includegraphics>.
3041
3042 By default the extracted environments are:
3043
3044 B<preview> B<pspicture> B<tikzpicture> B<pgfpicture> B<psgraph> B<postscript> B<PSTexample>
3045
3046 =head1 OPTIONS
3047
3048 Options that accept a value require either a blank space or C<=> between
3049 the option and the value. Multiple short options can be bundling and
3050 if the last option takes a comma separated list you need C<--> at the end.
3051 Relative or absolute paths for directories and files is not supported.
3052
3053 If used without [E<lt>I<options>E<gt>] the extracted environments are converted
3054 to I<pdf> image format and saved in C<./images> directory using C<pdflatex>
3055 and I<preview> package for process.
3056
3057 General script options:
3058
3059 =over 4
3060
3061 =item B<-h>, B<--help>
3062
3063 Display command line help and exit.
3064
3065 =item B<-v>, B<--version>
3066
3067 Display current version and exit.
3068
3069 =item B<-V>, B<--verbose>
3070
3071 Verbose printing information.
3072
3073 =item B<-l>, B<--log>
3074
3075 Write C<.log> file with debug information.
3076
3077 =item B<-t>, B<--tif>
3078
3079 Create C<.tif> files using I<ghostscript>.
3080
3081 =item B<-b>, B<--bmp>
3082
3083 Create C<.bmp> files using I<ghostscript>.
3084
3085 =item B<-j>, B<--jpg>
3086
3087 Create C<.jpg> files using I<ghostscript>.
3088
3089 =item B<-p>, B<--png>
3090
3091 Create C<.png> files using I<ghostscript>.
3092
3093 =item B<-e>, B<--eps>
3094
3095 Create C<.eps> files using I<pdftops>.
3096
3097 =item B<-s>, B<--svg>
3098
3099 Create C<.svg> files using I<pdftocairo>.
3100
3101 =item B<-P>, B<--ppm>
3102
3103 Create C<.ppm> files using I<pdftoppm>.
3104
3105 =item B<-g>, B<--gray>
3106
3107 Gray scale for images using I<ghostscript>.
3108
3109 =item B<-f>, B<--force>
3110
3111 Capture C<\psset> and C<\tikzset> to extract.
3112
3113 =item B<-n>, B<--noprew>
3114
3115 Create images files without I<preview> package.
3116
3117 =item B<-r> I<integer>, B<--runs>=I<integer>
3118
3119 Set the number of times the compiler will run on the F<input> file for
3120 environment extraction (default: 1).
3121
3122 =item B<-d> I<integer>, B<--dpi>=I<integer>
3123
3124 Dots per inch resolution for images (default: 150).
3125
3126 =item B<-m> I<integer>, B<--margins>=I<integer>
3127
3128 Set margins in bp for I<pdfcrop> (default: 0).
3129
3130 =item B<-o> F<filename>, B<--output>=F<filename>
3131
3132 Create F<output> file.
3133
3134 =item B<--imgdir>=I<dirname>
3135
3136 Set name of directory to save images and files (default: images).
3137
3138 =item B<--prefix>=I<string>
3139
3140 Set I<prefix> append to each generated files (default: fig).
3141
3142 =item B<--myverb>=I<macroname>
3143
3144 Add C<\macroname> to verbatim inline search (default: myverb).
3145
3146 =item B<--clean>=I<doc>|I<pst>|I<tkz>|I<all>|I<off>
3147
3148 Removes specific block text in F<output> file (default: doc).
3149
3150 =item B<--zip>
3151
3152 Compress files generated in C<.zip> format.
3153
3154 =item B<--tar>
3155
3156 Compress files generated in C<.tar.gz> format.
3157
3158 =item B<--srcenv>
3159
3160 Create files with only code of environments.
3161
3162 =item B<--subenv>
3163
3164 Create standalone files for environments.
3165
3166 =item B<--shell>
3167
3168 Enable C<\write18{SHELL COMMAND}>.
3169
3170 =item B<--latex>
3171
3172 Using C<latexE<gt>dvipsE<gt>ps2pdf> for compiler F<input> and C<pdflatex> for compiler
3173 F<output>.
3174
3175 =item B<--dvips>
3176
3177 Using C<latexE<gt>dvipsE<gt>ps2pdf> for compiler F<input> and C<latexE<gt>dvipsE<gt>ps2pdf> for
3178 compiler F<output>.
3179
3180 =item B<--dvilua>
3181
3182 Using C<dvilualatexE<gt>dvipsE<gt>ps2pdf> for compiler F<input> and C<lualatex> for
3183 compiler F<output>.
3184
3185 =item B<--dvipdf>
3186
3187 Using C<latexE<gt>dvipdfmx> for compiler F<input> and C<latexE<gt>dvipdfmx> for compiler
3188 F<output>.
3189
3190 =item B<--xetex>
3191
3192 Using C<xelatex> for compiler F<input> and F<output>.
3193
3194 =item B<--luatex>
3195
3196 Using C<lualatex> for compiler F<input> and F<output>.
3197
3198 =item B<--arara>
3199
3200 Use C<arara> for compiler F<input> and F<output>.
3201
3202 =item B<--latexmk>
3203
3204 Using C<latexmk> for compiler F<output> file.
3205
3206 =item B<--norun>
3207
3208 Run script, but no create images files.
3209
3210 =item B<--nopdf>
3211
3212 Don't create a C<.pdf> image files.
3213
3214 =item B<--nocrop>
3215
3216 Don't run I<pdfcrop>.
3217
3218 =item B<--extrenv>=I<env1,env2,...>
3219
3220 Add new environments to extract.
3221
3222 =item B<--skipenv>=I<env1,env2,...>
3223
3224 Skip some default environments to extract.
3225
3226 =item B<--verbenv>=I<env1,env2,...>
3227
3228 Add new verbatim environments.
3229
3230 =item B<--writenv>=I<env1,env2,...>
3231
3232 Add new verbatim write environments.
3233
3234 =item B<--deltenv>=I<env1,env2,...>
3235
3236 Delete environments in F<output> file.
3237
3238 =back
3239
3240 =head1 EXAMPLE
3241
3242 B<ltximg> --latex -e -p --subenv -o test-out.ltx test-in.ltx
3243
3244 Create a C<./images> directory (if it doesn't exist) with all extracted
3245 environments converted to C<.pdf>, C<.eps>, C<.png> and I<standalone>
3246 files, a file F<test-in-fig-all.ltx> with all extracted environments
3247 and the file F<test-out.ltx> with all environments converted to
3248 C<\includegraphics> using C<latexE<gt>dvipsE<gt>ps2pdf> and I<preview>
3249 package for F<test-in.ltx> and C<pdflatex> for F<test-out.ltx>.
3250
3251 =head1 DOCUMENTATION
3252
3253 For full documentation use:
3254
3255 texdoc B<ltximg>
3256
3257 =head1 ISSUES AND REPORTS
3258
3259 B<Repository> : L<https://github.com/pablgonz/ltximg>
3260
3261 B<Bug tracker>: L<https://github.com/pablgonz/ltximg/issues>
3262
3263 =head1 AUTHOR
3264
3265 Pablo González Luengo, I<[email protected]>.
3266
3267 =head1 COPYRIGHT AND LICENSE
3268
3269 Copyright 2013-2021 Pablo González, I<[email protected]>.
3270
3271 This program is free software; you can redistribute it and/or modify
3272 it under the terms of the GNU General Public License as published by
3273 the Free Software Foundation; either version 3 of the License, or
3274 (at your option) any later version.
3275
3276 This program is distributed in the hope that it will be useful, but
3277 WITHOUT ANY WARRANTY; without even the implied warranty of
3278 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
3279 General Public License for more details.
3280
3281 =head1 SEE ALSO
3282
3283 gs(1), dvips(1), ps2pdf(1), pdfcrop(1), pdftops(1), pdftocairo(1), pdftoppm(1)
3284
3285 =cut