Debian Codegraph @

texmf-dist/doc/latex/fancytooltips/fancy-preview

raw
1 #!/usr/bin/env perl
2 #
3 # Copyright (C) 2012 by Robert Marik <[email protected]>
4 # ------------------------------------------------------
5 #
6 # This file may be distributed and/or modified under the conditions of
7 # the LaTeX Project Public License, either version 1.2 of this license
8 # or (at your option) any later version. The latest version of this
9 # license is in:
10 #
11 # http://www.latex-project.org/lppl.txt
12 #
13 # and version 1.2 or later is part of all distributions of LaTeX
14 # version 1999/12/01 or later.
15 #
16 # fancy-preview
17 # -------------
18 #
19 # This is a script which can be used to extract displayed equations,
20 # theorem-like environments, figures and bibliography references and
21 # attach this material as tooltip to LaTeX \ref, \eqref and \cite
22 # comand. This has been requested by several (pdf)(La)TeX users. See
23 # http://tex.stackexchange.com/questions/15356/showing-the-bibliographic-entry-in-a-popup-when-you-hover-over-the-citation-key
24 # for some discussion and papers
25 # http://permalink.gmane.org/gmane.comp.tex.pdftex/3898 and
26 # http://www.math.huji.ac.il/~erezla/papers/continuity_semisimple.pdf
27 # as demos of interactive PDF.
28 #
29 # Demos for the current script are at
30 # http://user.mendelu.cz/marik/fancy-preview site. Basicaly, you can
31 # find there PDF files with hyperref links. Each link is followed by a
32 # button. This button is invisible in mathematical papers and blue
33 # soap in presentations.
34 #
35 # 1. add "\usepackage{hyperref}" to the preamble of your document (say
36 # filename.tex),
37 #
38 # 2. add blank line after each \bibitem command,
39 #
40 # 3. compile with command "bash fancy-preview filename" i.e. no tex
41 # extension is used in the command line
42 #
43 # 4. You may customize this script.
44 #
45 # The script has been tested on Linux, Ubuntu 12.04,TeXlive 2011.
46 #
47 # It works as follows:
48 # 1. We extract desired environments in two runs. We crop the PDF
49 # files and save the information relatex labels from aux file.
50 # 2. We join the files together, we add some background and graphics
51 # to the tooltips.
52 #
53 #
54 # Known bugs, limitations.
55 # ------------------------
56 #
57 # * Do not use tags involving \ref command, do not use something like
58 # \tag{\ref{someting}-b} inside equation environment.
59 # * Do not use the word tocindent in the labels.
60 # * Do not use elsart class. Use for example article or elsarticle
61 # class.
62 # * Each bibitem must be finished by a blank line.
63 #
64 #
65 # History
66 # -------
67 #
68 # June 12, 2012: advanced posibilities for configuration
69 # May 24, 2012: bash script converted to Perl for better portability, tests on MS Windows.
70 # May 7, 2012: initial Linux version in bash
71 #
72 use strict;
73 use Getopt::Long;
74
75 my $filename = $ARGV[0];
76 my $filename_noext = $filename;
77 $filename_noext =~ s/\.tex//;
78 my $aux_file=$filename_noext.".aux";
79 my @tempfilenames=($filename_noext.".aux");
80 my %latex =();
81
82 # Setting for two passes of preview.sty
83 $latex{'a'}='\makeatletter\def\nononotags{\def\@eqnnum{\relax}\def\tagform@##1{}}\makeatother\AtBeginDocument{\usepackage[pdftex,active,tightpage,displaymath]{preview}\nononotags}';
84 $latex{'b'}='\AtEndDocument{\clearpage}\AtBeginDocument{\usepackage[pdftex,active,tightpage]{preview}\setlength\PreviewBorder{5pt}}';
85
86 # Do not use third pass of preview.sty by default
87 $latex{'c'}='';
88 $latex{'a_extra'}='';
89 $latex{'b_extra'}='';
90 $latex{'pass_order'}="acb";
91
92 # Hacks to get references (in the first pass).
93 # IMPORTANT: each bibitem must be finished by a blank line.
94 $latex{'preview_bibitem'}='\AtBeginDocument{\newenvironment{fakebibitem}{\begin{minipage}{0.75\textwidth}}{\end{minipage}}\PreviewEnvironment{fakebibitem}\renewcommand\bibitem[2][]{\BIBITEM {#2}}\def\BIBITEM#1#2\par{\begin{fakebibitem} #2 \label{fancy:cite:#1}\end{fakebibitem}}}';
95 $latex{'preview_biblatex'}='\AtBeginDocument{\PreviewEnvironment{fakebibitem}\def\fancycitation#1{\begin{fakebibitem}\setbox0=\hbox{\parbox{0.75\textwidth}{\fullcite{#1}\label{fancy:cite:#1}}}\pdfpagewidth=\wd0\pdfpageheight=\ht0\advance\pdfpageheight by \dp0\copy0\end{fakebibitem}\newpage}}\AtEndDocument{\input '.$filename_noext.'-fancybib.tmp}';
96
97 # The environments for extraction in the second pass of preview.sty.
98 $latex{'environments'}="Theorem,theorem,lemma,corollary,definition";
99 $latex{'snarfenvironments'}="figure";
100
101 # The variable with initial commands for all pdflatex calls.
102 $latex{'ini'}='\relax';
103 my $pdflatex="pdflatex";
104 my $bibtex="bibtex";
105 my $pdfcrop="pdfcrop";
106
107 # Default options for final compilation with fancytooltips. Change
108 # "previewall" into "preview" to omit tooltips with target on the same
109 # page (useful for presentations). You may also set this option from
110 # the comand line.
111 my $fancy_options="previewall,nosoap";
112 my $tooltipfile="";
113 my $help=0;
114 my $version=0;
115 my $date="24.6.2012";
116 my $versionnumber="0.2";
117
118 # The code used in premable. Should define macro \tooltipwraper which
119 # inserts the tooltip extracted in previous compilations into a box
120 # with nontransparent background
121 $latex{'tooltips_envelope_preamble'}='\usepackage{xcolor,tikz}\usetikzlibrary{shadows}\def\tooltipwraper#1{\begin{tikzpicture}\node[drop shadow,fill=yellow!30,draw=black!30, rounded corners=3pt,very thick]{#1};\end{tikzpicture}}';
122
123
124 $latex{'biblatex'}='
125 % from http://tex.stackexchange.com/questions/15356/showing-the-bibliographic-entry-in-a-popup-when-you-hover-over-the-citation-key/54831#54831
126 % thanks to Audrey
127
128 % Apply tooltip to "extratext" area just after inline citation links
129 \DeclareFieldFormat{bibhyperref}{%
130 \tooltip*{\bibhyperref{#1}}{fancy:cite:\thefield{entrykey}}}
131
132 % Define new citation commands that replace citation links with tooltips
133 \DeclareFieldFormat{bibtooltip}{\tooltip{#1}{fancy:cite:\thefield{entrykey}}}
134 \newrobustcmd*{\tooltiphook}{%
135 \AtNextCite{\DeclareFieldAlias{bibhyperref}{bibtooltip}}}
136 \newrobustcmd*{\tooltipcite}{\tooltiphook\cite}
137 \newrobustcmd*{\tooltipcites}{\tooltiphook\cites}
138
139 % Apply tooltip to instance where numeric-comp uses \bibhyperref instead
140 % of bibhyperref format
141 \makeatletter
142 \newbibmacro*{cite:dump:tooltip}{%
143 \ifnumgreater{\value{cbx@tempcnta}}{0}
144 {\ifnumgreater{\value{cbx@tempcnta}}{1}
145 {\bibrangedash}
146 {\multicitedelim}%
147 \tooltip*
148 {\bibhyperref[\cbx@lastkey]{%
149 \ifdef\cbx@lastprefix
150 {\printtext[prefixnumber]{\cbx@lastprefix}}
151 {}%
152 \printtext[labelnumber]{\cbx@lastnumber}}}
153 {fancy:cite:\cbx@lastkey}}
154 {}%
155 \setcounter{cbx@tempcnta}{0}%
156 \global\undef\cbx@lastprefix}
157 \ifcsundef{abx@macro@\detokenize{cite:dump}}
158 {}{\renewbibmacro*{cite:dump}{\usebibmacro{cite:dump:tooltip}}}
159 \makeatother
160 ';
161
162 my %options=();
163 GetOptions (
164 "fancy_options=s" => \$options{fancy_options},
165 "pdfcrop=s" => \$options{pdfcrop},
166 "tooltips=s" => \$options{tooltips},
167 "ini_file=s" => \$options{ini_file},
168 "version" => \$version,
169 "help" => \$help);
170
171 if ($version)
172 {
173 print "$versionnumber\n";
174 exit();
175 }
176
177 if ($help)
178 {
179 my $help_text='
180 This is fancy-preview script (R. Marik, http://user.mendelu.cz/marik)
181 ============================
182
183 The script converts LaTeX files into PDF files. The references are
184 followed by invisible buttons whih allow to show the target in a popup
185 window.
186
187 The homepage (last version, documentation, tips for users, examples)
188 of the script is http://user.mendelu.cz/marik/fancy-preview
189
190 OPTIONS:
191
192 For detailed description see Section 3 of the manual to the
193 fancytooltips package.
194
195 --fancy_options="text" text is passed as optional parameter to
196 fancytooltips package
197
198 --pdfcrop="filename" program to crop the boundaries of PDF file
199
200 --tooltips="filename" the file filename.pdf contains hand-created
201 tooltips and filename.tips optionally
202 keywords to acces these tooltips
203
204 --ini_file="filename" ini file with the configuration
205
206 --version prints version and exists
207
208 --help prints help and exists
209
210 EXAMPLES:
211 Compile file.tex
212
213 perl fancy-preview file
214
215 Compile file.tex, use pdfcrop2 to crop the boundary of PDF file, show
216 only previews where the target is on the different page
217
218 ./fancy-preview file --fancy_options="preview" --pdfcrop="pdfcrop2"
219
220 ';
221 print $help_text;
222 exit();
223 }
224
225
226 #### Read configuration from ~/.fancy-preview.ini and ./fancy-preview.ini
227 use Config::IniFiles;
228 my($cfg);
229
230 sub set_tex_variable
231 {
232 if ($cfg->exists( 'latex', $_[0] )) {$latex{$_[0]}=$cfg->val( 'latex', $_[0]);}
233 }
234
235 sub read_config
236 {
237 if ( -e $_[0])
238 {
239 $cfg = Config::IniFiles->new( -file => $_[0]);
240 if ($cfg->exists( 'main', 'pdfcrop' )) {$pdfcrop=$cfg->val( 'main', 'pdfcrop');}
241 if ($cfg->exists( 'main', 'fancy_options' )) {$fancy_options=$cfg->val( 'main', 'fancy_options');}
242 if ($cfg->exists( 'main', 'tooltips' )) {$tooltipfile=$cfg->val( 'main', 'tooltips');}
243 my @options=("tooltips_envelope_preamble","environments","snarfenvironments","a","a_extra","b","b_extra","c","ini","biblatex","pass_order");
244 foreach my $current_option (@options) {set_tex_variable($current_option);}
245 }
246 }
247
248 if ($options{ini_file})
249 {
250 read_config($options{ini_file});
251 }
252 else
253 {
254 read_config($ENV{"HOME"}."/.fancy-preview.ini");
255 read_config("./fancy-preview.ini");
256 }
257 #### end of configuration
258
259 # command line overrides config file
260 if ($options{fancy_options}) {$fancy_options=$options{fancy_options}};
261 if ($options{pdfcrop}) {$pdfcrop=$options{pdfcrop}};
262 if ($options{tooltips}) {$tooltipfile=$options{tooltips}};
263
264 my $biblatex=0;
265
266 # -----------------------------------------------------------------
267 # We extract stuff from the TeX file, extract the label definition
268 # from aux file and crop the PDF file. Since pdfcrop from texlive
269 # creates large files, we allow customization (see
270 # http://tex.stackexchange.com/questions/42236/pdfcrop-generates-larger-file
271 # )
272
273 unlink ("$filename_noext.aux");
274
275 # The first compilation to create numbers for equations, theorems, figures, ...
276 system("$pdflatex \"$latex{ini} \\input $filename\"");
277
278
279 # We test if the file uses biblatex. If not, thebibliography is supposed.
280 open(LOG, $filename_noext.".log");
281 my @log_data=<LOG>;
282 my @log_tmp = grep /^Package: biblatex/, @log_data;
283 my $log_tmp_size=@log_tmp;
284 if ($log_tmp_size>0) {$biblatex=1;}
285
286 my $preview_references="";
287 if ($biblatex)
288 {
289 optbibtex();
290 open(AUX, $aux_file);
291 my @aux_data=<AUX>;
292 my @result=();
293 foreach $a (@aux_data)
294 {
295 if (($a =~ m/\\citation{/)&&($a !~ m/{biblatex-control}/))
296 {
297 $a =~ s/\\citation{/\\fancycitation{/;
298 push(@result, $a);
299 }
300 }
301 close(AUX);
302
303 sub uniq {
304 return keys %{{ map { $_ => 1 } @_ }};
305 }
306
307 open(AUXA, ">$filename_noext"."-fancybib.tmp");
308 foreach $a (sort(uniq(@result)))
309 {
310 print AUXA $a;
311 }
312 close(AUXA);
313 push (@tempfilenames,$filename_noext."-fancybib.tmp");
314 $preview_references=$latex{'preview_biblatex'};
315 }
316 else
317 {
318 $preview_references=$latex{'preview_bibitem'};
319 }
320
321 system("$pdflatex \"$latex{ini}\\relax $latex{a}\\relax $latex{'a_extra'}\\relax $preview_references\\relax \\input $filename\"");
322 parse_aux_file_and_crop("a");
323
324 # The second pass, in this pass theorem-like environments are
325 # extracted. Two passes are necessary, since numbered equations which
326 # appear in theorems frequently have to been extracted separately (in
327 # the first pass).
328
329 if($latex{'environments'} ne "")
330 {
331 $latex{'b'}=$latex{'b'}.'\AtBeginDocument{\PreviewEnvironment[{[]}]{'.join('}\PreviewEnvironment[{[]}]{',split(/,/,$latex{'environments'}))."}}";
332 }
333 if($latex{'snarfenvironments'} ne "")
334 {
335 $latex{'b'}=$latex{'b'}.'\AtBeginDocument{\PreviewSnarfEnvironment[{[]}]{'.join('}\PreviewSnarfEnvironment[{[]}]{',split(/,/,$latex{'snarfenvironments'}))."}}";
336 }
337 $latex{'b'}=$latex{'b'}.$latex{'b_extra'};
338 compile_parse_aux_file_and_crop("b");
339
340 if($latex{'c'} ne "")
341 {
342 compile_parse_aux_file_and_crop("c");
343 }
344 else
345 {
346 $latex{'pass_order'} =~ s/c//;
347 }
348
349 print "\n----------------------------------------------\n------ pdflatex genearting tooltips ----------\n----------------------------------------------";
350
351 # We merge all the tooltips in one file. If some hand created
352 # tooltips are also present, we insert these tooltips first in a loop
353 # (multido). Then we insert theorem-like environments (from the second
354 # pass) and finaly equations and citations (from the first pass).
355
356 my $opt_pdfpages_a="";
357 my $opt_pdfpages_b="";
358 my $inserttooltips='\insertttp{'.join('}\insertttp{',split(//,$latex{'pass_order'})).'}';
359
360 if ($tooltipfile ne "")
361 {
362 $opt_pdfpages_a='\usepackage{multido}';
363 $opt_pdfpages_b='\ifx\pdfpagewrapper\undefined\let\pdfpagewrapper\relax\fi\pdfximage{'.$tooltipfile.'.pdf}\edef\FancyPreviewTotalPages{\the\pdflastximagepages}\multido{\i=1+1}{\FancyPreviewTotalPages}{\setbox0=\hbox{\pdfpagewrapper{\includegraphics[page=\i]{'.$tooltipfile.'.pdf}}}\pdfpagewidth=\wd0 \pdfpageheight=\ht0 \advance \pdfpageheight by \dp0 \copy0\newpage}\newpage';
364 }
365
366 system("$pdflatex".' "\documentclass{minimal}\usepackage{graphicx}'.$opt_pdfpages_a.'\usepackage[papersize={5in,5in},margin=1pt]{geometry}'.$latex{'tooltips_envelope_preamble'}.'\usepackage[createtips]{fancytooltips}\newdimen\dist \dist=5pt\relax\begin{document}\pagestyle{empty}'.$opt_pdfpages_b.'\relax \gdef\savemaplabels#1#2#3#4{\xdef\temp{#2}} \def\fancypreviewnewlabel#1#2{\savemaplabels#2 \expandafter\ifx\csname keytip:#1:used\endcsname\relax \expandafter\def\csname keytip:#1:used\endcsname{used}\setbox0=\vbox{\kern\dist\hbox{\kern\dist\tooltipwraper{\includegraphics[page=\temp]{'.$filename_noext.'-\ttpfilename-crop.pdf}}\kern\dist}\kern\dist}\pdfpagewidth=\wd0 \pdfpageheight=\ht0 \advance \pdfpageheight by \dp0 \copy0 \keytip{#1}\newpage\fi}\def\insertttp#1{\def\ttpfilename{#1}\input '.$filename_noext.'-#1.tmp}'.$inserttooltips.'\end{document}"');
367
368 if ($tooltipfile ne "")
369 {
370 open(TIPS1, ">>minimal.tips");
371 open(TIPS2, "$tooltipfile.tips");
372 while (<TIPS2>) { print TIPS1 $_; }
373 close (TIPS1);
374 close (TIPS2);
375 }
376
377 # If biblatex is used, we update the information in bib file and hack
378 # the cite-like commands according to the example
379 # http://tex.stackexchange.com/questions/15356/showing-the-bibliographic-entry-in-a-popup-when-you-hover-over-the-citation-key/54831#54831
380 #
381
382 $latex{'ini'}="";
383 if ($biblatex)
384 {
385 system("$pdflatex \"$latex{'ini'}\\relax \\input $filename\"");
386 system("$bibtex $filename_noext.aux");
387
388 open(BIBL, ">fancy-preview-biblatex-settings.tex");
389 print BIBL $latex{'biblatex'};
390 close (BIBL);
391 push (@tempfilenames,"fancy-preview-biblatex-settings.tex");
392 $latex{'ini'}='\AtBeginDocument{\input fancy-preview-biblatex-settings.tex}';
393 }
394
395 for my $i (1 .. 4){
396 my $hypersetup='\hypersetup{colorlinks=true}';
397 print "----------------------------------------------\n------ pdflatex final compilation $i ----------\n----------------------------------------------\n";
398 system("$pdflatex -jobname=$filename_noext \"$latex{'ini'}".'\RequirePackage{etoolbox}\PassOptionsToPackage{active,mouseover,movetips,filename=minimal,'.$fancy_options.'}{fancytooltips}\AtEndPreamble{\usepackage{fancytooltips}'.$hypersetup.'}\input '.$filename.'"')
399 }
400
401 foreach my $deletefile (@tempfilenames) {unlink ($deletefile);}
402
403 print "\n ---------------------------------------------\n fancy-preview with options \"$fancy_options\" on \"$filename\" finished \n The output is in $filename_noext.pdf \n\n If the pdf file is too large, consider pdfcrop option\n and http://tex.stackexchange.com/questions/42236/pdfcrop-generates-larger-file\n ---------------------------------------------\n\n";
404
405
406 sub parse_aux_file_and_crop
407 {
408 # opens aux file, finds lines starting with \newlabel and not involving tocindent and writes them into tmp file
409 open(AUX, $aux_file);
410 my @aux_data=<AUX>;
411 my @filtered_data_tmp = grep /^\\newlabel/, @aux_data;
412 my @filtered_data = grep !/tocindent/, @filtered_data_tmp;
413 my $aux_file_a=$filename_noext."-".@_[0].".tmp";
414 open(AUXA, ">$aux_file_a");
415 foreach my $aa (@filtered_data)
416 {
417 $aa =~ s/\\newlabel{/\\fancypreviewnewlabel{/;
418 print AUXA $aa;
419 }
420 close (AUXA);
421 close (AUX);
422 push(@tempfilenames,$aux_file_a);
423 # crops the file
424 print "\nCropping PDF file, this may take some time ...\n";
425 system("$pdfcrop $filename_noext.pdf $filename_noext-@_[0]-crop.pdf");
426 push(@tempfilenames,"$filename_noext-@_[0]-crop.pdf");
427 }
428
429
430 sub compile_parse_aux_file_and_crop
431 {
432 unlink ("$filename_noext.aux");
433 system("$pdflatex \"$latex{ini} \\input $filename\"");
434 optbibtex();
435 system("$pdflatex \"$latex{ini} $latex{$_[0]} \\input $filename\"");
436 parse_aux_file_and_crop($_[0]);
437 }
438
439
440 sub optbibtex
441 {
442 # runs bibtex and pdflatex if biblatex has been detected ($biblatex variable is 1)
443 if ($biblatex)
444 {
445 system("$bibtex $filename_noext.aux");
446 system("$pdflatex \"$latex{ini} \\input $filename\"");
447 }
448 }