The preview Package for L^{A}TEX Version 11.86

David Kastrup^{∗}

2010/02/14

1 Introduction

The main purpose of this package is the extraction of certain environments (most notably displayed formulas) from L^{A}TEX sources as graphics. This works with DVI files postprocessed by either Dvips and Ghostscript or dvipng, but it also works when you are using PDFTEX for generating PDF files (usually also postprocessed by Ghostscript).

Current uses of the package include the preview-latex package for WYSI-WYG functionality in the AUCTEX editing environment, generation of previews in LyX, as part of the operation of the ps4pdf package, the tbook XML system and some other tools.

Producing EPS files with Dvips and its derivatives using the -E option is not a good alternative: People make do by fiddling around with \thispagestyle{empty} and hoping for the best (namely, that the specified contents will indeed fit on single pages), and then trying to guess the baseline of the resulting code and stuff, but this is at best dissatisfactory. The preview package provides an easy way to ensure that exactly one page per request gets shipped, with a well-defined baseline and no page decorations. While you still can use the preview package with the ‘classic’

     dvips -E -i

invocation, there are better ways available that don’t rely on Dvips not getting confused by PostScript specials.

For most applications, you’ll want to make use of the tightpage option. This will embed the page dimensions into the PostScript or PDF code, obliterating the need to use the -E -i options to Dvips. You can then produce all image files with a single run of Ghostscript from a single PDF or PostScript (as opposed to EPS) file.

∗dak@gnu.org

Various options exist that will pass TEX dimensions and other information about the respective shipped out material (including descender size) into the log file, where external applications might make use of it.

The possibility for generating a whole set of graphics with a single run of Ghostscript (whether from L^{A}TEX or PDFL^{A}TEX) increases both speed and robustness of applications. It is also feasible to use dvipng on a DVI file with the options

-picky -noghostscript

to omit generating any image file that requires Ghostscript, then let a script generate all missing files using Dvips/Ghostscript. This will usually speed up the process significantly.

2 Package options

The package is included with the customary

\usepackage[⟨options⟩]{preview}

You should usually load this package as the last one, since it redefines several things that other packages may also provide.

The following options are available:

active is the most essential option. If this option is not specified, the preview package will be inactive and the document will be typeset as if the preview package were not loaded, except that all declarations and environments defined by the package are still legal but have no effect. This allows defining previewing characteristics in your document, and only activating them by calling L^{A}TEX as

    latex '\PassOptionsToPackage{active}{preview}
    \input{⟨filename⟩}'

noconfig Usually the file prdefault.cfg gets loaded whenever the preview package gets activated. prdefault.cfg is supposed to contain definitions that can cater for otherwise bad results, for example, if a certain document class would otherwise lead to trouble. It also can be used to override any settings made in this package, since it is loaded at the very end of it. In addition, there may be configuration files specific for certain preview options like auctex which have more immediate needs. The noconfig option suppresses loading of those option files, too.

psfixbb Dvips determines the bounding boxes from the material in the DVI file it understands. Lots of PostScript specials are not part of that. Since the TEX boxes do not make it into the DVI file, but merely characters, rules and specials do, Dvips might include far too small areas. The option psfixbb will include /dev/null as a graphic file in the ultimate upper left and lower right corner of the previewed box. This will make Dvips generate an appropriate bounding box. dvips If this option is specified as a class option or to other packages, several

packages pass things like page size information to Dvips, or cause crop marks or draft messages written on pages. This seriously hampers the usability of previews. If this option is specified, the changes will be undone if possible.

pdftex If this option is set, PDFTEX is assumed as the output driver. This mainly affects the tightpage option.

xetex If this option is set, XeTEX is assumed as the output driver. This mainly affects the tightpage option.

displaymath will make all displayed math environments subject to preview processing. This will typically be the most desired option.

floats will make all float objects subject to preview processing. If you want to be more selective about what floats to pass through to a preview, you should instead use the \PreviewSnarfEnvironment command on the floats you want to have previewed.

textmath will make all text math subject to previews. Since math mode is used throughly inside of L^{A}TEX even for other purposes, this works by redefining \(, \) and $ and the math environment (apparently some people use that). Only occurences of these text math delimiters in later loaded packages and in the main document will thus be affected.

graphics will subject all \includegraphics commands to a preview.

sections will subject all section headers to a preview.

delayed will delay all activations and redefinitions the preview package makes until \begin{document}. The purpose of this is to cater for documents which should be subjected to the preview package without having been prepared for it. You can process such documents with

    latex '\RequirePackage[active,delayed,⟨options⟩]{preview}
    \input{⟨filename⟩}'

This relaxes the requirement to be loading the preview package as last package.

⟨driver⟩ loads a special driver file pr⟨driver⟩.def. The remaining options are implemented through the use of driver files.

auctex This driver will produce fake error messages at the start and end of every preview environment that enable the Emacs package preview-latex in connection with AUCTEX to pinpoint the exact source location where the previews have originated. Unfortunately, there is no other reliable means of passing the current TEX input position in a line to external programs. In order to make the parsing more robust, this option also switches off quite a few diagnostics that could be misinterpreted.

You should not specify this option manually, since it will only be needed by automated runs that want to parse the pseudo error messages. Those runs will then use \PassOptionsToPackage in order to effect the desired behaviour. In addition, prauctex.cfg will get loaded unless inhibited by the noconfig option. This caters for the most frequently encountered problematic commands.

showlabels During the editing process, some people like to see the label names in their equations, figures and the like. Now if you are using Emacs for editing, and in particular preview-latex, I’d strongly recommend that you check out the RefTEX package which pretty much obliterates the need for this kind of functionality. If you still want it, standard L^{A}TEX provides it with the showkeys package, and there is also the less encompassing showlabels package. Unfortunately, since those go to some pain not to change the page layout and spacing, they also don’t change preview’s idea of the TEX dimensions of the involved boxes. So if you are using preview for determing bounding boxes, those packages are mostly useless. The option showlabels offers a substitute for them.

tightpage It is not uncommon to want to use the results of preview as graphic images for some other application. One possibility is to generate a flurry of EPS files with

dvips -E -i -Pwww -o ⟨outputfile⟩.000 ⟨inputfile⟩

However, in case those are to be processed further into graphic image files by Ghostscript, this process is inefficient since all of those files need to be processed one by one. In addition, it is necessary to extract the bounding box comments from the EPS files and convert them into page dimension parameters for Ghostscript in order to avoid full-page graphics. This is not even possible if you wanted to use Ghostscript in a single run for generating the files from a single PostScript file, since Dvips will in that case leave no bounding box information anywhere.

The solution is to use the tightpage option. That way a single command line like

    gs -sDEVICE=png16m -dTextAlphaBits=4 -r300
    -dGraphicsAlphaBits=4 -dSAFER -q -dNOPAUSE
    -sOutputFile=⟨outputfile ⟩%d.png ⟨inputfile ⟩.ps

will be able to produce tight graphics from a single PostScript file generated with Dvips without use of the options -E -i, in a single run.

The tightpage option actually also works when using the pdftex option and generating PDF files with PDFTEX. The resulting PDF file has separate page dimensions for every page and can directly be converted with one run of Ghostscript into image files.

If neither dvips or pdftex have been specified, the corresponding option will get autodetected and invoked.

If you need this in a batch environment where you don’t want to use preview’s automatic extraction facilities, no problem: just don’t use any of the extraction options, and wrap everything to be previewed into preview environments. This is how LyX does its math previews.

If the pages under the tightpage option are just too tight, you can adjust by setting the length \PreviewBorder to a different value by using \setlength. The default value is 0.50001bp, which is half of a usual PostScript point, rounded up. If you go below this value, the resulting page size may drop below 1bp, and Ghostscript does not seem to like that. If you need finer control, you can adjust the bounding box dimensions individually by changing the macro \PreviewBbAdjust with the help of \renewcommand. Its default value is

    \newcommand \PreviewBbAdjust {-\PreviewBorder
    -\PreviewBorder \PreviewBorder \PreviewBorder}

This adjusts the left, lower, right and upper borders by the given amount. The macro must contain 4 TEX dimensions after another, and you may not omit the units if you specify them explicitly instead of by register. PostScript points have the unit bp.

lyx This option is for the sake of LyX developers. It will output a few diagnostics relevant for the sake of LyX’ preview functionality (at the time of writing, mostly implemented for math insets, in versions of LyX starting with 1.3.0).

counters This writes out diagnostics at the start and the end of previews. Only the counters changed since the last output get written, and if no counters changed, nothing gets written at all. The list consists of counter name and value, both enclosed in {} braces, followed by a space. The last such pair is followed by a colon (:) if it is at the start of the preview snippet, and by a period (.) if it is at the end. The order of different diagnostics like this being issued depends on the order of the specification of the options when calling the package.

Systems like preview-latex use this for keeping counters accurate when single previews are regenerated.

footnotes This makes footnotes render as previews, and only as their footnote symbol. A convenient editing feature inside of Emacs.

The following options are just for debugging purposes of the package and similar to the corresponding TEX commands they allude to:

tracingall causes lots of diagnostic output to appear in the log file during the preview collecting phases of TEX’s operation. In contrast to the similarly named TEX command, it will not switch to \errorstopmode, nor will it change the setting of \tracingonline. showbox This option will show the contents of the boxes shipped out to the DVI

files. It also sets \showboxbreadth and \showboxdepth to their maximum values at the end of loading this package, but you may reset them if you don’t like that.

3 Provided Commands

preview The preview environment causes its contents to be set as a single preview image. Insertions like figures and footnotes (except those included in minipages) will typically lead to error messages or be lost. In case the preview package has not been activated, the contents of this environment will be typeset normally.

nopreview The nopreview environment will cause its contents not to undergo any special treatment by the preview package. When preview is active, the contents will be discarded like all main text that does not trigger the preview hooks. When preview is not active, the contents will be typeset just like the main text.

Note that both of these environments typeset things as usual when preview is not active. If you need something typeset conditionally, use the \ifPreview conditional for it.

\PreviewMacro If you want to make a macro like \includegraphics (actually, this is what is done by the graphics option to preview) produce a preview image, you put a declaration like

     \PreviewMacro[*[[!]{\includegraphics}

or, more readable,

     \PreviewMacro[{*[][]{}}]{\includegraphics}

into your preamble. The optional argument to \PreviewMacro specifies the arguments \includegraphics accepts, since this is necessary information for properly ending the preview box. Note that if you are using the more readable form, you have to enclose the argument in a [{ and }] pair. The inner braces are necessary to stop any included [] pairs from prematurely ending the optional argument, and to make a single {} denoting an optional argument not get stripped away by TEX’s argument parsing.

The letters simply mean

* indicates an optional * modifier, as in \includegraphics*.

[ indicates an optional argument in brackets. This syntax is somewhat baroque, but brief.

[] also indicates an optional argument in brackets. Be sure to have encluded the entire optional argument specification in an additional pair of braces as described above.

! indicates a mandatory argument.

{} indicates the same. Again, be sure to have that additional level of braces around the whole argument specification.

?⟨delimiter⟩{⟨true case⟩}{⟨false case⟩} is a conditional. The next character is checked against being equal to ⟨delimiter⟩. If it is, the specification ⟨true case⟩ is used for the further parsing, otherwise ⟨false case⟩ will be employed. In neither case is something consumed from the input, so {⟨true case⟩} will still have to deal with the upcoming delimiter.

@{⟨literal sequence⟩} will insert the given sequence literally into the executed call of the command.

- will just drop the next token. It will probably be most often used in the true branch of a ? specification.

#{⟨argument⟩}{⟨replacement⟩} is a transformation rule that calls a macro with the given argument and replacement text on the rest of the argument list. The replacement is used in the executed call of the command. This can be used for parsing arbitrary constructs. For example, the [] option could manually be implemented with the option string ?[{#{[#1]}{[{#1}]}}{}. PStricks users might enjoy this sort of flexibility.

:{⟨argument⟩}{⟨replacement⟩} is again a transformation rule. As opposed to #, however, the result of the transformation is parsed again. You’ll rarely need this.

There is a second optional argument in brackets that can be used to declare any default action to be taken instead. This is mostly for the sake of macros that influence numbering: you would want to keep their effects in that respect. The default action should use #1 for referring to the original (not the patched) command with the parsed options appended. Not specifying a second optional argument here is equivalent to specifying [#1].

\PreviewMacro* A similar invocation \PreviewMacro* simply throws the macro and all of its arguments declared in the manner above away. This is mostly useful for having things like \footnote not do their magic on their arguments. More often than not, you don’t want to declare any arguments to scan to \PreviewMacro* since you would want the remaining arguments to be treated as usual text and typeset in that manner instead of being thrown away. An exception might be, say, sort keys for \cite.

A second optional argument in brackets can be used to declare any default action to be taken instead. This is for the sake of macros that influence numbering: you would want to keep their effects in that respect. The default action might use #1 for referring to the original (not the patched) command with the parsed options appended. Not specifying a second optional argument here is equivalent to specifying [] since the command usually gets thrown away.

As an example for using this argument, you might want to specify

     \PreviewMacro*\footnote[{[]}][#1{}]

This will replace a footnote by an empty footnote, but taking any optional parameter into account, since an optional paramter changes the numbering scheme. That way the real argument for the footnote remains for processing by preview-latex.

\PreviewEnvironment  The macro \PreviewEnvironment works just as \PreviewMacro does, only

\PreviewEnvironment* for environments. And the same goes for \PreviewEnvironment* as compared to

\PreviewMacro*.

\PreviewSnarfEnvironment This macro does not typeset the original environment inside of a preview box, but instead typesets just the contents of the original environment inside of the preview box, leaving nothing for the original environment. This has to be used for figures, for example, since they would

1. produce insertion material that cannot be extracted to the preview properly,

2. complain with an error message about not being in outer par mode.

\PreviewOpen Those Macros form a matched preview pair. This is for macros that behave \PreviewClose similar as \begin and \end of an environment. It is essential for the operation of

\PreviewOpen that the macro treated with it will open an additional group even when the preview falls inside of another preview or inside of a nopreview environment. Similarly, the macro treated with \reviewClose will close an environment even when inactive.

\ifPreview In case you need to know whether preview is active, you can use the conditional

\ifPreview together with \else and \fi.

4 The Implementation

Here we go: the start is somewhat obtuse since we figure out version number and date from RCS strings. This should really be done at docstrip time instead. Takers?

\pr@version

1 ⟨∗style⟩ 2 ⟨∗!active⟩

 3 \NeedsTeXFormat{LaTeX2e} \def\reserved@a #1#2$#3:
 4 #4${\xdef#1{\reserved@c #2#4 $}} \def\reserved@c #1 #2${#1}
 5 \begingroup \catcode`\_=12
 6 \reserved@a\pr@version $Name: release_11_86 $ \ifx\pr@version\@empty
 7 \reserved@a\pr@version CVS-$Revision: 1.126 $ \endgroup \else
 8 \def\next release_{} \lccode`\_=`.
 9 \edef\next{\lowercase{\endgroup
10  \def\noexpand\pr@version{\expandafter\next\pr@version}}} \next \fi
11 \reserved@a\next $Date: 2010/02/14 16:19:00 $
12 \edef\next{\noexpand\ProvidesPackage{preview}%
13 [\next\space \pr@version\space (AUCTeX/preview-latex)]}
14 \next

Since many parts here will not be needed as long as the package is inactive, we will include them enclosed with <*active> and </active> guards. That way, we can append all of this stuff at a place where it does not get loaded if not necessary.

\ifPreview Setting the \ifPreview command should not be done by the user, so we don’t use \newif here. As a consequence, there are no \Previewtrue and \Previewfalse commands.

15 \let\ifPreview\iffalse

16 ⟨/!active⟩

\ifpr@outer We don’t allow previews inside of previews. The macro \ifpr@outer can be used for checking whether we are outside of any preview code.

17 ⟨∗active⟩

18 \newif\ifpr@outer
19 \pr@outertrue

20 ⟨/active⟩

\preview@delay The usual meaning of \preview@delay is to just echo its argument in normal preview operation. If preview is inactive, it swallows its argument. If the delayed option is active, the contents will be passed to the \AtBeginDocument hook.

\pr@advise The core macro for modifying commands is \pr@advise. You pass it the original command name as first argument and what should be executed before the saved original command as second argument.

\pr@advise@ship The most often used macro for modifying commands is \pr@advise@ship. It receives three arguments. The first is the macro to modify, the second specifies some actions to be done inside of a box to be created before the original macro gets executed, the third one specifies actions after the original macro got executed.

\pr@loadcfg The macro \pr@loadcfg is used for loading in configuration files, unless disabled by the noconfig option.

21 ⟨∗!active⟩

22 \let\preview@delay=\@gobble
23 \let\pr@advise=\@gobbletwo
24 \long\def\pr@advise@ship#1#2#3{}
25 \def\pr@loadcfg#1{\InputIfFileExists{#1.cfg}{}{}}
26 \DeclareOption{noconfig}{\let\pr@loadcfg=\@gobble}

\pr@addto@front This adds code globally to the front of a macro.

27 \long\def\pr@addto@front#1#2{%
28 \toks@{#2}\toks@\expandafter{\the\expandafter\toks@#1}%
29 \xdef#1{\the\toks@}}

These commands get more interesting when preview is active:

30 \DeclareOption{active}{%
31 \let\ifPreview\iftrue
32 \def\pr@advise#1{%
33  \expandafter\pr@adviseii\csname pr@\string#1\endcsname#1}%
34 \long\def\pr@advise@ship#1#2#3{\pr@advise#1{\pr@protect@ship{#2}{#3}}}%
35 \let\preview@delay\@firstofone}

\pr@adviseii Now \pr@advise needs its helper macro. In order to avoid recursive definitions, we advise only macros that are not yet advised. Or, more exactly, we throw away the old advice and only take the new one. We use eTEX’s \protected where available for some extra robustness.

36 \long\def\pr@adviseii#1#2#3{\preview@delay{%
37 \ifx#1\relax \let#1#2\fi
38 \toks@{#3#1}%
39 \ifx\@undefined\protected \else \protected\fi
40 \long\edef#2{\the\toks@}}}

The delayed option is easy to implement: this is not done with \let since at the course of document processing, L^{A}TEX redefines \AtBeginDocument and we want to follow that redefinition.

41 \DeclareOption{delayed}{%
42 \ifPreview \def\preview@delay{\AtBeginDocument}\fi

43 }

\ifpr@fixbb Another conditional. \ifpr@fixbb tells us whether we want to surround the typeset materials with invisible rules so that Dvips gets the bounding boxes right for, say, pure PostScript inclusions.

If you are installing this on an operating system different from the one preview has been developed on, you might want to redefine \pr@markerbox in your prdefault.cfg file to use a file known to be empty, like /dev/null is under Unix. Make this redefinition depend on \ifpr@fixbb since only then \pr@markerbox will be defined.

44 \newif\ifpr@fixbb
45 \pr@fixbbfalse
46 \DeclareOption{psfixbb}{\ifPreview%
47 \pr@fixbbtrue
48 \newbox\pr@markerbox
49 \setbox\pr@markerbox\hbox{\special{psfile=/dev/null}}\fi

50 }

\pr@graphicstype The dvips option redefines the bop-hook to reset the page size.

51 \let\pr@graphicstype=\z@
52 \DeclareOption{dvips}{%
53 \let\pr@graphicstype\@ne
54 \preview@delay{\AtBeginDvi{%
55  \special{!/preview@version(\pr@version)def}
56  \special{!userdict begin/preview-bop-level 0 def%
57  /bop-hook{/preview-bop-level dup load dup 0 le{/isls false def%
58  /vsize 792 def/hsize 612 def}if 1 add store}bind def%
59  /eop-hook{/preview-bop-level dup load dup 0 gt{1 sub}if
60  store}bind def end}}}}
The pdftex option just sets \pr@graphicstype.
61 \DeclareOption{pdftex}{%
62 \let\pr@graphicstype\tw@}

And so does the xetex option.

63 \DeclareOption{xetex}{%
64 \let\pr@graphicstype\thr@@}

65 ⟨/!active⟩

4.1 The internals

Those are only needed if preview is active.

66 ⟨∗active⟩

\pr@snippet \pr@snippet is the current snippet number. We need a separate counter to \c@page since several other commands might fiddle with the page number.

67 \newcount\pr@snippet
68 \global\pr@snippet=1

\pr@protect This macro gets one argument which is unpacked and executed in typesetting situations where we are not yet inside of a preview.

69 \def\pr@protect{\ifx\protect\@typeset@protect
70 \ifpr@outer \expandafter\expandafter\expandafter
71  \@secondoftwo\fi\fi\@gobble}

\pr@protect@ship Now for the above mentioned \pr@protect@ship. This gets three arguments. The first is what to do at the beginning of the preview, the second what to do at the end, the third is the macro where we stored the original definition.

In case we are not in a typesetting situation, \pr@protect@ship leaves the stored macro to fend for its own. No better or worse protection than the original. And we only do anything different when \ifpr@outer turns out to be true.

72 \def\pr@protect@ship{\pr@protect{\@firstoftwo\pr@startbox}%
73 \@gobbletwo}

\pr@insert \pr@mark \pr@marks We don’t want insertions to end up on our lists. So we disable them right now by replacing them with the following:

74 \def\pr@insert{\begingroup\afterassignment\pr@insertii\count@}
75 \def\pr@insertii{\endgroup\setbox\pr@box\vbox}

Similar things hold for marks.

76 \def\pr@mark{{\afterassignment}\toks@}
77 \def\pr@marks{{\aftergroup\pr@mark\afterassignment}\count@}

\pr@box \pr@startbox Previews will be stored in \box\pr@box. \pr@startbox gets two arguments: code to execute immediately before the following stuff, code to execute afterwards. You have to cater for \pr@endbox being called at the right time yourself. We will use a \vsplit on the box later in order to remove any leading glues, penalties and similar stuff. For this reason we start off the box with an optimal break point.

78 \newbox\pr@box
79 \long\def\pr@startbox#1#2{%
80 \ifpr@outer
81  \toks@{#2}%

 82  \edef\pr@cleanup{\the\toks@}%
 83  \setbox\pr@box\vbox\bgroup
 84  \break
 85  \pr@outerfalse\@arrayparboxrestore
 86  \let\insert\pr@insert
 87  \let\mark\pr@mark
 88  \let\marks\pr@marks
 89  \expandafter\expandafter\expandafter
 90  \pr@ship@start
 91  \expandafter\@firstofone
 92 \else
 93  \expandafter \@gobble
 94 \fi{#1}}

\pr@endbox Cleaning up also is straightforward. If we have to watch the bounding TEX box, we want to remove spurious skips. We also want to unwrap a possible single line paragraph, so that the box is not full line length. We use \vsplit to clean up leading glue and stuff, and we make some attempt of removing trailing ones. After that, we wrap up the box including possible material from \AtBeginDvi. If the psfixbb option is active, we adorn the upper left and lower right corners with copies of \pr@markerbox. The first few lines cater for L^{A}TEX hiding things like

 like the code for \paragraph in \everypar.
 95 \def\pr@endbox{%
 96 \let\reserved@a\relax
 97 \ifvmode \edef\reserved@a{\the\everypar}%
 98  \ifx\reserved@a\@empty\else
 99  \dimen@\prevdepth
100  \noindent\par
101  \setbox\z@\lastbox\unskip\unpenalty
102  \prevdepth\dimen@
103  \setbox\z@\hbox\bgroup\penalty-\maxdimen\unhbox\z@
104  \ifnum\lastpenalty=-\maxdimen\egroup
105  \else\egroup\box\z@ \fi\fi\fi
106 \ifhmode \par\unskip\setbox\z@\lastbox
107  \nointerlineskip\hbox{\unhbox\z@\/}%
108 \else \unskip\unpenalty\unskip \fi
109 \egroup
110 \setbox\pr@box\vbox{%
111  \baselineskip\z@skip \lineskip\z@skip \lineskiplimit\z@
112  \@begindvi
113  \nointerlineskip
114  \splittopskip\z@skip\setbox\z@\vsplit\pr@box to\z@
115  \unvbox\z@
116  \nointerlineskip
117  %\color@setgroup
118  \box\pr@box
119  %\color@endgroup

120 }%

\pr@ship@end At this point, \pr@ship@end gets called. You must not under any circumstances change \box\pr@box in any way that would add typeset material at the front of it, except for PostScript header specials, since the front of \box\pr@box may contain stuff from \AtBeginDvi. \pr@ship@end contains two types of code additions: stuff that adds to \box\pr@box, like the labels option does, and stuff that measures out things or otherwise takes a look at the finished \box\pr@box, like the auctex or showbox option do. The former should use \r@addto@front for adding to this hook, the latter use \@addto@macro for adding at the end of this hook.

Note that we shift the output box up by its height via \voffset. This has three reasons: first we make sure that no package-inflicted non-zero value of \voffset or \hoffset will have any influence on the positioning of our box. Second we shift the box such that its basepoint will exactly be at the (1in,1in) mark defined by TEX. That way we can properly take ascenders into account. And the third reason is that TEX treats a \hbox and a \vbox differently with regard to the treating of its depth. Shifting \voffset and \hoffset can be inhibited by setting

\pr@offset@override.
121 \pr@ship@end
122 {\let\protect\noexpand
123 \ifx\pr@offset@override\@undefined
124  \voffset=-\ht\pr@box
125  \hoffset=\z@
126 \fi
127 \c@page=\pr@snippet
128 \pr@shipout
129 \ifpr@fixbb\hbox{%
130  \dimen@\wd\pr@box
131  \@tempdima\ht\pr@box
132  \@tempdimb\dp\pr@box
133  \box\pr@box
134  \llap{\raise\@tempdima\copy\pr@markerbox\kern\dimen@}%
135  \lower\@tempdimb\copy\pr@markerbox}%
136 \else \box\pr@box \fi}%
137 \global\advance\pr@snippet\@ne
138 \pr@cleanup

139 }

Oh, and we kill off the usual meaning of \shipout in case somebody makes a special output routine. The following test is pretty much the same as in everyshi.sty. One of its implications is that if someone does a \shipout of a void box, things will go horribly wrong.

\shipout
140 \let\pr@shipout=\shipout
141 \def\shipout{\deadcycles\z@\bgroup\setbox\z@\box\voidb@x
142 \afterassignment\pr@shipoutegroup\setbox\z@}
143 \def\pr@shipoutegroup{\ifvoid\z@ \expandafter\aftergroup\fi \egroup}

4.2 Parsing commands

\pr@parseit \pr@endparse \pr@callafter The following stuff is for parsing the arguments of commands we want to somehow surround with stuff. Usage is

     \pr@callafter⟨aftertoken⟩⟨parsestring⟩\pr@endparse

⟨macro⟩⟨parameters⟩

⟨aftertoken⟩ is stored away and gets executed once parsing completes, with its first argument being the parsed material. ⟨parsestring⟩ would be, for example for the \includegraphics macro, *[[!, an optional * argument followed by two optional arguments enclosed in [], followed by one mandatory argument.

For the sake of a somewhat more intuitive syntax, we now support also the syntax {*[]{}} in the optional argument. Since TEX strips redundant braces, we have to write [{{}}] in this syntax for a single mandatory argument. Hard to avoid. We use an unusual character for ending the parsing. The implementation is rather trivial.

144 \def\pr@parseit#1{\csname pr@parse#1\endcsname}
145 \let\pr@endparse=\@percentchar
146 \def\next#1{%
147 \def\pr@callafter{%
148 \afterassignment\pr@parseit
149 \let#1= }}
150 \expandafter\next\csname pr@parse\pr@endparse\endcsname

\pr@parse* Straightforward, same mechanism L^{A}TEX itself employs. We take some care not to pass potential # tokens unprotected through macros.

151 \long\expandafter\def\csname pr@parse*\endcsname#1\pr@endparse#2{%
152 \begingroup\toks@{#1\pr@endparse{#2}}%
153 \edef\next##1{\endgroup##1\the\toks@}%
154 \@ifstar{\next{\pr@parse@*}}{\next\pr@parseit}}

\pr@parse[ \pr@brace Copies optional parameters in brackets if present. The additional level of braces is necessary to ensure that braces the user might have put to hide a ] bracket in an optional argument don’t get lost. There will be no harm if such braces were not there at the start.

155 \long\expandafter\def\csname pr@parse[\endcsname#1\pr@endparse#2{%
156 \begingroup\toks@{#1\pr@endparse{#2}}%
157 \edef\next##1{\endgroup##1\the\toks@}%
158 \@ifnextchar[{\next\pr@bracket}{\next\pr@parseit}}
159 \long\def\pr@bracket#1\pr@endparse#2[#3]{%
160 \pr@parseit#1\pr@endparse{#2[{#3}]}}

\pr@parse] This is basically a do-nothing, so that we may use the syntax {*[][]!} in the optional argument instead of the more concise but ugly *[[! which confuses the brace matchers of editors.

161 \expandafter\let\csname pr@parse]\endcsname=\pr@parseit

\pr@parse \pr@parse! Mandatory arguments are perhaps easiest to parse.

162 \long\def\pr@parse#1\pr@endparse#2#3{%
163 \pr@parseit#1\pr@endparse{#2{#3}}}
164 \expandafter\let\csname pr@parse!\endcsname=\pr@parse

\pr@parse? \pr@parsecond This does an explicit call of \@ifnextchar and forks into the given two alternatives as a result.

165 \long\expandafter\def\csname pr@parse?\endcsname#1#2\pr@endparse#3{%
166 \begingroup\toks@{#2\pr@endparse{#3}}%
167 \@ifnextchar#1{\pr@parsecond\@firstoftwo}%
168  {\pr@parsecond\@secondoftwo}}
169 \def\pr@parsecond#1{\expandafter\endgroup
170 \expandafter\expandafter\expandafter\pr@parseit
171 \expandafter#1\the\toks@}

\pr@parse@ This makes it possible to insert literal material into the argument list.

172 \long\def\pr@parse@#1#2\pr@endparse#3{%
173 \pr@parseit #2\pr@endparse{#3#1}}

\pr@parse- This will just drop the next token.

174 \long\expandafter\def\csname pr@parse-\endcsname
175 #1\pr@endparse#2{\begingroup
176 \toks@{\endgroup\pr@parseit #1\pr@endparse{#2}}%
177 {\aftergroup\the\aftergroup\toks@ \afterassignment}%
178 \let\next= }

\pr@parse: The following is a transform rule. A macro is being defined with the given argument list and replacement, and the transformed version replaces the original. The result of the transform is still subject to being parsed.

179 \long\expandafter\def\csname pr@parse:\endcsname
180 #1#2#3\pr@endparse#4{\begingroup
181  \toks@{\endgroup \pr@parseit#3\pr@endparse{#4}}%
182  \long\def\next#1{#2}%
183  \the\expandafter\toks@\next}

\pr@parse# Another transform rule, but this passes the transformed material into the token list.

184 \long\expandafter\def\csname pr@parse#\endcsname
185 #1#2#3\pr@endparse#4{\begingroup
186  \toks@{#4}%
187  \long\edef\next##1{\toks@{\the\toks@##1}}%
188  \toks@{\endgroup \pr@parseit#3\pr@endparse}%
189  \long\def\reserved@a#1{{#2}}%
190  \the\expandafter\next\reserved@a}

191 ⟨/active⟩

4.3 Selection options

The displaymath option. The equation environments in AMSL^{A}TEX already do too much before our hook gets to interfere, so we hook earlier. Some juggling is involved to ensure we get the original \everydisplay tokens only once and where appropriate.

The incredible hack with \dt@ptrue is necessary for working around bug ‘amslatex/3425’.

192 ⟨∗!active⟩

193 \begingroup
194 \catcode`\*=11
195 \@firstofone{\endgroup
196 \DeclareOption{displaymath}{%
197 \preview@delay{\toks@{%
198  \pr@startbox{\noindent$$%
199  \aftergroup\pr@endbox\@gobbletwo}{$$}\@firstofone}%
200  \everydisplay\expandafter{\the\expandafter\toks@
201  \expandafter{\the\everydisplay}}}%
202 \pr@advise@ship\equation{\begingroup\aftergroup\pr@endbox
203  \def\dt@ptrue{\m@ne=\m@ne}\noindent}%
204  {\endgroup}%
205 \pr@advise@ship\equation*{\begingroup\aftergroup\pr@endbox
206  \def\dt@ptrue{\m@ne=\m@ne}\noindent}%
207  {\endgroup}%
208 \PreviewOpen[][\def\dt@ptrue{\m@ne=\m@ne}\noindent#1]\[%
209 \PreviewClose\]%
210 \PreviewEnvironment[][\noindent#1]{eqnarray}%
211 \PreviewEnvironment[][\noindent#1]{eqnarray*}%
212 \PreviewEnvironment{displaymath}%

213 }}

The textmath option. Some folderol in order to define the active $ math mode delimiter. \pr@textmathcheck is used for checking whether we have a single $ or double $$. In the latter case, we enter display math (this sort of display math is not allowed inside of L^{A}TEX because of inconsistent spacing, but surprisingly many people use it nevertheless). Strictly speaking, this is incorrect, since not every $$ actually means display math. For example, \hbox{$$} will because of restricted horizontal mode rather yield an empty text math formula. Since our implementation moved the sequence inside of a \vbox, the interpretation will change. People should just not enter rubbish like that.

214 \begingroup
215 \def\next#1#2{%
216 \endgroup
217 \DeclareOption{textmath}{%
218  \PreviewEnvironment{math}%
219  \preview@delay{\ifx#1\@undefined \let#1=$%$
220  \fi\catcode`\$=\active
221  \ifx\xyreuncatcodes\@undefined\else
222  \edef\next{\catcode`@=\the\catcode`@\relax}%

223  \makeatother\expandafter\xyreuncatcodes\next\fi}%
224  \pr@advise@ship\(\pr@endaftergroup{}% \)
225  \pr@advise@ship#1{\@firstoftwo{\let#1=#2%
226  \futurelet\reserved@a\pr@textmathcheck}}{}}%
227 \def\pr@textmathcheck{\expandafter\pr@endaftergroup
228  \ifx\reserved@a#1{#2#2}\expandafter\@gobbletwo\fi#2}}
229 \lccode`\~=`\$
230 \lowercase{\expandafter\next\expandafter~}%
231 \csname pr@\string$%$
232 \endcsname

233 ⟨/!active⟩

\pr@endaftergroup This justs ends the box after the group opened by #1 is closed again.

234 ⟨∗active⟩

235 \def\pr@endaftergroup#1{#1\aftergroup\pr@endbox}

236 ⟨/active⟩

The graphics option.

237 ⟨∗!active⟩

238 \DeclareOption{graphics}{%
239 \PreviewMacro[*[[!]{\includegraphics}%]]

240 }

The floats option. The complications here are merely to spare us bug reports about broken document classes that use \let on \endfigure and similar. Notable culprits that have not been changed in years in spite of reports are elsart.cls and IEEEtran.cls. Complain when you are concerned.

241 \def\pr@floatfix#1#2{\ifx#1#2%
242 \ifx#1\@undefined\else
243 \PackageWarningNoLine{preview}{%
244 Your document class has a bad definition^^J
245 of \string#1, most likely^^J
246 \string\let\string#1=\string#2^^J
247 which has now been changed to^^J
248 \string\def\string#1{\string#2}^^J
249 because otherwise subsequent changes to \string#2^^J
250 (like done by several packages changing float behaviour)^^J
251 can't take effect on \string#1.^^J
252 Please complain to your document class author}%
253 \def#1{#2}\fi\fi}
254 \begingroup
255 \def\next#1#2{\endgroup
256 \DeclareOption{floats}{%
257  \pr@floatfix\endfigure\end@float
258  \pr@floatfix\endtable\end@float
259  \pr@floatfix#1\end@dblfloat
260  \pr@floatfix#2\end@dblfloat
261  \PreviewSnarfEnvironment[![]{@float}%]
262  \PreviewSnarfEnvironment[![]{@dblfloat}%]

263 }}

264 \expandafter\next\csname endfigure*\expandafter\endcsname
265 \csname endtable*\endcsname

The sections option. Two optional parameters might occur in memoir.cls.

266 \DeclareOption{sections}{%
267 \PreviewMacro[!!!!!!*[[!]{\@startsection}%]]
268 \PreviewMacro[*[[!]{\chapter}%]]

269 }

We now interpret any further options as driver files we load. Note that these driver files are loaded even when preview is not active. The reason is that they might define commands (like \PreviewCommand) that should be available even in case of an inactive package. Large parts of the preview package will not have been loaded in this case: you have to cater for that.

270 \DeclareOption*
271 {\InputIfFileExists{pr\CurrentOption.def}{}{\OptionNotUsed}}

4.4 Preview attaching commands

\PreviewMacro As explained above. Detect possible * and call appropriate macro.

272 \def\PreviewMacro{\@ifstar\pr@starmacro\pr@macro}

The version without * is now rather straightforward.

\pr@macro
\pr@domacro
\pr@macroii
\pr@endmacro

273 \long\def\pr@domacro#1#2{%
274 \long\def\next##1{#2}%
275 \pr@callafter\next#1]\pr@endparse}
276 \newcommand\pr@macro[1][]{%
277 \toks@{\pr@domacro{#1}}%
278 \long\edef\next[##1]##2{%
279  \noexpand\pr@advise@ship{##2}{\the\toks@{##1\noexpand\pr@endbox}}{}}%
280 \@ifnextchar[\next\pr@macroii}
281 \def\pr@macroii{\next[##1]}
282 \long\def\pr@endmacro#1{#1\pr@endbox}

PreviewMacro* \pr@protect@domacro \pr@starmacro The version with * has to parse the arguments, then throw them away. Some internal macros first, then the interface call.

283 \long\def\pr@protect@domacro#1#2{\pr@protect{%
284  \long\def\next##1{#2}%
285  \pr@callafter\next#1]\pr@endparse}}
286 \newcommand\pr@starmacro[1][]{\toks@{\pr@protect@domacro{#1}}%
287  \long\edef\next[##1]##2{%
288  \noexpand\pr@advise##2{\the\toks@{##1}}}%
289  \@ifnextchar[\next{\next[]}}

\PreviewOpen As explained above. Detect possible * and call appropriate macro.

290 \def\PreviewOpen{\@ifstar\pr@starmacro\pr@open}

The version without * is now rather straightforward.

\pr@open
291 \newcommand\pr@open[1][]{%
292 \toks@{\pr@domacro{#1}}%
293 \long\edef\next[##1]##2{%
294  \noexpand\pr@advise##2{\begingroup
295  \noexpand\pr@protect@ship
296  {\the\toks@{\begingroup\aftergroup\noexpand\pr@endbox##1}}%
297  {\endgroup}}}%
298 \@ifnextchar[\next\pr@macroii}

\PreviewClose As explained above. Detect possible * and call appropriate macro.

299 \def\PreviewClose{\@ifstar\pr@starmacro\pr@close}

The version without * is now rather straightforward.

\pr@close
300 \newcommand\pr@close[1][]{%
301 \toks@{\pr@domacro{#1}}%
302 \long\edef\next[##1]##2{%
303 \noexpand\pr@advise{##2}{\the\toks@{##1\endgroup}}}%
304 \@ifnextchar[\next\pr@macroii}

\PreviewEnvironment Actually, this ignores any syntax argument. But don’t tell anybody. Except for the * variant, it respects (actually ignores) any argument! Of course, we’ll need to deactivate \end{⟨environment⟩} as well.

305 \def\PreviewEnvironment{\@ifstar\pr@starenv\pr@env}
306 \newcommand\pr@starenv[1][]{\toks@{\pr@starmacro[{#1}]}%
307 \long\edef\next##1##2{%
308  \the\toks@[{##2}]##1}%
309 \begingroup\pr@starenvii}
310 \newcommand\pr@starenvii[2][]{\endgroup
311 \expandafter\next\csname#2\endcsname{#1}%
312 \expandafter\pr@starmacro\csname end#2\endcsname}
313 \newcommand\pr@env[1][]{%
314 \toks@{\pr@domacro{#1}}%
315 \long\edef\next[##1]##2{%
316 \noexpand\expandafter\noexpand\pr@advise@ship
317  \noexpand\csname##2\noexpand\endcsname{\the\toks@
318  {\begingroup\aftergroup\noexpand\pr@endbox##1}}{\endgroup}}%
319 \@ifnextchar[\next\pr@macroii %]

320 }

\PreviewSnarfEnvironment This is a nuisance since we have to advise both the environment and its end.

321 \newcommand{\PreviewSnarfEnvironment}[2][]{%
322 \expandafter\pr@advise
323 \csname #2\endcsname{\pr@snarfafter{#1}}%
324 \expandafter\pr@advise
325 \csname end#2\endcsname{\pr@endsnarf}}

326 ⟨/!active⟩

\pr@snarfafter \pr@startsnarf \pr@endsnarf Ok, this looks complicated, but we have to start a group in order to be able to hook \pr@endbox into the game only when \ifpr@outer has triggered the start. And we need to get our start messages out before parsing the arguments.

327 ⟨∗active⟩

328 \let\pr@endsnarf\relax
329 \long\def\pr@snarfafter#1{\ifpr@outer
330  \pr@ship@start
331  \let\pr@ship@start\relax
332  \let\pr@endsnarf\endgroup
333 \else
334  \let\pr@endsnarf\relax
335 \fi
336 \pr@protect{\pr@callafter\pr@startsnarf#1]\pr@endparse}}
337 \def\pr@startsnarf#1{#1\begingroup
338 \pr@startbox{\begingroup\aftergroup\pr@endbox}{\endgroup}%
339 \ignorespaces}

340 ⟨/active⟩

\pr@ship@start \pr@ship@end The hooks \pr@ship@start and \pr@ship@end can be added to by option

files by the help of the \g@addto@macro command from L^{A}TEX, and by the \pr@addto@front command from preview.sty itself. They are called just before starting to process some preview, and just after it. Here is the policy for adding to them: \pr@ship@start is called inside of the vbox \pr@box before typeset material gets produced. It is, however, preceded by a break command that is intended for usage in \vsplit, so that any following glue might disappear. In case you want to add any material on the list, you have to precede it with \unpenalty and have to follow it with \break. You have make sure that under no circumstances any other legal breakpoints appear before that, and your material should contribute no nonzero dimensions to the page. For the policies of the \pr@ship@end hook, see the description on page 12.

341 ⟨∗!active⟩

342 \let\pr@ship@start\@empty
343 \let\pr@ship@end\@empty

preview nopreview First we write the definitions of these environments when preview is inactive. We will redefine them if preview gets activated.

344 \newenvironment{preview}{\ignorespaces}{\ifhmode\unskip\fi}
345 \newenvironment{nopreview}{\ignorespaces}{\ifhmode\unskip\fi}

We now process the options and finish in case we are not active.

346 \ProcessOptions\relax
347 \ifPreview\else\expandafter\endinput\fi

348 ⟨/!active⟩

Now for the redefinition of the preview and endpreview environments:

349 ⟨∗active⟩

350 \renewenvironment{preview}{\begingroup
351 \pr@startbox{\begingroup\aftergroup\pr@endbox}%

352  {\endgroup}%
353 \ignorespaces}%
354 {\ifhmode\unskip\fi\endgroup}
355 \renewenvironment{nopreview}{\pr@outerfalse\ignorespaces}%
356 {\ifhmode\unskip\fi}

We use the normal output routine, but hijack it a bit for our purposes to preserve \AtBeginDvi hooks and not get previews while in output: that could become rather ugly.

The main work of disabling normal output relies on a \shipout redefinition.

\pr@output
357 \newtoks\pr@output
358 \pr@output\output
359 \output{%
360 \pr@outerfalse
361 \let\@begindvi\@empty
362 \the\pr@output}
363 \let\output\pr@output

\pr@typeinfos Then we have some document info that style files might want to output.

364 \def\pr@typeinfos{\typeout{Preview: Fontsize \f@size pt}%
365 \ifnum\mag=\@m\else\typeout{Preview: Magnification \number\mag}\fi
366 \ifx\pdfoutput\@undefined
367  \ifx\XeTeXversion\@undefined \else
368  % FIXME: The message should not be emitted if XeTeX does not produce
369  % PDF.  There does not seem to be a primitive for that, though.
370  \typeout{Preview: PDFoutput 1}%
371  \fi
372 \else
373  \ifx\pdfoutput\relax \else
374  \ifnum\pdfoutput>\z@
375  \typeout{Preview: PDFoutput 1}%
376  \fi
377  \fi
378 \fi

379 }

380 \AtBeginDocument{\pr@typeinfos}

And at the end we load the default configuration file, so that it may override settings from this package:

381 \pr@loadcfg{prdefault}

382 ⟨/active⟩ 383 ⟨/style⟩

5 The option files

5.1 The auctex option

The AUCTEX option will cause error messages to spew. We want them on the terminal, but we don’t want L^{A}TEX to stop its automated run. We delay \nonstopmode in case the user has any pseudo-interactive folderol like reading in of file names in his preamble. Because we are so good-hearted, we will not break this as long as the document has not started, but after that we need the error message mechanism operative.

The \nofiles command here tries to avoid clobbering input files used for references and similar. It will come too late if you call the package with \AtBeginDocument, so you’ll need to issue \nofiles yourself in that case. Previously, this was done unconditionally in the main style file, but since we don’t know what the package may be used for, this was inappropriate.

So here is the contents of the prauctex.def file:

384 ⟨auctex⟩\ifPreview\else\expandafter\endinput\fi

385 ⟨auctex⟩\nofiles

386 ⟨auctex⟩\preview@delay{\nonstopmode}

Ok, here comes creative error message formatting. It turns out a sizable portion of the runtime is spent in I/O. Making the error messages short is an advantage. It is not possible to convince TEX to make shorter error messages than this: TEX always wants to include context. This is about the shortest æsthetic one we can muster.

387 ⟨auctex⟩\begingroup
388 ⟨auctex⟩\lccode`\~=`\-
389 ⟨auctex⟩\lccode`\{=`\<
390 ⟨auctex⟩\lccode`\}=`\>
391 ⟨auctex⟩\lowercase{\endgroup
392 ⟨auctex⟩ \def\pr@msgi{{~}}}
393 ⟨auctex⟩\def\pr@msgii{Preview:
394 ⟨auctex⟩ Snippet \number\pr@snippet\space}
395 ⟨auctex⟩\begingroup
396 ⟨auctex⟩\catcode`\-=13
397 ⟨auctex⟩\catcode`\<=13
398 ⟨auctex⟩\@firstofone{\endgroup
399 ⟨auctex⟩\def\pr@msg#1{{%
400 ⟨auctex⟩ \let<\pr@msgi
401 ⟨auctex⟩ \def-{\pr@msgii#1}%
402 ⟨auctex⟩ \errhelp{Not a real error.}%
403 ⟨auctex⟩ \errmessage<}}}
404 ⟨auctex⟩\g@addto@macro\pr@ship@start{\pr@msg{started}}
405 ⟨auctex⟩\g@addto@macro\pr@ship@end{\pr@msg{ended.%
406 ⟨auctex⟩ (\number\ht\pr@box+\number\dp\pr@box x\number\wd\pr@box)}}

This looks pretty baffling, but it produces something short and semi-graphical, namely <-><->. That is a macro < that expands into <->, where < and > are the braces around an \errmessage argument and - is a macro expanding to the full text of the error message. Cough cough. You did not really want to know, did you?

Since over/underfull boxes are about the messiest things to parse, we disable them by setting the appropriate badness limits and making the variables point to junk. We also disable other stuff. While we set \showboxbreadth and \showboxdepth to indicate as little diagnostic output as possible, we keep them operative, so that the user retains the option of debugging using this stuff. The other variables concerning the generation of warnings and daignostics, however, are more often set by commonly employed packages and macros such as \sloppy. So we kill them off for good.

407 ⟨auctex⟩\hbadness=\maxdimen
408 ⟨auctex⟩\newcount\hbadness
409 ⟨auctex⟩\vbadness=\maxdimen
410 ⟨auctex⟩\let\vbadness=\hbadness
411 ⟨auctex⟩\hfuzz=\maxdimen
412 ⟨auctex⟩\newdimen\hfuzz
413 ⟨auctex⟩\vfuzz=\maxdimen
414 ⟨auctex⟩\let\vfuzz=\hfuzz
415 ⟨auctex⟩\showboxdepth=-1
416 ⟨auctex⟩\showboxbreadth=-1

Ok, now we load a possible configuration file.

417 ⟨auctex⟩\pr@loadcfg{prauctex}

And here we cater for several frequently used commands in prauctex.cfg:

418 ⟨auccfg⟩\PreviewMacro*[[][#1{}]\footnote
419 ⟨auccfg⟩\PreviewMacro*[?[{@{[]}}{}][#1]\item
420 ⟨auccfg⟩\PreviewMacro*\emph
421 ⟨auccfg⟩\PreviewMacro*\textrm
422 ⟨auccfg⟩\PreviewMacro*\textit
423 ⟨auccfg⟩\PreviewMacro*\textsc
424 ⟨auccfg⟩\PreviewMacro*\textsf
425 ⟨auccfg⟩\PreviewMacro*\textsl
426 ⟨auccfg⟩\PreviewMacro*\texttt
427 ⟨auccfg⟩\PreviewMacro*\textcolor
428 ⟨auccfg⟩\PreviewMacro*\mbox
429 ⟨auccfg⟩\PreviewMacro*[][#1{}]\author
430 ⟨auccfg⟩\PreviewMacro*[][#1{}]\title
431 ⟨auccfg⟩\PreviewMacro*\and
432 ⟨auccfg⟩\PreviewMacro*\thanks
433 ⟨auccfg⟩\PreviewMacro*[][#1{}]\caption
434 ⟨auccfg⟩\preview@delay{\@ifundefined{pr@\string\@startsection}{%
435 ⟨auccfg⟩ \PreviewMacro*[!!!!!!*][#1{}]\@startsection}{}}
436 ⟨auccfg⟩\preview@delay{\@ifundefined{pr@\string\chapter}{%
437 ⟨auccfg⟩ \PreviewMacro*[*][#1{}]\chapter}{}}
438 ⟨auccfg⟩\PreviewMacro*\index

5.2 The lyx option

The following is the option providing LyX with info for its preview implementation.

439 ⟨lyx⟩\ifPreview\else\expandafter\endinput\fi
440 ⟨lyx⟩\pr@loadcfg{prlyx}
441 ⟨lyx⟩\g@addto@macro\pr@ship@end{\typeout{Preview:
442 ⟨lyx⟩ Snippet \number\pr@snippet\space
443 ⟨lyx⟩ \number\ht\pr@box\space \number\dp\pr@box \space\number\wd\pr@box}}

5.3 The counters option

This outputs a checkpoint. We do this by saving all counter registers in backup macros starting with \pr@c@ in their name. A checkpoint first writes out all changed counters (previously unchecked counters are not written out unless different from zero), then saves all involved counter values. L^{A}TEX tracks its counters in the global variable \cl@ckpt.

444 ⟨counters⟩\ifPreview\else\expandafter\endinput\fi
445 ⟨counters⟩\def\pr@eltprint#1{\expandafter\@gobble\ifnum\value{#1}=0%
446 ⟨counters⟩ \csname pr@c@#1\endcsname\else\relax
447 ⟨counters⟩ \space{#1}{\arabic{#1}}\fi}
448 ⟨counters⟩\def\pr@eltdef#1{\expandafter\xdef
449 ⟨counters⟩ \csname pr@c@#1\endcsname{\arabic{#1}}}
450 ⟨counters⟩\def\pr@ckpt#1{{\let\@elt\pr@eltprint\edef\next{\cl@@ckpt}%
451 ⟨counters⟩ \ifx\next\@empty\else\typeout{Preview: Counters\next#1}%
452 ⟨counters⟩ \let\@elt\pr@eltdef\cl@@ckpt\fi}}
453 ⟨counters⟩\pr@addto@front\pr@ship@start{\pr@ckpt:}
454 ⟨counters⟩\pr@addto@front\pr@ship@end{\pr@ckpt.}

5.4 Debugging options

Those are for debugging the operation of preview, and thus are mostly of interest for people that want to use preview for their own purposes. Since debugging output is potentially confusing to the error message parsing from AUCTEX, you should not turn on \tracingonline or switch from \nonstopmode unless you are certain your package will never be used with preview-latex.

The showbox option will generate diagnostic output for every produced box. It does not delay the resetting of the \showboxbreadth and \showboxdepth parameters so that you can still change them after the loading of the package. It does, however, move them to the end of the package loading, so that they will not be affected by the auctex option.

455 ⟨showbox⟩\ifPreview\else\expandafter\endinput\fi
456 ⟨showbox⟩\AtEndOfPackage{%
457 ⟨showbox⟩ \showboxbreadth\maxdimen
458 ⟨showbox⟩ \showboxdepth\maxdimen}
459 ⟨showbox⟩\g@addto@macro\pr@ship@end{\showbox\pr@box}

The tracingall option is for the really heavy diagnostic stuff. For the reasons mentioned above, we do not want to change the setting of the interaction mode, nor of the tracingonline flag. If the user wants them different, he should set them outside of the preview boxes.

460 ⟨tracingall⟩\ifPreview\else\expandafter\endinput\fi
461 ⟨tracingall⟩\pr@addto@front\pr@ship@start{\let\tracingonline\count@
462 ⟨tracingall⟩ \let\errorstopmode\@empty\tracingall}

5.5 Supporting conversions

It is not uncommon to want to use the results of preview as images. One possibility is to generate a flurry of EPS files with

dvips -E -i -Ppdf -o ⟨outputfile⟩.000 ⟨inputfile⟩

However, in case those are to be processed further into graphic image files by Ghostscript, this process is inefficient. One cannot use Ghostscript in a single run for generating the files, however, since one needs to set the page size (or full size pages will be produced). The tightpage option will set the page dimensions at the start of each PostScript page so that the output will be sized appropriately. That way, a single pass of Dvips followed by a single pass of Ghostscript will be sufficient for generating all images.

You will have to specify the output driver to be used, either dvips or pdftex.

\PreviewBorder \PreviewBbAdjust We start this off with the user tunable parameters which get defined even in the case of an inactive package, so that redefinitions and assignments to them will always work:

463 ⟨tightpage⟩\ifx\PreviewBorder\@undefined
464 ⟨tightpage⟩ \newdimen\PreviewBorder
465 ⟨tightpage⟩ \PreviewBorder=0.50001bp

466 ⟨tightpage⟩\fi

467 ⟨tightpage⟩\ifx\PreviewBbAdjust\@undefined
468 ⟨tightpage⟩ \def\PreviewBbAdjust{-\PreviewBorder -\PreviewBorder
469 ⟨tightpage⟩  \PreviewBorder \PreviewBorder}

470 ⟨tightpage⟩\fi

Here is stuff used for parsing this:

471 ⟨tightpage⟩\ifPreview\else\expandafter\endinput\fi
472 ⟨tightpage⟩\def\pr@nextbb{\edef\next{\next\space\number\dimen@}%
473 ⟨tightpage⟩ \expandafter\xdef\csname pr@bb@%
474 ⟨tightpage⟩  \romannumeral\count@\endcsname{\the\dimen@}%
475 ⟨tightpage⟩ \advance\count@\@ne\ifnum\count@<5
476 ⟨tightpage⟩ \afterassignment\pr@nextbb\dimen@=\fi}

And here is the stuff that we fudge into our hook. Of course, we have to do it in a box, and we start this box off with our special. There is one small consideration here: it might come before any \AtBeginDvi stuff containing header specials. It turns out Dvips rearranges this amicably: header code specials get transferred to the appropriate header section, anyhow, so this ensures that we come right after the bop section. We insert the 7 numbers here: the 4 bounding box adjustments, and the 3 TEX box dimensions. In case the box adjustments have changed since the last time, we write them out to the console.

477 ⟨tightpage⟩\ifnum\pr@graphicstype=\z@

478 ⟨tightpage⟩ \ifcase

479 ⟨tightpage⟩  \ifx\XeTeXversion\@undefined
480 ⟨tightpage⟩  \ifx\pdfoutput\@undefined \@ne\fi
481 ⟨tightpage⟩  \ifx\pdfoutput\relax \@ne\fi
482 ⟨tightpage⟩  \ifnum\pdfoutput>\z@ \tw@\fi \@ne
483 ⟨tightpage⟩  \else \thr@@\fi
484 ⟨tightpage⟩ \or \ExecuteOptions{dvips}\relax
485 ⟨tightpage⟩ \or \ExecuteOptions{pdftex}\relax
486 ⟨tightpage⟩ \or \ExecuteOptions{xetex}\relax\fi\fi
487 ⟨tightpage⟩\global\let\pr@bbadjust\@empty
488 ⟨tightpage⟩\pr@addto@front\pr@ship@end{\begingroup
489 ⟨tightpage⟩ \let\next\@gobble
490 ⟨tightpage⟩ \count@\@ne\afterassignment\pr@nextbb
491 ⟨tightpage⟩ \dimen@\PreviewBbAdjust
492 ⟨tightpage⟩ \ifx\pr@bbadjust\next
493 ⟨tightpage⟩ \else \global\let\pr@bbadjust\next
494 ⟨tightpage⟩ \typeout{Preview: Tightpage \pr@bbadjust}%

495 ⟨tightpage⟩ \fi\endgroup}

496 ⟨tightpage⟩\ifcase\pr@graphicstype

497 ⟨tightpage⟩\or

498 ⟨tightpage⟩ \g@addto@macro\pr@ship@end{\setbox\pr@box\hbox{%
499 ⟨tightpage⟩  \special{ps::\pr@bbadjust\space
500 ⟨tightpage⟩  \number\ifdim\ht\pr@box>\z@ \ht\pr@box

501 ⟨tightpage⟩ \else \z@ 502 ⟨tightpage⟩ \fi \space

503 ⟨tightpage⟩  \number\ifdim\dp\pr@box>\z@ \dp\pr@box

504 ⟨tightpage⟩ \else \z@ 505 ⟨tightpage⟩ \fi \space

506 ⟨tightpage⟩  \number\ifdim\wd\pr@box>\z@ \wd\pr@box

507 ⟨tightpage⟩ \else \z@

508 ⟨tightpage⟩  \fi}\box\pr@box}}

509 ⟨tightpage⟩\or

510 ⟨tightpage⟩ \g@addto@macro\pr@ship@end{{\dimen@\ht\pr@box
511 ⟨tightpage⟩  \ifdim\dimen@<\z@ \dimen@\z@\fi
512 ⟨tightpage⟩  \advance\dimen@\pr@bb@iv
513 ⟨tightpage⟩  \dimen@ii=\dimen@
514 ⟨tightpage⟩  \global\pdfvorigin\dimen@
515 ⟨tightpage⟩  \dimen@\dp\pr@box
516 ⟨tightpage⟩  \ifdim\dimen@<\z@ \dimen@\z@\fi
517 ⟨tightpage⟩  \advance\dimen@-\pr@bb@ii
518 ⟨tightpage⟩  \advance\dimen@\dimen@ii
519 ⟨tightpage⟩  \global\pdfpageheight\dimen@
520 ⟨tightpage⟩  \dimen@\wd\pr@box
521 ⟨tightpage⟩  \ifdim\dimen@<\z@ \dimen@=\z@\fi
522 ⟨tightpage⟩  \advance\dimen@-\pr@bb@i

523 ⟨tightpage⟩  \advance\dimen@\pr@bb@iii
524 ⟨tightpage⟩  \global\pdfpagewidth\dimen@
525 ⟨tightpage⟩  \global\pdfhorigin-\pr@bb@i}}

526 ⟨tightpage⟩\or

527 ⟨tightpage⟩ \g@addto@macro\pr@ship@end{\dimen@\ht\pr@box
528 ⟨tightpage⟩  \ifdim\dimen@<\z@ \dimen@\z@\fi
529 ⟨tightpage⟩  \advance\dimen@\pr@bb@iv
530 ⟨tightpage⟩  \dimen@ii=\dimen@

531 ⟨tightpage⟩ \voffset=-1in

532 ⟨tightpage⟩  \advance\voffset\dimen@
533 ⟨tightpage⟩  \advance\voffset-\ht\pr@box
534 ⟨tightpage⟩  \dimen@\dp\pr@box
535 ⟨tightpage⟩  \ifdim\dimen@<\z@ \dimen@\z@\fi
536 ⟨tightpage⟩  \advance\dimen@-\pr@bb@ii
537 ⟨tightpage⟩  \advance\dimen@\dimen@ii
538 ⟨tightpage⟩  \global\pdfpageheight\dimen@
539 ⟨tightpage⟩  \global\paperheight\dimen@
540 ⟨tightpage⟩  \dimen@\wd\pr@box
541 ⟨tightpage⟩  \ifdim\dimen@<\z@ \dimen@=\z@\fi
542 ⟨tightpage⟩  \advance\dimen@-\pr@bb@i
543 ⟨tightpage⟩  \advance\dimen@\pr@bb@iii
544 ⟨tightpage⟩  \global\pdfpagewidth\dimen@

545 ⟨tightpage⟩ \hoffset=-1in

546 ⟨tightpage⟩  \advance\hoffset-\pr@bb@i
547 ⟨tightpage⟩  \let\pr@offset@override\@empty}

548 ⟨tightpage⟩\fi

Ok, here comes the beef. First we fish the 7 numbers from the file with token and convert them from TEX sp to PostScript points.

549 ⟨tightpage⟩\ifnum\pr@graphicstype=\@ne
550 ⟨tightpage⟩\preview@delay{\AtBeginDvi{%

Backwards-compatibility. Once we are certain that dvipng-1.6 or later is widely used, the three following specials can be exchanged for the simple

 \special{!/preview@tightpage true def}
551 ⟨tightpage⟩ \special{!/preview@tightpage true def (%
552 ⟨tightpage⟩  compatibility PostScript comment for dvipng<=1.5 }
553 ⟨tightpage⟩ \special{!userdict begin/bop-hook{%
554 ⟨tightpage⟩  7{currentfile token not{stop}if
555 ⟨tightpage⟩  65781.76 div DVImag mul}repeat
556 ⟨tightpage⟩  72 add 72 2 copy gt{exch}if 4 2 roll
557 ⟨tightpage⟩  neg 2 copy lt{exch}if dup 0 gt{pop 0 exch}%
558 ⟨tightpage⟩  {exch dup 0 lt{pop 0}if}ifelse 720 add exch 720 add

559 ⟨tightpage⟩ 3 1 roll

560 ⟨tightpage⟩  4{5 -1 roll add 4 1 roll}repeat
561 ⟨tightpage⟩  <</PageSize[5 -1 roll 6 index sub 5 -1 roll 5 index sub]%
562 ⟨tightpage⟩  /PageOffset[7 -2 roll [1 1 dtransform exch]%
563 ⟨tightpage⟩  {0 ge{neg}if exch}forall]>>setpagedevice%
564 ⟨tightpage⟩  //bop-hook exec}bind def end}
565 ⟨tightpage⟩ \special{!userdict (some extra code to avoid

566 ⟨tightpage⟩  dvipng>=1.6 unknown special:
567 ⟨tightpage⟩  7{currentfile token not{stop}if 65781.76 div })) pop}

The “userdict” at the start of the last special is also there to avoid an unknown special in dvipng¡=1.6. This is the end of the backwards-compatibility code.

568 ⟨tightpage⟩ \special{!userdict begin/bop-hook{%
569 ⟨tightpage⟩ preview-bop-level 0 le{%
570 ⟨tightpage⟩  7{currentfile token not{stop}if
571 ⟨tightpage⟩  65781.76 div DVImag mul}repeat

Next we produce the horizontal part of the bounding box as

(1in, 1in) + (min(\wd\pr@box, 0), max(\wd\pr@box, 0))

and roll it to the bottom of the stack:

572 ⟨tightpage⟩  72 add 72 2 copy gt{exch}if 4 2 roll

Next is the vertical part of the bounding box. Depth counts in negatively, and we again take min and max of possible extents in the vertical direction, limited by 0. 720 corresponds to 10 in and is the famous 1 in distance away from the edge of letterpaper.

573 ⟨tightpage⟩  neg 2 copy lt{exch}if dup 0 gt{pop 0 exch}%
574 ⟨tightpage⟩  {exch dup 0 lt{pop 0}if}ifelse 720 add exch 720 add

575 ⟨tightpage⟩ 3 1 roll

Ok, we now have the bounding box on the stack in the proper order llx, lly, urx, ury. We add the adjustments:

576 ⟨tightpage⟩  4{5 -1 roll add 4 1 roll}repeat

The page size is calculated as the appropriate differences, the page offset consists of the coordinates of the lower left corner, with those coordinates negated that would be reckoned positive in the device coordinate system.

577 ⟨tightpage⟩  <</PageSize[5 -1 roll 6 index sub 5 -1 roll 5 index sub]%
578 ⟨tightpage⟩  /PageOffset[7 -2 roll [1 1 dtransform exch]%
579 ⟨tightpage⟩  {0 ge{neg}if exch}forall]>>setpagedevice}if%

So we now bind the old definition of bop-hook into our new definition and finish it.

580 ⟨tightpage⟩  //bop-hook exec}bind def end}}}

581 ⟨tightpage⟩\fi

5.6 The showlabels option

During the editing process, some people like to see the label names in their equations, figures and the like. Now if you are using Emacs for editing, and in particular preview-latex, I’d strongly recommend that you check out the RefTEX package which pretty much obliterates the need for this kind of functionality. If you still want it, standard L^{A}TEX provides it with the showkeys package, and there is also the less encompassing showlabels package. Unfortunately, since those go to some pain not to change the page layout and spacing, they also don’t change preview’s idea of the TEX dimensions of the involved boxes.

So those packages are mostly useless. So we present here an alternative hack that will get the labels through.

\pr@labelbox This works by collecting them into a separate box which we then tack to the right of the previews.

582 ⟨showlabels⟩\ifPreview\else\expandafter\endinput\fi
583 ⟨showlabels⟩\newbox\pr@labelbox

\pr@label We follow up with our own definition of the \label macro which will be active only in previews. The original definition is stored in \pr@@label. \pr@lastlabel contains the last typeset label in order to avoid duplication in certain environments, and we keep the stuff in \pr@labelbox.

584 ⟨showlabels⟩\def\pr@label#1{\pr@@label{#1}%

Ok, now we generate the box, by placing the label below any existing stuff.

585 ⟨showlabels⟩ \ifpr@setbox\z@{#1}%
586 ⟨showlabels⟩  \global\setbox\pr@labelbox\vbox{\unvbox\pr@labelbox
587 ⟨showlabels⟩  \box\z@}\egroup\fi}

\ifpr@setbox \ifpr@setbox receives two arguments, #1 is the box into which to set a label, #2 is the label text itself. If a label needs to be set (if it is not a duplicate in the current box, and is nonempty, and we are in the course of typesetting and so on), we are left in a true conditional and an open group with the preset box. If nothing should be set, no group is opened, and we get into skipping to the closing of the conditional. Since \ifpr@setbox is a macro, you should not place the call to it into conditional text, since it will not pair up with \fi until being expanded.

We have some trickery involved here. \romannumeral\z@ expands to empty, and will also remove everything between the two of them that also expands to empty, like a chain of \fi.

588 ⟨showlabels⟩\def\ifpr@setbox#1#2{%

589 ⟨showlabels⟩ \romannumeral%

590 ⟨showlabels⟩ \ifx\protect\@typeset@protect\ifpr@outer\else

Ignore empty labels…

591 ⟨showlabels⟩ \z@\bgroup

592 ⟨showlabels⟩ \protected@edef\next{#2}\@onelevel@sanitize\next
593 ⟨showlabels⟩ \ifx\next\@empty\egroup\romannumeral\else

and labels equal to the last one.

594 ⟨showlabels⟩ \ifx\next\pr@lastlabel\egroup\romannumeral\else
595 ⟨showlabels⟩ \global\let\pr@lastlabel\next
596 ⟨showlabels⟩ \setbox#1\pr@boxlabel\pr@lastlabel
597 ⟨showlabels⟩ \expandafter\expandafter\romannumeral\fi\fi\fi\fi
598 ⟨showlabels⟩ \z@\iffalse\iftrue\fi}

\pr@boxlabel Now the actual typesetting of a label box is done. We use a small typewriter font inside of a framed box (the default frame/box separating distance is a bit large).

599 ⟨showlabels⟩\def\pr@boxlabel#1{\hbox{\normalfont
600 ⟨showlabels⟩ \footnotesize\ttfamily\fboxsep0.4ex\relax\fbox{#1}}}

\pr@maketag And here is a version for amsmath equations. They look better when the label is right beside the tag, so we place it there, but augment \box\pr@labelbox with an appropriate placeholder.

601 ⟨showlabels⟩\def\pr@maketag#1{\pr@@maketag{#1}%
602 ⟨showlabels⟩ \ifpr@setbox\z@{\df@label}%
603 ⟨showlabels⟩  \global\setbox\pr@labelbox\vbox{%
604 ⟨showlabels⟩  \hrule\@width\wd\z@\@height\z@
605 ⟨showlabels⟩  \unvbox\pr@labelbox}%

Set the width of the box to empty so that the label placement gets not disturbed, then append it.

606 ⟨showlabels⟩  \wd\z@\z@\box\z@ \egroup\fi}

\pr@lastlabel Ok, here is how we activate this: we clear out box and label info

607 ⟨showlabels⟩\g@addto@macro\pr@ship@start{%
608 ⟨showlabels⟩ \global\setbox\pr@labelbox\box\voidb@x
609 ⟨showlabels⟩ \xdef\pr@lastlabel{}%

The definitions above are global because we might be in any amount of nesting. We then reassign the appropriate labelling macros:

610 ⟨showlabels⟩ \global\let\pr@@label\label \let\label\pr@label
611 ⟨showlabels⟩ \global\let\pr@@maketag\maketag@@@
612 ⟨showlabels⟩ \let\maketag@@@\pr@maketag

613 ⟨showlabels⟩}

Now all we have to do is to add the stuff to the box in question. The stuff at the front works around a bug in ntheorem.sty.

614 ⟨showlabels⟩\pr@addto@front\pr@ship@end{%
615 ⟨showlabels⟩ \ifx \label\pr@label \global\let\label\pr@@label \fi
616 ⟨showlabels⟩ \ifx \maketag@@@\pr@maketag
617 ⟨showlabels⟩  \global\let\maketag@@@\pr@@maketag \fi
618 ⟨showlabels⟩ \ifvoid\pr@labelbox
619 ⟨showlabels⟩ \else \setbox\pr@box\hbox{%
620 ⟨showlabels⟩  \box\pr@box\,\box\pr@labelbox}%

621 ⟨showlabels⟩ \fi}

5.7 The footnotes option

This is rather simplistic right now. It overrides the default footnote action (which is to disable footnotes altogether for better visibility).

622 ⟨footnotes⟩\PreviewMacro[[!]\footnote %]

6 Various driver files

The installer, in case it is missing. If it is to be used via make, we don’t specify an installation path, since

      make install

is supposed to cater for the installation itself.

623 ⟨installer⟩ \input docstrip
624 ⟨installer & make⟩ \askforoverwritefalse

625 ⟨installer⟩ \generate{

626 ⟨installer⟩  \file{preview.drv}{\from{preview.dtx}{driver}}
627 ⟨installer&!make⟩  \usedir{tex/latex/preview}
628 ⟨installer⟩  \file{preview.sty}{\from{preview.dtx}{style}
629 ⟨installer⟩  \from{preview.dtx}{style,active}}
630 ⟨installer⟩  \file{prauctex.def}{\from{preview.dtx}{auctex}}
631 ⟨installer⟩  \file{prauctex.cfg}{\from{preview.dtx}{auccfg}}
632 ⟨installer⟩  \file{prshowbox.def}{\from{preview.dtx}{showbox}}
633 ⟨installer⟩  \file{prshowlabels.def}{\from{preview.dtx}{showlabels}}
634 ⟨installer⟩  \file{prtracingall.def}{\from{preview.dtx}{tracingall}}
635 ⟨installer⟩  \file{prtightpage.def}{\from{preview.dtx}{tightpage}}
636 ⟨installer⟩  \file{prlyx.def}{\from{preview.dtx}{lyx}}
637 ⟨installer⟩  \file{prcounters.def}{\from{preview.dtx}{counters}}
638 ⟨installer⟩  \file{prfootnotes.def}{\from{preview.dtx}{footnotes}}

639 ⟨installer⟩ } 640 ⟨installer⟩ \endbatchfile

And here comes the documentation driver.

641 ⟨driver⟩ \documentclass{ltxdoc}
642 ⟨driver⟩ \usepackage{preview}
643 ⟨driver⟩ \let\ifPreview\relax
644 ⟨driver⟩ \newcommand\previewlatex{\texttt{preview-latex}}
645 ⟨driver⟩ \begin{document}
646 ⟨driver⟩ \DocInput{preview.dtx}
647 ⟨driver⟩ \end{document}