summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/source/latex/pstool/pstool.tex
blob: cf7901521efe2e9f89c0860c81bcefc802a4c6a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
\RequirePackage{filecontents}
\begin{filecontents*}{README.txt}
__________________
The pstool package
v1.3

A package like "pst-pdf" for processing PostScript graphics
with psfrag labels within pdfLaTeX documets. The difference
with this package is that every graphic is compiled individually,
drastically speeding up compilation time when only a single
figure needs re-processing.

Running `latex` on pstool.tex will produce the files
  pstool.ins, pstool.sty, and README.txt,
and compile the PDF documentation.

Executing `latex pstool.ins` produces the files above
except pstool.ins (and the PDF file, obviously).

Please see the PDF documentation for further information.

Will Robertson & Zebb Prime
Copyright 2008-2009

____________________
Brief change history

v1.3, July 2009: 
  - [bitmap] option to control compression of bitmap graphics,
  - Package options may now be set anywhere with \pstoolsetup{},
  - localised pstool options can be set per-graphic.

\end{filecontents*}

\begin{filecontents}{pstool.sty}
\ProvidesPackage{pstool}[2009/07/17 v1.3
  Wrapper for processing PostScript/psfrag figures]

% External packages
\RequirePackage{%
  catchfile,color,ifpdf,ifplatform,
  graphicx,pdftexcmds,psfrag,suffix,xkeyval}

% Allocations
\newif\if@pstool@pdfcrop@
\newif\if@pstool@verbose@
\newwrite\pstool@out

% These are cute
\providecommand\OnlyIfFileExists[2]{\IfFileExists{#1}{#2}{}}
\providecommand\NotIfFileExists[2]{\IfFileExists{#1}{}{#2}}

% \subsection{Package options}

\define@choicekey*{pstool.sty}{crop}
    [\@tempa\@tempb]{preview,pdfcrop}{%
  \ifcase\@tempb\relax
    \@pstool@pdfcrop@false
  \or
    \@pstool@pdfcrop@true
  \or
  \fi
}

\define@choicekey*{pstool.sty}{process}
    [\@tempa\pstool@process@choice]{all,none,auto}{}
\ExecuteOptionsX{process=auto}

\define@choicekey*{pstool.sty}{mode}
    [\@tempa\@tempb]{errorstop,nonstop,batch}{%
  \ifnum\@tempb=2\relax
    \@pstool@verbose@false
  \else
    \@pstool@verbose@true
  \fi
  \edef\pstool@mode{\@tempa mode}%
}
\ExecuteOptionsX{mode=batch}

\DeclareOptionX{cleanup}{\def\pstool@rm@files{#1}}
\ExecuteOptionsX{cleanup={.tex,.dvi,.ps,.pdf,.log,.aux}}

\DeclareOptionX{suffix}{\def\pstool@suffix{#1}}
\ExecuteOptionsX{suffix={-pstool}}

% There is an implicit |\space| after the bitmap options.
\define@choicekey*{pstool.sty}{bitmap}
    [\@tempa\@tempb]{auto,lossless,lossy}{%
  \ifcase\@tempb
    \let\pstool@bitmap@opts\@empty
  \or
    \def\pstool@bitmap@opts{%
      "-dAutoFilterColorImages=false"
      "-dAutoFilterGrayImages=false"
      "-dColorImageFilter=/FlateEncode"
      "-dGrayImageFilter=/FlateEncode" % space
    }
  \or
    \def\pstool@bitmap@opts{%
      "-dAutoFilterColorImages=false"
      "-dAutoFilterGrayImages=false"
      "-dColorImageFilter=/DCTEncode"
      "-dGrayImageFilter=/DCTEncode" % space
    }
  \fi
}
\ExecuteOptionsX{bitmap=lossless}

% \HideAllDefining
% \Define*{latex-options}
% \Define*{dvips-options}
% \Define*{ps2pdf-options}
% \Define*{pdfcrop-options}
\DeclareOptionX{latex-options}{\def\pstool@latex@opts{#1}}
\DeclareOptionX{dvips-options}{\def\pstool@dvips@opts{#1}}
\DeclareOptionX{ps2pdf-options}{\def\pstool@pspdf@opts{#1}}
\DeclareOptionX{pdfcrop-options}{\def\pstool@pdfcrop@opts{#1}}
% \ResumeAllDefining
\ExecuteOptionsX{
  latex-options={},
  dvips-options={},
  ps2pdf-options={"-dPDFSETTINGS=/prepress"},
  pdfcrop-options={}
}

\ifpdf
  \ifshellescape\else
    \ExecuteOptionsX{process=none}
    \PackageWarning{pstool}{^^J\space\space%
      Package option [process=none] activated^^J\space\space
      because -shell-escape is not enabled.^^J%
      This warning occurred}
  \fi
\fi

\ProcessOptionsX

% A command to set \pkg{pstool} options after the package is loaded.
\newcommand\pstoolsetup{%
  \setkeys{pstool.sty}%
}

% \section{Macros}

% Used to echo information to the console output.
% Can't use |\typeout| because it's asynchronous with
% any |\immediate\write18| processes (for some reason).
\def\pstool@echo#1{%
  \if@pstool@verbose@
    \pstool@echo@verbose{#1}%
  \fi
}

\def\pstool@echo@verbose#1{%
  \immediate\write18{echo "#1"}%
}

\let\pstool@includegraphics\includegraphics

% Command line abstractions between platforms:
\edef\pstool@cmdsep{\ifwindows\string&\else\string;\fi\space}
\edef\pstool@rm@cmd{\ifwindows del \else rm -- \fi}

% Delete a file if it exists:\\
% |#1|: path\\
% |#2|: filename
\newcommand\pstool@rm[2]{%
  \OnlyIfFileExists{#1#2}{%
    \immediate\write18{%
      cd "#1"\pstool@cmdsep\pstool@rm@cmd "#2"
    }%
  }%
}

% Generic function to execute a command on the shell and pass its exit status back into \LaTeX. Any number of \cmd\pstool@exe\ statements can be made consecutively followed by \cmd\pstool@endprocess, which also takes an argument. If \emph{any} of the shell calls failed, then the execution immediately skips to the end and expands \cmd\pstool@error\ instead of the argument to \cmd\pstool@endprocess.
%
% |#1|: `name' of process\\
% |#2|: relative path where to execute the command\\
% |#3|: the command itself
\newcommand\pstool@exe[3]{%
  \pstool@echo{^^J=== pstool: #1 ===}%
  \pstool@shellexecute{#2}{#3}%
  \pstool@retrievestatus{#2}%
  \ifnum\pstool@status > \z@
    \PackageWarning{pstool}{Execution failed during process:^^J\space\space#3^^JThis warning occurred}%
    \expandafter\pstool@abort
  \fi
}

% Edit this definition to print something else when graphic processing fails.
\def\pstool@error{%
  \fbox{%
    \parbox{0.8\linewidth}{%
      \color{red}\raggedright\ttfamily\scshape\small
      An error occured processing graphic 
      \upshape`\pstool@path\pstool@filestub'%
    }%
  }%
}

\def\pstool@abort#1\pstool@endprocess{\pstool@error\@gobble}
\let\pstool@endprocess\@firstofone

% It is necessary while executing commands on the shell to write the exit status to a temporary file to test for failures in processing. (If all versions of |pdflatex| supported input pipes, things might be different.)
\def\pstool@shellexecute#1#2{%
  \immediate\write18{%
    cd "#1" \pstool@cmdsep
    #2 \pstool@cmdsep
    \ifwindows
       call echo
         \string^\@percentchar ERRORLEVEL\string^\@percentchar
    \else
       echo \detokenize{$?}
    \fi
    > \pstool@statusfile}%
% That's the execution; now we need to flush the write buffer to the status file. This ensures the file is written to disk properly (allowing it to be read by \cmd\CatchFileEdef). Not necessary on Windows, whose file writing is evidently more crude/immediate.
  \ifwindows\else
    \immediate\write18{%
      touch #1\pstool@statusfile}%
  \fi
}
\def\pstool@statusfile{pstool-statusfile.txt}

% Read the exit status from the temporary file and delete it.\\
% |#1| is the path\\
% Status is recorded in \cmd\pstool@status.
\def\pstool@retrievestatus#1{%
  \CatchFileEdef{\pstool@status}{#1\pstool@statusfile}{}%
  \pstool@rm{#1}{\pstool@statusfile}%
  \ifx\pstool@status\pstool@statusfail
    \PackageWarning{pstool}{%
      Status of process unable to be determined:^^J  #1^^J%
      Trying to proceed... }%
    \def\pstool@status{0}%
  \fi
}
\def\pstool@statusfail{\par }% what results when \TeX\ reads an empty file

% \subsection{File age detection}
\def\pstool@IfnewerEPS{%
  \ifnum\pdf@strcmp{\pdf@filemoddate{\pstool@path\pstool@filestub.pdf}}
                   {\pdf@filemoddate{\pstool@path\pstool@filestub.eps}}
        < \z@
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
}

% Grab filename and filepath. Always need a relative path to a filename even if it's in the same directory.
\def\pstool@getpaths#1{%
  \filename@parse{#1}%
  \ifx\filename@area\@empty
    \def\pstool@path{./}%
  \else
    \let\pstool@path\filename@area
  \fi
  \let\pstool@filestub\filename@base
}

% \section{Command parsing}
% User input is \cmd\pstool\ (with optional |*| or |!| suffix) which turns into one of the following three macros depending on the mode.

\newcommand\pstool@alwaysprocess[3][]{%
  \pstool@getpaths{#2}%
  \pstool@process{#1}{#3}%
}

\ifpdf
  \newcommand\pstool@neverprocess[3][]{%
    \pstool@includegraphics{#2}%
  }
\else
  \newcommand\pstool@neverprocess[3][]{%
    \begingroup
      \setkeys*{pstool.sty}{#1}%
      #3%
      \expandafter\pstool@includegraphics\expandafter[\XKV@rm]{#2}%
    \endgroup
  }
\fi

% For regular operation, which processes the figure only if
% the command is starred, or the PDF doesn't exist.
\newcommand\pstool@maybeprocess[3][]{%
  \pstool@getpaths{#2}%
  \IfFileExists{#2.pdf}{%
    \pstool@IfnewerEPS{% needs info from |\pstool@getpaths|
      \pstool@process{#1}{#3}%
    }{%
      \pstool@includegraphics{#2}%
    }%
  }{%
    \pstool@process{#1}{#3}%
  }%
}

% \section{User commands}
%  Finally, define \cmd\pstool\ as appropriate for the mode: (|all|, |none|, |auto|, respectively)
\ifpdf
  \newcommand\pstool{%
    \ifcase\pstool@process@choice\relax
      \expandafter \pstool@alwaysprocess \or
      \expandafter \pstool@neverprocess  \or
      \expandafter \pstool@maybeprocess
    \fi
  }
  \WithSuffix\def\pstool!{%
    \ifcase\pstool@process@choice\relax
      \expandafter \pstool@alwaysprocess \or
      \expandafter \pstool@neverprocess  \or
      \expandafter \pstool@neverprocess
    \fi
  }
  \WithSuffix\def\pstool*{%
    \ifcase\pstool@process@choice\relax
      \expandafter \pstool@alwaysprocess \or
      \expandafter \pstool@neverprocess  \or
      \expandafter \pstool@alwaysprocess
    \fi
  }
\else
  \let\pstool\pstool@neverprocess
  \WithSuffix\def\pstool!{\pstool@neverprocess}
  \WithSuffix\def\pstool*{\pstool@neverprocess}
\fi

% \section{The figure processing}

% \cmd\pstool@filestub\ is the filename of the figure stripped of its path (if any)
\def\pstool@jobname{\pstool@filestub\pstool@suffix}

% And this is the main macro.
\newcommand\pstool@process[2]{%
  \begingroup
  \setkeys*{pstool.sty}{#1}%
  \pstool@echo@verbose{%
      ^^J^^J=== pstool: begin processing ===}%
  \pstool@write@processfile{#1}
      {\pstool@path\pstool@filestub}{#2}%
  \pstool@exe{auxiliary process: \pstool@filestub\space}
    {./}{latex
      -shell-escape
      -output-format=dvi
      -output-directory="\pstool@path"
      -interaction=\pstool@mode\space
      \pstool@latex@opts\space
          "\pstool@jobname.tex"}%
% Execute |dvips| in quiet mode if |latex| is not run in (non/error)stop mode:
  \pstool@exe{dvips}{\pstool@path}{%
    dvips \if@pstool@verbose@\else -q \fi -Ppdf 
        \pstool@dvips@opts\space "\pstool@jobname.dvi"}%
  \if@pstool@pdfcrop@
    \pstool@exe{ps2pdf}{\pstool@path}{%
      ps2pdf \pstool@bitmap@opts \pstool@pspdf@opts \space
          "\pstool@jobname.ps" "\pstool@jobname.pdf"}%
    \pstool@exe{pdfcrop}{\pstool@path}{%
      pdfcrop \pstool@pdfcrop@opts\space
          "\pstool@jobname.pdf" "\pstool@filestub.pdf"}%
  \else
    \pstool@exe{ps2pdf}{\pstool@path}{%
      ps2pdf \pstool@bitmap@opts \pstool@pspdf@opts \space
          "\pstool@jobname.ps" "\pstool@filestub.pdf"}%
  \fi
  \pstool@endprocess{%
    \pstool@cleanup
    \pstool@includegraphics{%
      \pstool@path\pstool@filestub}%
  }%
  \pstool@echo@verbose{^^J=== pstool: end processing ===^^J}%
  \endgroup
}

% The file that is written for processing is set up to read the preamble of the original document and set the graphic on an empty page (cropping to size is done either here with \pkg{preview} or later with \pkg{pdfcrop}).
\def\pstool@write@processfile#1#2#3{%
  \immediate\openout\pstool@out #2\pstool@suffix.tex\relax
  \immediate\write\pstool@out{%
% Input the main document; redefine the document environment so only the preamble is read:
    \unexpanded{%
      \pdfoutput=0^^J% force DVI mode if not already
      \let\origdocument\document^^J%
      \let\EndPreamble\endinput^^J%
      \def\document{\endgroup\endinput}^^J%
    }%
    \noexpand\input{\jobname}^^J%
%
% Now the preamble of the process file: (restoring document's original meaning; empty \cmd\pagestyle\ removes the page number)
    \if@pstool@pdfcrop@\else
      \noexpand\usepackage[active,tightpage]{preview}^^J%
    \fi
    \unexpanded{%
      \let\document\origdocument^^J%
      \pagestyle{empty}^^J%
    }%
%
% And the document body to place the graphic on a page of its own:
    \unexpanded{%
      \begin{document}^^J%
      \centering\null\vfill^^J%
    }%
    \if@pstool@pdfcrop@\else
      \noexpand\begin{preview}^^J%
    \fi
    \unexpanded{#3^^J}% this is the "psfrag" material
    \noexpand\includegraphics
        [\unexpanded\expandafter{\XKV@rm}]
        {\pstool@filestub}^^J%
    \if@pstool@pdfcrop@\else
      \noexpand\end{preview}^^J%
    \fi
    \unexpanded{\vfill\end{document}}^^J%
  }%
  \immediate\closeout\pstool@out
}

\def\pstool@cleanup{%
  \@for\@ii:=\pstool@rm@files\do{%
    \pstool@rm{\pstool@path}{\pstool@jobname\@ii}%
  }%
}

\providecommand\EndPreamble{}

% \section{User commands}
%
% These all support the suffixes |*| and |!|, so each user command is defined as a wrapper to \cmd\pstool.

% for EPS figures with psfrag:
\newcommand\psfragfig[2][]{\pstool@psfragfig{#1}{#2}{}}
\WithSuffix\newcommand\psfragfig*[2][]{%
  \pstool@psfragfig{#1}{#2}{*}%
}
\WithSuffix\newcommand\psfragfig![2][]{%
  \pstool@psfragfig{#1}{#2}{!}%
}

% Parse optional \<input definitions>
\newcommand\pstool@psfragfig[3]{%
  \@ifnextchar\bgroup{%
    \pstool@@psfragfig{#1}{#2}{#3}%
  }{%
    \pstool@@psfragfig{#1}{#2}{#3}{}%
  }%
}

% Search for both \<filename> and \<filename>|-psfrag| inputs.
%
% |#1|: possible graphicx options\\
% |#2|: graphic name (possibly with path)\\
% |#3|: |\pstool| suffix (i.e., |!| or |*| or \<empty>)\\
% |#4|: possible \pkg{psfrag} (or other) macros
\newcommand\pstool@@psfragfig[4]{%
  % Find the .eps file to use.
  \IfFileExists{#2-psfrag.eps}{%
    \edef\pstool@eps{#2-psfrag}%
    \OnlyIfFileExists{#2.eps}{%
      \PackageWarning{pstool}{Graphic "#2.eps" exists but "#2-psfrag.eps" is being used}%
    }%
  }{%
    \IfFileExists{#2.eps}{%
      \edef\pstool@eps{#2}%
    }{%
      \PackageError{pstool}{%
        No graphic "#2.eps" or "#2-psfrag.eps" found%
      }{%
        Check the path and whether the file exists.%
      }%
    }%
  }%
  % Find the .tex file to use.
  \IfFileExists{#2-psfrag.tex}{%
    \edef\pstool@tex{#2-psfrag.tex}%
    \OnlyIfFileExists{#2.tex}{%
      \PackageWarning{pstool}{%
        File "#2.tex" exists that may contain macros
        for "\pstool@eps.eps"^^J%
        But file "#2-psfrag.tex" is being used instead.%
      }%
    }%
  }{%
    \IfFileExists{#2.tex}{%
      \edef\pstool@tex{#2.tex}%
    }{%
      \let\pstool@tex\@empty
      \PackageWarning{pstool}{%
        No file "#2.tex" or "#2-psfrag.tex" can be found
        that may contain macros for "\pstool@eps.eps"%
      }%
    }%
  }%
  \ifx\pstool@tex\@empty
    \pstool#3[#1]{\pstool@eps}{#4}%
  \else
    \expandafter\pstool@@@psfragfig
      \expandafter{\pstool@tex}{#3[#1]}{#4}%
  \fi
}

% Break out the separate function in order to expand |\pstool@tex| before writing it.
\newcommand\pstool@@@psfragfig[3]{%
  \pstool#2{\pstool@eps}{%
    \csname @input\endcsname{#1}%
    #3%
  }%
}

% That's it.
\end{filecontents}
%%%%%%%%%1%%%%%%%%%2%%%%%%%%%3%%%%%%%%%4%%%%%%%%%5




% Conditionally compile the documentation & generate the .ins file:
\providecommand\pstoolCompile{Y}
\if\pstoolCompile N
  \expandafter\endinput
\fi


\begin{filecontents*}{pstool.ins}
%&latex
\def\pstoolCompile{N}
\input pstool.tex
\csname @@end\endcsname
\end{filecontents*}




\makeatletter
\documentclass{article}

\usepackage[rm,medium]{titlesec}

\usepackage{xcolor}
\usepackage[colorlinks,linktocpage]{hyperref}
\usepackage{gmdoc}
\usepackage{gmverb}
\dekclubs
\stanzaskip=\bigskipamount 
\CodeSpacesGrey

\usepackage{enumitem}
\setlist{noitemsep}

\usepackage{tocloft,varwidth}
\setcounter{tocdepth}{1}
\def\tocwidthA{0.45}
\def\tocwidthB{0.45}
\def\cftpartfont{\scshape}
\def\cftsecfont{\small}
\cftbeforesecskip=0pt
\def\cftpartleader{}
\def\cftpartafterpnum{\cftparfillskip}
\def\cftsecleader{}
\def\cftsecafterpnum{\cftparfillskip}

\let\pkg\textsf
\def\pkgopt#1{\texttt{[#1]}}

\def\PDF{\textsc{pdf}}
\def\PS{\textsc{ps}}
\def\DVI{\textsc{dvi}}
\def\EPS{\textsc{eps}}

\usepackage{pstool}
\usepackage[T1]{fontenc}
\usepackage{microtype}
\usepackage{lmodern}
\usepackage[sc,osf]{mathpazo}
\linespread{1.1}
\frenchspacing

\GetFileInfo{pstool.sty}
\begin{document}
{\addtocontents{toc}{\protect\begin{varwidth}[t]{\tocwidthA\linewidth}}}

\title{The \pkg{pstool} package}
\author{
  \normalsize Concept by Zebb Prime\\
  \normalsize Package by Will Robertson\footnote{\texttt{wspr81@gmail.com}}}
\date{\fileversion\qquad\filedate}

\maketitle

\begin{abstract}
This package defines the \cmd\psfragfig\ user command for including \EPS\ files that use \pkg{psfrag} features in a pdf\/\LaTeX\ document. The command \cmd\pstool\ can be used to define other commands with similar behaviour.
\end{abstract}

\tableofcontents

\part{User documentation}

\section{Introduction}

While directly producing \PDF\ output with pdf\/\LaTeX\ is a great improvement in many ways over the `old method' of \DVI$\to$\PS$\to$\PDF, it loses the ability to interface with a generic PostScript workflow, used to great effect in numerous packages, most notably \pkg{PSTricks} and \pkg{psfrag}.

Until now, the best way to use these packages while running pdf\/\LaTeX\ has been to use the \pkg{pst-pdf} package, which processes the entire document through a filter, sending the relevant PostScript environments (only) through a single pass of \LaTeX\ producing \DVI$\to$\PS$\to$\PDF. The resulting \PDF\ versions of each graphic are then included into the pdf\/\LaTeX\ document in a subsequent compilation. The \pkg{auto-pst-pdf} package provides a wrapper to perform all of this automatically.

The disadvantage with this method is that for every document compilation, \emph{every} graphic must be re-processed. The \pkg{pstool} package uses a different approach to allow each graphic to be processed only as needed, speeding up and simplifying the typesetting of the main document.

At present this package is designed solely as a replacement for \pkg{pst-pdf} in the r\^ole of supporting the \pkg{psfrag} package (which it loads) in pdf\/\LaTeX. 

More flexible usage to provide a complete replacement for \pkg{pst-pdf} (e.g., supporting the \cs{begin\{postscript\}} environment) is planned for a later release. If you simply need to automatically convert plain \EPS\ files to \PDF, I recommend using the \pkg{epstopdf} package with the \pkgopt{update,prepend} package options (\pkg{epstopdf} and \pkg{pstool} should be completely compatible).

\section{Getting started}

Processing pdf\/\LaTeX\ documents with \pkg{pstool} requires the `shell escape' feature of pdf\/\TeX\ to be activated.
This allows execution of auxiliary commands from within \LaTeX, a feature which is often disabled by default for security reasons.
If shell escape is not enabled, a warning will be issued in console output when the package is loaded.
Depending how you compile your \LaTeX\ document, shell escape is enabled in different ways.%
\footnote{On the command line, use the \texttt{-shell-escape} switch. Otherwise, you're on your own.}

Load the package as usual; no package options are required by default, but there are a few useful options described later in section~\ref{pkgopt}.
Note that you do not need to load \pkg{psfrag} separately.
You also do not need to load \pkg{graphicx} separately, but if you do so, ensure that you do \emph{not} include driver information (such as |[pdftex]|); this will play havoc with \pkg{pstool}'s automatic processing stage.

The generic command provided by this package is\par
{\centering
  \cmd\pstool\ \arg[options] \arg{filename} \arg{input definitions}
\par}
It converts the graphic \<filename>|.eps| to \<filename>|.pdf| through a unique \DVI$\to$\PS$\to$\PDF\ process for each graphic, using the preamble of the main document.
The resulting graphic is then inserted into the document, with \<options> consisting of options for \pkg{graphicx} (e.g., \texttt{angle}, \texttt{scale}) or for \pkg{pstool} (as described later in Section~\ref{pkgopt}).
Note that these optional arguments take effect in the \emph{processing stage}; if you change the \<options>, you must manually re-process the figure.
The third argument to \cmd\pstool\ allows arbitrary \<input definitions> (such as \cmd\psfrag\ directives) to be inserted before the figure as it is processed. 

The command \cmd\pstool\ can take an optional |*| or |!| suffix to change the behaviour of the command:
\begin{description}
\item[\cs{pstool}] Process the graphic \<filename>|.eps| if \<filename>|.pdf| does not already exist, or if the \EPS\ file is \emph{newer} than the \PDF;
\item[\cs{pstool*}] Always process this figure; and,
\item[\cs{pstool!}] Never process this figure.
\end{description}
The behaviour in these three cases can be overridden globally by the package option \pkgopt{process} as described in section~\ref{process}.

It is useful to define higher-level commands based on \cmd\pstool\ for including specific types of \EPS\ graphics that take advantage of \pkg{psfrag}. As an example, this package defines the following command, which also supports the |*| or |!| suffixes described above.
\begin{description}
\item[{\cmd\psfragfig\arg[opts]\arg{filename}}] 
This is the catch-all macro to support a wide range of graphics naming schemes. It inserts an \EPS\ file named either \<filename>|-psfrag.eps| or \<filename>|.eps| (in that order of preference), and uses \pkg{psfrag} definitions contained within either \<filename>|-psfrag.tex| or \<filename>|.tex|. 
\end{description}
This command can be used to insert figures produced by the \textsc{Mathematica} package \pkg{MathPSfrag} or the \textsc{Matlab} package \pkg{matlabfrag}. \cmd\psfragfig\ also accepts an optional braced argument:
\begin{description}
\item[{\cmd\psfragfig\arg[opts]\arg{filename}\arg{input definitions}}] 
As above, but inserts the arbitrary code \<input definitions>, which will usually be used to define new or override existing \pkg{psfrag} commands.
\end{description}

\section{Package options}
\label{pkgopt}

Package options can be set or overridden at any time with \cmd\pstoolsetup\marg{pstool settings}.
As mentioned in the previous section, these options also may be set in the optional argument to \cmd\pstool\ and \cmd\psfragfig, in which case they apply to that figure alone.

\subsection{Forcing/disabling graphics processing}
\label{process}

While the suffixes |*| and |!| can be used to force or disable (respectively) the processing of each individual graphic, sometimes we want to do this on a global level. The following package options override \emph{all} \pkg{pstool}  macros: 
\begin{description}
\item[\pkgopt{process=auto}] This is the default mode as described in the previous section, in which graphics without suffixes are only (re-)processed if the \EPS\ file is newer or the \PDF\ file does not exist;
\item[\pkgopt{process=all}] Suffixes are ignored and all \cmd\pstool\ graphics are processed;
\item[\pkgopt{process=none}] Suffixes are ignored and no \cmd\pstool\ graphics are processed.\footnote{If \pkg{pstool} is loaded in a \LaTeX\ document in \DVI\ mode, this is the option that is used since no external processing is required for these graphics.}
\end{description}

\subsection{Cropping graphics}
The default option \pkgopt{crop=preview} selects the \pkg{preview} package to crop graphics to the appropriate size for each auxiliary process.

However, when an inserted label protrudes from the natural bounding box of the figure, or when the original bounding box of the figure is wrong, the \pkg{preview} package will not always produce a good result (with parts of the graphic trimmed off the edge). A robust method to solve this problem is to use the \pkg{pdfcrop} program instead.%
\footnote{\pkg{pdfcrop} requires a Perl installation under Windows, freely available from \url{http://www.activestate.com/Products/activeperl/index.plex}} This can be activated in \pkg{pstool} with the \pkgopt{crop=pdfcrop} package option. 

\subsection{Temporary files \& cleanup}
Each figure that is processed spawns an auxiliary \LaTeX\ compilation through \DVI$\to$\PS$\to$\PDF. This process is named after the name of the figure with an appended string suffix; the default is \pkgopt{suffix=\{-pstool\}}. All of these suffixed files are ``temporary'' in that they may be deleted once they are no longer needed.

As an example, if the figure is called |ex.eps|, the files that are created are |ex-pstool.tex|, |ex-pstool.dvi|, \dots. The \pkgopt{cleanup} package option declares via a list of filename suffixes which temporary files are to be deleted after processing.

The default is \pkgopt{cleanup=\{.tex,\,.dvi,\,.ps,\,.pdf,\,.log,\,.aux\}}. To delete none of the temporary files, choose \pkgopt{cleanup=\{\}} (useful for debugging).

\subsection{Interaction mode of the auxiliary processes}
Each graphic echoes the output of its auxiliary process to the console window; unless you are trying to debug errors there is little interest in seeing this information. The behaviour of these auxiliary processes are governed globally by the \pkgopt{mode} package option, which takes the following parameters:
\begin{description}
\item[\pkgopt{mode=batch}] hide almost all of the \LaTeX\ output (\emph{default});
\item[\pkgopt{mode=nonstop}] echo all \LaTeX\ output but continues right past any errors; and 
\item[\pkgopt{mode=errorstop}] prompt for user input when errors in the source are encountered.
\end{description}
These three package options correspond to the \LaTeX\ command line options \texttt{-interaction=batchmode}, \texttt{=nonstopmode}, and \texttt{=errorstopmode}, respectively. When \pkgopt{mode=batch} is activated, then \pkg{dvips} is also run in `quiet mode'.

\subsection{Auxiliary processing command line options}
The command line options passed to each program of the auxiliary processing can be changed with the following package options:
\begin{description}
\item[\pkgopt{latex-options=...}]
\item[\pkgopt{dvips-options=...}]
\item[\pkgopt{ps2pdf-options=...}] and,
\item[\pkgopt{pdfcrop-options=...}] (if applicable).
\end{description}
For the most part these will be unnecessary, although passing the correct options to |ps2pdf| can sometimes be a little obscure.\footnote{The manual is here: \url{http://pages.cs.wisc.edu/~ghost/doc/cvs/Ps2pdf.htm}} For example, I use the following for generating figures in my thesis:%
\footnote{Note that each \texttt{ps2pdf} option must be quoted in Windows, which is unnecessary but does no harm in Linux and Mac~OS~X.}%
\par{\centering|ps2pdf-options={"-dPDFSETTINGS=/prepress"}|\par}
This forces the `base fourteen' fonts to be embedded within the individual figure files, without which some printers and \textsc{pdf} viewers have trouble with the textual labels. In fact, from v1.3 of \pkg{pstool}, this option is now the default.
Note that subsequent calls to \pkgopt{ps2pdf-options=...} will override the \pkg{pstool} default; use |ps2pdf-options={}| to chose |ps2pdf|'s defaults if necessary. 

\subsection{Compression of bitmap data}
In the conversion using |ps2pdf|, bitmap images are stored using either lossy or lossless compression. The default behaviour for \pkg{pstool} is to force lossless compression, because we believe that to be the most commonly desired use case (you don't want scientific graphics rendered with possible compression artifacts). This behaviour can be adjusted using one of these options:
\begin{description}
\item[\pkgopt{bitmap=auto}] do whatever |ps2pdf| does by default, which seems to be to use lossy compression most, if not all, of the time;
\item[\pkgopt{bitmap=lossy}] bitmap images are compressed like \textsc{jpg}; this is only really suitable for photographs;
\item[\pkgopt{bitmap=lossless}] bitmap images are compressed like \textsc{png}; this is suitable for screenshots and generated data such as a surface plot within Matlab (\emph{default}).
\end{description}
These are just special cases of the \pkgopt{ps2pdf-options=...} option, but using \pkgopt{bitmap=...} is much more convenient since the |ps2pdf| options to effect this behaviour are quite verbose.
Note that the |auto| and |lossy| outputs differ in quality; |lossy| is lower quality than |auto| even when the latter uses a lossy compression scheme. Adjusting the quality for these options is only possible with relatively complex Ghostscript options.

\section{Miscellaneous details}

\subsection{The \cmd\EndPreamble\ command}

At present, \pkg{pstool} scans the preamble of the main document by redefining |\begin{document}|, but this is rather fragile  because many classes and packages do their own redefining which overwrites \pkg{pstool}'s attempt. In this case, place the command \cmd\EndPreamble\ where-ever you'd like the preamble in the auxiliary processing to end (although is must be placed before |\begin{document}| for obvious reasons). This is also handy to bypass anything in the preamble that will never be required for the figures but which will slow down or otherwise conflict with the auxiliary processing.

\subsection{Cross-reference limitations}

The initial release of this package does not support cross-references within the \pkg{psfrag} labels of the included graphics. (If, say, you wish to refer to an equation number or a citation within a figure.)

\subsection{A note on file paths}

\pkg{pstool} tries to ensure that you can put image files in subdirectories of the main document and the auxiliary processing will still function correctly. In order to ensure this,  the external |pdflatex| compilation uses the |-output-directory| feature of \pdfTeX. This command line option is definitely supported on all platforms from TeX~Live~2008 and MiKTeX~2.7 onwards, but earlier distributions may not be supported.

One problem that \pkg{pstool} does not solve on its own is the inclusion of images that do not exist in subdirectories of the main document. For example, |\pstool{../Figures/myfig}| can not process by default because \pdfTeX\ usually does not have permission to write into folders that are higher in the heirarchy than the main document. This can be worked around presently in two different ways: (although maybe only for Mac~OS~X and Linux)
\begin{enumerate}
\item Give |pdflatex| permission to write anywhere with the command:\\
|openout_any=a pdflatex ...|
\item Create a symbolic link in the working directory to a point higher in the path: |ln -s ../../PhD ./PhD|, for example, and then refer to the graphics through this symbolic link.
\end{enumerate}

\section{Package information}
The most recent publicly released version of \pkg{pstool} is available at \textsc{ctan}: \url{http://tug.ctan.org/pkg/pstool/}. Historical and developmental versions are available at GitHub: \url{http://github.com/wspr/pstool/}. While general feedback via email is welcomed, specific bugs or feature requests should be reported through the issue tracker: \url{http://github.com/wspr/pstool/issues}.

\subsection{Licence}

This package is freely modifiable and distributable under the terms and conditions of the \LaTeX\ Project Public Licence, version 1.3c or greater (your choice).\footnote{\url{http://www.latex-project.org/lppl.txt}} This work consists of the files |pstool.tex| and the derived files |pstool.sty|, |pstool.ins|, and |pstool.pdf|. This work is maintained by \textsc{Will Robertson}.

{\addtocontents{toc}{\protect\end{varwidth}\protect\hfill}}
{\addtocontents{toc}{\protect\begin{varwidth}[t]{\protect\tocwidthB\protect\linewidth}}}
\clearpage
\part{Implementation}
\parindent=0pt
\DocInput{pstool.sty}

{\addtocontents{toc}{\protect\end{varwidth}}}
\end{document}