Debian Codegraph @

texmf-dist/doc/latex/robust-externalize/robust-externalize.tex

raw
1 %\pdfoutput=1% Do not remove, needed for arxiv
2 \documentclass[a4paper,doc2]{ltxdoc} % doc2 is needed to force the old version, or links get colored in a weird red way even with hidelinks. https://github.com/latex3/latex2e/issues/822
3
4 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5 %%% Packages
6 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
7 %% Warning: if you compile and get:
8 %% ERROR: Argument of \tikz@lib@matrix@with@options has an extra }.
9 %% make sure to fix catcodes around it as | is given a different meaning in ltxdoc.
10
11 \usepackage{amsmath}
12 \usepackage[margin=3cm]{geometry}
13 \usepackage{calc}
14 \usepackage{siunitx}
15 \usepackage{tikz}
16 \usepackage{tikzit}
17 \input{new_zxstyle.tikzstyles}
18 \usetikzlibrary{shadows,fit}
19 % \usetikzlibrary fails because file is not in current directory, lazy to setup TEXINPUTS
20 \makeatletter
21 \usepackage{robust-externalize}
22 \makeatother
23 \robExtConfigure{
24 enable optimizations,
25 copy file to cache={zx-calculus.sty},
26 copy file to cache={tikzlibraryzx-calculus.code.tex},
27 % You need to uncomment that line to rename the .tex files into .tex-backup
28 % backup source for arxiv,
29 rename backup files for arxiv,
30 print source when saving, % debug
31 }
32 \usepackage{zx-calculus}
33 \usepackage{forest}
34 \setlength{\marginparwidth}{2cm}
35 \usepackage{todonotes}
36 % Loads the great package that produces tikz-like manual (see also tikzcd for examples)
37 \input{pgfmanual-en-macros.tex} % Is supposed to be included in recent TeX distributions, but I get errors...
38
39 \usepackage{gnuplot-lua-tikz} %% Generate with gnuplot -e "set terminal tikz createstyle"
40
41 %% For verbatim environments:
42
43 \NewDocumentEnvironment{codeAndResult}{}{\XSIMfilewritestart{\jobname-codeAndResult-tmp-file-you-can-remove.tmp}}%
44 {%
45 \XSIMfilewritestop%
46 \par
47 \medskip
48 \noindent\colorbox{graphicbackground}{\noindent\begin{minipage}{1.0\linewidth}
49 {\input{\jobname-codeAndResult-tmp-file-you-can-remove.tmp}}
50 \end{minipage}}
51 % I don't know why, but sometimes this prints nothing, while input works:
52 %{\codeexample[width=0pt, leave comments, vbox, from file={\jobname-codeAndResult-tmp-file-you-can-remove.tmp}]}%
53 {\codeexample[code only, from file={\jobname-codeAndResult-tmp-file-you-can-remove.tmp}]}%
54 }
55
56 \usepackage{makeidx} % Produces an index of commands.
57 \makeindex % Useful or not index will be created
58 \usepackage{alertmessage} % For warning, info...
59 \newcommand{\mylink}[2]{\href{#1}{#2}\footnote{\url{#1}}}
60 \usepackage{verbatim}
61 \usepackage{mathtools}
62 \usepackage{float} %figure inside minipage
63 \usepackage{pythonhighlight}
64 \usepackage{tcolorbox}
65
66 \usepackage{listings}
67 \definecolor{codegreen}{rgb}{0,0.6,0}
68 \definecolor{codegray}{rgb}{0.5,0.5,0.5}
69 \definecolor{codepurple}{rgb}{0.58,0,0.82}
70 \definecolor{backcolour}{rgb}{0.95,0.95,0.92}
71
72 \lstdefinestyle{mystyle}{
73 backgroundcolor=\color{backcolour},
74 commentstyle=\color{codegreen},
75 keywordstyle=\color{magenta},
76 numberstyle=\tiny\color{codegray},
77 stringstyle=\color{codepurple},
78 basicstyle=\ttfamily\footnotesize,
79 breakatwhitespace=false,
80 breaklines=true,
81 captionpos=b,
82 keepspaces=true,
83 numbers=left,
84 numbersep=5pt,
85 showspaces=false,
86 showstringspaces=false,
87 showtabs=false,
88 tabsize=2
89 }
90
91 \lstset{style=mystyle}
92
93
94 \usepackage[hidelinks]{hyperref}
95 \usepackage{cleveref}
96
97 \begin{document}
98 %%% Title: thanks tikzcd for the styling
99 \begin{center}
100 \vspace*{1em} % Thanks tikzcd
101 \tikz\node[scale=1.2]{%
102 \color{gray}\Huge\ttfamily \char`\{\raisebox{.09em}{\textcolor{red!75!black}{robust\raisebox{-0.1em}{-}externalize}}\char`\}};
103
104 \vspace{0.5em}
105 {\Large\bfseries Cache anything (\tikzname, tikz-cd, python…),\\in a robust, efficient and pure way.}
106
107 \vspace{1em}
108 {Léo Colisson \quad Version 3.0}\\[3mm]
109 {\href{https://github.com/leo-colisson/robust-externalize}{\texttt{github.com/leo-colisson/robust-externalize}}}
110 \end{center}
111
112 \tableofcontents
113
114 \bigskip
115
116 \textbf{WARNING: Even if we try to stay backward compatible, the only guaranteed way to be 100\% immune to changes is to copy/paste the\ .sty file of the library in your main project folder. Please report any bug to \url{https://github.com/leo-colisson/robust-externalize}!}
117
118 \textbf{WARNING 2: the recent versions 2.1 and 2.2 improves significantly the compilation time compared with 2.0 that was surprisingly slow. Now, it is fairly well optimized, and version 2.3 is even more optimized.}
119
120 \textbf{WARNING 3: If you read this documentation from the arXiv or CTAN, you might prefer to read it from \mylink{https://github.com/leo-colisson/robust-externalize}{Github} to get the latest version.}
121
122 \section{A taste of this library}
123
124 This library allows you to cache any language: not only \LaTeX{} documents and \tikzname{} images, taking into account depth and overlays, but also arbitrary code. To use it, make sure to have v2.0 installed (see instructions below), and load:
125 \begin{verbatim}
126 \usepackage{robust-externalize}
127 \robExtConfigure{
128 % To display instructions in the PDF to manually compile pictures if
129 % you forgot/do not want to compile with -shell-escape
130 enable fallback to manual mode,
131 }
132 \end{verbatim}
133 Then type something like this (note the |C| for |cached| at the end of |tikzpictureC|, see below to override the original tikz commands), and compile with |pdflatex -shell-escape yourfile.tex| (or \textcolor{red}{\textbf{read below if you do not want to use }}|-shell-escape|\textcolor{red}{\textbf{ (note that overleaf enables shell-escape by default, and it is not needed once all pictures are cached)}}):
134 \begin{codeexample}[width=0pt,vbox]
135 \robExtConfigure{
136 add to preset={tikz}{
137 % we load some packages that will be loaded by figures based on the tikz preset
138 add to preamble={\usepackage{pifont}}
139 }
140 }
141 The next picture is cached %
142 \begin{tikzpictureC}[baseline=(A.base)]
143 \node[fill=red, rounded corners](A){My node respecting baseline \ding{164}.};
144 \node[fill=red, rounded corners, opacity=.3,overlay] at (A.north east){I am an overlay text};
145 \end{tikzpictureC} and you can see that overlay and depth works.
146 \end{codeexample}
147
148 Since v2.3 we also provide a way to include online pictures with |\includegraphicsWeb|:
149 \begin{codeexample}[width=0pt,vbox]
150 Here is a picture of bear downloaded online: \includegraphicsWeb[width=3cm]{https://placebear.com/400/300}.
151 \end{codeexample}
152
153 You can also cache arbitrary code (e.g.\ python). Note that if you use a version before 2.7, you cannot indent the python code. You can also define arbitrary compilation commands, inclusion commands, and presets to fit you need. For instance, you can create a preset to obtain:
154
155 \begin{codeAndResult}
156 \begin{CacheMeCode}{python print code and result, set title={The for loop}}
157 for name in ["Alice", "Bob"]:
158 print(f"Hello {name}")
159 \end{CacheMeCode}
160 \end{codeAndResult}
161
162 Actually, we also provide this style by default (and explain how to write it yourself), just use the above code (WARNING: in v2.7, a bug was introduced, fixed in v2.8, that was adding a new line in front of the code), just make sure to load:
163 \begin{verbatim}
164 \usepackage{pythonhighlight}
165 \usepackage[most]{tcolorbox}
166 \end{verbatim}
167
168 You can also cache any environment and command using something like:
169 \begin{itemize}
170 \item For environments:
171 \begin{codeAndResult}
172 % We cache the environment forest
173 \cacheEnvironment{forest}{latex, add to preamble={\usepackage{forest}}}
174
175 A forest tree automatically cached %
176 \begin{forest}
177 [VP
178 [DP[John]]
179 [V’
180 [V[sent]]
181 [DP[Mary]]
182 [DP[D[a]][NP[letter]]]
183 ]
184 ]
185 \end{forest}\\
186 And one not cached: %
187 \begin{forest}<disable externalization>
188 [VP
189 [DP[John]]
190 [V’
191 [V[sent]]
192 [DP[Mary]]
193 [DP[D[a]][NP[letter]]]
194 ]
195 ]
196 \end{forest}
197 \end{codeAndResult}
198 People interested by |tikz-cd| might like this example:
199 \begin{codeAndResult}
200 \cacheEnvironment{tikzcd}{tikz, add to preamble={\usepackage{tikz-cd}}}
201 \begin{tikzcd}
202 A \rar & B
203 \end{tikzcd}
204 \end{codeAndResult}
205 \item For commands:
206 \begin{codeAndResult}
207 % We cache the command \zx
208 % O{} = optional argument, m = mandatory argument.
209 % Autodetected if command defined with xparse (NewDocumentCommand)
210 % (in this example it is redundant since zx IS defined with xparse syntax)
211 \cacheCommand{zx}[O{}O{}O{}m]{latex, add to preamble={\usepackage{zx-calculus}}}
212
213 A ZX figure %
214 \zx{
215 \zxX{\alpha} \rar \ar[d,C] & \zxZ*{a\pi} \\
216 \zxZ{\beta} \rar & \zxX*{b\pi}
217 }, we can disable externalization: %
218 \zx<disable externalization>{
219 \zxX{\alpha} \rar \ar[d,C] & \zxZ*{a\pi} \\
220 \zxZ{\beta} \rar & \zxX*{b\pi}
221 } or add more options: %
222 \zx<add to preamble={\usepackage{amsmath}\def\hello#1{Hello #1.}}>{
223 \zxX{\alpha} \rar \ar[d,C] & \zxZ{\text{\hello{Alice}}} \\
224 \zxZ{\beta} \rar & \zxX*{b\pi}
225 }
226 \end{codeAndResult}
227 \end{itemize}
228
229 We also provide methods to cache automatically \mylink{https://tikzit.github.io/}{TikZit} pictures (|\cacheCommand| alone would not be sufficient as the source relies on an external file):
230
231 \begin{codeexample}[vbox]
232 %%%%%%% In your preamble:
233 \cacheTikzitWithStyle{new_zxstyle.tikzstyles}
234
235 %%%%%%% In your document:
236 \tikzfig{demo} %figures/ can be omitted
237 \end{codeexample}
238
239 You can also cache all tikz pictures by default, except those that are run from some commands (as remember picture does not work yet, this is important). For instance, this code will allow you to freely use the |todonotes| package (that uses internally tikz but is not cachable with this library since it uses remember picture) while caching all other elements:
240 \begin{codeexample}[code only]
241 %% this will cache \tikz and tikzpictures by default (using the tikz preset)
242 \cacheTikz
243 %% possibly add stuff to the tikz preset
244 \robExtConfigure{
245 add to preset={tikz}{
246 add to preamble={
247 \def\whereIAm{(I am cached)}
248 }
249 },
250 }%
251 %% We say not to cache the todo commands:
252 \cacheCommand{todo}[O{}m]{disable externalization}%
253 \todo{Check how to use cacheCommand and cacheEnvironment}
254 \tikz[baseline=(A.base)] \node(A)[rounded corners,fill=green]{my cached node \whereIAm};
255 \end{codeexample}
256
257 will give you: {%
258 %% this will cache \tikz and tikzpictures by default (using the tikz preset)
259 \cacheTikz
260 %% possibly add stuff to the tikz preset
261 \robExtConfigure{
262 add to preset={tikz}{
263 add to preamble={
264 \def\whereIAm{(I am cached)}
265 }
266 },
267 }%
268 %% We say not to cache the todo commands:
269 \cacheCommand{todo}[O{}m]{disable externalization}%
270 \todo{Check how to use cacheCommand and cacheEnvironment}
271 \tikz[baseline=(A.base)] \node(A)[rounded corners,fill=green]{my cached node \whereIAm};
272 }
273
274 Note that most options can either be specified anywhere in the document like
275 \begin{verbatim}
276 \robExtConfigure{
277 disable externalization
278 }
279 \end{verbatim}
280 , inside a preset (that is nothing more than a pgf style), or in the options of the cached environment (either inside |CacheMe| or inside the first parameter |<...>| for automatically cached environments):
281 \begin{codeexample}[vbox]
282 \robExtConfigure{
283 new preset={my preset with xcolor}{
284 latex, % load the latex preset, you can also use the tikz preset and more
285 add to preamble={
286 % load xcolor in the preamble of the cached document
287 \usepackage{xcolor}
288 },
289 },
290 }
291 \begin{CacheMe}{my preset with xcolor, add to preamble={\def\hello#1{Hello #1!}} }
292 \begin{minipage}{5cm}
293 \textcolor{red}{\hello{Alice} See, you can cache any data, including minipages,
294 define macros, combine presets, override a single picture or a whole part of
295 a document etc.}
296 \end{minipage}
297 \end{CacheMe}
298 \end{codeexample}
299 (see that |CacheMe| can be used to cache arbitrary pictures)
300
301 Or include images generated in python, note that if you use a version before 2.7, you cannot indent the python code:
302
303 \begin{codeexample}[code only]
304 \begin{CacheMeCode}{python, set includegraphics options={width=.8\linewidth}}
305 import matplotlib.pyplot as plt
306 year = [2014, 2015, 2016, 2017, 2018, 2019]
307 tutorial_count = [39, 117, 111, 110, 67, 29]
308 plt.plot(year, tutorial_count, color="#6c3376", linewidth=3)
309 plt.xlabel('Year')
310 plt.ylabel('Number of futurestud.io Tutorials')
311 plt.savefig("__ROBEXT_OUTPUT_PDF__")
312 \end{CacheMeCode}
313 \end{codeexample}
314
315 You can also include files from the root folder, if you want, recompile all pictures if this files changes (nice to ensure maximum purity):
316 \begin{codeexample}[width=0pt,vbox]
317 \begin{CacheMe}{latex,
318 add dependencies={common_inputs.tex},
319 add to preamble={\input{__ROBEXT_WAY_BACK__common_inputs.tex}}}
320 The answer is \myValueDefinedInCommonInputs.
321 \end{CacheMe}
322 \end{codeexample}
323
324 Since v2.1, we also provide easy ways to export counters:
325 \begin{codeexample}[width=0pt]
326 \begin{tikzpictureC}<forward counter=page>
327 \node[rounded corners, fill=red]{The current page is \thepage.};
328 \end{tikzpictureC}
329 \end{codeexample}
330 or even macros (we can also export evaluated macros):
331 \begin{codeexample}[width=0pt]
332 \cacheTikz
333 \newcommand{\MyNodeWithNewCommand}[2][draw,thick]{\node[rounded corners,fill=red,#1]{#2};}
334 \begin{tikzpicture}<forward=\MyNodeWithNewCommand>
335 \MyNodeWithNewCommand{Alice}
336 \MyNodeWithNewCommand[xshift=2cm]{Bob}
337 \end{tikzpicture}
338 \end{codeexample}
339
340 Since manually forwarding elements can be quite verbose, it is also possible to automatically apply some styles depending on the content of the element to cache. For instance, we provide a way to automatically forward some macros:
341 \begin{codeexample}[vbox]
342 \cacheTikz
343 \robExtConfigure{add to preset={tikz}{auto forward}}
344
345 \newcommandAutoForward{\MyNode}[2][draw,thick]{\node[rounded corners,fill=red,#1]{#2};}
346 \newcommandAutoForward{\MyGreenNode}[2][draw,thick]{\node[rounded corners,fill=green,#1]{#2};}
347
348 \begin{tikzpicture}
349 \MyNode{Recompiled only if MyNode is changed}
350 \MyNode[xshift=8cm]{but not if the (unused) MyGreenNode is changed.}
351 \end{tikzpicture}\\
352
353 \begin{tikzpicture}
354 \MyGreenNode{Recompiled only if MyGreenNode is changed}
355 \MyGreenNode[xshift=8cm]{but not if the (unused) MyNode is changed.}
356 \end{tikzpicture}
357 \end{codeexample}
358
359 We also provide a number of other functionalities, among others:
360 \begin{itemize}
361 \item To achieve a pleasant and configurable interface (e.g. pass options to a preset with default values), we introduced placeholders, that can be of independent interest.
362 \item To get maximum purity while minimizing the number of rebuild, we provide functions to forward macros defined in the parent document, and the set of macros that must be forwarded can be automatically detected for each element to cache. It is also possible to conditionally import a library if the element contains a given macro.
363 \item We provide a way to compile a template via:\\
364 |new compiled preset={compiled ZX}{templateZX, compile latex template}{}|\\
365 in order to make the compilation even faster (but you cannot use placeholders except |add to preamble|)
366 \item We give a highly configurable template, compilation and inclusion system, to cache basically anything
367 \item We show how to compile all images in parallel using |\robExtConfigure{compile in parallel}| or |\robExtConfigure{compile in parallel after=5}| (make sure to have xargs installed, which is available by default on linux but must be installed on Windows by installing the lightweight GNU On Windows (Gow) \url{https://github.com/bmatzelle/gow} if you use the default command) even during the first run, so that the first run becomes faster to compile than a normal run(!)
368 \item We furnish commands to automatically clean the cache while keeping cached elements that are still needed.
369 \item And more\dots
370 \end{itemize}
371
372 \section{Acknowledgments}
373
374 I am deeply indebted to many users on \url{tex.stackexchange.com} that made the writing of this library possible. I can't list you all, but thank you so much! A big thanks also to the project \url{https://github.com/sasozivanovic/memoize/} from which I borrowed most of the code to automatically wrap commands. Thanks to kiryph and dflvunoooooo for providing very useful feedbacks.
375
376 \section{Support}
377
378 If you find this library useful, please consider citing the arXiv version of this documentation, possibly using |\nocite|. If you want to support me financially and offer me a virtual coffee, you can use my \mylink{https://github.com/sponsors/tobiasBora}{GitHub sponsor page}.
379
380 \section{Introduction}
381
382 \subsection{Why do I need to cache (a.k.a. externalize) parts of my document?}
383
384 One often wants to cache (i.e.\ store pre-compiled parts of the document, like figures) operations that are long to do: For instance, TikZ is great, but TikZ figures often take time to compile (it can easily take a few seconds per picture). This can become really annoying with documents containing many pictures, as the compilation can take multiple minutes: for instance my thesis needed roughly 30mn to compile as it contains many tiny figures, and LaTeX needs to compile the document multiple times before converging to the final result. But even on much smaller documents you can easily reach a few minutes of compilation, which is not only high to get a useful feedback in real time, but worse, when using online \LaTeX{} providers (e.g. overleaf), this can be a real pain as you are unable to process your document due to timeouts.
385
386 Similarly, you might want to cache the result of some codes, for instance a text or an image generated via python and matplotlib, without manually compiling them externally.
387
388 \subsection{Why not using \tikzname{}'s externalize library?}
389
390 \tikzname{} has an externalize library to pre-compile these images on the first run. Even if this library is quite simple to use, it has multiple issues:
391 \begin{itemize}
392 \item If you add a picture before existing pre-compiled pictures, the pictures that are placed after will be recompiled from scratch. This can be mitigated by manually adding a different prefix to each picture, but it is highly not practical to use.
393 \item To compile each picture, TikZ's externalize library reads the document's preamble and needs to process (quickly) the whole document. In large documents (or in documents relying on many packages), this can result in a significant loading time, sometimes much bigger than the time to compile the document without the externalize library: for instance, if the document takes 10 seconds to be processed, and if you have 200 pictures that take 1s each to be compiled, the first compilation with the TikZ's externalize library will take roughly half an hour (200 $\times$ 10s = 33mn) instead of 3mn without the library. And if you add a single picture at the beginning of the document… you need to restart everything from scratch. For these reasons, I was not even able to compile my thesis with TikZ's external library in a reasonable time.
394 \item If two pictures share the same code, it will be compiled twice
395 \item Little purity is enforced: if a macro changes before a pre-compiled picture that uses this macro, the figure will not be updated. This can result in different documents depending on whether the cache is cleared or not.
396 \item As far as I know, it is made for TikZ picture mostly, and is not really made for inserting other stuff, like matplotlib images generated from python etc...
397 \item According to some maintainers of TikZ, ``\mylink{https://github.com/pgf-tikz/pgf/issues/758}{the code of the externalization library is mostly unreadable gibberish}'', and therefore most of the above issues are unlikely to be solved in a foreseable future.
398 \end{itemize}
399
400 \subsection{FAQ}
401
402 \paragraph{What is supported?}
403
404 You can cache most things, including tikz pictures, (including ones with overlays (but not with remember picture), with depth etc.), python code etc. We tried to make the library as customizable as possible to be useful in most scenarios. You can also send some data (e.g.\ : the current page) to the compiled pictures, and feed some data back to the main document (say that you want to compute a value that takes time to compute, or compute the number of pages of the produced document in order to increase the number of pages accordingly\dots{}). Since v2.0, you can also cache automatically any environment.
405
406 \paragraph{What is not supported?}
407
408 We do not yet support remember picture, and you can't use (yet) cross-references inside your images (at least not without further hacks) or links as links are stripped when the pdf is included. I might have some ideas to solve this\footnote{\url{https://tex.stackexchange.com/questions/695277/clickable-includegraphics-for-cross-reference-data}}, meanwhile you can just disable locally the library on problematic figures. Note that this library is quite young, so expect untested things.
409
410 \paragraph{What OS are supported?}
411
412 I tested the library on Linux and Windows, but the library should work on all OS, including MacOs. Please let me know if it fails for you.
413
414 \paragraph{Do I need to compile using -shell-escape?}
415
416 Since we need to compile the images via an external command the first time, the simpler option is to add the argument |-shell-escape| to let the library run the compilation command automatically (this is also the case of \tikzname's externalize library). Note that overleaf already defines this option by default, so you don't need to do anything special in overleaf. Moreover, this is only needed \textbf{during the first compilation} since once the image is cached, |-shell-escape| is not needed anymore (therefore, on the arXiv website, you can upload the |robustExternalize| folder containing the cached images without any issue, see \cref{sec:arxiv} for details). However, people worried by security issues of |-shell-escape| (that allows arbitrary code execution if you don't trust the \LaTeX{} code) might be interested by these facts:
417 \begin{itemize}
418 \item You can choose to display a dummy content explaining how to manually compile the pictures instead of giving an error until they are compiled, see |enable fallback to manual mode|.
419 \item You can compile manually the images: all the commands that are left to be executed are also listed in \texttt{JOBNAME-robExt-compile-missing-figures.sh} and you can just inspect and run them, either with \texttt{bash robExt-compile-missing-figures.sh} or by typing them manually (most of the time it's only a matter of running \texttt{pdflatex somefile.tex} from the \texttt{robustExternalize} folder).
420 \item If you allowed:
421 \begin{itemize}
422 \item |pdflatex| (needed to compile latex documents)
423 \item |cd| (not needed when using |no cache folder|)
424 \item and |mkdir| (not needed when using |no cache folder| or if the cache folder that defaults to |robustExternalize| is already created)
425 \end{itemize}
426 to run in restricted mode (so without enabling |-shell-escape|), then there is no need for |-shell-escape|. In that case, set |force compilation| and this library will compile even if |-shell-escape| is disabled.
427 \item If images are all already cached, you don't need to enable \texttt{-shell-escape} (this might be interesting e.g. to send a pre-cached document to the arxiv or to a publisher: just make sure to include the cache folder).
428 \item We use very few commands to compile latex files, basically only pdflatex, mkdir (to create the cache folder if needed) and cd (if the cache folder is not present). You might want to allow them in restricted mode.
429 \end{itemize}
430
431
432 \paragraph{Is it working on overleaf?}
433
434 Yes: overleaf automatically compiles documents with |-shell-escape|, so nothing special needs to be done there (of course, if you use this library to run some code, the programming language might not be available, but I heard that python is installed on overleaf servers for instance, even if this needs to be doubled checked). If the first compilation of the document to cache images times out, you can just repeat this operation multiple times until all images are cached. In case of doubt, you can look at the log file to see which file is getting cached. If overleaf still times out, read the next paragraph.
435
436 \paragraph{Overleaf still times-out, why?}
437
438 During the first compilation, the pictures are not compiled, so you may obtain a time out. However, at each compilation, new pictures should be added to the cache, so you should eventually be able to compile (check the log file, you should read ``No need to recompile XX.pdf'' if the picture is already in the cache). If you want this to be faster, you can try to enable |\robExtConfigure{compile in parallel}| in order to compile the pictures in parallel (need 2 compilations). If you do not often change all pictures, you can also locally download the project (it might be more practical to use the git bridge if you have it enabled), compile them locally, and copy back the |robustExternalize| folder containing all cached pictures.
439
440 If all pictures are still compiled, but you still experience timeouts, you can try to use compiled presets, with something like:
441 \begin{verbatim}
442 \robExtConfigure{
443 new compiled preset={compiled ZX}{templateZX, compile latex template}{}
444 }
445 \end{verbatim}
446 to create a new, more efficient (we call it compiled) preset called |compiled ZX| from a preset |templateZX|.
447
448 You can also try to reduce the compilation time by reducing the number of compilation passes. Indeed, overleaf will run |pdflatex| multiple times to make it converge to the final version, increasing mechanically the compilation time (for instance a file that takes 6s to compile locally was not able to compile online). You can force overleaf to compile a single time the document by creating a |latexmkrc| file at the root of the project, containing:
449 \begin{verbatim}
450 $max_repeat=1
451 \end{verbatim}
452 Of course, you might need to recompile more than once the document to reach the final version.
453
454 \paragraph{Do you have some benchmarks?}
455
456 We completely rewrote the \href{https://github.com/leo-colisson/robust-externalize/commit/09a05a86ec9c04eb6687b75831ebb84185786ac5}{original library} to introduce the notion of placeholders (before, the template was fixed forever), allowing for greater flexibility. The original rewrite (1.0) had really poor performance compared to the original library (only x3 improvement compared to no externalization, while the old library could be 20x faster), but we made some changes (v2.0) that correct this issue to recover the original speed (at least when using compiled templates). Here is a benchmark we made on an article with 159 small pictures (ZX diagrams from the zx-calculus library):
457 \begin{itemize}
458 \item without externalization: 1mn25
459 \item with externalization, v2.0 (first run, not in parallel): 3mn05, so takes twice the time; but (first run in parallel) takes 60s (so faster by a factor of 1.5).
460 \item with externalization, v2.0 (next runs): 5.77s (it is 15x times faster)
461 \item with externalization, v2.0, with a ``compiled'' template (less flexible) like in the old version: 4.0s (22x faster)
462 \item with externalization, old library (next runs): 4.16s (so 21x faster)
463 \end{itemize}
464
465 \paragraph{Can I compile pictures in parallel to speed up notably the first run?}
466
467 The first run might be particularly long to compile since many elements are still not cached and re-starting \LaTeX{} on each picture can take quite some time. If you have v2.1 or above, and if you have xargs installed (installed by default on most linux, on Windows you need to install the lightweight GNU On Windows (Gow) \url{https://github.com/bmatzelle/gow}), you can simply compile all images in parallel by typing at the beginning of the file:
468 \begin{codeexample}[code only]
469 \robExtConfigure{
470 compile in parallel
471 }
472 \end{codeexample}
473 In my benchmark, I observed a compilation 1.5x faster than a normal compilation without any caching involved. We provide more options in \cref{sec:compileParallel}.
474
475 \paragraph{Can I use version-control to keep the cached files in my repository?} Sure, each cached figure is stored in a few files (typically one pdf and one \LaTeX{} file, plus the source) having the same prefix (the hash), avoiding collision between runs. Just commit these files and you are good to go.
476
477 \paragraph{Can I deal with baseline position and overlays ?} Yes, the depth of the box is automatically computed and used to include the figure by default, and additional margin is added to the image (30cm by default) to allow overlay text.
478
479 \paragraph{How is purity enforced?} Purity is the property that if you remove the cached files and recompile your document, you should end-up with the same output. To enforce purity, we compute the hash of the final program, including the compilation command, the dependency files used for instance in |\input{include.tex}| (unless you prefer not to, for instance to keep parts of the process impure for efficiency reasons), the forwarded macros, and put the code in a file named based on this hash. Then we compile it if it has not been used before, and include the output. Changing a single character in the file, the tracked dependencies, or the compilation command will lead to a new hash, and therefore to a new generated picture.
480
481 \paragraph{What if I don't want purity for all files?} If you do not want your files to be recompiled if you modify a given file, then just do not add this file to the list of dependencies.
482
483 \paragraph{Can I extend it easily?} We tried to take a quite modular approach in order to allow easy extensions. Internally, to support a new cache scheme, we only expect a string containing the program (possibly produced using a template), a list of dependencies, a command to compile this program (e.g. producing a pdf and possibly a tex file with the properties (depth…) of the pdf), and a command to load the result of the compilation into the final document (called after loading the previously mentioned optional tex file). Thanks to pgfkeys, it is then possible to create simple pre-made settings to automatically apply when needed.
484
485 \paragraph{How does it compare with \url{https://github.com/sasozivanovic/memoize}?} I recently became aware of the great \url{https://github.com/sasozivanovic/memoize}. While we aim to solve a similar goal, our approaches are quite different. While I focus on purity, and therefore create a different file for each picture, the above project puts all pictures in a single file and compile them all at once to avoid losing time to run the latex command for each picture (this mostly makes a difference for the first compilation). Our understanding of the main differences is the following:
486
487 Pros of \url{https://github.com/sasozivanovic/memoize}:
488 \begin{itemize}
489 \item The above library might be easier to setup as they do not need to specify the preamble of the file to compile (the preamble of the main file is used), and tikz pictures are automatically memoized (we provide |\cacheTikz| for that, but you still need to specify the preamble once).
490 \item This library allows to compile multiple pictures while loading \LaTeX{} only once, saving the time to start \LaTeX{} for each picture. However, it is not clear that it brings a faster compilation time compared to our library for multiple reasons:
491 \begin{itemize}
492 \item While during the first run all pictures are compiled with a single \LaTeX{} instance\footnote{We could also do something similar using some scripting to merge multiple cached files together, but this is not yet implemented.} (and inserted at the beginning of the document), they still need to extract each picture in a separate pdf file to include it at the right place in the document. This is done by default using |pdflatex|, which means that you need to call |pdflatex| once per picture, mitigating the advantage of compiling all pictures at once. Note that they also provide a python script to separate the pictures more efficiently, but this needs further manual interventions.
493 \item We provide an option |compile in parallel| to compile all images in parallel, and the time is in my benchmark 1.5x faster than a normal compilation without any caching. Using this option, we should therefore compile faster than |memoized| that is not able to run jobs in parallel.
494 \end{itemize}
495 \item Even if it does not officially support contexts, context might be automatically transmitted (while we need to do a bit of work to manually or semi-automatically define the context needed to compile a picture). However, this can break purity (see below).
496 \end{itemize}
497
498 Cons of \url{https://github.com/sasozivanovic/memoize}:
499 \begin{itemize}
500 \item The purity is not enforced so strongly since all images are in the same file. Notably, the hash only depends on the picture, but not on its context. So for instance if you define |\def\mycolor{blue}| before the picture, and use |\mycolor| inside the picture, if you change later the color to, say, |\def\mycolor{red}|, the picture will not be recompiled (so cleaning the cache and recompiling would produce a different result). In our case, the purity is always strictly enforced (unless you choose not to) since the context must be passed (explicitly or semi-automatically) to the compiled file.
501 \item As a result, the above library has poor support for contexts (in our case, you can easily, for instance, make a picture depend on the current page, and recompile the picture only if the current page changes: you can also do it the other way, and change some counters, say, depending on the cached file).
502 \item The above library only focuses on \LaTeX{} while our library works for any language.
503 \item The above library can only cache in pdf format, while we can generate any format (text, tex, jpg\dots{} and even videos that I include in my beamer presentations\dots{} but it is another topic!).
504 \item We have an arguably more complete documentation.
505 \end{itemize}
506
507 Note that |remember picture| is not supported in both libraries, but we can provide multiple methods to disable externalizations when |remember picture| is used.
508
509 \subsection{How to use with arXiv}\label{sec:arxiv}
510
511 You can completely use this library with the arXiv's website (this documentation is also compiled in arXiv), but you need to follow a few steps due to arXiv's particularities:
512 \begin{itemize}
513 \item First, arXiv does NOT allow |-shell-escape|. So you either need to disable externalization (not recommended since this will of course increase the compilation time and will not work when working with non-latex code like python or external images), or you need to compile locally the document to cache all images locally\footnote{Make sure to recompile from scratch, by removing the .aux file, if your cached pictures can depend on counters (like the current page) that can change across compilations.}, and upload the |robustExternalize/| folder containing all cached images online in a zip file.
514 \item Moreover, if you choose to upload the |robustExternalize/| folder, the arXiv website will automatically remove all |.pdf| files if a |.tex| file is present (which will break this library, since it puts all sources in the |.tex| file and the output in a |.pdf| file). The trick is to rename all the source |.tex| files into |.tex-backup| (this library will automatically recreate the |.tex| from the |.tex-backup| starting from v2.4). We provide two approaches for that:
515 \begin{itemize}
516 \item \textbf{Solution 1}: if you have python installed the most robust solution is to run
517 \begin{verbatim}
518 $ python robExt-prepare-for-arxiv.py
519 \end{verbatim}
520 before sending the document to the arXiv. This will rename all the |.tex| files in the |robust-externalize| folder that have a matching |*.pdf| file into |.tex-backup|, and list these files in |robExt-arxiv-files-to-rename.txt|. Then, add in the preamble of your document:
521 \begin{codeexample}[code only]
522 \robExtConfigure{
523 rename backup files for arxiv,
524 }
525 \end{codeexample}
526 This will automatically rename back the |.tex-backup| files into |.tex| (without needing shell-escape), based on the |robExt-arxiv-files-to-rename.txt| file (if this file exists and if the files have not already been renamed: it is therefore safe to keep this option on even without running the python code), allowing the rest of the document to compile normally.
527 \item \textbf{Solution 2}: if you do \textbf{not} have python installed, you can simply run:
528 \begin{codeexample}[code only]
529 \robExtConfigure{
530 backup source for arxiv,
531 }
532 \end{codeexample}
533 This will automatically rename the source files |.tex| into |.tex-backup| (make sure to comment this line on the final pdf sent to the arXiv). Note however that this is less robust than solution 1 since the |.tex-backup| will be renamed into |.tex| only if it is in the source, but sometimes other |.tex| files might need to be renamed as well: for instance, |gnuplot| with |cairolatex| terminal creates two files |-gnuplot-.tex| and |-gnuplot-.pdf|, and this file will not be renamed with this method, so the |-gnuplot-.pdf| file will be lost.
534 \end{itemize}
535 \item This should be enough to compile most documents. But note that since the arXiv uses a different Texlive version and might try to compile other document formats, it might be the case that the number of page varies from your original document: if you uses things like |forward counter=page|, it might cause you some troubles since your local cache might contain the cache for |page=42| while the arXiv would ask for the cached value for |page=45|, producing an error like |enable -shell-escape|. There are a few steps you can follow to fix these issues:
536 \begin{itemize}
537 \item First, make sure to have the same margins/paper on your local file and online (by default arXiv will create a document in |letterpaper|). To that end, you can force the paper format with |\documentclass[a4paper]{article}|.
538 \item ArXiv might try to compile with various output formats like eps, so it might help to force a pdf output by starting your document with |\pdfoutput=1| (not sure how helpful this is, it might already be forced when we insert a pdf?).
539 \item ArXiv will automatically remove all empty files. While for some files it is not an issue (aux files and compilation logs), if this file is the |.pdf| it will be an issue. So make sure to always generate non-empty output files.
540 \item If despite these options, arXiv still tries to fetch a cached value that is not present in your local cache, you can enable
541 \begin{verbatim}
542 \robExtConfigure{print source when saving}
543 \end{verbatim}
544 This will print in the log file the content of the |.deps| file, of the |.tex| file, and the compilation command that would have been run without the error. You can then recreate these files in the cache and compile it locally. If you do not want to copy/paste the content of the file, it might be simpler to simply see the value that differs from your own local cache and just temporarily change this value in your local document to automatically generate the correct cache entry. If the value is obtained via |forward counter=page|, you can use |forward counter force value={page}{45}| to force the value of the counter.
545 \end{itemize}
546 \end{itemize}
547
548 \section{Tutorial}
549
550 \subsection{Installation}
551
552 To install the library, just copy the |robust-externalize.sty| file into the root of the project. Then, load the library using:\\
553
554 \begin{verbatim}
555 \usepackage{robust-externalize}
556 \end{verbatim}
557
558 If you want to display a message in the pdf on how to manually compile the file if |-shell-escape| is disabled, you can also load this configuration (only available on v2.0):
559
560 \begin{verbatim}
561 \robExtConfigure{
562 enable fallback to manual mode,
563 }
564 \end{verbatim}
565
566 \noindent (otherwise, it will give you an error if |-shell-escape| is disabled and if some pictures are not yet cached)
567
568 If you forget/do not want to enable |-shell-escape|, this will give you this kind of message with instructions to follow to compile without shell escape:
569
570 \noindent {
571 \robExtConfigure{
572 enable manual mode
573 }
574 \begin{tikzpictureC}[baseline=(A.base)]
575 \node[fill=red, rounded corners](A){I must be manually compiled.};
576 \node[fill=red, rounded corners, opacity=.3,overlay] at (A.north east){I am an overlay text};
577 \end{tikzpictureC}
578 }
579
580
581 If you use an editor, you can usually configure |-shell-escape| directly inside the editor, even on a per-document basis. Shell-escape is enabled by default on overleaf. In emacs/auctex, just add at the end of your document:
582 \begin{verbatim}
583 % Local Variables:
584 % TeX-command-extra-options: "--shell-escape"
585 % End:
586 \end{verbatim}
587 save, and run |M-x revert-buffer| (Note that it seems that |--shell-escape| can be used with one or two dashes on Linux, I am not sure about the number of dashes needed in Windows.)
588
589 For TeXstudio, you can enable shell-escape on the current document by adding in your document:
590 \begin{verbatim}
591 % !TeX TXS-program:compile = txs:///pdflatex/[--shell-escape]
592 \end{verbatim}
593 and you might also want to enable:
594 \begin{verbatim}
595 \robExtConfigure{texstudio}
596 \end{verbatim}
597 to get clearer error messages as TeXstudio is \mylink{https://github.com/texstudio-org/texstudio/issues/1410}{fairly bad at parsing error messages} (see also |print whole file in error message|).
598
599 If you use |latexmk| (with any editor), you can create a file called |.latexmkrc| containing:
600 \begin{verbatim}
601 $pdf_mode = 1;
602 $pdflatex = 'pdflatex --shell-escape';
603 \end{verbatim}
604
605 For other editors, \mylink{https://tex.stackexchange.com/questions/598818/how-can-i-enable-shell-escape}{this answer} describes pretty accurately the solutions you have depending on your software.
606
607 \subsection{Caching a tikz picture}
608
609 If you only care about \tikzname's picture, you have 4 options:
610 \begin{enumerate}
611 \item Call once |\cacheTikz| that will redefine |tikzpicture| and |\tikz| to use our library (if you use this solution, make sure to read how to disable externalization (\cref{sec:disableExternalization}) as we do not support for instance |remember picture|). Then, configure the default preamble for cached files as explained below by extending the |tikz| or |tikzpicture| presets (that first loads |tikz|).
612 \item Use the generic commands that allows you to wrap an arbitrary environment:
613 \begin{verbatim}
614 % name environment ---v v----- preset options
615 \cacheEnvironment{tikzpicture}{tikzpicture}
616 \end{verbatim}
617 Note that you can also wrap commands (that you call with |\foo| instead of |\begin{foo}...\end{foo}|) using this:\\
618 |\cacheCommand{yourcommand}[O{default val}m]{your preset options}|\\
619 (|O{default val}m| means that the command accepts one optional argument with default value |default val| and one mandatory argument) but \textbf{we do recommend} to use |\cacheCommand| to cache |\tikz| since |\tikz| has a quite complicated parsing strategy (e.g.\ you can write |\tikz[options] \node{foo};| which has no mandatory argument enclosed in |{}|). |\cacheTikz| takes care of this already and caches both the environment |\begin{tikzpicture}| and the macro |\tikz|.
620 \item Use |tikzpictureC| instead of |tikzpicture| (this is mostly done to easily convert existing code to this library, but works only for |tikz| pictures).
621 \item Use the more general |CacheMe| environment, or |CacheMeCode| if you use non-\LaTeX{} code\footnote{The later involves a more advanced parsing that allows it to contain special symbols like percent, but on the other hand it cannot be used inside macros and some environments directly. On the other hand, the former will remove some characters like percent (that are considered as comments) or newlines (which is harmless for \LaTeX{} code), but can be used anywhere.}, to cache \tikzname, \LaTeX{}, python and much more.
622 \end{enumerate}
623
624 These 4 options are illustrated below (note that all commands accept a first optional argument enclosed in |<...>| that contains the options to pass to |CacheMe| after loading the |tikzpicture| preset, that loads itself the |tikz| preset first):
625
626 Option 1:
627 \begin{codeexample}[width=0pt]
628 %% We override the default tikzpicture environment
629 %% to externalize all pictures
630 %% Warning: it will cause troubles with pictures relying on |remember pictures|
631 \cacheTikz
632
633 I am a cached picture: \begin{tikzpicture}[baseline=(A.base)]
634 \node[draw,rounded corners,fill=pink!60](A){Hello World!};
635 \end{tikzpicture}. %
636
637 I am a non-cached picture: \begin{tikzpicture}<disable externalization>[baseline=(A.base)]
638 \node[draw,rounded corners,fill=pink!60](A){Hello World!};
639 \end{tikzpicture}.
640 \end{codeexample}
641
642 Option 2:
643 \begin{codeexample}[width=0pt]
644 \cacheEnvironment{tikzpicture}{tikzpicture}
645 I am a cached picture: \begin{tikzpicture}[baseline=(A.base)]
646 \node[draw,rounded corners,fill=pink!60](A){Hello World!};
647 \end{tikzpicture}.
648 \end{codeexample}
649
650 Option 3:
651 \begin{codeexample}[width=0pt]
652 I am a cached picture: \begin{tikzpictureC}[baseline=(A.base)]
653 \node[draw,rounded corners,fill=pink!60](A){Hello World!};
654 \end{tikzpictureC}.
655 \end{codeexample}
656
657
658 Option 4:
659 \begin{codeexample}[width=0pt]
660 I am a cached picture: \begin{CacheMe}{tikzpicture}[baseline=(A.base)]
661 \node[draw,rounded corners,fill=pink!60](A){Hello World!};
662 \end{CacheMe}.
663 \end{codeexample}
664
665 Since |CacheMe| is more general as it applies also to non-tikz pictures (just replace |tikzpicture| with the style of your choice), we will mostly use this syntax from now.
666
667 \subsection{Custom preamble}
668
669 Note that the pictures are compiled in a separate document, with a different preamble and class (we use the standalone class). This is interesting to reduce the compilation time of each picture (loading a large preamble is really time consuming) and to avoid unnecessary recompilation (do you want to recompile all your pictures when you add a single new macro?) without sacrificing the purity. But of course, you need to provide the preamble of the pictures. The easiest way is probably to modify the |tikz| preset (since |tikzpicture| loads this style first, it will also apply to tikzpictures. Note that you can also modify the |latex| preset if you want the change to apply to all \LaTeX{} documents):
670
671 \begin{codeexample}[width=0pt,vbox]
672 \robExtConfigure{
673 add to preset={tikz}{
674 add to preamble={\usetikzlibrary{shadows}},
675 },
676 }
677
678 See, tikz's style now packs the |shadows| library by default: %
679 \begin{CacheMe}{tikzpicture}[even odd rule]
680 \filldraw [drop shadow,fill=white] (0,0) circle (.5) (0.5,0) circle (.5);
681 \end{CacheMe}
682 \end{codeexample}
683
684 and you can also create a new preset, and why not mix multiple presets together:
685 \begin{codeexample}[width=0pt,vbox]
686 \robExtConfigure{
687 new preset={load forest}{
688 latex,
689 add to preamble={\usepackage{forest}},
690 },
691 new preset={load hello}{
692 add to preamble={\def\hello#1{Hello #1.}},
693 },
694 }
695
696 \begin{CacheMe}{load forest, load hello}
697 \begin{forest}
698 [VP
699 [DP[\hello{John}]]
700 [V’
701 [V[sent]]
702 [DP[Mary]]
703 [DP[D[a]][NP[letter]]]
704 ]
705 ]
706 \end{forest}
707 \end{CacheMe}
708 \end{codeexample}
709
710
711 \textbf{Note:} the |add to preset| and |new preset| directives have been added in v2.0, together with the |tikzpicture| preset. In v1.0, you would do |tikz/.append style={...}| (and you can still do this if you prefer), the difference is that |.append style| and |.style| require the user to double all hashes like |\def\mymacro##1{Hello ##1.}| which can lead to confusing errors.
712
713 You can also choose to overwrite the preset options for a single picture (or even a block of picture if you run the |\robExtConfigure| and |CacheMe| inside a group |{ ... }|):
714 \begin{codeexample}[width=0pt,vbox]
715 See, you can add something to the preamble of a single picture: %
716 \begin{CacheMe}{tikzpicture, add to preamble={\usetikzlibrary{shadows}}}[even odd rule]
717 \filldraw [drop shadow,fill=white] (0,0) circle (.5) (0.5,0) circle (.5);
718 \end{CacheMe}
719 \end{codeexample}
720
721 Note that if you use the |tikzpictureC| or |tikzpicture| syntax, you want to add the options right after the name of the command or environment, enclosed in |<>| (by default):
722 \begin{codeexample}[width=0pt,vbox]
723 See, you can add something to the preamble of a single picture: %
724 \begin{tikzpictureC}<add to preamble={\usetikzlibrary{shadows}}>[even odd rule]
725 \filldraw [drop shadow,fill=white] (0,0) circle (.5) (0.5,0) circle (.5);
726 \end{tikzpictureC}
727 \end{codeexample}
728
729 \textbf{Important}: Note that the preset options can be specified in a number of places: in |\robExtConfigure| (possibly in a group, or inside a preset), in the options of the picture, in the default options of |cacheEnvironment| and |cacheCommand| etc. Most options can be used in all these places, the only difference being the scope of the options.
730
731 If you find yourself duplicating code between the main document and the preamble of the cached file, we provide multiple solutions with different properties:
732 \begin{itemize}
733 \item Recommended: |\newcommandAutoForward| etc, to automatically forward specific macros/colors etc: see \cref{sec:forwardIntro}. Very useful if you want maximum purity without annoying recompilation.
734 \item |\runHereAndInPreambleOfCachedFiles|: mostly useful if you want to always add a text both in the current file and in the cached files, like a font etc.
735 \item Share a common input file with or without dependencies (see \cref{sec:dependencies}), useful if you need to work with external files or if you do NOT want purity (i.e.\ you can choose not to recompile the file even if its content changes).
736 \end{itemize}
737
738 |\runHereAndInPreambleOfCachedFiles{XXX}| is very simple (need at least version 2.3), as it is simply a shortcut for typing |XXX| in the current file and in the preamble of the cached files (default to latex preset). For instance if you want the current file and all cached files to use the Times New Roman font, you can do:
739
740 \begin{codeexample}[code only]
741 % By default adds
742 \runHereAndInPreambleOfCachedFiles{
743 \usepackage{fontspec}
744 % need lualatex or xelatex to compile
745 \setmainfont{Times New Roman}
746 }
747
748 \robExtConfigure{
749 add to preset={latex}{
750 use lualatex, % Make sure to compile with lualatex the cached images.
751 },
752 }
753 \end{codeexample}
754
755 You can also define your common macros (even if we recommend |\newcommandAutoForward| to avoid frequent recompilations when the definitions changes):
756 \begin{codeexample}[width=0pt,vbox]
757 \runHereAndInPreambleOfCachedFiles{
758 \def\name#1{The great lady #1 and her friends.}
759 }
760
761 \cacheTikz
762 This is the picture of \name{Alice}:
763 \begin{tikzpicture}
764 \node[fill=orange]{\name{Alice}};
765 \end{tikzpicture}
766 \end{codeexample}
767
768 \subsection{Dependencies}\label{sec:dependencies}
769
770 \textbf{Note: dependencies can sometimes be advantageously replaced with auto-forwarding of arguments, cf.\ \cref{sec:forwardIntro}, or |\runHereAndInPreambleOfCachedFiles|.}
771
772 It might be handy to have a file that is loaded in both the main document and in the cached pictures. For instance, if you have a logo that might be included in the cached files, or if you have a file |common_inputs.tex| that you want to input in both the main file and in the cached files, that contains, say:\\
773 |\def\myValueDefinedInCommonInputs{42}|\\
774 then you can add it as a dependency this way (here we use the |latex| preset that does not wrap the code inside a |tikzpicture| only to illustrate that we can also cache things that are not generated by tikz):
775 \begin{codeexample}[width=0pt,vbox]
776 \begin{CacheMe}{latex,
777 add dependencies={common_inputs.tex},
778 add to preamble={\input{__ROBEXT_WAY_BACK__common_inputs.tex}}}
779 The answer is \myValueDefinedInCommonInputs.
780 \end{CacheMe}
781 \end{codeexample}
782 Note that the placeholder |__ROBEXT_WAY_BACK__| contains the path from the cache folder (containing the |.tex| that will be cached) to the root folder, and will be replaced when creating the file. This way, you can easily input files contained in the root folder. You can also create your own placeholders, read more below.
783
784 You can note that we used |add dependencies={common_inputs.tex}|: this allows us to recompile the files if |common_inputs.tex| changes. If you do not want this behavior (e.g. |common_inputs.tex| changes too often and you do not want to recompile everything at every change), you can remove this line, but beware: if you do a breaking changes in |common_inputs.tex| (e.g.\ redefine |42| to |43|), then the previously cached picture will not be recompiled! (So you will still read 42 instead of 43.)
785
786 Sometimes, it can also be useful to copy a file in the cache folder. This can be done via:
787 \begin{codeexample}[code only]
788 \robExtConfigure{
789 copy file to cache={zx-calculus.sty},
790 }
791 \end{codeexample}
792
793 \subsection{Wrap arbitrary environments}
794
795 You can wrap arbitrary environments using the already presented |cacheEnvironment| and |cacheCommand|, where the first mandatory argument is the name of the environment/macro, and the second mandatory argument contains the default preset. |cacheEnvironment| works for any environment while |cacheCommand| might need a bit of help to determine the signature of the macro if the function is defined via xparse. Long story short, |O{foo}| is an optional argument with default value foo, |m| is a mandatory argument. By default, you can pass an optional arguments via the first argument enclosed in |<>|:
796 \begin{codeexample}[width=0pt,vbox]
797 \cacheCommand{zx}[O{}O{}O{}m]{latex, add to preamble={\usepackage{zx-calculus}\def\hello#1{Hello #1.}}}
798 \zx<add to preamble={\usepackage{amsmath}\def\bye#1{Bye #1.}}>[mbr=1]{ % amsmath provides \text
799 \zxX{\alpha} \rar \ar[d,C] & \zxZ{\text{\hello{Alice}}} \\
800 \zxZ{\beta} \rar & \zxZ{\text{\bye{Bob}}}
801 }
802 \end{codeexample}
803
804 you can also disable externalization for some commands using this same command, here is for instance the code to use |todonotes|:
805 \begin{codeexample}[code only]
806 \cacheCommand{todo}[O{}m]{disable externalization}
807 \todo{Check how to use cacheCommand and cacheEnvironment}
808 \end{codeexample}
809
810 Which gives you {
811 \cacheCommand{todo}[O{}m]{disable externalization}
812 \todo{Check how to use cacheCommand and cacheEnvironment}
813 }
814
815
816 See \cref{sec:wrapAutomatically} for more details.
817
818 \subsection{Disabling externalization}
819
820 You can use |disable externalization| to disable externalization (which is particularly practical if you set |\cacheTikz|). You can configure the exact command run in that case using |command if no externalization/.code={...}|, but most of the time it should work out of the box (see \cref{sec:disableExternalization} for details).
821
822 \begin{codeexample}[width=0pt,vbox]
823 % In theory all pictures should be externalized (so remember picture should fail)
824 \tikz[remember picture,baseline=(pointtome1.base)]
825 \node[rounded corners, fill=orange](pointtome1){Point to me if you can};\\
826 \cacheTikz
827 % But we can disable it temporarily
828 \begin{tikzpicture}<disable externalization>[remember picture]
829 \node[rounded corners, fill=red](A){This figure is not externalized.
830 This way, it can use remember picture.};
831 \draw[->,overlay] (A) to[bend right] (pointtome1);
832 \end{tikzpicture}\\
833
834 % You can also disable it globally/in a group:
835 {
836 \robExtConfigure{disable externalization}
837
838 \begin{tikzpicture}[remember picture]
839 \node[rounded corners, fill=red](A){This figure is not externalized.
840 This way, it can use remember picture.};
841 \draw[->,overlay] (A.west) to[bend left] (pointtome1);
842 \end{tikzpicture}\\
843
844 \begin{tikzpicture}[remember picture]
845 \node[rounded corners, fill=red](A){This figure is not externalized.
846 This way, it can use remember picture.};
847 \draw[->,overlay] (A.east) to[bend right] (pointtome1);
848 \end{tikzpicture}\\
849 }
850
851 \begin{tikzpicture}
852 \node[rounded corners, fill=green](A){This figure is externalized, but cannot use remember picture.};
853 \end{tikzpicture}
854 \end{codeexample}
855
856 You can also disable externalization for some kinds of commands. For instance, the package |todonotes| requires |remember picture| and is therefore not compatible with externalization provided by this package. To disable externalization on all |\todo|, you can do:
857
858 \begin{codeexample}[code only]
859 \cacheCommand{todo}[O{}m]{disable externalization}
860 \todo{Check how to use cacheCommand and cacheEnvironment}
861 \end{codeexample}
862
863 Which gives you {
864 \cacheCommand{todo}[O{}m]{disable externalization}
865 \todo{Check how to use cacheCommand and cacheEnvironment}
866 }
867
868 You can also disable externalization on elements that contain a specific string/regex. For instance, you can disable externalization on all elements containing |remember picture|:
869 \begin{codeexample}[vbox]
870 \cacheTikz
871 \robExtConfigure{
872 add to preset={tikz}{
873 if matches={remember picture}{disable externalization},
874 },
875 }
876 \begin{tikzpicture}[remember picture]
877 \node[fill=green](my node){Point to me};
878 \end{tikzpicture} %
879 Some text %
880 \begin{tikzpicture}[overlay, remember picture]
881 \draw[->] (0,0) to[bend left] (my node);
882 \end{tikzpicture}
883 \end{codeexample}
884
885
886 \subsection{Feeding data from the main document to the cached documents}\label{sec:forwardIntro}
887
888 You can feed data from the main document to the cached file using placeholders, since |set placeholder eval={__foo__}{\bar}| will evaluate |\bar| and put the result in |__foo__|. For instance, if the picture depends on the current page, you can do:
889
890 \message{We will export the page: \thepage}
891 \begin{codeexample}[width=0pt,vbox]
892 \begin{tikzpictureC}<set placeholder eval={__thepage__}{\thepage}>
893 \node[rounded corners, fill=red]{The current page is __thepage__.};
894 \end{tikzpictureC}
895 \end{codeexample}
896
897 However, since v2.1, we also provide a method to specifically export a counter using |forward counter=my counter| and a macro using |forward=\macroToExport|, possibly by evaluating first using |forward eval=\macroToEval|:
898 \begin{codeexample}[width=0pt]
899 \cacheTikz
900 \NewDocumentCommand{\MyNode}{O{}m}{\node[rounded corners,fill=red,#1]{#2};}
901 \begin{tikzpicture}<forward=\MyNode>
902 \MyNode{Alice}
903 \MyNode[xshift=2cm]{Bob}
904 \end{tikzpicture}
905 \end{codeexample}
906
907 To avoid manually writing |forward=...| for each picture, we can instead load |auto forward| and define the macro for instance using |\newcommandAutoForward| (we also provide alternatives for xparse and def-based definitions):
908 \begin{codeexample}[vbox]
909 \cacheTikz
910 \robExtConfigure{add to preset={tikz}{auto forward}}
911
912 \newcommandAutoForward{\MyNode}[2][draw,thick]{\node[rounded corners,fill=red,#1]{#2};}
913 \newcommandAutoForward{\MyGreenNode}[2][draw,thick]{\node[rounded corners,fill=green,#1]{#2};}
914
915 \begin{tikzpicture}
916 \MyNode{Recompiled only if MyNode is changed}
917 \MyNode[xshift=8cm]{but not if the (unused) MyGreenNode is changed.}
918 \end{tikzpicture}\\
919
920 \begin{tikzpicture}
921 \MyGreenNode{Recompiled only if MyGreenNode is changed}
922 \MyGreenNode[xshift=8cm]{but not if the (unused) MyNode is changed.}
923 \end{tikzpicture}
924 \end{codeexample}
925
926 If a macro depends on another macro/package, it is possible to load any additional style like using the last optional argument of |\newcommandAutoForward|:
927 \begin{codeexample}[vbox]
928 \cacheTikz
929 \robExtConfigure{add to preset={tikz}{auto forward}}
930
931 \newcommandAutoForward{\MyName}{Alice}
932 \newcommandAutoForward{\MyNode}[2][draw,thick]{
933 \node[rounded corners,fill=red,#1]{\ding{164} \MyName: #2};
934 }[forward=\MyName, add to preamble={\usepackage{pifont}}]
935
936 \begin{tikzpicture}
937 \MyNode{Recompiled if MyNode or MyName are changed}
938 \end{tikzpicture}
939 \end{codeexample}
940
941 If instead of forwarding the macro you want to, say, load a package or any other style, you should use instead |\robExtConfigIfMacroPresent|:
942 \begin{codeexample}[vbox]
943 \cacheTikz
944 \robExtConfigure{add to preset={tikz}{auto forward}}
945
946 \robExtConfigIfMacroPresent{\ding}{add to preamble={\usepackage{pifont}}}
947
948 \begin{tikzpicture}
949 \node[fill=green, circle]{\ding{164}};
950 \end{tikzpicture}
951 \end{codeexample}
952
953 For more details and functions, see \cref{sec:forward}.
954
955 \subsection{Defining macros}
956
957 You can define macros in the preamble:
958 \begin{codeexample}[width=0pt,vbox]
959 \cacheMe[latex, add to preamble={\def\sayhello#1{Hello #1.}}]{
960 \sayhello{my friend}
961 }
962 \end{codeexample}
963
964 \subsection{Feeding data back into the main document}
965
966 For more advanced usage, you might want to compute a data and cache the result in a macro that you could use later. This is possible if you write into the file |\jobname-out.tex| during the compilation of the cached file (by default, we already open |\writeRobExt| to write to this file). This file will be automatically loaded before loading the pdf (but you can customize all these operations, for instance if you do not want to load the pdf at all; the only requirement is that you should generate a |.pdf| file to specify that the compilation is finished).
967
968 For instance:
969
970 \begin{codeexample}[width=0pt,vbox]
971 \begin{CacheMe}{latex, add to preamble={\usepackage{tikz}}, do not include pdf}
972 We compute this data that is long to compute:
973 \pgfmathparse{(1 + sqrt(5))/2}% result is stored in \pgfmathresult
974 % We write the result to the -out file (\string\foo writes \foo to the file without evaluating it,
975 % so this will write "\gdef\myLongResult{1.61803}"):
976 % Note that CacheMe is evaluated in a group, so you want to use \gdef to define it
977 % outside of the group
978 \immediate\write\writeRobExt{%
979 \string\gdef\string\myLongResult{\pgfmathresult}%
980 }
981 \end{CacheMe}
982
983 We computed the cached value \myLongResult.
984 \end{codeexample}
985
986 \subsection{A note on font handling}
987
988 Cached pictures are basically simple latex files that are compiled in a separate |standalone| document. Therefore, if the main document loads a different font, there is no reason for the cached document to also use that font. Fully-automatically forwarding the current font by default is not so easy because there are so many ways to load a font in LaTeX (by loading a package like |\usepackage{times}|, by using xelatex or lualatex, by calling locally |\rmfamily|, by loading a different class… and here I'm not even mentioning math font where each symbol \mylink{https://tex.stackexchange.com/questions/603475/is-there-any-command-to-find-out-the-current-math-font-used)}{can use a different font}, and this is even more complicated if the main file is compiled with a different engine (e.g.\ what should I do if the main document is compiled with lualatex but the inner cached images are compiled with pdflatex, that supports very few fonts by default?). For these reasons, it is simpler to simply let the user load fonts as they want, for instance using something like:
989 \begin{codeexample}[width=0pt]
990 \robExtConfigure{
991 add to preset={latex}{
992 add to preamble={\usepackage{times}},
993 },
994 }
995
996 \begin{tikzpictureC}
997 \node[fill=green]{See I am using times font};
998 \end{tikzpictureC}
999 \end{codeexample}
1000 or:
1001 \begin{codeexample}[width=0pt]
1002 \robExtConfigure{
1003 add to preset={latex}{
1004 add to latex options={12pt},
1005 },
1006 }
1007
1008 \begin{tikzpictureC}
1009 \node[fill=green]{See I am using a 12pt font};
1010 \end{tikzpictureC}
1011 \end{codeexample}
1012
1013 But if you want to use the same font as the current document, you might want to avoid code duplication (this might also be useful for any arbitrary code). Since v2.3, you can do:
1014 \begin{codeexample}[code only]
1015 \runHereAndInPreambleOfCachedFiles{
1016 \usepackage{fontspec}
1017 % need lualatex or xelatex to compile
1018 \setmainfont{Times New Roman}
1019 }
1020
1021 \robExtConfigure{
1022 add to preset={latex}{
1023 use lualatex, % Make sure to compile with lualatex the cached images.
1024 },
1025 }
1026 \end{codeexample}
1027 and it will automatically compile the cached images with lualatex, and configure the font of the current document and of the cached documents to follow |Times New Roman|.
1028
1029 If you like to often change the font in the document, you can also do something like that to always compile the document with the font currently in use if you use lualatex (this code fails with \mylink{https://tex.stackexchange.com/questions/705208/get-current-font}{xelatex}, currently trying to understand why):
1030 \begin{codeexample}[code only]
1031 \usepackage{fontspec}
1032 \setmainfont{Times New Roman}
1033
1034 %% needed since \f@family contains a @ in its name:
1035 \makeatletter
1036 \def\myCurrentFont{\f@family}
1037 \makeatother
1038
1039 \robExtConfigure{
1040 add to preset={latex}{
1041 use lualatex,
1042 % create a new placeholder containing the name of the current font:
1043 set placeholder eval={__MY_FONT__}{\myCurrentFont},
1044 add to preamble={
1045 \usepackage{fontspec}
1046 \setmainfont{__MY_FONT__}
1047 },
1048 },
1049 }
1050 \end{codeexample}
1051 If you want this to work on xelatex, you can either manually attribute a |NFSSFamily| name like:
1052 \begin{codeexample}[code only]
1053 \runHereAndInPreambleOfCachedFiles{
1054 \usepackage{fontspec}
1055 % need lualatex or xelatex to compile, make sure to use a different NFSSFamily for each new font you add here
1056 \setmainfont[NFSSFamily=tmsnr]{Times New Roman}
1057 }
1058 \end{codeexample}
1059 and use the above solution for lualatex (you can change the font with |\fontfamily{tmsnr}\selectfont|), or do instead something like this:
1060 \begin{codeexample}[code only]
1061 % Create a new command \mysetmainfont which forwards the font to the picture.
1062 \NewDocumentCommand{\mysetmainfont}{m}{%
1063 \def\myCurrentFont{#1}% Stores the name of the current font in \myCurrentFont
1064 \setmainfont{#1}%
1065 }
1066
1067 % Use mysetmainfont from now to change font:
1068 \mysetmainfont{Times New Roman}
1069
1070 \usepackage{robust-externalize}
1071 \robExtConfigure{
1072 add to preset={latex}{
1073 use xelatex,
1074 set placeholder eval={__MY_FONT__}{\myCurrentFont},
1075 add to preamble={
1076 \usepackage{fontspec}
1077 \setmainfont{__MY_FONT__}
1078 },
1079 },
1080 }
1081 \end{codeexample}
1082
1083
1084
1085 \subsection{Compile in parallel}
1086 Make sure to have xargs installed (installed by default on most linux, on Windows you need to install the lightweight GNU On Windows (Gow) \url{https://github.com/bmatzelle/gow}), and type in your preamble:
1087 \begin{codeexample}[code only]
1088 \robExtConfigure{
1089 compile in parallel
1090 }
1091 \end{codeexample}
1092 to compile all figures in parallel (you need to compile your document twice). Your document should build significantly faster, possibly faster than a normal run. If you want to compile in parallel
1093 only if you have more than, say, 5 new elements to cache, do:
1094 \begin{codeexample}[code only]
1095 \robExtConfigure{
1096 compile in parallel after=5
1097 }
1098 \end{codeexample}
1099
1100 \subsection{Compile a preset}\label{sec:compilePreset}
1101
1102 Long story short: you can compile even faster (around 1.5x in our tests) by compiling presets, but beware that you will not be able to modify the placeholders except |add to preamble| with the default compiler we provide:
1103
1104 \begin{codeexample}[vbox]
1105 % We create a latex-based preset and compile it
1106 \robExtConfigure{
1107 new preset={templateZX}{
1108 latex,
1109 add to preamble={
1110 \usepackage{tikz}
1111 \usepackage{tikz-cd}
1112 \usepackage{zx-calculus}
1113 },
1114 %% possibly add some dependencies
1115 },
1116 % We compile it into a new preset
1117 new compiled preset={compiled ZX}{templateZX, compile latex template}{},
1118 }
1119
1120 % we use that preset automatically for ZX environments
1121 \cacheEnvironment{ZX}{compiled ZX}
1122 \cacheCommand{zx}{compiled ZX}
1123
1124 % Usage: (you can't use placeholders except for the preamble, trade-off of the compiled template)
1125 \begin{ZX}<add to preamble={\def\sayHey#1{Hey #1!}}>
1126 \zxX{\sayHey{Bob}}
1127 \end{ZX}
1128 \end{codeexample}
1129
1130 For details, see \cref{sec:compileFaster}.
1131
1132 \subsection{For non-\LaTeX{} code}
1133
1134 Due to the way \LaTeX{} works, non-\LaTeX{} code can't be reliably read inside macros and some environments that parse their body (e.g. align) as some characters are removed (e.g. percent symbols are comments and are removed). For this reason, we sometimes need to separate the time where we define the code and where we insert it (this is done using placeholders, see |PlaceholderFromCode|), and we need to introduce new environments to populate the template (see \cref{sec:placeholders} for more details, to generate them from filename, to get the path of a file etc).
1135
1136 The environment |CacheMeCode| can be used for this purpose.
1137
1138 \subsubsection{Python code}
1139 Note that if you use a version before 2.7, you cannot indent the python code (i.e. the first line must not start with any space).
1140
1141 \paragraph{Generate an image}
1142
1143 For instance, you can use the default |python| template to generate an image with python. The following code:
1144
1145
1146 \begin{codeexample}[code only]
1147 \begin{CacheMeCode}{python, set includegraphics options={width=.8\linewidth}}
1148 import matplotlib.pyplot as plt
1149 year = [2014, 2015, 2016, 2017, 2018, 2019]
1150 tutorial_count = [39, 117, 111, 110, 67, 29]
1151 plt.plot(year, tutorial_count, color="#6c3376", linewidth=3)
1152 plt.xlabel('Year')
1153 plt.ylabel('Number of futurestud.io Tutorials')
1154 plt.savefig("__ROBEXT_OUTPUT_PDF__")
1155 \end{CacheMeCode}
1156 \end{codeexample}
1157
1158 will produce the image visible in \cref{fig:pythonGeneratedImage}.
1159 \begin{figure}
1160 \centering
1161 \begin{CacheMeCode}{python, set includegraphics options={width=.8\linewidth}}
1162 import matplotlib.pyplot as plt
1163 year = [2014, 2015, 2016, 2017, 2018, 2019]
1164 tutorial_count = [39, 117, 111, 110, 67, 29]
1165 plt.plot(year, tutorial_count, color="#6c3376", linewidth=3)
1166 plt.xlabel('Year')
1167 plt.ylabel('Number of futurestud.io Tutorials')
1168 plt.savefig("__ROBEXT_OUTPUT_PDF__")
1169 \end{CacheMeCode}
1170 \caption{Image generated with python.}
1171 \label{fig:pythonGeneratedImage}
1172 \end{figure}
1173
1174 \paragraph{Compute a value}
1175
1176 We also provide by default a number of helper functions. For instance, |write_to_out(text)| will write |text| to the |*-out.tex| file that is loaded automatically by \LaTeX{}. This is useful to compute data that is not an image (note that |r"some string"| does not consider backslash as an escape string, which is handy to write \LaTeX{} code in python):
1177
1178 For instance:
1179 \begin{codeAndResult}
1180 \begin{CacheMeCode}{python, do not include pdf}
1181 import math
1182 write_to_out(r"\gdef\cosComputedInPython{" + str(math.cos(1)) + r"}")
1183 \end{CacheMeCode}
1184
1185 $\rightarrow$ The cosinus of 1 is \cosComputedInPython.
1186 \end{codeAndResult}
1187
1188 \paragraph{Improve an existing preset}
1189
1190 If you often use the same code (e.g.\ load matplotlib, save the file etc), you can directly modify the |__ROBEXT_MAIN_CONTENT__| placeholder to add the redundant information (or create a new template from scratch, see below). By default, it points to |__ROBEXT_MAIN_CONTENT_ORIG__| that contains directly the code typed by the user (this is true for all presets, as |CacheMe*| is in charge of setting this placeholder). When dealing with \LaTeX{} code, |__ROBEXT_MAIN_CONTENT__| should ideally contain a code that can be inserted as-it in the document in order to be compatible by default with |disable externalization|. So if you want to wrap the content of the user in an environment like |\begin{tikzpicture}...\end{tikzpicture}|, this is the placeholder to modify.
1191
1192 \begin{codeAndResult}
1193 %% Create your style:
1194 \begin{PlaceholderFromCode}{__MY_MATPLOTLIB_TEMPLATE_BEFORE__}
1195 import matplotlib.pyplot as plt
1196 import sys
1197 \end{PlaceholderFromCode}
1198
1199 \begin{PlaceholderFromCode}{__MY_MATPLOTLIB_TEMPLATE_AFTER__}
1200 plt.savefig("__ROBEXT_OUTPUT_PDF__")
1201 \end{PlaceholderFromCode}
1202
1203 \robExtConfigure{
1204 new preset={my matplotlib}{
1205 python,
1206 add before placeholder no space={__ROBEXT_MAIN_CONTENT__}{__MY_MATPLOTLIB_TEMPLATE_BEFORE__},
1207 add to placeholder no space={__ROBEXT_MAIN_CONTENT__}{__MY_MATPLOTLIB_TEMPLATE_AFTER__},
1208 },
1209 }
1210
1211 %% Use your style:
1212 %% See, you don't need to load matplotlib or save the file:
1213 \begin{CacheMeCode}{my matplotlib, set includegraphics options={width=.5\linewidth}}
1214 year = [2014, 2015, 2016, 2017, 2018, 2019]
1215 tutorial_count = [39, 117, 111, 110, 67, 29]
1216 plt.plot(year, tutorial_count, color="#6c3376", linewidth=3)
1217 plt.xlabel('Year')
1218 plt.ylabel('Number of futurestud.io Tutorials')
1219 \end{CacheMeCode}
1220 \end{codeAndResult}
1221
1222 \paragraph{Custom parameters and placeholders}
1223
1224 Let us say that you would like to define a default font size for your figure, but that you would like to allow the user to change this font size. Then, you should create a new placeholder with your default value, and use |set placeholder| to change this value later (see also the documentation of |CacheMeCode| to see how to create a new command to avoid typing |set placeholder|):
1225
1226 \begin{codeAndResult}
1227 %% Create your style:
1228
1229 \begin{PlaceholderFromCode}{__MY_MATPLOTLIB_TEMPLATE_BEFORE__}
1230 import matplotlib as mpl
1231 import matplotlib.pyplot as plt
1232 import sys
1233 mpl.rcParams['font.size'] = __MY_MATPLOTLIB_FONT_SIZE__
1234 \end{PlaceholderFromCode}
1235
1236 \begin{PlaceholderFromCode}{__MY_MATPLOTLIB_TEMPLATE_AFTER__}
1237 plt.savefig("__ROBEXT_OUTPUT_PDF__")
1238 \end{PlaceholderFromCode}
1239
1240 \robExtConfigure{
1241 new preset={my matplotlib}{
1242 python,
1243 % We create a new placeholder (it is simple enough that you don't need to use PlaceholderFromCode)
1244 set placeholder={__MY_MATPLOTLIB_FONT_SIZE__}{12},
1245 add before placeholder no space={__ROBEXT_MAIN_CONTENT__}{__MY_MATPLOTLIB_TEMPLATE_BEFORE__},
1246 add to placeholder no space={__ROBEXT_MAIN_CONTENT__}{__MY_MATPLOTLIB_TEMPLATE_AFTER__},
1247 },
1248 }
1249
1250 %% Use your style:
1251 %% See, you don't need to load matplotlib or save the file:
1252 Default font size: \begin{CacheMeCode}{my matplotlib, set includegraphics options={width=.5\linewidth}}
1253 year = [2014, 2015, 2016, 2017, 2018, 2019]
1254 tutorial_count = [39, 117, 111, 110, 67, 29]
1255 plt.plot(year, tutorial_count, color="#6c3376", linewidth=3)
1256 plt.xlabel('Year')
1257 plt.ylabel('Number of futurestud.io Tutorials')
1258 \end{CacheMeCode}
1259
1260 With font size 16:
1261 \begin{CacheMeCode}{my matplotlib,
1262 set includegraphics options={width=.5\linewidth},
1263 set placeholder={__MY_MATPLOTLIB_FONT_SIZE__}{16}}
1264 year = [2014, 2015, 2016, 2017, 2018, 2019]
1265 tutorial_count = [39, 117, 111, 110, 67, 29]
1266 plt.plot(year, tutorial_count, color="#6c3376", linewidth=3)
1267 plt.xlabel('Year')
1268 plt.ylabel('Number of futurestud.io Tutorials')
1269 \end{CacheMeCode}
1270 \end{codeAndResult}
1271
1272 Note that if you manage to move all the code in the template and that the user can configure everything using the options and an empty content, you can use |CacheMeNoContent| that takes no argument and that consider its body as the options.
1273
1274 \paragraph{Custom include command}
1275
1276 There may be some cases where you do not want to include a picture. We already saw the option |do not include pdf| if you do not want to include anything. But you can customize the include function, using notably:\\
1277 |custom include command={your include command}|
1278
1279 For instance, let us say that you would like to display both the source code used to obtain a given code, together with the output of this code. Then, you can write this style:
1280
1281 \begin{codeexample}[code only]
1282 {
1283 %% Create your style:
1284 \begin{PlaceholderFromCode}{__MY_PRINT_BOTH_TEMPLATE_BEFORE__}
1285 # File where print("bla") should be redirected
1286 # get_filename_from_extension("-foo.txt") will give you the path of the file
1287 # in the cache that looks like robExt-somehash-foo.txt
1288 print_file = open(get_filename_from_extension("-print.txt"), "w")
1289 sys.stdout = print_file
1290 # This code will read the current code, and extract the lines between
1291 # that starts with "### CODESTARTSHERE" and "### CODESTOPSHERE", and will write
1292 # it into the *-code.text (we do not want to print all these functions in
1293 # the final code)
1294 with open(get_filename_from_extension("-code.txt"), "w") as f:
1295 # The current script has extension .tex
1296 with open(get_current_script(), "r") as script:
1297 should_write = False
1298 for line in script:
1299 if line.startswith("### CODESTARTSHERE"):
1300 should_write = True
1301 elif line.startswith("### CODESTOPSHERE"):
1302 should_write = False
1303 elif "HIDEME" in line:
1304 pass
1305 else:
1306 if should_write:
1307 f.write(line)
1308 ### CODESTARTSHERE
1309 \end{PlaceholderFromCode}
1310
1311
1312 \begin{PlaceholderFromCode}{__MY_PRINT_BOTH_TEMPLATE_AFTER__}
1313 ### CODESTOPSHERE
1314 print_file.close()
1315 \end{PlaceholderFromCode}
1316
1317 \robExtConfigure{
1318 new preset={my python print both}{
1319 python,
1320 add before placeholder no space={__ROBEXT_MAIN_CONTENT__}{__MY_PRINT_BOTH_TEMPLATE_BEFORE__},
1321 add to placeholder no space={__ROBEXT_MAIN_CONTENT__}{__MY_PRINT_BOTH_TEMPLATE_AFTER__},
1322 set title/.style={
1323 set placeholder={__MY_TITLE__}{#1},
1324 },
1325 set title={Example},
1326 custom include command={
1327 % Useful to replace __MY_TITLE__:
1328 \evalPlaceholder{
1329 \begin{tcolorbox}[colback=red!5!white,colframe=red!75!black,title=__MY_TITLE__]
1330 \lstinputlisting[frame=single,
1331 breakindent=.5\textwidth,
1332 frame=single,
1333 breaklines=true,
1334 % On old distribution, this is called mypython
1335 style=pythonhighlight-style]{\robExtAddCachePathAndName{\robExtFinalHash-code.txt}}
1336 Output:
1337 \verbatiminput{\robExtAddCachePathAndName{\robExtFinalHash-print.txt}}
1338 \end{tcolorbox}
1339 }
1340 },
1341 },
1342 }
1343 \end{codeexample}
1344
1345 Once the style is defined (actually we already defined in the library under the name |python print code and result|), you can just write:
1346 \begin{codeexample}[code only]
1347 \begin{CacheMeCode}{my python print both, set title={The for loop}}
1348 for name in ["Alice", "Bob"]:
1349 print(f"Hello {name}")
1350 \end{CacheMeCode}
1351 \end{codeexample}
1352 to get:
1353 {
1354 %% Create your style:
1355 \begin{PlaceholderFromCode}{__MY_PRINT_BOTH_TEMPLATE_BEFORE__}
1356 # File where print("bla") should be redirected
1357 # get_filename_from_extension("-foo.txt") will give you the path of the file
1358 # in the cache that looks like robExt-somehash-foo.txt
1359 print_file = open(get_filename_from_extension("-print.txt"), "w")
1360 sys.stdout = print_file
1361 # This code will read the current code, and extract the lines between
1362 # that starts with "### CODESTARTSHERE" and "### CODESTOPSHERE", and will write
1363 # it into the *-code.text (we do not want to print all these functions in
1364 # the final code)
1365 with open(get_filename_from_extension("-code.txt"), "w") as f:
1366 # The current script has extension .tex
1367 with open(get_current_script(), "r") as script:
1368 should_write = False
1369 for line in script:
1370 if line.startswith("### CODESTARTSHERE"):
1371 should_write = True
1372 elif line.startswith("### CODESTOPSHERE"):
1373 should_write = False
1374 elif "HIDEME" in line:
1375 pass
1376 else:
1377 if should_write:
1378 f.write(line)
1379 ### CODESTARTSHERE
1380 \end{PlaceholderFromCode}
1381
1382
1383 \begin{PlaceholderFromCode}{__MY_PRINT_BOTH_TEMPLATE_AFTER__}
1384 ### CODESTOPSHERE
1385 print_file.close()
1386 \end{PlaceholderFromCode}
1387
1388 \robExtConfigure{
1389 new preset={my python print both}{
1390 python,
1391 add before placeholder no space={__ROBEXT_MAIN_CONTENT__}{__MY_PRINT_BOTH_TEMPLATE_BEFORE__},
1392 add to placeholder no space={__ROBEXT_MAIN_CONTENT__}{__MY_PRINT_BOTH_TEMPLATE_AFTER__},
1393 set title/.style={
1394 set placeholder={__MY_TITLE__}{#1},
1395 },
1396 set title={Example},
1397 custom include command={
1398 % Useful to replace __MY_TITLE__:
1399 \evalPlaceholder{
1400 \begin{tcolorbox}[colback=red!5!white,colframe=red!75!black,title=__MY_TITLE__]
1401 % \noindent Code:
1402 \lstinputlisting[frame=single,breakindent=.5\textwidth,frame=single,breaklines=true,style=pythonhighlight-style]{\robExtAddCachePathAndName{\robExtFinalHash-code.txt}}
1403 Output:
1404 \verbatiminput{\robExtAddCachePathAndName{\robExtFinalHash-print.txt}}
1405 \end{tcolorbox}
1406 }
1407 },
1408 },
1409 }
1410
1411 %% Use your style:
1412 \begin{CacheMeCode}{my python print both, set title={The for loop}}
1413 for name in ["Alice", "Bob"]:
1414 print(f"Hello {name}")
1415 \end{CacheMeCode}
1416 }
1417
1418 \subsubsection{Other languages}\label{sec:otherLanguages}
1419
1420 We also provide support for other languages, notably |bash|, but it is relatively easy to add basic support for any new language. You only need to configure |set compilation command| to your command, |set template| to the file to compile (|__ROBEXT_MAIN_CONTENT__| contains the code typed by the user), and possibly a custom include command with |custom include command| if you do not want to do |\includegraphics| on the final pdf. For instance, to define a basic template for bash, you just need to use:
1421
1422 \begin{codeAndResult}
1423 % Create your style
1424 \begin{PlaceholderFromCode}{__MY_BASH_TEMPLATE__}
1425 # Quit if there is an error
1426 set -e
1427 __ROBEXT_MAIN_CONTENT__
1428 # Create the pdf file to certify that no compilation error occured
1429 # (non empty file to avoid arXiv error)
1430 echo "ok" > "__ROBEXT_OUTPUT_PDF__"
1431 \end{PlaceholderFromCode}
1432
1433 \robExtConfigure{
1434 new preset={my bash}{
1435 set compilation command={bash "__ROBEXT_SOURCE_FILE__"},
1436 set template={__MY_BASH_TEMPLATE__},
1437 %%% Version 1:
1438 % verbatim output,
1439 %%% Version 2:
1440 custom include command={%
1441 \evalPlaceholder{%
1442 \verbatiminput{__ROBEXT_CACHE_FOLDER____ROBEXT_OUTPUT_PREFIX__-out.txt}%
1443 }%
1444 },
1445 % Ensure that the code does not break when externalization is disabled
1446 print verbatim if no externalization,
1447 }
1448 }
1449
1450 % Use your style
1451 \begin{CacheMeCode}{my bash}
1452 # Write the system conf to a file *-out.txt
1453 uname -srv > "__ROBEXT_OUTPUT_PREFIX__-out.txt"
1454 \end{CacheMeCode}
1455 \end{codeAndResult}
1456
1457
1458 \paragraph{Code inside a macro}
1459
1460 Due to fundamental \LaTeX{} restrictions, it is impossible to use |CacheMeCode| inside a macro or some environments as \LaTeX{} will strip all lines containing a percent character for instance. The solution here is to define our main content before, and then set it using |set main content| (that simply sets |__ROBEXT_MAIN_CONTENT_ORIG__|). In this example, we also show how |CacheMeNoContent| can be used when their is no content (the arguments to |CacheMe| are directly given in the body of |CacheMeNoContent|):
1461
1462 \begin{codeAndResult}
1463 \begin{PlaceholderFromCode}{__TMP_MAIN_CONTENT__}
1464 import matplotlib.pyplot as plt
1465 year = [2014, 2015, 2016, 2017, 2018, 2019]
1466 tutorial_count = [39, 117, 111, 110, 67, 29]
1467 plt.plot(year, tutorial_count, color="#6c3376", linewidth=3)
1468 plt.xlabel('Year')
1469 plt.ylabel('Number of futurestud.io Tutorials')
1470 plt.savefig("__ROBEXT_OUTPUT_PDF__")
1471 \end{PlaceholderFromCode}
1472
1473 \fbox{\begin{CacheMeNoContent}
1474 python,
1475 set includegraphics options={width=.8\linewidth},
1476 set main content={__TMP_MAIN_CONTENT__},
1477 \end{CacheMeNoContent}}
1478 \end{codeAndResult}
1479
1480 \subsection{Force to recompile or remove a cached item}
1481
1482 If you want to recompile a file (e.g. an untracked dependency was changed\dots{} and you do not want to track it to avoid recompilation when you change a single line in this file), you can use the |recompile| style since v2.1:
1483
1484 \begin{codeexample}[vbox,
1485 %TURN_INTO_CODE_ONLY_ARXIV
1486 ]
1487 \cacheEnvironment{tikzcd}{tikz, add to preamble={\usepackage{tikz-cd}}}
1488 \begin{tikzcd}<recompile>
1489 A \rar & B
1490 \end{tikzcd}
1491 \end{codeexample}
1492
1493 Note that this assumes that your compilation command is idempotent (so running it twice is like running it once) since the aux files are not cached. If you want to clean aux files or if you run an older version, see the documentation of |recompile| in \cref{sec:configureCompilationCommand}.
1494
1495 \section{Documentation}
1496
1497 Before starting this documentation, note that all commands are prefixed with |robExt| and all environments are prefixed with |RobExt|, but we also often define aliases without this prefix. The user is free to use any version, but we recommend to use the non-prefixed version unless a clash with a package forbids you from using it. In the following, we will only print the non-prefixed name when it exists. Note also that we follow the convention that environment names start with an upper case letter while commands start with a lower case letter.
1498
1499 \subsection{How it works}
1500
1501 This library must be able to generate 3 elements for any cached content:
1502 \begin{itemize}
1503 \item a source file, that will be compiled, and is obtained by expanding the placeholder |__ROBEXT_TEMPLATE__| (see \cref{sec:placeholders}),
1504 \item a compilation command obtained by expanding the placeholder |__ROBEXT_COMPILATION_COMMAND__|,
1505 \item a dependency file, that contains the hash of all the dependencies (see \cref{sec:dependencies} for details) and the compilation command,
1506 \item an inclusion command (this one is not used during the caching process, it is only used when including the compiled document in the main document), that you can set using |custom include command={your command}|.
1507 \end{itemize}
1508
1509 The hash of all these elements is computed in order to obtain a reference hash, denoted |somehash| that looks like a unique random value (note that |__ROBEXT_OUTPUT_PDF__| and alike are expanded after knowing the hash since they depend on the final hash value). This hash |somehash| will change whenever a dependency changes, or if the compilation command changes, ensuring purity. Then, the dependency file and the source file are written in the cache, by default in |robustExternalize/robExt-somehash.tex| and |robustExternalize/robExt-somehash.deps|. Then, the compilation command will be run from the cache folder. At the end, by default, we check if a file |robustExternalize/robExt-somehash.pdf| exists: if not we abort, otherwise we |\input| the file |robustExternalize/robExt-somehash-out.tex| and we run the include command (that includes the pdf by default). As we saw earlier, this command can be customized to use other files. \textbf{Importantly, all the files created during the compilation must be prefixed by} |robExt-somehash|, which can be obtained at runtime using |__ROBEXT_OUTPUT_PREFIX__|. This way, we can easily clean the cache while ensuring maximum purity.
1510
1511 In the following, we will denote by |*-foo.bar| the file in:\\
1512 |robustExternalize/robExt-somehash-foo.bar|.
1513
1514 Note also that we usually define two names for each function, one normal and one prefixed with |robExt| (or |RobExt|) for environments. In this documentation, we only write the first form, but the second form is kept in case a conflicting package redefines some functions.
1515
1516 \subsection{Placeholders}\label{sec:placeholders}
1517
1518 Placeholders are the main concept allowing this library to generate the content of a source file based on a template (a template will itself be a placeholder containing other placeholders). A placeholder is a special strings like |__COLOR_IMAGE__| that should start and end with two underscores, ideally containing no space or double underscores inside the name directly (we might use this property even more in a future release to improve further the efficiency). Placeholders are inserted for instance in a string and will be given a value later. This value will be used to replace (recursively) the placeholder in the template. For instance, if a placeholder |__LIKES__| contains |I like __FRUIT__ and __VEGETABLE__|, if the placeholder |__FRUIT__| contains |oranges| and if the placeholder |__VEGETABLE__| contains |salad|, then evaluating |__LIKES__| will output |I like oranges and salad.|
1519
1520 Note that you are not strictly forced to follow the above convention (it allows us to optimize the code to find and replace placeholders), but in that case you should enable |not all placeholders have underscores|.
1521
1522 Placeholders are local variables (internally just some \LaTeX{} 3 strings). You can therefore define a placeholder in a local group surrounded by brackets |{ ... }| if you want it to have a reduced scope.
1523
1524 \subsubsection{Reading a placeholder}
1525
1526 \begin{pgfmanualentry}
1527 \extractcommand\getPlaceholder\opt{\oarg{new placeholder name}}\marg{name placeholder or string}\@@
1528 \extractcommand\getPlaceholderInResult\opt{\oarg{new placeholder name}}\marg{name placeholder or string}\@@
1529 \extractcommand\getPlaceholderInResultFromList\marg{list,of,placeholders,to,replace}\opt{\oarg{new placeholder name}}\marg{name placeholder or string}\@@
1530 \pgfmanualbody
1531
1532 Get the value of a placeholder after replacing (recursively) all the inner placeholders. |\getPlaceholderInResult| puts the resulting string in a \LaTeX{} 3 string |\l_robExt_result_str| and in |\robExtResult|, while |\getPlaceholder| directly outputs this string. You can also put inside the argument
1533 any arbitrary string, allowing you, for instance, to concatenate multiple placeholders, copy a placeholder etc. Note that you will get a string, but this string will not be evaluated by \LaTeX{} (see |\evalPlaceholder| for that), for instance math will not be interpreted:
1534 \begin{codeexample}[width=0pt,vbox]
1535 \setPlaceholder{__MY_PLACEHOLDER__}{Hello __NAME__, I am a template $\delta_n$.}
1536 \setPlaceholder{__NAME__}{Alice __NICKNAME__}
1537 \setPlaceholder{__NICKNAME__}{the great}
1538 The placeholder evaluates to:\\
1539 \texttt{\getPlaceholder{__MY_PLACEHOLDER__}}\\
1540 Combining placeholders produces:\\
1541 \texttt{\getPlaceholder{In ``__MY_PLACEHOLDER__'', the name is __NAME__.}}
1542 \end{codeexample}
1543 You can also specify the optional argument in order to additionally define a new placeholder containing the resulting string (but you might prefer to use its alias |\setPlaceholderRec| described below):
1544 \begin{codeexample}[width=0pt,vbox]
1545 \setPlaceholder{__MY_PLACEHOLDER__}{Hello __NAME__, I am a template $\delta_n$.}
1546 \setPlaceholder{__NAME__}{Alice __NICKNAME__}
1547 \setPlaceholder{__NICKNAME__}{the great}
1548 \getPlaceholderInResult[__NEW_PLACEHOLDER__]{In ``__MY_PLACEHOLDER__'', the name is __NAME__.}
1549 \printImportedPlaceholdersExceptDefaults
1550 \end{codeexample}
1551 The variation |\getPlaceholderInResultFromList| allows you to specify a set of placeholder to replace from:
1552 \begin{codeexample}[width=0pt,vbox]
1553 \setPlaceholder{__MY_PLACEHOLDER__}{Hello __NAME1__, __NAME2__ and __NAME3__, I am a template $\delta_n$.}
1554 \setPlaceholder{__NAME1__}{Alice}
1555 \setPlaceholder{__NAME2__}{Bob}
1556 \setPlaceholder{__NAME3__}{Charlie}
1557 \getPlaceholderInResultReplaceFromList{__MY_PLACEHOLDER__,__NAME1__,__NAME2__}[__NEW_PLACEHOLDER__]{
1558 Here we go: __MY_PLACEHOLDER__
1559 }
1560 \printImportedPlaceholdersExceptDefaults
1561 \end{codeexample}
1562 \end{pgfmanualentry}
1563
1564
1565 \begin{pgfmanualentry}
1566 \extractcommand\evalPlaceholder\marg{name placeholder or string}\@@
1567 \pgfmanualbody
1568
1569 Evaluate the value of a placeholder after replacing (recursively) all the inner placeholders. You can also put inside any arbitrary string.
1570 \begin{codeexample}[width=0pt,vbox]
1571 \setPlaceholder{__MY_PLACEHOLDER__}{Hello __NAME__, I am a template $\delta_n$.}
1572 \setPlaceholder{__NAME__}{Alice __NICKNAME__}
1573 \setPlaceholder{__NICKNAME__}{the great}
1574 % The placeholder evaluates to \texttt{\getPlaceholder{__MY_PLACEHOLDER__}}.
1575 The placeholder evaluates to:\\
1576 \evalPlaceholder{__MY_PLACEHOLDER__}\\
1577 Combining placeholders produces:\\
1578 \evalPlaceholder{In ``__MY_PLACEHOLDER__'', the name is __NAME__.}
1579 \end{codeexample}
1580 \end{pgfmanualentry}
1581
1582 \subsubsection{List and debug placeholders}\label{sec:listAndDebugPlaceholders}
1583
1584 It can sometimes be handy to list all placeholders, print their contents etc (see also \cref{sec:debug}). We list here commands that are mostly useful for debugging purposes.
1585
1586 \begin{pgfmanualentry}
1587 \extractcommand\printImportedPlaceholdersExceptDefaults\opt{*}\@@
1588 \makeatletter%
1589 \def\extrakeytext{style, }
1590 \extractkey/robExt/print imported placeholders except default\@nil
1591 \makeatother%
1592 \pgfmanualbody
1593
1594 Prints the verbatim content of all defined and imported placeholders (without performing any replacement of inner placeholders), except for the placeholders that are defined by default in this library (that we identify as they start with |__ROBEXT_|). The stared version does print the name of the placeholder defined in this library, but not their definition. This is mostly for debugging purposes.
1595 \begin{codeexample}[width=0pt,vbox]
1596 \placeholderFromContent{__LIKES__}{Hello __NAME__ I am a really basic template $\delta_n$.}
1597 \placeholderFromContent{__NAME__}{Alice}
1598 \printImportedPlaceholdersExceptDefaults
1599 \end{codeexample}
1600 Compare with:
1601 \begin{codeexample}[width=0pt,vbox]
1602 \placeholderFromContent{__LIKES__}{Hello __NAME__ I am a really basic template $\delta_n$.}
1603 \placeholderFromContent{__NAME__}{Alice}
1604 \printImportedPlaceholdersExceptDefaults*
1605 \end{codeexample}
1606
1607 \end{pgfmanualentry}
1608
1609 \begin{pgfmanualentry}
1610 \extractcommand\printImportedPlaceholders\@@
1611 \makeatletter%
1612 \def\extrakeytext{style, }
1613 \extractkey/robExt/print imported placeholders\@nil
1614 \makeatother%
1615 \pgfmanualbody
1616
1617 Prints the verbatim content of all defined and imported placeholders (without performing any replacement of inner placeholders), including the placeholders that are defined by default in this library (those starting with |__ROBEXT_|). This is mostly for debugging purposes. Here is the result of |\printImportedPlaceholders|:
1618
1619 \printImportedPlaceholders
1620 \end{pgfmanualentry}
1621
1622 \begin{pgfmanualentry}
1623 \extractcommand\printPlaceholderNoReplacement\marg{name placeholder}\@@
1624 \pgfmanualbody
1625
1626 Prints the verbatim content of a given placeholder, without evaluating it and \textbf{without replacing inner placeholders: it is used mostly for debugging purposes} and will be used in this documentation to display the content of the placeholder for educational purposes. The stared version prints it inline.
1627 \begin{codeexample}[width=0pt,vbox]
1628 \placeholderFromContent{__LIKES__}{Hello __NAME__ I am a really basic template $\delta_n$.}
1629 \placeholderFromContent{__NAME__}{Alice}
1630 The (unexpanded) template contains \printPlaceholderNoReplacement{__LIKES__}.\\
1631 The (unexpanded) template contains \printPlaceholderNoReplacement*{__LIKES__}
1632 \end{codeexample}
1633 \end{pgfmanualentry}
1634
1635 \begin{pgfmanualentry}
1636 \extractcommand\printPlaceholder\marg{name placeholder}\@@
1637 \pgfmanualbody
1638
1639 Like |\printPlaceholderNoReplacement| except that it first replaces the inner placeholders. The stared version prints it inline.
1640 \begin{codeexample}[width=0pt,vbox]
1641 \placeholderFromContent{__LIKES__}{Hello __NAME__ I am a really basic template $\delta_n$.}
1642 \placeholderFromContent{__NAME__}{Alice}
1643 The (unexpanded) template contains \printPlaceholder{__LIKES__}.\\
1644 The (unexpanded) template contains \printPlaceholder*{__LIKES__}
1645 \end{codeexample}
1646 \end{pgfmanualentry}
1647
1648 \begin{pgfmanualentry}
1649 \extractcommand\evalPlaceholderNoReplacement\marg{name placeholder}\@@
1650 \pgfmanualbody
1651
1652 Evaluates the content of a given placeholder as a \LaTeX{} code, \textbf{without replacing the placeholders contained inside (mostly used for debugging purposes).}
1653 \begin{codeexample}[width=0pt,vbox]
1654 \placeholderFromContent{__LIKES__}{Hello I am a really basic template $\delta_n$.}
1655 The (unexpanded) template evaluates to ``\evalPlaceholderNoReplacement{__LIKES__}''.
1656 \end{codeexample}
1657 \end{pgfmanualentry}
1658
1659 \begin{pgfmanualentry}
1660 \extractcommand\rescanPlaceholderInVariableNoReplacement\marg{name macro}\marg{name placeholder}\@@
1661 \pgfmanualbody
1662 (new v2.0) Create a new macro that executes the \LaTeX{} code in the placeholder.
1663 \end{pgfmanualentry}
1664
1665 \begin{pgfmanualentry}
1666 \extractcommand\getPlaceholderNoReplacement\marg{name placeholder}\@@
1667 \pgfmanualbody
1668
1669 Like |\evalPlaceholderNoReplacement| except that it only outputs the string without evaluating the macros inside.
1670 \begin{codeexample}[width=0pt,vbox]
1671 \placeholderFromContent{__LIKES__}{Hello __NAME__ I am a really basic template $\delta_n$.}
1672 \placeholderFromContent{__NAME__}{Alice}
1673 The (unexpanded) template contains \texttt{\getPlaceholderNoReplacement{__LIKES__}}
1674 \end{codeexample}
1675 Note that this macro is expandable, which can be helpful for instance if you use |siunitx| that expects an expandable content:
1676 \begin{codeexample}[width=0pt,vbox]
1677 \setPlaceholder{__TEST__}{4.42345}
1678 \num[round-mode=figures,round-precision=3]{\getPlaceholderNoReplacement{__TEST__}}
1679 \end{codeexample}
1680 This is contrary to |\getPlaceholder| that is not expandable, so if you do want expandable |\getPlaceholder| with replacements, you should rather first evaluate the placeholder with |\getPlaceholderInResult{__TEST_VARIABLE__}|:
1681 \begin{codeexample}[width=0pt,vbox]
1682 \setPlaceholder{__TEST_A__}{4.42345}
1683 \setPlaceholder{__TEST__}{__TEST_A__}
1684 \getPlaceholderInResult{__TEST_A__}
1685 \num[round-mode=figures,round-precision=3]{\robExtResult}
1686 \end{codeexample}
1687 \end{pgfmanualentry}
1688
1689 \subsubsection{Setting a value to a placeholder}
1690
1691
1692 \begin{pgfmanualentry}
1693 \extractcommand\placeholderFromContent\opt{*}\marg{name placeholder}\marg{content placeholder}\@@
1694 \extractcommand\setPlaceholder\opt{*}\marg{name placeholder}\marg{content placeholder}\@@
1695 \makeatletter%
1696 \def\extrakeytext{style, }
1697 \extractkey/robExt/set placeholder=\marg{name placeholder}\marg{content placeholder}\@nil
1698 \extractkey/robExt/set placeholder no import=\marg{name placeholder}\marg{content placeholder}\@nil
1699 \extractkey/robExt/set placeholder from content=\marg{name placeholder}\marg{content placeholder}\@nil
1700 \makeatother%
1701 \pgfmanualbody
1702
1703 |\placeholderFromContent| (and its alias |\setPlaceholder| and its equivalent pgf styles |/robExt/set placeholder| and |/robExt/set placeholder from content|) is useful to set a value to a given placeholder.
1704 \begin{codeexample}[width=0pt,vbox]
1705 \placeholderFromContent{__LIKES__}{Hello I am a basic template with math $\delta_n$ and macros \hello}
1706 The (unexpanded) template contains \printPlaceholderNoReplacement{__LIKES__} and %
1707 after evaluation and setting the value of hello,%
1708 \def\hello{Hello my friend!}%
1709 you get ``\evalPlaceholder{__LIKES__}''.
1710 \end{codeexample}
1711 As you can see, \textbf{the precise content is not exactly identical to the original string}: \LaTeX{} comments are removed, spaces are added after macros, some newlines are removed etc. While this is usually not an issue when dealing with \LaTeX{} code, it causes some troubles when dealing with non-\LaTeX{} code. For this reason, we define \textbf{other commands} (see for instance |PlaceholderFromCode| below) that can accept verbatim content; the downside being that \LaTeX{} forbids usage of these verbatim commands inside other macros, so you should always define them at the top level (this seems to be fundamental to how \LaTeX{} works, as any input to a macro gets interpreted first as a \LaTeX{} string, losing all comments for instance). Note that this is not as restrictive as it may sound, as it is always possible to define the needed placeholders before any macro, while using them inside the macro, possibly combining them with other placeholders (defined either before or inside the macro).
1712 \end{pgfmanualentry}
1713
1714
1715 \begin{pgfmanualentry}
1716 \extractenvironement{PlaceholderFromCode}\opt{*}\opt{\oarg{style}}\marg{name placeholder}\@@
1717 \extractenvironement{SetPlaceholderCode}\opt{*}\opt{\oarg{style}}\marg{name placeholder}\@@
1718 \pgfmanualbody
1719
1720 These two (aliased) environments are useful to set a verbatim value to a given placeholder: the advantage is that you can put inside any code, including \LaTeX{} comments, the downside is that you cannot use it inside macros and some environments (so you typically define it before the macros and call it inside).
1721 % \begin{codeexample}[width=0pt,vbox]
1722 % \placeholderFromContent{__PYTHON_CODE__}{}
1723 % The (unexpanded) template contains \printPlaceholderNoReplacement{__LIKES__} and %
1724 % after evaluation (no replacement), you get ``\evalPlaceholderNoReplacement{__LIKES__}''.
1725 % \end{codeexample}
1726
1727 \begin{codeexample}[width=0pt,vbox]
1728 \begin{PlaceholderFromCode}{__PYTHON_CODE__}
1729 def my_function(b): # this is a python code
1730 c = {}
1731 d[42] = 0
1732 return b
1733 \end{PlaceholderFromCode}
1734 \printImportedPlaceholdersExceptDefaults
1735 \end{codeexample}
1736
1737
1738 Note that |PlaceholderFromCode| should not be used inside other macros or inside some environments (notably the ones that need to evaluate the body of the environment, e.g. using |+b| argument or |environ|) as verbatim content is parsed first by the macro, meaning that some characters might be changed or removed. For instance, any percent character would be considered as a comment, removing the rest of the line. However, this should not be be problem if you use it outside of any macro or environment, or if you load it from a file. For instance this code:
1739 \begin{verbatim}
1740 \begin{PlaceholderFromCode}{__PYTHON_CODE__}
1741 def my_function(b): # this is a python code
1742 c = {}
1743 d[42] = 0
1744 return b % 2
1745 \end{PlaceholderFromCode}
1746 \printImportedPlaceholdersExceptDefaults
1747 \end{verbatim}
1748 would produce:
1749
1750 {
1751 \begin{PlaceholderFromCode}{__PYTHON_CODE__}
1752 def my_function(b): # this is a python code
1753 c = {}
1754 d[42] = 0
1755 return b % 2
1756 \end{PlaceholderFromCode}
1757 \begin{codeexample}[width=0pt,vbox]
1758 \printImportedPlaceholdersExceptDefaults
1759 \end{codeexample}
1760 }
1761 Note that of course, you can define a placeholder before a macro and call it inside (explaining how we can generate this documentation).
1762
1763 You can use the optional style (only after 2.7; note that it defaults to |defaultPlaceholderFromCodeStyle|, which contains by default |remove leading spaces|) to apply some operations on the style. This way, by default, it will remove any leading indentation, allowing you, for instance, to indent your python code based on the surrounding LaTeX environment):
1764 \begin{codeAndResult}
1765 \begin{PlaceholderFromCode}{__TMP_MAIN_CONTENT__}
1766 # See, you can indent this code with two spaces without disturbing python (that expects no indentation)
1767 import matplotlib.pyplot as plt
1768 year = [2014, 2015, 2016, 2017, 2018, 2019]
1769 tutorial_count = [39, 117, 111, 110, 67, 29]
1770 plt.plot(year, tutorial_count, color="#6c3376", linewidth=3)
1771 plt.xlabel('Year')
1772 plt.ylabel('Number of futurestud.io Tutorials')
1773 plt.savefig("__ROBEXT_OUTPUT_PDF__")
1774 \end{PlaceholderFromCode}
1775
1776 \fbox{\begin{CacheMeNoContent}
1777 python,
1778 set includegraphics options={width=.8\linewidth},
1779 set main content={__TMP_MAIN_CONTENT__},
1780 \end{CacheMeNoContent}}
1781 \end{codeAndResult}
1782
1783
1784 Note that the star and no import version does NOT import the placeholder it the main group (unless you try to optimize the compilation time you should not need it, but see \cref{sec:importSystem} for details).
1785 \end{pgfmanualentry}
1786
1787 \begin{pgfmanualentry}
1788 \extractcommand\placeholderPathFromFilename\opt{*}\marg{name placeholder}\marg{filename}\@@
1789 \makeatletter%
1790 \def\extrakeytext{style, }
1791 \extractkey/robExt/set placeholder path from filename=\marg{name placeholder}\marg{filename}\@nil
1792 \makeatother%
1793 \pgfmanualbody
1794
1795 |\placeholderPathFromFilename{__MYLIB__}{mylib.py}| will copy |mylib.py| in the cache (setting its hash depending on its content), and set the content of the placeholder |__MYLIB__| to the \textbf{path} of the library in the cache. Note that the path is relative to the cache folder (it is easier to use for instance if you want to call this library from a code already in the cache).
1796 \begin{codeexample}[width=0pt,vbox]
1797 \placeholderPathFromFilename{__MYLIB__}{mylib.py}
1798 \printImportedPlaceholdersExceptDefaults
1799 You can also get the path relative to the root folder:\\
1800 \robExtAddCachePath{\getPlaceholderNoReplacement{__MYLIB__}}
1801 \end{codeexample}
1802 Note that the star and no import version does NOT import the placeholder it the main group (unless you try to optimize the compilation time you should not need it, but see \cref{sec:importSystem} for details).
1803 \end{pgfmanualentry}
1804
1805
1806 \begin{pgfmanualentry}
1807 \extractcommand\placeholderFromFileContent\opt{*}\marg{name placeholder}\marg{filename}\@@
1808 \makeatletter%
1809 \def\extrakeytext{style, }
1810 \extractkey/robExt/set placeholder from file content=\marg{name placeholder}\marg{filename}\@nil
1811 \extractkey/robExt/set placeholder from file content no import=\marg{name placeholder}\marg{filename}\@nil
1812 \makeatother%
1813 \pgfmanualbody
1814
1815 |\placeholderFromFileContent{__MYLIB__}{mylib.py}| will set the content of the placeholder |__MYLIB__| to the content of |mylib.py|.
1816 \begin{codeexample}[width=0pt,vbox]
1817 \placeholderFromFileContent{__MYLIB__}{mylib.py}
1818 \printImportedPlaceholdersExceptDefaults
1819 \end{codeexample}
1820 Note that the star and no import version does NOT import the placeholder it the main group (unless you try to optimize the compilation time you should not need it, but see \cref{sec:importSystem} for details).
1821 \end{pgfmanualentry}
1822
1823 \begin{pgfmanualentry}
1824 \extractcommand\placeholderPathFromContent\opt{*}\marg{name placeholder}\opt{\oarg{suffix}}\marg{content}\@@
1825 \makeatletter%
1826 \def\extrakeytext{style, }
1827 \extractkey/robExt/set placeholder path from content=\marg{name placeholder}\marg{suffix}\marg{content}\@nil
1828 \extractkey/robExt/set placeholder path from content no import=\marg{name placeholder}\marg{suffix}\marg{content}\@nil
1829 \makeatother%
1830 \pgfmanualbody
1831
1832 |\placeholderPathFromContent{__MYLIB__}{some content}| will copy |some content| in a file in the cache (setting its hash depending on its content, the filename will end with |suffix| that defaults to |.tex|), and set the content of the placeholder |__MYLIB__| to the \textbf{path} of the file in the cache. Note that the path is relative to the cache folder (it is easier to use for instance if you want to call this library from a code already in the cache).
1833 \begin{codeexample}[width=0pt,vbox]
1834 \placeholderPathFromContent{__MYLIB__}[.py]{some contents b}
1835 \printImportedPlaceholdersExceptDefaults
1836 You can also get the path relative to the root folder:\\
1837 \robExtAddCachePath{\getPlaceholderNoReplacement{__MYLIB__}}\\
1838 As a sanity check, this file contains
1839 \verbatiminput{\robExtAddCachePath{\getPlaceholderNoReplacement{__MYLIB__}}}
1840 \end{codeexample}
1841 Note that the star and no import version does NOT import the placeholder it the main group (unless you try to optimize the compilation time you should not need it, but see \cref{sec:importSystem} for details).
1842 \end{pgfmanualentry}
1843
1844 \begin{pgfmanualentry}
1845 \extractenvironement{PlaceholderPathFromCode}\opt{*}\opt{\oarg{suffix}}\marg{name placeholder}\@@
1846 \pgfmanualbody
1847
1848 This environment is similar to |\placeholderPathFromContent| except that it accepts verbatim code (therefore \LaTeX{} comments, newlines etc. will not be removed). However, due to \LaTeX{} limitations, this environment cannot be used inside macros or some environments, or this property will not be preserved.
1849 For instance, if you create your placeholder using:
1850 \begin{verbatim}
1851 \begin{PlaceholderPathFromCode}[.py]{__MYLIB__}
1852 def my_function(b): # this is a python code
1853 c = {}
1854 d[42] = 0
1855 return b % 2
1856 \end{PlaceholderPathFromCode}
1857 \end{verbatim}
1858 %% The code cannot be placed inside codeexample as it needs to parse the body:
1859 \begin{PlaceholderPathFromCode}[.py]{__MYLIB__}
1860 def my_function(b): # this is a python code
1861 c = {}
1862 d[42] = 0
1863 return b % 2
1864 \end{PlaceholderPathFromCode}
1865 You can then use it like:
1866 \begin{codeexample}[width=0pt,vbox]
1867 \printImportedPlaceholdersExceptDefaults
1868 You can also get the path relative to the root folder:\\
1869 \robExtAddCachePath{\getPlaceholderNoReplacement{__MYLIB__}}\\
1870 As a sanity check, this file contains
1871 \verbatiminput{\robExtAddCachePath{\getPlaceholderNoReplacement{__MYLIB__}}}
1872 \end{codeexample}
1873 Note that the star version does NOT import the placeholder it the main group (unless you try to optimize the compilation time you should not need it, but see \cref{sec:importSystem} for details).
1874 \end{pgfmanualentry}
1875
1876
1877 \begin{pgfmanualentry}
1878 \extractcommand\copyPlaceholder\opt{*}\marg{new placeholder}\marg{old placeholder}\@@
1879 \makeatletter%
1880 \def\extrakeytext{style, }
1881 \extractkey/robExt/copy placeholder=\marg{new placeholder}\marg{old placeholder}\@nil
1882 \extractkey/robExt/copy placeholder no import=\marg{new placeholder}\marg{old placeholder}\@nil
1883 \makeatother%
1884 \pgfmanualbody
1885
1886 This creates a new placeholder with the content of |old placeholder|. Note that this is different from:\\
1887 |\setPlaceholder{new placeholder}{old placeholder}|\\
1888 because if we modify |old placeholder|, this will not affect |new placeholder|.
1889 \begin{codeexample}[width=0pt,vbox]
1890 \setPlaceholder{__MY_CONTENT__}{Some content}
1891 \copyPlaceholder{__MY_OLD_CONTENT__}{__MY_CONTENT__}
1892 \setPlaceholder{__MY_CONTENT__}{The content used to be __MY_OLD_CONTENT__}
1893 \printImportedPlaceholdersExceptDefaults
1894 \end{codeexample}
1895 Note that the star and no import version does NOT import the placeholder it the main group (unless you try to optimize the compilation time you should not need it, but see \cref{sec:importSystem} for details).
1896 \end{pgfmanualentry}
1897
1898 Now, we see how we can define a placeholder recursively, by giving it a value based on its previous value (useful for instance in order to add stuff to it).
1899
1900 \begin{pgfmanualentry}
1901 \extractcommand\setPlaceholderRec\marg{new placeholder}\marg{content with placeholder}\@@
1902 \extractcommand\setPlaceholderRecReplaceFromList\marg{list,of,placeholder,to,replace}\marg{new placeholder}\marg{content with placeholder}\@@
1903 \makeatletter%
1904 \def\extrakeytext{style, }
1905 \extractkey/robExt/set placeholder rec=\marg{name placeholder}\marg{content placeholder}\@nil
1906 \extractkey/robExt/set placeholder rec replace from list=\marg{list,of,placeholder,to,replace}\marg{name placeholder}\marg{content placeholder}\@nil
1907 \makeatother%
1908 \pgfmanualbody
1909
1910 |\setPlaceholderRec{foo}{bar}| is actually an alias for |\getPlaceholderInResult[foo]{bar}|. Note that contrary to |\setPlaceholder|, it recursively replaces all inner placeholders. This is particularly useful to add stuff to an existing (or not) placeholder:
1911 \begin{codeexample}[width=0pt,vbox]
1912 \setPlaceholderRec{__MY_COMMAND__}{pdflatex}
1913 \setPlaceholderRec{__MY_COMMAND__}{__MY_COMMAND__ myfile}
1914 \printImportedPlaceholdersExceptDefaults
1915 \end{codeexample}
1916 Note that the if the placeholder content contains at the end the placeholder name, we will automatically remove it to avoid infinite recursion at evaluation time. This has the benefit that you can add something to a placeholder even if this placeholder does not exists yet (in which case it will be understood as the empty string):
1917 \begin{codeexample}[width=0pt,vbox]
1918 \setPlaceholderRec{__COMMAND_ARGS__}{__COMMAND_ARGS__ -l}
1919 \setPlaceholderRec{__COMMAND_ARGS__}{__COMMAND_ARGS__ -s}
1920 \printImportedPlaceholdersExceptDefaults
1921 \end{codeexample}
1922 The variation |\setPlaceholderRecReplaceFromList| allows us to specify a subset of placeholder that will be allowed to be expanded, and is an alias for |\getPlaceholderInResultReplaceFromList| (except that the optional argument is mandatory):
1923 \begin{codeexample}[width=0pt,vbox]
1924 \placeholderFromContent{__MY_PLACEHOLDER__}{Hello __NAME1__, __NAME2__ and __NAME3__,
1925 I am a template $\delta_n$.
1926 }
1927 \placeholderFromContent{__NAME1__}{Alice}
1928 \placeholderFromContent{__NAME2__}{Bob}
1929 \placeholderFromContent{__NAME3__}{Charlie}
1930 \setPlaceholderRecReplaceFromList{__MY_PLACEHOLDER__,__NAME2__,__NAME3__}{__OTHER_PLACEHOLDER__}{
1931 Here we go: __MY_PLACEHOLDER__
1932 }
1933 \printImportedPlaceholdersExceptDefaults
1934 \end{codeexample}
1935 Note that the star and no import version does NOT import the placeholder it the main group (unless you try to optimize the compilation time you should not need it, but see \cref{sec:importSystem} for details).
1936 \end{pgfmanualentry}
1937
1938 Note that sometimes, you might not want to use |\setPlaceholderRec| to simply append some data to the placeholder as it will also evaluate the inner placeholders (meaning that you will not be able to redefine them later). For this reason, we also provide functions to add something to the placeholder without evaluating it first:
1939 \begin{pgfmanualentry}
1940 \extractcommand\addToPlaceholder\opt{*}\marg{placeholder}\marg{content to add}\@@
1941 \extractcommand\addToPlaceholderNoImport\opt{*}\marg{placeholder}\marg{content to add}\@@
1942 \extractcommand\addBeforePlaceholder\opt{*}\marg{placeholder}\marg{content to add}\@@
1943 \extractcommand\addBeforePlaceholderNoImport\opt{*}\marg{placeholder}\marg{content to add}\@@
1944 \makeatletter%
1945 \def\extrakeytext{style, }
1946 \extractkey/robExt/add to placeholder=\marg{name placeholder}\marg{content to add}\@nil
1947 \extractkey/robExt/add to placeholder no space=\marg{name placeholder}\marg{content to add}\@nil
1948 \extractkey/robExt/add before placeholder=\marg{name placeholder}\marg{content to add}\@nil
1949 \extractkey/robExt/add before placeholder no space=\marg{name placeholder}\marg{content to add}\@nil
1950 \extractkey/robExt/add before main content=\marg{name placeholder}\marg{content to add}\@nil
1951 \extractkey/robExt/add to placeholder no import=\marg{name placeholder}\marg{content to add}\@nil
1952 \extractkey/robExt/add to placeholder no space no import=\marg{name placeholder}\marg{content to add}\@nil
1953 \extractkey/robExt/add before placeholder no import=\marg{name placeholder}\marg{content to add}\@nil
1954 \extractkey/robExt/add before placeholder no space no import=\marg{name placeholder}\marg{content to add}\@nil
1955 \extractkey/robExt/add before main content no import=\marg{name placeholder}\marg{content to add}\@nil
1956 \makeatother%
1957 \pgfmanualbody
1958
1959 |\addToPlaceholder{foo}{bar}| adds |bar| at the end of the placeholder |foo| (by default it also adds a space, unless you use the star version), creating it if it does not exist (the |before| variants add the content\dots{} before).
1960 \begin{codeexample}[width=0pt,vbox]
1961 \setPlaceholder{__ENGINE__}{pdflatex}
1962 \setPlaceholder{__COMMAND__}{__ENGINE__ --option}
1963 \addToPlaceholder{__COMMAND__}{--other}
1964 \addToPlaceholder*{__COMMAND__}{-option}
1965 \addBeforePlaceholder{__COMMAND__}{time}
1966 \printImportedPlaceholdersExceptDefaults
1967 \end{codeexample}
1968 |add before main content| is a particular case where the placeholder is |__ROBEXT_MAIN_CONTENT__|. It is practical if you want to define for instance a macro, but in a way that even if you disable externalization, the command should still compile (if you define the macro in the preamble, it will not be added when disabling externalization). For instance:
1969 \begin{codeexample}[width=0pt,vbox]
1970 \robExtConfigure{
1971 new preset={my preset}{latex, add before main content={\def\hello#1{Hello #1.}}},
1972 }
1973 \cacheMe[my preset]{Here I am cached (\hello{Alice})} and \cacheMe[my preset, disable externalization]{Here I am not (\hello{Bob}).}
1974 \end{codeexample}
1975 The |no import| versions do not import the placeholder in the current group (only needed if you want to optimize the compilation time, see \cref{sec:importSystem} for details).
1976 \end{pgfmanualentry}
1977
1978 \begin{pgfmanualentry}
1979 \extractcommand\placeholderFromString\opt{*}\marg{latex3 string}\@@
1980 \extractcommand\setPlaceholderFromString\opt{*}\marg{latex3 string}\@@
1981 \pgfmanualbody
1982 (new in v2.0) This allows you to assign an existing \LaTeX{}3 string to a placeholder (the star version does not import the placeholder, see \cref{sec:importSystem}).
1983 \begin{codeexample}[width=0pt,vbox]
1984 \ExplSyntaxOn
1985 \setPlaceholderFromString{__my_percent_string__}{\c_percent_str}
1986 \printImportedPlaceholdersExceptDefaults
1987 \ExplSyntaxOff
1988 \end{codeexample}
1989 We provide a list of placeholders that are useful to escape parts of the strings (but you should not really need them, if you need weird characters like percent, most of the time you want to use placeholderFromCode):
1990 \begin{codeexample}[width=0pt,vbox]
1991 \printPlaceholder{
1992 String containing
1993 __ROBEXT_LEFT_BRACE__,
1994 __ROBEXT_RIGHT_BRACE__,
1995 __ROBEXT_BACKSLASH__,
1996 __ROBEXT_HASH__,
1997 __ROBEXT_UNDERSCORE__,
1998 __ROBEXT_PERCENT__.
1999 }
2000 \end{codeexample}
2001 \end{pgfmanualentry}
2002
2003 \begin{pgfmanualentry}
2004 \extractcommand\placeholderReplaceInplace\marg{placeholder}\marg{from}\marg{to}\@@
2005 \extractcommand\placeholderReplaceInplaceEval\marg{placeholder}\marg{from}\marg{to}\@@
2006 \makeatletter%
2007 \def\extrakeytext{style, }
2008 \extractkey/robExt/placeholder replace in place=\marg{placeholder}\marg{from}\marg{to}\@nil
2009 \extractkey/robExt/placeholder replace in place eval=\marg{placeholder}\marg{from}\marg{to}\@nil
2010 \makeatother%
2011 \pgfmanualbody
2012 (new in v2.0) This allows you to replace a value in a placeholder. The |eval| variation first evaluates the string.
2013 \begin{codeexample}[width=0pt,vbox]
2014 \def\nameFrom{Bob}
2015 \def\nameTo{Dylan}
2016 \robExtConfigure{
2017 set placeholder={__NAMES__}{Hello Alice and Bob.},
2018 placeholder replace in place={__NAMES__}{Alice}{Charlie},
2019 placeholder replace in place eval={__NAMES__}{\nameFrom}{\nameTo},
2020 }
2021 \printImportedPlaceholdersExceptDefaults
2022 \end{codeexample}
2023 \end{pgfmanualentry}
2024
2025 \begin{pgfmanualentry}
2026 \extractcommand\placeholderRemoveSpacesUntil\marg{placeholder}\opt{\oarg{nb of additional letters to remove}}\marg{separator}\@@
2027 \makeatletter%
2028 \def\extrakeytext{style, }
2029 \extractkey/robExt/placeholder remove spaces until=\marg{placeholder}\marg{separator}\@nil
2030 \extractkey/robExt/remove spaces until=\marg{separator}\@nil
2031 \extractkey/robExt/placeholder strictly remove spaces until=\marg{placeholder}\marg{separator}\@nil
2032 \extractkey/robExt/strictly remove spaces until=\marg{separator}\@nil
2033 \makeatother%
2034 \pgfmanualbody
2035 (new in v2.6) Removes all the spaces before |separator|, together with the separator itself and the next character (unless you use the |strictly| version, in that case the next character is not dropped, or if you change the default value of |additional letters to remove| that defaults to 1). Note that |prepend all lines| automatically apply it to the |__ROBEXT_MAIN_CONTENT_ORIG__| placeholder, i.e. the text typed by the user.
2036
2037 This is useful, for instance, if your editor tends to automatically remove the indentation of your python code while indenting automatically the document.
2038 \begin{codeAndResult}
2039 %% See that the python code can be freely indented now:
2040 \begin{CacheMeCode}{python print code and result, remove spaces until={>>>}}
2041 >>> for i in range(2):
2042 >>> print(f"Hello {i}")
2043 \end{CacheMeCode}
2044 \end{codeAndResult}
2045 \end{pgfmanualentry}
2046
2047
2048 \begin{pgfmanualentry}
2049 \extractcommand\placeholderPrependAllLines\marg{placeholder}\marg{text}\@@
2050 \makeatletter%
2051 \def\extrakeytext{style, }
2052 \extractkey/robExt/placeholder prepend all lines=\marg{placeholder}\marg{text}\@nil
2053 \extractkey/robExt/prepend all lines=\marg{text}\@nil
2054 \makeatother%
2055 \pgfmanualbody
2056 (new in v2.6) Prepend all lines with |text|. This can be useful, for instance, if you want to indent a whole block of python code automatically. Note that the text is evaluated, so in case you want to insert multiple spaces, use |\space| like in:\\
2057 |prepend all lines={\space\space\space\space}|\\
2058 \begin{codeAndResult}
2059 \begin{PlaceholderFromCode}{__TMP__}
2060 >>> def f(x): % hye # 42
2061 >>> return 42
2062 >>>
2063 >>> def g(z):
2064 >>> return 48
2065 \end{PlaceholderFromCode}
2066 \placeholderRemoveSpacesUntil{__TMP__}{>>>}
2067 \placeholderPrependAllLines{__TMP__}{My text\space\space\space\space}
2068 \printPlaceholderNoReplacement{__TMP__}
2069 \end{codeAndResult}
2070 Note that |prepend all lines| automatically adds the text to the |__ROBEXT_MAIN_CONTENT_ORIG__| placeholder, i.e. the text typed by the user.
2071 \end{pgfmanualentry}
2072
2073 \begin{pgfmanualentry}
2074 \extractcommand\placeholderRemoveLeadingSpaces\marg{placeholder}\@@
2075 \makeatletter%
2076 \def\extrakeytext{style, }
2077 \extractkey/robExt/placeholder remove leading spaces=\marg{placeholder}\@nil
2078 \extractkey/robExt/remove leading spaces\@nil
2079 \extractkey/robExt/remove leading spaces if not disabled\@nil
2080 \extractkey/robExt/do not remove leading spaces\@nil
2081 \makeatother%
2082 \pgfmanualbody
2083 (new in v2.6) Remove the indentation of a placeholder (the |__ROBEXT_MAIN_CONTENT_ORIG__| placeholder, containing the content typed by the user, is used when not specified), by removing on each line the highest possible number of leading spaces (the same number of spaces is removed on all lines).
2084 \begin{codeAndResult}
2085 \begin{PlaceholderFromCode}{__TMP__}
2086 def f(x): % hye # 42
2087 return 42
2088
2089 def g(z):
2090 return 48
2091 \end{PlaceholderFromCode}
2092 \placeholderRemoveLeadingSpaces{__TMP__}
2093 \printPlaceholderNoReplacement{__TMP__}
2094 \end{codeAndResult}
2095 Note that |remove leading spaces if not disabled| is like |remove leading spaces|, except that it is not run if the |do not remove leading spaces| style is applied before. This is used inside some styles like |python| that cares about indentation to remove the leading spaces (before v2.6, it was forbidden to add any indentation to the python code), while allowing the user to disable it temporarily (who knows why?) by using the style:
2096 \begin{verbatim}
2097 do not remove leading spaces, python
2098 \end{verbatim}
2099 Since |remove leading spaces if not disabled| is enabled by default on python, it is therefore fine to indent your python code like in:
2100 \begin{codeAndResult}
2101 \begin{CacheMeCode}{python print code and result}
2102 for i in range(3):
2103 print(f"Hello {i}")
2104 \end{CacheMeCode}
2105 \end{codeAndResult}
2106 \end{pgfmanualentry}
2107
2108 \begin{pgfmanualentry}
2109 \extractcommand\placeholderHalveNumberHashesInplace\marg{placeholder}\@@
2110 \extractcommand\placeholderDoubleNumberHashesInplace\marg{placeholder}\@@
2111 \makeatletter%
2112 \def\extrakeytext{style, }
2113 \extractkey/robExt/placeholder halve number hashes in place=\marg{placeholder}\@nil
2114 \extractkey/robExt/placeholder double number hashes in place=\marg{placeholder}\@nil
2115 \makeatother%
2116 \pgfmanualbody
2117 (new in v2.0) This allows you to either turn any |##| into |#| or the other way around (may be practical when dealing with arguments to functions).
2118 \begin{codeexample}[width=0pt,vbox]
2119 \robExtConfigure{
2120 set placeholder={__DEMO__}{\def\hey##1{Hey ##1.}},
2121 placeholder halve number hashes in place={__DEMO__},
2122 }
2123 \printImportedPlaceholdersExceptDefaults
2124 \end{codeexample}
2125 \end{pgfmanualentry}
2126
2127 \begin{pgfmanualentry}
2128 \extractcommand\removePlaceholder\marg{placeholder}\@@
2129 \makeatletter%
2130 \def\extrakeytext{style, }
2131 \extractkey/robExt/remove placeholder=\marg{placeholder}\@nil
2132 \extractkey/robExt/remove placeholders=\marg{list,of,placeholder}\@nil
2133 \makeatother%
2134 \pgfmanualbody
2135 (new in v2.0) Remove placeholders.
2136 \begin{codeexample}[width=0pt,vbox]
2137 \robExtConfigure{
2138 set placeholder={__DEMOA__}{Alice},
2139 set placeholder={__DEMOB__}{Bob},
2140 set placeholder={__DEMOC__}{Charlie},
2141 remove placeholders={__DEMOA__,__DEMOC__},
2142 }
2143 \printImportedPlaceholdersExceptDefaults
2144 \end{codeexample}
2145 \end{pgfmanualentry}
2146
2147
2148
2149 \begin{pgfmanualentry}
2150 \extractcommand\evalPlaceholderInplace\marg{name placeholder}\@@
2151 \makeatletter%
2152 \def\extrakeytext{style, }
2153 \extractkey/robExt/eval placeholder inplace=\marg{name placeholder}\@nil
2154 \makeatother%
2155 \pgfmanualbody
2156 This command will update (inplace) the content of a macro by first replacing recursively the placeholders, and finally by expanding the \LaTeX{} macros.
2157 \begin{codeexample}[width=0pt,vbox]
2158 \def\mymacro{Initial value}
2159 \placeholderFromContent{__MACRO_NOT_EVALUATED__}{\mymacro}
2160 \placeholderFromContent{__MACRO_EVALUATED__}{\mymacro}
2161 \evalPlaceholderInplace{__MACRO_EVALUATED__}
2162 \printImportedPlaceholdersExceptDefaults
2163 \def\mymacro{Final value}
2164 Compare \evalPlaceholder{__MACRO_EVALUATED__} and \evalPlaceholder{__MACRO_NOT_EVALUATED__}.
2165 \end{codeexample}
2166 \end{pgfmanualentry}
2167
2168 \begin{pgfmanualentry}
2169 \makeatletter%
2170 \def\extrakeytext{style, }
2171 \extractkey/robExt/set placeholder eval=\marg{name placeholder}\marg{content placeholder}\@nil
2172 \makeatother%
2173 \pgfmanualbody
2174 Alias for |\setPlaceholderRec{#1}{#2}\evalPlaceholderInplace{#1}|: set and evaluate recursively the placeholders and macros. This can be practical to pass the value of a counter/macro to the template (of course, if this value is fixed, you can also directly load it from the preambule):
2175 \begin{codeexample}[width=0pt,vbox]
2176 \begin{CacheMe}{tikzpicture, set placeholder eval={__thepage__}{\thepage}}
2177 \node[rounded corners, fill=red]{The current page is __thepage__.};
2178 \end{CacheMe}
2179 \end{codeexample}
2180 Note that this works well for commands that expand completely, but some more complex commands might not expand properly (like |cref|). I need to investigate how to solve this issue, meanwhile you can still disable externalization for these pictures.
2181 \end{pgfmanualentry}
2182
2183 \begin{pgfmanualentry}
2184 \extractcommand\lenToCm\opt{\oarg{unit}}\marg{expression}\@@
2185 \extractcommand\lenToCmNoUnit\opt{\oarg{unit}}\marg{expression}\@@
2186 \pgfmanualbody
2187 |\lenToCm{.75\linewidth}| will output the length of |.75\linewidth| in cm by default, like |10cm|. If you want to change the unit, you can use the optional argument to specify a different unit (like |in| for inches, see |\dim_to_decimal_in_unit| for details). You can remove the unit at the end using |\lenToCmNoUnit{.75\linewidth}| (needs v2.6) to obtain something like |10| instead of |10cm|. These commands are helpful with |set placeholder eval| to send length from \LaTeX{} to your environment:
2188 \begin{codeAndResult}
2189 \begin{CacheMeCode}{python, set placeholder eval={__LINEWIDTH__}{\lenToCmNoUnit[in]{.75\linewidth}}}
2190 import matplotlib.pyplot as plt
2191 import matplotlib
2192 from matplotlib.pyplot import figure
2193 figure(figsize=(__LINEWIDTH__, __LINEWIDTH__))
2194 year = [2014, 2015, 2016, 2017, 2018, 2019]
2195 tutorial_count = [39, 117, 111, 110, 67, 29]
2196 plt.plot(year, tutorial_count, color="#6c3376", linewidth=2)
2197 plt.title("Simple plot")
2198 plt.xlabel('Year')
2199 plt.ylabel('Number of futurestud.io Tutorials')
2200 print(get_filename_from_extension(".pgf"))
2201 # https://stackoverflow.com/a/52587591/4987648
2202 plt.savefig("__ROBEXT_OUTPUT_PDF__", bbox_inches="tight")
2203 \end{CacheMeCode}
2204 \end{codeAndResult}
2205 \end{pgfmanualentry}
2206
2207 \subsubsection{Groups: the import system}\label{sec:importSystem}
2208
2209 (This whole system was added v2.0.)
2210
2211 In order to replace placeholders, we need to know their list, but to get the best possible performance we do not maintain a single list of all placeholders since \LaTeX{} is quite slow when doing list manipulations. Therefore, we group them inside smaller groups (e.g.\ one group for |latex|, one group for |python| etc), and the user is free to import groups. By default, new placeholders are imported inside the |main| group, and this group will be used when doing placeholder replacements. Note that for most of the case, we define a star variant of functions like |\setPlaceholder*{__FOO__}{bar}| (or |set placeholder no import| for styles) in order to create a placeholder without importing it (but this is certainly not used a lot by end users unless they want to make them even faster).
2212
2213 Note that basically all commands to create a placeholder have a command/environment where you add a star like |\setPlaceholder*{}| or a style where you add |no import| like |set placeholder no import| in order to create a placeholder that is not imported at all.
2214
2215 \begin{pgfmanualentry}
2216 \extractcommand\importPlaceholder\marg{name placeholder}\@@
2217 \extractcommand\importPlaceholdersFromGroup\marg{name placeholder}\@@
2218 \extractcommand\importAllPlaceholders\@@
2219 \extractcommand\importPlaceholderFirst\@@
2220 \makeatletter%
2221 \def\extrakeytext{style, }
2222 \extractkey/robExt/import placeholder=\marg{name placeholder}\@nil
2223 \extractkey/robExt/import placeholders from group=\marg{name group}\@nil
2224 \extractkey/robExt/import all placeholders\@nil
2225 \extractkey/robExt/import placeholder first=\marg{name placeholders}\@nil
2226 \makeatother%
2227 \pgfmanualbody
2228 Import placeholders, either individually, from a group of placeholders (exists either in style form or command), or from all registered groups (warning: you should avoid importing all placeholders if care too much about efficiency, as this can significantly slow down the replacement procedure). The |first| variant inserts the placeholder at the beginning of the import list, which can speed up compilation when this placeholder must be replaced first (but not so useful for basic usage).
2229 \begin{codeexample}[width=0pt,vbox]
2230 \robExtConfigure{
2231 set placeholder no import={__name__}{Alice},
2232 set placeholder no import={__name2__}{Bob},
2233 print imported placeholders except default,
2234 import placeholder={__name__},
2235 print imported placeholders except default,
2236 print imported placeholders,
2237 import placeholders from group={latex},
2238 print imported placeholders,
2239 }
2240 \end{codeexample}
2241
2242 \begin{codeexample}[width=0pt,vbox]
2243 \printPlaceholder{First try: __ROBEXT_LATEX_TRIM_LENGTH__}
2244 \importAllPlaceholders
2245 \printPlaceholder{Second try: __ROBEXT_LATEX_TRIM_LENGTH__}
2246 \end{codeexample}
2247 \end{pgfmanualentry}
2248
2249 \begin{pgfmanualentry}
2250 \extractcommand\clearImportedPlaceholders\marg{name placeholder}\@@
2251 \makeatletter%
2252 \def\extrakeytext{style, }
2253 \extractkey/robExt/clear imported placeholders\@nil
2254 \makeatother%
2255 \pgfmanualbody
2256 Clear all imported placeholders (comma separated list of placeholders)
2257 \begin{codeexample}[width=0pt,vbox]
2258 \robExtConfigure{
2259 set placeholder={__name__}{Alice},
2260 print imported placeholders except default,
2261 clear imported placeholders,
2262 print imported placeholders except default,
2263 }
2264 \end{codeexample}
2265 \end{pgfmanualentry}
2266
2267 \begin{pgfmanualentry}
2268 \extractcommand\removeImportedPlaceholder\marg{name placeholder}\@@
2269 \makeatletter%
2270 \def\extrakeytext{style, }
2271 \extractkey/robExt/remove imported placeholders\@nil
2272 \makeatother%
2273 \pgfmanualbody
2274 Comma separated list of placeholders to remove from the list of imported placeholders.
2275 \begin{codeexample}[width=0pt,vbox]
2276 \robExtConfigure{
2277 set placeholder={__name__}{Alice},
2278 set placeholder={__name2__}{Alice},
2279 print imported placeholders except default,
2280 remove imported placeholders={__name__,__name2__},
2281 print imported placeholders except default,
2282 }
2283 \end{codeexample}
2284 \end{pgfmanualentry}
2285
2286 \begin{pgfmanualentry}
2287 \extractcommand\printAllRegisteredGroups\@@
2288 \extractcommand\printAllRegisteredGroupsAndPlaceholders\opt{*}\@@
2289 \makeatletter%
2290 \def\extrakeytext{style, }
2291 \extractkey/robExt/print all registered groups\@nil
2292 \extractkey/robExt/print all registered groups and placeholders\@nil
2293 \extractkey/robExt/show all registered groups\@nil
2294 \extractkey/robExt/show all registered groups and placeholders\@nil
2295 \makeatother%
2296 \pgfmanualbody
2297 Print (or shows in the console for the alternative versions) all registered groups of placeholders (possibly with the placeholders they contain), mostly for debugging purpose, with the star prints also the content of the inner placeholders.
2298 \begin{codeexample}[width=0pt,vbox]
2299 \printAllRegisteredGroups
2300 \end{codeexample}
2301 \end{pgfmanualentry}
2302
2303 \begin{pgfmanualentry}
2304 \extractcommand\printGroupPlaceholders\opt{*}\@@
2305 \makeatletter%
2306 \def\extrakeytext{style, }
2307 \extractkey/robExt/print group placeholders=\marg{name group}\@nil
2308 \makeatother%
2309 \pgfmanualbody
2310 Print all placeholders (star = with content) of a given group.
2311 \begin{codeexample}[width=0pt,vbox]
2312 \printGroupPlaceholders*{bash}
2313 \end{codeexample}
2314 \end{pgfmanualentry}
2315
2316 \begin{pgfmanualentry}
2317 \extractcommand\printAllRegisteredGroupsAndPlaceholders\opt{*}\@@
2318 \pgfmanualbody
2319 Print all registered groups of placeholders with their inner content, mostly for debugging purpose, with the star prints only the content of the inner placeholders.
2320 \begin{codeexample}[width=0pt,vbox]
2321 \printAllRegisteredGroupsAndPlaceholders
2322 \end{codeexample}
2323 \end{pgfmanualentry}
2324
2325 \begin{pgfmanualentry}
2326 \extractcommand\newGroupPlaceholders\marg{name group}\@@
2327 \extractcommand\addPlaceholderToGroup\marg{name group}\marg{list,of,placeholders}\@@
2328 \extractcommand\addPlaceholdersToGroup\marg{name group}\marg{list,of,placeholders}\@@
2329 \extractcommand\removePlaceholderFromGroup\marg{name group}\marg{list,of,placeholders}\@@
2330 \extractcommand\removePlaceholdersFromGroup\marg{name group}\marg{list,of,placeholders}\@@
2331 \makeatletter%
2332 \def\extrakeytext{style, }
2333 \extractkey/robExt/new group placeholders=\marg{name group}\@nil
2334 \extractkey/robExt/add placeholder to group=\marg{name group}\marg{name placeholder}\@nil
2335 \extractkey/robExt/add placeholders to group=\marg{name group}\marg{list,of,placeholders}\@nil
2336 \extractkey/robExt/add placeholders to group=\marg{name group}\marg{list,of,placeholders}\@nil
2337 \extractkey/robExt/remove placeholders from group=\marg{name group}\marg{list,of,placeholders}\@nil
2338 \extractkey/robExt/remove placeholder from group=\marg{name group}\marg{list,of,placeholders}\@nil
2339 \makeatother%
2340 \pgfmanualbody
2341 Create a new group and add placeholders to it (you can put multiple placeholders separated by commas).
2342 \begin{codeAndResult}
2343 \robExtConfigure{
2344 new group placeholders={my dummy group},
2345 set placeholder no import={__name__}{Alice},
2346 add placeholders to group={my dummy group}{__name__},
2347 }
2348 \printGroupPlaceholders{my dummy group}
2349 \removePlaceholdersFromGroup{my dummy group}{__name__}
2350 \printGroupPlaceholders{my dummy group}
2351 \end{codeAndResult}
2352 \end{pgfmanualentry}
2353
2354 \begin{pgfmanualentry}
2355 \extractcommand\clearGroupPlaceholders\marg{name group}\@@
2356 \makeatletter%
2357 \def\extrakeytext{style, }
2358 % \extractkey/robExt/new group placeholders=\marg{name group}\@nil
2359 \makeatother%
2360 \pgfmanualbody
2361 Remove all elements in a group.
2362 \begin{codeexample}[vbox]
2363 \robExtConfigure{
2364 new group placeholders={my dummy group},
2365 set placeholder no import={__name__}{Alice},
2366 add placeholders to group={my dummy group}{__name__},
2367 }
2368 \clearGroupPlaceholders{my dummy group}
2369 \printGroupPlaceholders{my dummy group}
2370 \end{codeexample}
2371 \end{pgfmanualentry}
2372
2373
2374 \begin{pgfmanualentry}
2375 \extractcommand\copyGroupPlaceholders\marg{name group}\marg{name group to copy}\@@
2376 \makeatletter%
2377 \def\extrakeytext{style, }
2378 \extractkey/robExt/copy group placeholders=\marg{name group}\marg{name group to copy}\@nil
2379 \makeatother%
2380 \pgfmanualbody
2381 Remove all elements in a group.
2382 \begin{codeexample}[vbox]
2383 \robExtConfigure{
2384 new group placeholders={my dummy group},
2385 set placeholder no import={__name__}{Alice},
2386 add placeholders to group={my dummy group}{__name__},
2387 }
2388 \copyGroupPlaceholders{my copy}{my dummy group}
2389 \printGroupPlaceholders{my copy}
2390 \end{codeexample}
2391 \end{pgfmanualentry}
2392
2393 \begin{pgfmanualentry}
2394 \extractcommand\appendGroupPlaceholders\marg{name group}\marg{name group to append}\@@
2395 \extractcommand\appendBeforeGroupPlaceholders\marg{name group}\marg{name group to append}\@@
2396 \makeatletter%
2397 \def\extrakeytext{style, }
2398 \extractkey/robExt/append group placeholders=\marg{name group}\marg{name group to copy}\@nil
2399 \extractkey/robExt/append before group placeholders=\marg{name group}\marg{name group to copy}\@nil
2400 \makeatother%
2401 \pgfmanualbody
2402 Append a group to another group (after or before).
2403 \begin{codeexample}[vbox]
2404 \robExtConfigure{
2405 new group placeholders={my dummy group},
2406 set placeholder no import={__name__}{Alice},
2407 add placeholders to group={my dummy group}{__name__},
2408 new group placeholders={my dummy group2},
2409 set placeholder no import={__name2__}{Bob},
2410 add placeholders to group={my dummy group2}{__name2__},
2411 append group placeholders={my dummy group}{my dummy group2},
2412 }
2413 \printGroupPlaceholders{my dummy group}
2414 \end{codeexample}
2415 \end{pgfmanualentry}
2416
2417 \begin{pgfmanualentry}
2418 \extractcommand\importPlaceholdersFromGroup\marg{name group}\@@
2419 \extractcommand\importAllPlaceholders\@@
2420 \makeatletter%
2421 \def\extrakeytext{style, }
2422 \extractkey/robExt/import placeholders from group=\marg{name group}\@nil
2423 \extractkey/robExt/import all placeholders\@nil
2424 \makeatother%
2425 \pgfmanualbody
2426 Import a group/all registered groups (note that this is equivalent to appending to the group called |main|). Note that for the later, you should be sure that the group is ``registered'', which is the case if you created it via |new group placeholders|.
2427 \begin{codeexample}[vbox]
2428 \robExtConfigure{
2429 new group placeholders={my dummy group},
2430 set placeholder no import={__name__}{Alice},
2431 add placeholder to group={my dummy group}{__name__},
2432 import all placeholders,
2433 }
2434 \printImportedPlaceholdersExceptDefaults
2435 \end{codeexample}
2436 \end{pgfmanualentry}
2437
2438
2439 \subsection{Caching a content}
2440
2441 \subsubsection{Basics}
2442
2443 \begin{pgfmanualentry}
2444 \extractcommand\cacheMe\opt{\oarg{preset style}}\marg{content to cache}\@@
2445 \extractenvironement{CacheMe}\marg{preset style}\@@
2446 \pgfmanualbody
2447 This command (and its environment alias) is the main entry point if you want to cache the result of a file. The preset style is a pgfkeys-based style that is used to configure the template that is used, the compilation command, and more. You can either inline the style, or use some presets that configure the style automatically. After evaluating the style, the placeholders |__ROBEXT_TEMPLATE__| (containing the content of the file) and |__ROBEXT_COMPILATION_COMMAND__| (containing the compilation command run in the cache folder, that can use other placeholders internally like |__ROBEXT_SOURCE_FILE__| to get the path to the source file) should be set. Note that we provide some basic styles that allow settings these placeholders easily. See \cref{sec:placeholders} for a list of existing placeholders and presets. The placeholder |__ROBEXT_MAIN_CONTENT_ORIG__| will automatically be set by this command (or environment) so that it equals the content of the second argument (or the body of the environment). By default, |__ROBEXT_MAIN_CONTENT__| will point to |__ROBEXT_MAIN_CONTENT_ORIG__|, possibly wrapping it inside an environment like |\begin{tikzpicture}| (most of the time, you want to modify and display |__ROBEXT_MAIN_CONTENT__| rather than the |_ORIG_| to easily recover the input of the user). This style can also configure the command to use to include the file and more. By default it will insert the compiled PDF, making sure that the depth is respected (internally, we read the depth from an aux file created by our \LaTeX{} preset), but you can easily change it to anything you like.
2448
2449 For an educational purpose, we write here an example that does not exploit any preset. In practice, we recommend however to use our presets, or to define new presets based on our presets (see below for examples).
2450 \begin{codeexample}[width=0pt,vbox]
2451 \begin{CacheMe}{set template={
2452 \documentclass{standalone}
2453 \begin{document}
2454 __ROBEXT_MAIN_CONTENT__
2455 \end{document}
2456 },
2457 set compilation command={pdflatex -shell-escape -halt-on-error "__ROBEXT_SOURCE_FILE__"},
2458 custom include command={%
2459 \includegraphics[width=4cm,angle=45]{\robExtAddCachePathAndName{\robExtFinalHash.pdf}}%
2460 },
2461 }
2462 This content is cached $\delta$.
2463 \end{CacheMe}
2464 \end{codeexample}
2465 \end{pgfmanualentry}
2466
2467 \begin{pgfmanualentry}
2468 \extractcommand\robExtConfigure\marg{preset style}\@@
2469 \makeatletter%
2470 \def\extrakeytext{style, }
2471 \extractkey/robExt/new preset=\marg{name preset}\marg{preset options}\@nil
2472 \extractkey/robExt/add to preset=\marg{name preset}\marg{preset options}\@nil
2473 \extractkey/robExt/add before preset=\marg{name preset}\marg{preset options}\@nil
2474 \makeatother%
2475 \pgfmanualbody
2476 You can then create your own style (or preset) in |\robExtConfigure| (that is basically an alias for |\pgfkeys{/robExt/.cd,#1}|) containing your template, add your own placeholders and commands to configure them etc. We provide two helper functions since v2.0:\\
2477 |new preset={your preset}{your configuration}|\\
2478 and\\
2479 |add to preset={your preset}{your configuration}|\\
2480 in order to create/modify the presets. You can also use |my preset/.style| or\\
2481 |my preset/.append style|\\
2482 to configure them instead, but in that case make sure to double the number of hashes like in |\def\mymacro##1{hello ##1}|, as the |#1| in |\def\mymacro#1{hello #1}.| would be understood as the (non-existent) argument of |my preset|.
2483
2484 \begin{codeexample}[width=0pt,vbox]
2485 %% Define your presets once:
2486 \robExtConfigure{%
2487 new preset={my latex preset}{
2488 %% Create a default value for my new placeholders:
2489 set placeholder={__MY_COLOR__}{red},
2490 set placeholder={__MY_ANGLE__}{45},
2491 % We can also create custom commands to "hide" the notion of placeholder
2492 set my angle/.style={
2493 set placeholder={__MY_ANGLE__}{#1}
2494 },
2495 set template={
2496 \documentclass{standalone}
2497 \usepackage{xcolor}
2498 \begin{document}
2499 \color{__MY_COLOR__}__ROBEXT_MAIN_CONTENT__
2500 \end{document}
2501 },
2502 set compilation command={pdflatex -shell-escape -halt-on-error "__ROBEXT_SOURCE_FILE__"},
2503 custom include command={%
2504 % The include command is a regular LaTeX command, but using
2505 % \evalPlaceholder avoids the need to play with expandafter, getPlaceholder etc...
2506 \evalPlaceholder{%
2507 \includegraphics[width=4cm,angle=__MY_ANGLE__,origin=c]{%
2508 \robExtAddCachePathAndName{\robExtFinalHash.pdf}%
2509 }%
2510 }%
2511 },
2512 },
2513 }
2514
2515 % Reuse them later...
2516 \begin{CacheMe}{my latex preset}
2517 This content is cached $\delta$.
2518 \end{CacheMe}
2519 % And configure them at will
2520 \begin{CacheMe}{my latex preset, set placeholder={__MY_COLOR__}{green}, set my angle=-45}
2521 This content is cached $\delta$.
2522 \end{CacheMe}
2523 \end{codeexample}
2524 The |before| variation (from 2.6) simply adds the style before the existing style. May be useful to disable default options of a style.
2525 \end{pgfmanualentry}
2526
2527 \begin{pgfmanualentry}
2528 \extractenvironement{CacheMeCode}\marg{preset style}\@@
2529 \pgfmanualbody
2530 Like |CacheMe|, except that the code is read verbatim by \LaTeX{}. This way, you can put non-\LaTeX{} code inside safely, but you will not be able to use it inside a macro or some environments that read their body. Here is an example where we define an environment that automatically import matplotlib, save the figure, and insert it into a figure. Note that we define in this example new commands to type |set caption=foo| instead of |set placeholder={__FIG_CAPTION__}{foo}|.
2531 %% codeexample cannot deal with verbatim content
2532
2533 \begin{codeexample}[code only]
2534 %% Define the python code to use as a template
2535 %% (impossible to define it in \robExtConfigure directly since
2536 %% it is a verbatim environment)
2537 \begin{PlaceholderFromCode}{__MY_MATPLOTLIB_TEMPLATE__}
2538 import matplotlib.pyplot as plt
2539 import sys
2540 __ROBEXT_MAIN_CONTENT__
2541 plt.savefig("__ROBEXT_OUTPUT_PDF__")
2542 \end{PlaceholderFromCode}
2543
2544 % Create a new preset called matplotlib
2545 \robExtConfigure{
2546 new preset={matplotlib figure}{
2547 set template={__MY_MATPLOTLIB_TEMPLATE__},
2548 set compilation command={python "__ROBEXT_SOURCE_FILE__"},
2549 set caption/.style={
2550 set placeholder={__FIG_CAPTION__}{#1}
2551 },
2552 set label/.style={
2553 set placeholder={__FIG_LABEL__}{#1}
2554 },
2555 set includegraphics options/.style={
2556 set placeholder={__INCLUDEGRAPHICS_OPTIONS__}{#1}
2557 },
2558 set caption={},
2559 set label={},
2560 set includegraphics options={width=1cm},
2561 custom include command={%
2562 \evalPlaceholder{%
2563 \begin{figure}
2564 \centering
2565 \includegraphics[__INCLUDEGRAPHICS_OPTIONS__]{\robExtAddCachePathAndName{\robExtFinalHash.pdf}}%
2566 \caption{__FIG_CAPTION__a}
2567 \label{__FIG_LABEL__}
2568 \end{figure}%
2569 }%
2570 },
2571 },
2572 }
2573
2574 %% Use it
2575 \begin{CacheMeCode}{matplotlib figure, set includegraphics options={width=.8\linewidth}, set caption={Hello}}
2576 year = [2014, 2015, 2016, 2017, 2018, 2019]
2577 tutorial_count = [39, 117, 111, 110, 67, 29]
2578 plt.plot(year, tutorial_count, color="#6c3376", linewidth=3)
2579 plt.xlabel('Year')
2580 plt.ylabel('Number of futurestud.io Tutorials')
2581 \end{CacheMeCode}
2582 \end{codeexample}
2583
2584 %% Define the python code to use as a template
2585 %% (impossible to define it in \robExtConfigure directly since
2586 %% it is a verbatim environment)
2587 \begin{PlaceholderFromCode}{__MY_MATPLOTLIB_TEMPLATE__}
2588 import matplotlib.pyplot as plt
2589 import sys
2590 __ROBEXT_MAIN_CONTENT__
2591 plt.savefig("__ROBEXT_OUTPUT_PDF__")
2592 \end{PlaceholderFromCode}
2593
2594 % Create a new preset called matplotlib
2595 \robExtConfigure{
2596 new preset={matplotlib figure}{
2597 set template={__MY_MATPLOTLIB_TEMPLATE__},
2598 set compilation command={python "__ROBEXT_SOURCE_FILE__"},
2599 set caption/.style={
2600 set placeholder={__FIG_CAPTION__}{#1}
2601 },
2602 set label/.style={
2603 set placeholder={__FIG_LABEL__}{#1}
2604 },
2605 set includegraphics options/.style={
2606 set placeholder={__INCLUDEGRAPHICS_OPTIONS__}{#1}
2607 },
2608 set caption={},
2609 set label={},
2610 set includegraphics options={width=1cm},
2611 custom include command={%
2612 \evalPlaceholder{%
2613 \begin{figure}
2614 \centering
2615 \includegraphics[__INCLUDEGRAPHICS_OPTIONS__]{\robExtAddCachePathAndName{\robExtFinalHash.pdf}}%
2616 \caption{__FIG_CAPTION__}
2617 \label{__FIG_LABEL__}
2618 \end{figure}%
2619 }%
2620 },
2621 },
2622 }
2623
2624 %% Use it
2625 \begin{CacheMeCode}{matplotlib figure, set includegraphics options={width=.8\linewidth}, set caption={An example to show how matplotlib pictures can be inserted}}
2626 year = [2014, 2015, 2016, 2017, 2018, 2019]
2627 tutorial_count = [39, 117, 111, 110, 67, 29]
2628 plt.plot(year, tutorial_count, color="#6c3376", linewidth=3)
2629 plt.xlabel('Year')
2630 plt.ylabel('Number of futurestud.io Tutorials')
2631 \end{CacheMeCode}
2632
2633 Note that as we explained it before, due to \LaTeX{} limitations, it is impossible to call |CacheMeCode| inside macros and inside some environments that evaluate their body. To avoid that issue, it is always possible to define the macro before and call it inside. We will exemplify this on the previous example, but note that \textbf{this example is only for educational purposes} since the environment |figure| does not evaluate its body, and |CacheMeCode| can therefore safely be used inside without using this trickery:
2634 \begin{codeexample}[code only]
2635 %% Define the python code to use as a template
2636 %% (impossible to define it in \robExtConfigure directly since
2637 %% it is a verbatim environment)
2638 \begin{PlaceholderFromCode}{__MY_MATPLOTLIB_TEMPLATE__}
2639 import matplotlib.pyplot as plt
2640 import sys
2641 __ROBEXT_MAIN_CONTENT__
2642 plt.savefig("__ROBEXT_OUTPUT_PDF__")
2643 \end{PlaceholderFromCode}
2644
2645 % Create a new preset called matplotlib
2646 \robExtConfigure{
2647 new preset={matplotlib}{
2648 set template={__MY_MATPLOTLIB_TEMPLATE__},
2649 set compilation command={python "__ROBEXT_SOURCE_FILE__"},
2650 set includegraphics options/.style={
2651 set placeholder={__INCLUDEGRAPHICS_OPTIONS__}{#1}
2652 },
2653 set includegraphics options={width=1cm},
2654 custom include command={%
2655 \evalPlaceholder{%
2656 \includegraphics[__INCLUDEGRAPHICS_OPTIONS__]{\robExtAddCachePathAndName{\robExtFinalHash.pdf}}%
2657 }%
2658 },
2659 },
2660 }
2661
2662
2663 %% You cannot use CacheMeCode inside some macros or environments due to fundamental LaTeX limitations.
2664 %% But you can always define them before, and call them inside:
2665 \begin{SetPlaceholderCode}{__TMP__}
2666 year = [2014, 2015, 2016, 2017, 2018, 2019]
2667 tutorial_count = [39, 117, 111, 110, 67, 29]
2668 plt.plot(year, tutorial_count, color="#6c3376", linewidth=3)
2669 plt.xlabel('Year')
2670 plt.ylabel('Number of futurestud.io Tutorials')
2671 \end{SetPlaceholderCode}
2672
2673 \begin{figure}
2674 \centering
2675 \cacheMe[matplotlib, set includegraphics options={width=.8\linewidth}, set caption={Hello}]{__TMP__}
2676 \caption{An example to show how code can be inserted into macros or environments that evaluate their contents (this trick is actually not needed for figures)}
2677 \end{figure}
2678 \end{codeexample}
2679 \end{pgfmanualentry}
2680
2681
2682 \subsubsection{Options to configure the template}
2683
2684
2685 \begin{pgfmanualentry}
2686 \makeatletter%
2687 \def\extrakeytext{style, }
2688 \extractkey/robExt/set template=\marg{content template}\@nil
2689 \makeatother%
2690 \pgfmanualbody
2691 Style that alias to |set placeholder={__ROBEXT_TEMPLATE__}{#1}|, in order to define the placeholder that will hold the template of the final file.
2692 \end{pgfmanualentry}
2693
2694 \begin{pgfmanualentry}
2695 \makeatletter%
2696 \def\extrakeytext{style, }
2697 \extractkey/robExt/set template=\marg{content template}\@nil
2698 \makeatother%
2699 \pgfmanualbody
2700 Style that alias to |set placeholder={__ROBEXT_TEMPLATE__}{#1}|, in order to define the placeholder that will hold the template of the final file.
2701 \end{pgfmanualentry}
2702
2703 \subsubsection{Options to configure the compilation command}\label{sec:configureCompilationCommand}
2704
2705 \begin{pgfmanualentry}
2706 \makeatletter%
2707 \def\extrakeytext{style, }
2708 \extractkey/robExt/set compilation command=\marg{compilation command}\@nil
2709 \extractkey/robExt/set compilation command create if no error=\marg{compilation command}\@nil
2710 \extractkey/robExt/set compilation command move if no error=\marg{compilation command}\@nil
2711 \makeatother%
2712 \pgfmanualbody
2713 |set compilation command| is equivalent to |set placeholder={__ROBEXT_COMPILATION_COMMAND__}{#1}|, in order to define the placeholder that will hold the compilation command.
2714
2715 Then, |set compilation command move if no error| (new in v2.4)
2716 is like |set compilation command| except that it will copy the file located in |__ROBEXT_OUTPUT_PDF__-tmp| into |__ROBEXT_OUTPUT_PDF__| if the command succeeds (returns a status code of 0), and otherwise it will not create the |__ROBEXT_OUTPUT_PDF__| at all, creating an error message. This is needed by some programs that will create an output file even if an error occurs, for instance wget will still create an empty file if there is no internet connection, producing no error during the compilation, which can be confusing.
2717
2718 |set compilation command create if no error| (new in v2.4) will, on the other hand, create an empty |__ROBEXT_OUTPUT_PDF__| file if the command succeeds (only useful if you use a custom include command).
2719 \end{pgfmanualentry}
2720
2721 \begin{pgfmanualentry}
2722 \makeatletter%
2723 \def\extrakeytext{style, }
2724 \extractkey/robExt/add argument to compilation command=\marg{argument}\@nil
2725 \extractkey/robExt/add arguments to compilation command=\marg{argument}\@nil
2726 \makeatother%
2727 \pgfmanualbody
2728 |add argument to compilation command| is a style that alias to:\\
2729 |set placeholder={__ROBEXT_COMPILATION_COMMAND__}{__ROBEXT_COMPILATION_COMMAND__ "#1"}|
2730 in order to add an argument to the compilation command. |add arguments to compilation command| (note the |s|) accepts multiple arguments separated by a comma.
2731 \end{pgfmanualentry}
2732
2733 \begin{pgfmanualentry}
2734 \makeatletter%
2735 \def\extrakeytext{style, }
2736 \extractkey/robExt/add key value argument to compilation command=\marg{key=value}\@nil
2737 \makeatother%
2738 \pgfmanualbody
2739 Adds to the command line two arguments |key| and |value|. This is a way to quickly pass arguments to a script: the script just needs to loop over the arguments and consider the odd elements as keys and the next elements as the value. Another option is to insert some placeholders directly in the script.
2740 \end{pgfmanualentry}
2741
2742 \begin{pgfmanualentry}
2743 \makeatletter%
2744 \def\extrakeytext{style, }
2745 \extractkey/robExt/add key and file argument to compilation command=\marg{key=filename}\@nil
2746 \makeatother%
2747 \pgfmanualbody
2748 |filename| is the path to a file in the root folder. This adds, as:\\
2749 |add key value argument to compilation command|\\
2750 two arguments, where the first argument is the key, but this time the second argument is the path of |filename| relative to the cache folder (useful since scripts run from this folder). Moreover, it automatically ensures that when |filename| changes, the file gets recompiled. Note that contrary to some other commands, this does not copy the file in the cache, which is practical notably for large files like videos.
2751 \end{pgfmanualentry}
2752
2753 \begin{pgfmanualentry}
2754 \makeatletter%
2755 \def\extrakeytext{style, }
2756 \extractkey/robExt/force compilation\@nil
2757 \extractkey/robExt/do not force compilation\@nil
2758 \makeatother%
2759 \pgfmanualbody
2760 By default, we compile cached documents only if |-shell-escape| is enabled. However, if the user allowed |pdflatex| (needed to compile latex documents), |cd| (not needed when using |no cache folder|), and |mkdir| (not needed when using |no cache folder| or if the cache folder that defaults to |robustExternalize| is already created) to run in restricted mode (so without enabling |-shell-escape|), then there is no need for |-shell-escape|. In that case, set |force compilation| and this library will compile even if |-shell-escape| is disabled.
2761 \end{pgfmanualentry}
2762
2763 \begin{pgfmanualentry}
2764 \makeatletter%
2765 \def\extrakeytext{style, }
2766 \extractkey/robExt/recompile\@nil
2767 \extractkey/robExt/do not recompile\@nil
2768 \makeatother%
2769 \pgfmanualbody
2770 (new to v2.1) |recompile| will force a compilation even if the image is already cached (mostly useful if you made a change to a non-tracked dependency). Note that since this library does not want to remove any file on the hard drive (we do not want to risk to remove important files in case of a bug), this command will NOT clear the auxiliary files already present, so for maximum purity, ensure that your compiling command is idempotent (so that compiling twice gives the same outcome as compiling once).
2771
2772 \begin{codeexample}[vbox,
2773 %TURN_INTO_CODE_ONLY_ARXIV
2774 ]
2775 \cacheEnvironment{tikzcd}{tikz, add to preamble={\usepackage{tikz-cd}}}
2776 \begin{tikzcd}<recompile>
2777 A \rar & B
2778 \end{tikzcd}
2779 \end{codeexample}
2780
2781 If you want to actually remove the aux files, you can either change the compilation command, or add something like this to remove the file (note that it will prompt a message before running the actual command), using the hook |robust-externalize/just-before-writing-files| that we introduced in v2.1:
2782 \begin{codeexample}[code only]
2783 \cacheTikz
2784
2785 \robExtConfigure{
2786 clean and recompile/.code={%
2787 \AddToHook{robust-externalize/just-before-writing-files}{%
2788 \edef\command{rm -f "\robExtAddCachePathAndName{\robExtFinalHash.pdf}" && %
2789 rm -f "\robExtAddCachePathAndName{\robExtFinalHash.aux}"}%
2790 \message{You will run the command ``\command''}%
2791 \message{Press X if you do NOT want to run it, otherwise press ENTER.}%
2792 \show\def% this is just used to wait a user input
2793 \immediate\write18{\command}%
2794 }%
2795 },%
2796 }
2797
2798 \begin{tikzpicture}<clean and recompile>
2799 \node[fill=red] {B};
2800 \end{tikzpicture}
2801 \end{codeexample}
2802 Note that if you do not want to run a command from \LaTeX{}, or if you are on a version smaller than 2.1, you can also simply print the name of the file in the pdf and remove it manually:
2803
2804 \begin{codeexample}[width=0cm,vbox]
2805 \begin{CacheMe}{tikzpicture, name output=filetodelete}[baseline=(A.base)]
2806 \node[draw,rounded corners,fill=pink!60](A){Hello World!};
2807 \end{CacheMe}\\
2808
2809 You want to delete the file \texttt{\filetodeleteInCache.pdf}. %
2810 \end{codeexample}
2811
2812 \end{pgfmanualentry}
2813
2814 \begin{pgfmanualentry}
2815 \extractcommand\robExtMv\@@
2816 \extractcommand\robExtCp\@@
2817 \pgfmanualbody
2818 (new in v2.4) Respectively expands to |mv| and |cp| in linux/unix and to |move| and |copy| in Windows (needed to create a compilation command that works in both linux and windows). Note that |set compilation command| does NOT expand its argument by default and spaces after macros are removed by latex, so you need to use |/.expanded| and |\space| like in:
2819 \begin{codeexample}[code only]
2820 set compilation command/.expanded={\robExtCp\space"__ROBEXT_SOURCE_FILE__" "__ROBEXT_OUTPUT_PDF__"}
2821 \end{codeexample}
2822 \end{pgfmanualentry}
2823
2824 \subsubsection{Options to configure the inclusion command}
2825
2826 The inclusion command is the command that is run to include the cached file back in the pdf (e.g. based on |\includegraphics|). We describe now how to configure this command.
2827
2828 \begin{pgfmanualentry}
2829 \makeatletter%
2830 \def\extrakeytext{style, }
2831 \extractkey/robExt/custom include command advanced=\marg{include command}\@nil
2832 \makeatother%
2833 \pgfmanualbody
2834 Sets the command to run to include the compiled file. You can use:\\
2835 |\robExtAddCachePathAndName{\robExtFinalHash.pdf}|\\
2836 in order to get the path of the compiled pdf file. Note that we recommend rather to use |custom include command| that automatically checks if the file compiled correctly and that load the |*-out.tex| file if it exists (useful to pass information back to the pdf).
2837 \end{pgfmanualentry}
2838
2839 \begin{pgfmanualentry}
2840 \makeatletter%
2841 \def\extrakeytext{style, }
2842 \extractkey/robExt/custom include command=\marg{include command}\@nil
2843 \extractkey/robExt/include command is input=\opt{\oarg{additional code to run}}\@nil
2844 \makeatother%
2845 \pgfmanualbody
2846 Sets the command to run to include the compiled file, after checking if the file has been correctly compiled and loading |*-out.tex| (useful to pass information back to the pdf). |include command is input={SOME CODE}| is a shortcut for:
2847 \begin{verbatim}
2848 custom include command={SOME CODE\input{\robExtAddCachePathAndName{\robExtFinalHash.pdf}}},
2849 \end{verbatim}
2850 \end{pgfmanualentry}
2851
2852 \begin{pgfmanualentry}
2853 \makeatletter%
2854 \def\extrakeytext{style, }
2855 \extractkey/robExt/do not include pdf\@nil
2856 \extractkey/robExt/include command is input=\opt{additional command}\@nil
2857 \makeatother%
2858 \pgfmanualbody
2859 |do not include pdf| do not include the pdf. Useful if you only want to compile the file but use it later (note that you should still generate a |.pdf| file, possibly empty, to indicate that the compilation runs smootly). Equivalent to:\\
2860 |custom include command={}|
2861 Use |include command is input| (v2.3 and after) in order to specify that you should |\input| the |.pdf| file (note that despite the extension, it should still contain a LaTeX code). You can also specify an optional command to run before. Equivalent to:
2862 |custom include command={#1\input{\robExtAddCachePathAndName{\robExtFinalHash.pdf}}}|
2863 \end{pgfmanualentry}
2864
2865 \begin{pgfmanualentry}
2866 \makeatletter%
2867 \def\extrakeytext{style, }
2868 \extractkey/robExt/enable manual mode\@nil
2869 \extractkey/robExt/disable manual mode\@nil
2870 \extractkey/robExt/enable fallback to manual mode\@nil
2871 \extractkey/robExt/disable fallback to manual mode\@nil
2872 \makeatother%
2873 \pgfmanualbody
2874 If you do or do not want to ask latex to run the compilation commands itself (for instance for security
2875 reasons), you can use these commands and run the command manually later:
2876 \begin{codeexample}[width=0pt,vbox]
2877 \robExtConfigure{
2878 enable manual mode
2879 }
2880
2881 The next picture must be manually compiled %
2882 (see JOBNAME-robExt-compile-missing-figures.sh):\\ %
2883 \begin{tikzpictureC}[baseline=(A.base)]
2884 \node[fill=red, rounded corners](A){I must be manually compiled.};
2885 \node[fill=red, rounded corners, opacity=.3,overlay] at (A.north east){I am an overlay text};
2886 \end{tikzpictureC}
2887 \end{codeexample}
2888 The main difference between |manual mode| and |fallback to manual mode| is that |fallback to manual mode| will try to compile the file if |-shell-escape| is enabled, while |manual mode| will never run any command, even if |-shell-escape| is enabled. Note that |enable fallback to manual mode| is available starting from v2.0.
2889
2890 See \cref{sec:operationsCache} for more details.
2891 \end{pgfmanualentry}
2892
2893 \begin{pgfmanualentry}
2894 \makeatletter%
2895 \def\extrakeytext{style, }
2896 \extractkey/robExt/include graphics args\@nil
2897 \makeatother%
2898 \pgfmanualbody
2899 By default, the include commands runs |\includegraphics| on the pdf, and possibly raises it if needed. You can customize the arguments passed to |\includegraphics| here.
2900 \end{pgfmanualentry}
2901
2902 \begin{pgfmanualentry}
2903 \makeatletter%
2904 \def\extrakeytext{style, }
2905 \extractkey/robExt/add cache to graphicspath\@nil
2906 \makeatother%
2907 \pgfmanualbody
2908 This will add the folder containing the cache in the |\graphicspath{}|. Mostly useful if you need to input a file from the cache that does |\includegraphics{foo}| where |foo| is an image from the cache itself (looking at you gnuplot).
2909 \end{pgfmanualentry}
2910
2911
2912 \subsubsection{Configuration of the cache}
2913
2914 If needed, you can configure the cache:
2915
2916 \begin{pgfmanualentry}
2917 \makeatletter%
2918 \def\extrakeytext{style, }
2919 \extractkey/robExt/set filename prefix=\marg{prefix}\@nil
2920 \makeatother%
2921 \pgfmanualbody
2922 By default, the files in the cache starts with |robExt-|. If needed you can change this here, or by manually defining |\def\robExtPrefixFilename{yourPrefix-}|.
2923 \end{pgfmanualentry}
2924
2925 \begin{pgfmanualentry}
2926 \makeatletter%
2927 \def\extrakeytext{style, }
2928 \extractkey/robExt/set subfolder and way back=\marg{cache folder}\marg{path to project from cache}\@nil
2929 \extractkey/robExt/set cache folder and way back=\marg{cache folder}\marg{path to project from cache}\@nil
2930 \makeatother%
2931 \pgfmanualbody
2932 By default, the cache is located in |robustExternalize/|, using:\\
2933 |set cache folder and way back={robustExternalize/}{../},|\\
2934 You can customize it the way you want, just be make sure that going to the second arguments after going to the first argument leads you back to the original position, and make sure to terminate the path with a |/| so that |__ROBEXT_WAY_BACK__common_inputs.tex| gives the path of the file |common_inputs.tex| in the root folder (do not write |__ROBEXT_WAY_BACK__/common_inputs.tex| as this would expand to the absolute path |/common_inputs.tex| if you disable the cache folder). Note that both:\\
2935 |set cache folder and way back|\\
2936 and\\
2937 |set subfolder and way back|\\
2938 are alias, but the first one was introduced in v2.0 as it is clearer, the second one being kept for backward compatibility.
2939 \end{pgfmanualentry}
2940
2941 \begin{pgfmanualentry}
2942 \makeatletter%
2943 \def\extrakeytext{style, }
2944 \extractkey/robExt/set output directory=\marg{output directory}\@nil
2945 \makeatother%
2946 \pgfmanualbody
2947 If you compile with |--output-directory build|, you also need to tell this library that you are compiling with |--output-directory build|. As I can't find a reliable way to get this value, even using |TEXMF_OUTPUT_DIRECTORY|, you need to specify manually the compilation directory. To do that, you can either compile with:
2948 \begin{codeexample}[code only]
2949 pdflatex -shell-escape -output-directory=build "\def\robExtOutputDirectory{build}\input{test.tex}"
2950 \end{codeexample}
2951 or add in your file:
2952 \begin{codeexample}[code only]
2953 \robExtConfigure{
2954 set output directory=build,
2955 }
2956 \end{codeexample}
2957 \end{pgfmanualentry}
2958
2959 \begin{pgfmanualentry}
2960 \makeatletter%
2961 \def\extrakeytext{style, }
2962 \extractkey/robExt/no cache folder\@nil
2963 \makeatother%
2964 \pgfmanualbody
2965 Do not put the cache in a separate subfolder.
2966 \end{pgfmanualentry}
2967
2968
2969 \newpage
2970 \subsubsection{Customize or disable externalization}\label{sec:disableExternalization}
2971
2972 You might want (sometimes or always) to disable externalization, for instance to use |remember picture| \tikz[remember picture,baseline=(pointtome.base)] \node[rounded corners, fill=orange](pointtome){Point to me if you can};, even if you used |\cacheTikz|:
2973
2974 \begin{pgfmanualentry}
2975 \makeatletter%
2976 \def\extrakeytext{style, }
2977 \extractkey/robExt/disable externalization\@nil
2978 \extractkey/robExt/de\@nil
2979 \extractkey/robExt/disable externalization now\@nil
2980 \extractkey/robExt/enable externalization\@nil
2981 \makeatother%
2982 \pgfmanualbody
2983 Enable or disable externalization.
2984 \begin{codeexample}[width=0pt,vbox]
2985 % In theory all pictures should be externalized (so remember picture should fail)
2986 \cacheTikz
2987 % But we can disable it temporarily
2988 \begin{tikzpicture}<disable externalization>[remember picture]
2989 \node[rounded corners, fill=red](A){This figure is not externalized.
2990 This way, it can use remember picture.};
2991 \draw[->,overlay] (A) to[bend right] (pointtome);
2992 \end{tikzpicture}\\
2993
2994 % You can also disable it globally/in a group:
2995 {
2996 \robExtConfigure{disable externalization}
2997
2998 \begin{tikzpicture}[remember picture]
2999 \node[rounded corners, fill=red](A){This figure is not externalized.
3000 This way, it can use remember picture.};
3001 \draw[->,overlay] (A.west) to[bend left] (pointtome);
3002 \end{tikzpicture}\\
3003
3004 \begin{tikzpicture}[remember picture]
3005 \node[rounded corners, fill=red](A){This figure is not externalized.
3006 This way, it can use remember picture.};
3007 \draw[->,overlay] (A.east) to[bend right] (pointtome);
3008 \end{tikzpicture}
3009 }
3010 \end{codeexample}
3011 |disable externalization now| additionally redefines all automatically cached commands and environments to their default value right now (|disable externalization| would only do so when running the |command if no externalization| is run, which should be preferred if possible). This is mostly useful when an automatically cached command cannot be parsed (e.g.\ you specified the signature |O{}m| but in fact the command expects a more complicated parsing algorithm. For instance, in |tikz| we can omit the brackets, and it might confuse the system if we defined it as:
3012 \begin{codeexample}[width=0pt,vbox]
3013 %% Not the recommended way to proceed, but this is for the example
3014 \cacheCommand{tikz}[O{}m]{tikz}
3015 {
3016 % Needed, or the parser would be confused by the next command
3017 \robExtConfigure{disable externalization now}
3018 \tikz\node[fill=green]{The short version of tikz can be confusing.};
3019 }
3020 \end{codeexample}
3021 Since v2.1 you can also automatically disable externalization if the input contains a given string, for instance |remember picture| (that is not cachable with this library):
3022 \begin{codeexample}[vbox]
3023 \cacheTikz
3024 \robExtConfigure{
3025 add to preset={tikzpicture}{
3026 % \b means "word boundary", and spaces must be escaped
3027 if matches={remember picture}{disable externalization},
3028 },
3029 }
3030 \begin{tikzpicture}[remember picture]
3031 \node[fill=green](my original node){Point to me};
3032 \end{tikzpicture} %
3033 Some text %
3034 \begin{tikzpicture}[overlay, remember picture]
3035 \draw[->] (0,0) to[bend left] (my original node);
3036 \end{tikzpicture}
3037 \end{codeexample}
3038 \end{pgfmanualentry}
3039
3040 \begin{pgfmanualentry}
3041 \makeatletter%
3042 \def\extrakeytext{style, }
3043 \extractkey/robExt/command if no externalization\@nil
3044 \extractkey/robExt/command if externalization\@nil
3045 \extractkey/robExt/run command if externalization=\marg{code}\@nil
3046 \makeatother%
3047 \pgfmanualbody
3048 You can easily change the command to run if externalization is disabled using by setting the \textbf{.code} of this key. By default, it is configured as:\\
3049 \begin{verbatim}
3050 command if no externalization/.code={%
3051 \robExtDisableTikzpictureOverwrite\evalPlaceholder{__ROBEXT_MAIN_CONTENT__}%
3052 }
3053 \end{verbatim}
3054 Unless you know what you are doing, you should include |\robExtDisableTikzpictureOverwrite| as it is often necessary to avoid infinite recursion when externalization is disabled and the original command has been replaced with a cached version (for instance done by |\cacheTikz|). Note that if you write your own style, try to modify |__ROBEXT_MAIN_CONTENT__| so that it can be included as-it in a document: this way you do not need to change this command.
3055 You can also use |command if externalization/.append code={...}| if you want to run a code only if externalization is enabled (this is used for instance by the |forward| functionality), but we advise you rather to use |run command if externalization={...}| as this will also work if the style is executed while |command if externalization| is already running (this might occur when calling the style inside |if matches word|, for instance when forwarding colors).
3056 \end{pgfmanualentry}
3057
3058 \begin{pgfmanualentry}
3059 \makeatletter%
3060 \def\extrakeytext{style, }
3061 \extractkey/robExt/print verbatim if no externalization\@nil
3062 \makeatother%
3063 \pgfmanualbody
3064 Sets |command if no externalization| to print the verbatim content of |__ROBEXT_MAIN_CONTENT__| if externalization is disabled. Internally, it just sets it to:\\
3065 |\printPlaceholder{__ROBEXT_MAIN_CONTENT__}|\\
3066 This is mostly useful when typesetting |__ROBEXT_MAIN_CONTENT__| directly does not make sense (e.g. in python code). This style is used for instance in the |python| preset, allowing us to get:
3067
3068 \begin{codeAndResult}
3069 \begin{CacheMeCode}{python,
3070 verbatim output,
3071 set placeholder eval={__thepage__}{\thepage},
3072 %% We disable externalization
3073 disable externalization}
3074 with open("__ROBEXT_OUTPUT_PREFIX__-out.txt", "w") as f:
3075 for i in range(5):
3076 f.write(f"Hello {i}, we are on page __thepage__\n")
3077 \end{CacheMeCode}
3078 \end{codeAndResult}
3079
3080 You can also disable the externalization on all elements that use a common preset, for instance you can disable externalization on all |bash| instances (useful if you are on Windows for instance):
3081 \begin{codeAndResult}
3082 \robExtConfigure{
3083 % bash code will not be compiled (useful on windows for instance)
3084 add to preset={bash}{
3085 disable externalization
3086 },
3087 }
3088 \begin{CacheMeCode}{bash, verbatim output}
3089 # $outputTxt contains the path of the file that will be printed via \verbatiminput
3090 uname -srv > "${outputTxt}"
3091 \end{CacheMeCode}
3092 \end{codeAndResult}
3093
3094 \end{pgfmanualentry}
3095
3096 \begin{pgfmanualentry}
3097 \makeatletter%
3098 \def\extrakeytext{style, }
3099 \extractkey/robExt/execute after each externalization\@nil
3100 \extractkey/robExt/execute before each externalization\@nil
3101 \makeatother%
3102 \pgfmanualbody
3103 By doing |execute after each externalization={some code}|, you will run some code after the externalization. This might be practical for instance to update a counter (e.g. the number of pages\dots) based on the result of the compiled file.
3104 \end{pgfmanualentry}
3105
3106 \subsubsection{Dependencies}\label{sec:dependenciesDoc}
3107
3108 In order to enforce reproducibility, you should tell what are the files that your code depends on, by adding this file as a dependency. This has the advantage that if this file is changed, your code is automatically recompiled. On the other hand, you might not want this behavior (e.g. if this file often changes in a non-important way): in that case, just don't add the file as a dependency (but keep that in mind as you might not be able to recompile your file if you clear the cache if you introduced breaking changes).
3109
3110 \begin{pgfmanualentry}
3111 \makeatletter%
3112 \def\extrakeytext{style, }
3113 \extractkey/robExt/dependencies=\marg{list,of,dependencies}\@nil
3114 \extractkey/robExt/add dependencies=\marg{list,of,dependencies}\@nil
3115 \extractkey/robExt/reset dependencies\@nil
3116 \makeatother%
3117 \pgfmanualbody
3118 Set/add/reset the dependencies (you can put multiple files separated by commas). These files should be relative to the main compiled file. For instance, if you have a file |common_inputs.tex| that you want to input in both the main file and in the cached files, that contains, say:\\
3119 |\def\myValueDefinedInCommonInputs{42}|\\
3120 then you can add it as a dependency using:
3121 \begin{codeexample}[width=0pt,vbox]
3122 \begin{CacheMe}{latex,
3123 add dependencies={common_inputs.tex},
3124 add to preamble={\input{__ROBEXT_WAY_BACK__common_inputs.tex}}}
3125 The answer is \myValueDefinedInCommonInputs.
3126 \end{CacheMe}
3127 \end{codeexample}
3128 Note that the placeholder |__ROBEXT_WAY_BACK__| contains the path from the cache folder (containing the |.tex| that will be cached) to the root folder.\\ This way, you can easily input files contained in the root folder.
3129 \end{pgfmanualentry}
3130
3131 \begin{pgfmanualentry}
3132 \extractcommand\copyFileToCache\@@
3133 \extractcommand\forceCopyFileToCache\@@
3134 \makeatletter%
3135 \def\extrakeytext{style, }
3136 \extractkey/robExt/copy file to cache=\marg{file}\@nil
3137 \makeatother%
3138 \pgfmanualbody
3139 It can sometimes be handy to copy a file to the cache folder to avoid using |__ROBEXT_WAY_BACK__| for instance to refer to another file. This can be done with |copy file to cache|, either in a preset or in |\robExtConfigure| like:
3140 \begin{codeexample}[code only]
3141 \robExtConfigure{
3142 copy file to cache={zx-calculus.sty},
3143 }
3144 \end{codeexample}
3145 Note that |copy file to cache| will always compare the md5 sum to check if a copy must be done or not.
3146 \end{pgfmanualentry}
3147
3148 \subsubsection{Forward macros}\label{sec:forward}
3149
3150 (since v2.1)
3151
3152 You can also see the tutorial (\cref{sec:forwardIntro}) for some examples. So far, we have seen multiple approaches to use a macro in both the main document and in cached pictures, having different advantages:
3153 \begin{itemize}
3154 \item if we define the macro in a file say |common_inputs.tex|, if we include that file in both files \textbf{and} if we add it to the list of dependencies (\cref{sec:dependenciesDoc}), then you will have great purity (if |common_inputs.tex| changes, all files are recompiled), but this might be a problem if you often change the file |common_inputs.tex| since you will need to recompile all pictures every time you add a new macro
3155 \item If you follow the same procedure, but \textbf{without} adding the file in the list of dependencies, then you will save compilation time (no need to recompile everything if you add a macro in |common_inputs.tex|), but you will lose purity (if you change the definition of a macro in that file, you will need to manually specify the list of figures to recompile, e.g. using |recompile|).
3156 \item You can also create multiple files like
3157 \begin{verbatim}
3158 common_inputs_functionality_A.tex
3159 \end{verbatim}
3160 and
3161 \begin{verbatim}
3162 common_inputs_functionality_B.tex
3163 \end{verbatim}
3164 and use the first solution (maybe by creating a preset that automatically calls |add to preamble| and |add dependencies|), and only input the appropriate file depending on the set of macro that you need. This gives a tradeoff of above approaches (good purity, with less recompilation), but you will still compile often if you put many macros in a single file (and nobody wants to create one macro per file!).
3165 \end{itemize}
3166
3167 In this section, we provide a third solution that tries to solve the above issue (purity without frequent recompilations), by allowing the user to forward only a specific macro, with something like |forward=\myMacro|. In order to avoid to manually forward all macros used for each picture, we also provide some functions to automatically detect the macros to forward.
3168
3169 \begin{pgfmanualentry}
3170 \makeatletter%
3171 \def\extrakeytext{style, }
3172 \extractkey/robExt/forward=macro to forward\@nil
3173 \extractkey/robExt/fw=macro to forward\@nil
3174 \extractkey/robExt/forward at letter=macro to forward\@nil
3175 \makeatother%
3176 \pgfmanualbody
3177 |forward| (alias |fw|) will forward the definition of a macro to the picture if externalization is enabled:
3178 \begin{codeexample}[width=0pt]
3179 \cacheTikz
3180 \def\myName{Alice}
3181 \begin{tikzpicture}<forward=\myName>
3182 \node[fill=red]{\myName};
3183 \end{tikzpicture}
3184 \end{codeexample}
3185 Note that it works for macro defined with |\def|, |\newcommand| (or alike) and |\NewDocumentCommand| (or other xparse commands). For instance with xparse:
3186 \begin{codeexample}[width=0pt]
3187 \cacheTikz
3188 \NewDocumentCommand{\MyNode}{O{}m}{\node[rounded corners,fill=red,#1]{#2};}
3189 \begin{tikzpicture}<forward=\MyNode>
3190 \MyNode{Alice}
3191 \MyNode[xshift=2cm]{Bob}
3192 \end{tikzpicture}
3193 \end{codeexample}
3194 and with |\newcommand|:
3195 \begin{codeexample}[width=0pt]
3196 \cacheTikz
3197 \newcommand{\MyNodeWithNewCommand}[2][draw,thick]{\node[rounded corners,fill=red,#1]{#2};}
3198 \begin{tikzpicture}<forward=\MyNodeWithNewCommand>
3199 \MyNodeWithNewCommand{Alice}
3200 \MyNodeWithNewCommand[xshift=2cm]{Bob}
3201 \end{tikzpicture}
3202 \end{codeexample}
3203 Note that this might not work with quite involved macros. Notably, if the macro is defined by calling other macros, you need to also forward these macros.
3204 \begin{codeexample}[width=0pt]
3205 \cacheTikz
3206 \def\myName{Alice}
3207 \NewDocumentCommand{\MyNodeWithInnerMacros}{O{}m}{\node[rounded corners,fill=red,#1]{\myName: #2};}
3208 \begin{tikzpicture}<forward=\MyNodeWithInnerMacros,forward=\myName>
3209 \MyNodeWithInnerMacros{she is tall}
3210 \end{tikzpicture}
3211 \end{codeexample}
3212 Really involved macros (e.g.\ defined inside libraries) might call many other macros, possibly using the @ letter (used only in module code). If you REALLY want, you can forward such macros if you forward \textbf{all} macros that are used internally, using |forward at letter| that will automatically wrap the macro inside |\makeatletter...\makeatother|, but you should certainly use |add to preamble={\usepackage{yourlib}}| if you need to do something like that:
3213 \begin{codeexample}[width=0pt]
3214 \cacheTikz
3215 \makeatletter
3216 \def\module@name{Alice}
3217 \newcommand{\MyNodeWithAtCommands}[2][draw,thick]{\node[rounded corners,fill=red,#1]{\module@name};}
3218 \begin{tikzpicture}<forward at letter=\MyNodeWithAtCommands,forward at letter=\module@name>
3219 \MyNodeWithAtCommands{Alice}
3220 \end{tikzpicture}
3221 \makeatother
3222 \end{codeexample}
3223 \end{pgfmanualentry}
3224
3225 \begin{pgfmanualentry}
3226 \makeatletter%
3227 \def\extrakeytext{style, }
3228 \extractkey/robExt/forward eval=macro to eval and forward\@nil
3229 \makeatother%
3230 \pgfmanualbody
3231 Evaluate a macro, and defines it using this new value when compiling the function. This might be useful for instance if your macro depends on other macros that you do not want to export:
3232 \begin{codeexample}[width=0pt]
3233 \def\name{Alice}
3234 \def\fullName{\name}
3235 \begin{tikzpictureC}<forward eval=\fullName>
3236 \node[rounded corners, fill=red]{\fullName.};
3237 \end{tikzpictureC}
3238 \end{codeexample}
3239 \end{pgfmanualentry}
3240
3241 \begin{pgfmanualentry}
3242 \makeatletter%
3243 \def\extrakeytext{style, }
3244 \extractkey/robExt/forward counter=counter to forward\@nil
3245 \extractkey/robExt/forward counter force value=\marg{counter to forward}\marg{value of counter}\@nil
3246 \extractkey/robExt/forward counter back=counter to forward\@nil
3247 \extractkey/robExt/forward counter and back=counter to forward\@nil
3248 \makeatother%
3249 \pgfmanualbody
3250 |forward counter| forwards a counter to the cached picture:
3251 \begin{codeexample}[width=0pt]
3252 \begin{tikzpictureC}<forward counter=page>
3253 \node[rounded corners, fill=red]{The current page is \thepage.};
3254 \end{tikzpictureC}
3255 \end{codeexample}
3256 The force value also assigns a value to the counter irrespective of the current value (might be useful for instance to generate a cached value for the arXiv).
3257 \begin{codeexample}[width=0pt]
3258 \begin{tikzpictureC}<forward counter force value={page}{65}>
3259 \node[rounded corners, fill=red]{The current page is \thepage.};
3260 \end{tikzpictureC}
3261 \end{codeexample}
3262 |forward counter back| does the opposite, it gets the value of the counter at the end of the cached file, and redefines it in the main file, while |forward counter and back| does both |forward counter| and |forward counter back|:
3263 \begin{codeexample}[width=0pt,vbox]
3264 \newcounter{mycounter}
3265 \setcounter{mycounter}{12}
3266 \begin{CacheMe}{latex, forward counter and back=mycounter}
3267 Inside the cached picture, the value of mycounter is \the\value{mycounter}.
3268 Let's change it to 42! \setcounter{mycounter}{42}
3269 \end{CacheMe}\\
3270 Outside the cached picture, the new value of the counter is \the\value{mycounter}.
3271 \end{codeexample}
3272
3273 \end{pgfmanualentry}
3274
3275 \begin{pgfmanualentry}
3276 \makeatletter%
3277 \def\extrakeytext{style, }
3278 \extractkey/robExt/forward color=color to forward\@nil
3279 \extractkey/robExt/auto forward color=\marg{preset}\marg{color to forward}\@nil
3280 \makeatother%
3281 \pgfmanualbody
3282 |forward color| forwards a color (defined with xcolor). It works with colors defined with |\definecolor|:
3283 \begin{codeexample}[width=0pt]
3284 \definecolor{myred}{HTML}{F01122}
3285 \begin{tikzpictureC}<forward color=myred>
3286 \node[fill=myred]{A};
3287 \end{tikzpictureC}
3288 \end{codeexample}
3289 but also with colors defined with |\colorlet|:
3290 \begin{codeexample}[width=0pt]
3291 \definecolor{myred}{HTML}{F01122}
3292 \colorlet{myviolet}{blue!50!myred}
3293 \begin{tikzpictureC}<forward color=myviolet>
3294 \node[fill=myviolet,yshift=-1cm]{B};
3295 \end{tikzpictureC}
3296 \end{codeexample}
3297 Note that using |if matches word|, you can also automatically forward colors. This command also scales better than |if matches|: if |if matches| is used to register $N$ words, the compilation time will increase for each new |if matches| (since we need to check each time if the string contains the expression). |if matches word|, on the other hand, is more clever, and extracts in a single loop all the words of the string: the running time is therefore independent of the number of times |if matches word| was called. You can call |if matches word| outside of any preset like in:
3298 \begin{codeexample}[width=0pt]
3299 \definecolor{myred}{HTML}{F01122}
3300 \colorlet{myviolet}{blue!50!myred}
3301 \colorlet{mypink}{pink!90!orange}
3302 \robExtConfigure{
3303 if matches word={mypink}{forward color=mypink},
3304 }
3305 \begin{tikzpictureC}
3306 \node[fill=mypink,yshift=-1cm]{B};
3307 \end{tikzpictureC}
3308 \end{codeexample}
3309 And this will automatically allow all presets based on |latex| to forward this color (see also |\definecolorAutoForward| to do that even quicker). You can also simply call it on any preset of your choice like:
3310 \begin{codeexample}[width=0pt]
3311 \definecolor{myred}{HTML}{F01122}
3312 \colorlet{myviolet}{blue!50!myred}
3313 \colorlet{mypink}{pink!90!orange}
3314 \robExtConfigure{
3315 add to preset={latex}{
3316 if matches word={mypink}{forward color=mypink},
3317 },
3318 }
3319 \begin{tikzpictureC}
3320 \node[fill=mypink,yshift=-1cm]{B};
3321 \end{tikzpictureC}
3322 \end{codeexample}
3323 or, equivalently:
3324 \begin{codeexample}[width=0pt]
3325 \definecolor{myred}{HTML}{F01122}
3326 \colorlet{myviolet}{blue!50!myred}
3327 \colorlet{mypink}{pink!90!orange}
3328 \robExtConfigure{
3329 auto forward color={tikz}{mypink},
3330 }
3331 \begin{tikzpictureC}
3332 \node[fill=mypink,yshift=-1cm]{B};
3333 \end{tikzpictureC}
3334 \end{codeexample}
3335 \end{pgfmanualentry}
3336
3337 \begin{pgfmanualentry}
3338 \makeatletter%
3339 \def\extrakeytext{style, }
3340 \extractkey/robExt/auto forward\@nil
3341 \extractkey/robExt/auto forward only macros\@nil
3342 \extractkey/robExt/auto forward words\@nil
3343 \makeatother%
3344 \pgfmanualbody
3345 |auto forward| enables automatic forwarding of macros marked with |*AutoForward| commands or |\configIfMacroPresent| or |if matches word|. This command naively extracts all used macros via a simple regex match and forwards them/execute the style configured in |\configIfMacroPresent| if it exists. It does a similar thing for words registered via |if matches word| or |register word with namespace|. If you want to only forward macros or words, you can use |auto forward only macros| or |auto forward words|.
3346 \begin{codeexample}[vbox]
3347 \cacheTikz
3348 \robExtConfigure{add to preset={tikz}{auto forward}}
3349
3350 \newcommandAutoForward{\MyNode}[2][draw,thick]{\node[rounded corners,fill=red,#1]{#2};}
3351 \newcommandAutoForward{\MyGreenNode}[2][draw,thick]{\node[rounded corners,fill=green,#1]{#2};}
3352
3353 \begin{tikzpicture}
3354 \MyNode{Recompiled only if MyNode is changed}
3355 \MyNode[xshift=8cm]{but not if the (unused) MyGreenNode is changed.}
3356 \end{tikzpicture}\\
3357
3358 \begin{tikzpicture}
3359 \MyGreenNode{Recompiled only if MyGreenNode is changed}
3360 \MyGreenNode[xshift=8cm]{but not if the (unused) MyNode is changed.}
3361 \end{tikzpicture}
3362 \end{codeexample}
3363
3364 \end{pgfmanualentry}
3365
3366 \begin{pgfmanualentry}
3367 \extractcommand\configIfMacroPresent\marg{macro}\marg{style to run if macro is present}\@@
3368 \pgfmanualbody
3369 Runs the corresponding style if the macro |macro| is present (make sure to enable |auto forward|).
3370 \begin{codeexample}[vbox]
3371 \cacheTikz
3372 \robExtConfigure{add to preset={tikz}{auto forward}}
3373
3374 \configIfMacroPresent{\ding}{add to preamble={\usepackage{pifont}}}
3375
3376 \begin{tikzpicture}
3377 \node[fill=green, circle]{\ding{164}};
3378 \end{tikzpicture}
3379 \end{codeexample}
3380 \end{pgfmanualentry}
3381
3382 \begin{pgfmanualentry}
3383 \extractcommand\newcommandAutoForward\marg{macro}\opt{\oarg{nb args}}\opt{\oarg{optional default value}}\marg{definition}\opt{\oarg{additional style}}\@@
3384 \extractcommand\renewcommandAutoForward\marg{macro}\opt{\oarg{nb args}}\opt{\oarg{optional default value}}\marg{definition}\opt{\oarg{additional style}}\@@
3385 \extractcommand\providecommandAutoForward\marg{macro}\opt{\oarg{nb args}}\opt{\oarg{optional default value}}\marg{definition}\opt{\oarg{additional style}}\@@
3386 \extractcommand\NewDocumentCommandAutoForward\marg{macro}\marg{arg spec}\opt{\oarg{additional style}}\marg{definition}\@@
3387 \extractcommand\RenewDocumentCommandAutoForward\marg{macro}\marg{arg spec}\opt{\oarg{additional style}}\marg{definition}\@@
3388 \extractcommand\ProvideDocumentCommandAutoForward\marg{macro}\marg{arg spec}\opt{\oarg{additional style}}\marg{definition}\@@
3389 \extractcommand\DeclareDocumentCommandAutoForward\marg{macro}\marg{arg spec}\opt{\oarg{additional style}}\marg{definition}\@@
3390 \extractcommand\NewExpandableDocumentCommandAutoForward\marg{macro}\marg{arg spec}\opt{\oarg{additional style}}\marg{definition}\@@
3391 \extractcommand\RenewExpandableDocumentCommandAutoForward\marg{macro}\marg{arg spec}\opt{\oarg{additional style}}\marg{definition}\@@
3392 \extractcommand\ProvideExpandableDocumentCommandAutoForward\marg{macro}\marg{arg spec}\opt{\oarg{additional style}}\marg{definition}\@@
3393 \extractcommand\DeclareExpandableDocumentCommandAutoForward\marg{macro}\marg{arg spec}\opt{\oarg{additional style}}\marg{definition}\@@
3394 \extractcommand\defAutoForward\marg{macro}\opt{\oarg{def-style arg spec}}\marg{macro}\opt{\oarg{additional style}}\@@
3395 \extractcommand\genericAutoForward\opt{*}\opt{\oarg{preset}}\opt{\oarg{namespace}}\marg{word}\opt{\oarg{additional style}}\marg{code to run}\@@
3396 \extractcommand\genericAutoForwardStringMatch\opt{*}\opt{\oarg{preset}}\marg{string}\opt{\oarg{additional style}}\marg{code to run}\@@
3397 \pgfmanualbody
3398 \begin{verbatim}
3399 \newcommandAutoForward{\macro}[nb args][default value]{def}[STYLE]
3400 \end{verbatim}
3401 is like
3402 \begin{verbatim}
3403 \newcommand{\macro}[nb args][default value]{def}
3404 \end{verbatim}
3405 but it additionally runs
3406 \begin{verbatim}
3407 \configIfMacroPresent{\macro}{forward=\macro,STYLE}
3408 \end{verbatim}
3409 to automatically forward the macro if it is used. It is really practical to automatically define a macro and forward it:
3410 \begin{codeexample}[vbox]
3411 \cacheTikz
3412 \robExtConfigure{add to preset={tikz}{auto forward}}
3413
3414 \newcommandAutoForward{\MyName}{\ding{164} Alice}[add to preamble={\usepackage{pifont}}]
3415 \newcommandAutoForward{\MyNode}[2][draw,thick]{\node[rounded corners,fill=green,#1]{\MyName: #2};}[
3416 load auto forward macro config=\MyName
3417 ]
3418
3419 \begin{tikzpicture}
3420 \MyNode{Recompiled only if MyNode is changed}
3421 \MyNode[yshift=-1cm]{or if MyName is changed}
3422 \end{tikzpicture}
3423 \end{codeexample}
3424
3425 This works similarly for other commands (note that for |\defAutoForward|, you need to put the arguments in a bracket, like |\defAutoForward\myMacro[#1 and #2]{Hey #1, #2}| for |\def\myMacro#1 and #2{Hey #1, #2}|). |\genericAutoForward| and |\genericAutoForwardStringMatch| are a bit special, as it can be used to run any code assuming that |word|/|string to match| is present (|\genericAutoForward| is more efficient as it does not scale with the number of words, but do not allow spaces etc in the name). For instance, you can use it to automatically forward the code that defines a new tikz style assuming |mystyle| is preset:
3426 \begin{codeexample}[width=0pt]
3427 \cacheTikz
3428 \genericAutoForward{mystyle}{
3429 \tikzset{mystyle/.style={fill=#1!10!white,text=#1!50!black}}
3430 }
3431
3432 \begin{tikzpicture}
3433 \node[mystyle=green]{A};
3434 \end{tikzpicture}
3435 \end{codeexample}
3436 This will also run the code to define it in the current document (practical for instance if some pictures are not externalized), use the stared version of |\genericAutoForward| if you do not want to run the code in the current document. By default, the code is added to the |latex| preset, but you can choose another preset if you want using the optional option. The additional style might be specified to run other style if the matches is true. Note that you should be able to use definitions inside the code (a bug in v2.1 was making this code fail):
3437 \begin{codeexample}[width=0pt]
3438 \genericAutoForward{mystyle}{
3439 \tikzset{mystyle/.style={fill=#1!10!white,text=#1!50!black}}
3440 }
3441 \newcommandAutoForward{\myName}{Alice}
3442 \robExtConfigure{
3443 add to preset={tikz}{
3444 auto forward, % not needed for genericAutoForward, but for newcommandAutoForward
3445 if matches word={pmatrix}{add to preamble={\usepackage{amsmath}}}
3446 }
3447 }
3448
3449 \begin{tikzpicture}
3450 \node[mystyle=green]{%
3451 \def\hey#1{Hey #1 :)}% You can define macros inside the cached elements
3452 \hey{Coucou \myName} %
3453 $\begin{pmatrix}% Fixing a bug introduced in v2.1, we can also use macros
3454 A & B\\
3455 C & D\\
3456 \end{pmatrix}$
3457 };
3458 \end{tikzpicture}
3459 \end{codeexample}
3460 \begin{codeexample}[vbox]
3461 % space is not allowed in the name with this more efficient version:
3462 \robExtGenericAutoForward{mystyle}{%
3463 \tikzset{%
3464 mystyle/.style={fill=#1!30!white,text=#1!40!black},
3465 }%
3466 }
3467 \begin{tikzpictureC}
3468 \node[mystyle=green]{My style automatically forwarded};
3469 \end{tikzpictureC}
3470 \end{codeexample}
3471 \begin{codeexample}[vbox]
3472 % space is allowed in the name with this slightly less efficient version:
3473 \robExtGenericAutoForwardStringMatch{my style}{%
3474 \tikzset{%
3475 my style/.style={fill=#1!30!white,text=#1!40!black},
3476 }%
3477 }
3478 \begin{tikzpictureC}
3479 \node[my style=green]{My style with a space in the name automatically forwarded};
3480 \end{tikzpictureC}
3481 \end{codeexample}
3482 Note that by default, this forwards elements in the |latex| preset, but you can change it via |preset|. You can also configure additional style to run, and choose another namespace for the word version (practical only if you want to forward different codes to different presets: note that a single namespace is allowed per preset).
3483 \end{pgfmanualentry}
3484
3485 \begin{pgfmanualentry}
3486 \extractcommand\runHereAndInPreambleOfCachedFiles\opt{\oarg{preset}}\marg{code}\@@
3487 \pgfmanualbody
3488 (from v2.3) This will run |code| right now and it will add it in the preamble of the files that use the preset |preset| (defaults to |latex|). This is practical to avoid duplicating the code into |add to preamble|. For instance, if want the configure the font of the current document and of all latex documents at the same time, use:
3489 \begin{codeexample}[code only]
3490 \runHereAndInPreambleOfCachedFiles{
3491 \usepackage{fontspec}
3492 \setmainfont{Times New Roman}
3493 }
3494
3495 \robExtConfigure{
3496 add to preset={latex}{
3497 use lualatex, % Make sure to compile with lualatex the cached images.
3498 },
3499 }
3500 \end{codeexample}
3501 \end{pgfmanualentry}
3502
3503 \begin{pgfmanualentry}
3504 \extractcommand\definecolorAutoForward\marg{color}\marg{model}\marg{value}\opt{\oarg{additional style}}\@@
3505 \extractcommand\colorletAutoForward\marg{color}\marg{value}\opt{\oarg{additional style}}\@@
3506 \pgfmanualbody
3507 Define colors like |\definecolor| and |\colorlet|, but also runs
3508 \begin{verbatim}
3509 if matches word={COLOR}{forward color=COLOR}
3510 \end{verbatim}
3511 to automatically forward the color (this will forward it only in latex-based presets). You can provide additional style to run as well in option.
3512 \begin{codeexample}[vbox]
3513 \definecolorAutoForward{myred}{HTML}{F01122}
3514 \colorletAutoForward{myviolet}{blue!50!myred}
3515 \begin{tikzpictureC}
3516 \node[fill=myred,yshift=-1cm]{Uses myred};
3517 \end{tikzpictureC}
3518 \begin{tikzpictureC}
3519 \node[fill=myviolet,yshift=-1cm]{Myviolet};
3520 \end{tikzpictureC}
3521 \end{codeexample}
3522 \end{pgfmanualentry}
3523
3524 \begin{pgfmanualentry}
3525 \makeatletter%
3526 \def\extrakeytext{style, }
3527 \extractkey/robExt/load auto forward macro config=\marg{macro}\@nil
3528 \makeatother%
3529 \pgfmanualbody
3530 Like |forward| except that it loads the configuration that would have been loaded if the macro was present in the file. This is mostly useful to say that a macro depends on the style of another macro without copy/pasting the style of the second macro inside the first one.
3531 \begin{codeexample}[vbox]
3532 \cacheTikz
3533 \robExtConfigure{add to preset={tikz}{auto forward}}
3534
3535 \newcommandAutoForward{\MyName}{\ding{164} Alice}[add to preamble={\usepackage{pifont}}]
3536 \newcommandAutoForward{\MyNode}[2][draw,thick]{\node[rounded corners,fill=green,#1]{\MyName: #2};}[
3537 load auto forward macro config=\MyName
3538 ]
3539
3540 \begin{tikzpicture}
3541 \MyNode{Recompiled only if MyNode is changed}
3542 \MyNode[yshift=-1cm]{or if MyName is changed}
3543 \end{tikzpicture}
3544 \end{codeexample}
3545 \end{pgfmanualentry}
3546
3547 \begin{pgfmanualentry}
3548 \makeatletter%
3549 \def\extrakeytext{style, }
3550 \extractkey/robExt/if matches=\marg{string}\marg{style to apply}\@nil
3551 \extractkey/robExt/if matches else=\marg{string}\marg{style to apply if match}\marg{style to apply if no match}\@nil
3552 \extractkey/robExt/if matches word=\marg{string}\marg{style to apply}\@nil
3553 \extractkey/robExt/if matches regex=\marg{latex3 regex}\marg{style to apply}\@nil
3554 \extractkey/robExt/register word with namespace=\marg{namespace}\marg{word}\marg{style}\@nil
3555 \extractkey/robExt/auto forward words\@nil
3556 \extractkey/robExt/auto forward words namespace=\marg{namespace}\@nil
3557 \makeatother%
3558 \pgfmanualbody
3559 |if matches *| applies the corresponding style if the string (resp.\ word or regex in \LaTeX{}3 format) matches is matched in the content. |if matches word| is more efficient that |if matches string| since the running time is independent of the number of times |if matches word| is called\footnote{Scaling with $O(s)$ instead of $O(sn)$, where $s$ is the size of the string typed in |cacheMe| and $n$ is the number of times |if matches| is used, for instance when replacing multiple strings.}. |if matches word| make it only match words that are mostly made of consecutive letters and numbers |[A-Za-z0-9]| (more precisely separated by elements in |\robExtWordSeparators|). The regex version can be more expressive, but is significantly slower (it can easily multiply by 2 the compilation time).
3560 \begin{codeexample}[vbox]
3561 \robExtConfigure{
3562 add to preset={my python}{
3563 python print code and result,
3564 % \b is for word border, and ( needs to be escaped in regex
3565 if matches={cos(}{add import={from math import cos}},
3566 if matches={sin(}{add import={from math import sin}},
3567 },
3568 }
3569 \begin{CacheMeCode}{my python}
3570 print(cos(1)+sin(2))
3571 \end{CacheMeCode}
3572 \end{codeexample}
3573 With regex:
3574 \begin{codeexample}[vbox]
3575 \robExtConfigure{
3576 add to preset={my python}{
3577 python print code and result,
3578 % \b is for word border, and ( needs to be escaped in regex
3579 if matches regex={\b cos\(}{add import={from math import cos}},
3580 if matches regex={\b sin\(}{add import={from math import sin}},
3581 },
3582 }
3583 \begin{CacheMeCode}{my python}
3584 print(cos(1)+sin(2))
3585 \end{CacheMeCode}
3586 \end{codeexample}
3587 This can also be practical to disable caching if some pictures uses |remember picture| (which is not supported by this library):
3588 \begin{codeexample}[vbox]
3589 \cacheTikz
3590 \robExtConfigure{
3591 add to preset={tikzpicture}{
3592 % \b means "word boundary", and spaces must be escaped
3593 if matches={remember picture}{disable externalization},
3594 },
3595 }
3596 \begin{tikzpicture}[remember picture]
3597 \node[fill=green](my original node){Point to me};
3598 \end{tikzpicture} %
3599 Some text %
3600 \begin{tikzpicture}[overlay, remember picture]
3601 \draw[->] (0,0) to[bend left] (my original node);
3602 \end{tikzpicture}
3603 \end{codeexample}
3604 Note that to make |if matches word| even more efficient, you can call it before the preset. It will "register" the corresponding word with |register word| (itself a shortcut for |register word with namespace| with an empty namespace), and call |auto forward words| (shortcut for |auto forward words namespace={}|) in the |latex| preset (or in the current preset if we are already in a preset) to forward all words registered in the corresponding namespace (empty by default). Unless you want to forward different words to different presets, these more advanced functions involving namespaces should not be really useful for the end user.
3605 \end{pgfmanualentry}
3606
3607
3608 \subsubsection{Pass compiled file to another template}\label{sec:passOutputToOtherTemplate}
3609
3610 It can sometimes be handy to use the result of a previous cached file to cache another file, or to do anything else (e.g.\ it can also be practical to debug an issue). |name output| can be used to do that
3611 \begin{pgfmanualentry}
3612 \makeatletter%
3613 \def\extrakeytext{style, }
3614 \extractkey/robExt/name output=\marg{macro name}\@nil
3615 \makeatother%
3616 \pgfmanualbody
3617 |name output=foo| will create two global macros |\foo| and |\fooInCache|: |\foo| expands to the prefix of the files created in the template like |robExt-somehash|, and |\fooInCache| also adds the cache folder like |robustExternalize/robExt-somehash|. You can then use |set placeholder eval| to send it to another cached file. It is then your role to add the extension, usually |.tex| to get the source (even if the source is a python file), |.pdf| to get the pdf, |-out.tex| to get the file that is loaded before the import, |-out.txt| if you wanted to make it compatible with |verbatim output| (this list is not exhaustive as each script might decide to create a different output file). Here is a demo:
3618
3619 \begin{codeexample}[width=0cm,vbox]
3620 \begin{CacheMe}{tikzpicture, do not add margins, name output=mycode}[baseline=(A.base)]
3621 \node[draw,rounded corners,fill=pink!60](A){Hello World!};
3622 \end{CacheMe}\\[3mm]
3623
3624 The prefix is \texttt{\mycode} and with the cache folder it is in:\\
3625 \texttt{\mycodeInCache}.\\
3626 It this can be helpful for instance to debug, as you can inspect the source:
3627 \verbatiminput{\mycodeInCache.tex}
3628 but it is also practical to define a template based on the previously cached files:\\
3629
3630 \begin{CacheMe}{tikzpicture, set placeholder eval={__previous__}{\mycode.pdf}}
3631 \node[rounded corners, fill=green!50]{A cached file can use result from another cached file:
3632 \includegraphics[width=2cm]{__previous__}\includegraphics[width=2cm]{__previous__}};
3633 \end{CacheMe}
3634 \end{codeexample}
3635
3636 Note that if you do not want to display the first cached file, you can use |do not include pdf| to hide it.
3637
3638 \end{pgfmanualentry}
3639
3640 \subsubsection{Compile in parallel}\label{sec:compileParallel}
3641
3642 (introduced in v2.1, read below on how to do it manually on v2.0)
3643
3644 \begin{pgfmanualentry}
3645 \makeatletter%
3646 \def\extrakeytext{style, }
3647 \extractkey/robExt/compile in parallel=\opt{nb of pictures to compile normally} (default 0)\@nil
3648 \extractkey/robExt/compile in parallel after=\opt{nb pictures to compile normally} (default 0)\@nil
3649 \makeatother%
3650 \pgfmanualbody
3651 These two commands are alias. Typing in the preamble:
3652 \begin{codeexample}[code only]
3653 \robExtConfigure{
3654 compile in parallel
3655 }
3656 \end{codeexample}
3657 will cause the cached elements to be compiled in parallel (this requires two compilations of the main project). For this to work out of the box, you need to have |xargs| installed (on windows, install the lightweight GNU On Windows (Gow) \url{https://github.com/bmatzelle/gow} to get |xargs|). Typing |compile in parallel after=3| will start the compilation in parallel only if you have more than 3 new elements to compile, and compile the first 3 elements normally (useful when you work on one picture at a time since you do not need to compile twice the document).
3658 \end{pgfmanualentry}
3659
3660 \begin{pgfmanualentry}
3661 \makeatletter%
3662 \def\extrakeytext{style, }
3663 \extractkey/robExt/compile in parallel command=\marg{command to run}\@nil
3664 \extractkey/robExt/compile in parallel with xargs=\opt{number threads} (default 16\%)\@nil
3665 \extractkey/robExt/compile in parallel with gnu parallel=\opt{--jobs option} (default 200\%)\@nil
3666 \makeatother%
3667 \pgfmanualbody
3668 You can customize the compilation command to run via something like:
3669 \begin{codeexample}[code only]
3670 \robExtConfigure{
3671 compile in parallel command={
3672 parallel --jobs 200\% :::: '\jobname-\robExtAddPrefixName{compile-missing-figures.sh}
3673 },
3674 }
3675 \end{codeexample}
3676 The other styles are predefined commands to compile with xargs (by default, already installed in linux, on Windows you can get it by installing the lightweight GNU On Windows (Gow) \url{https://github.com/bmatzelle/gow}) or gnu parallel. You can use these commands directly like:
3677 \begin{codeexample}[code only]
3678 \robExtConfigure{
3679 compile in parallel with gnu parallel
3680 }
3681 \end{codeexample}
3682 or use the optional parameter to configure the number of threads (xargs starts with 16 threads by default, and gnu parallel takes twice the number of CPU threads available), like in:
3683 \begin{codeexample}[code only]
3684 \robExtConfigure{
3685 compile in parallel with xargs=64,% Compiles with 64 processes at a time
3686 }
3687 \end{codeexample}
3688 \end{pgfmanualentry}
3689
3690 \begin{pgfmanualentry}
3691 \makeatletter%
3692 \def\extrakeytext{style, }
3693 \extractkey/robExt/if unix=\marg{style to run if running linux or unix}\@nil
3694 \extractkey/robExt/if windows=\marg{style to run if windows}\@nil
3695 \makeatother%
3696 \pgfmanualbody
3697 Since windows does not pack |xparse| by default, you might want to enable parallel compilation only in Linux/MacOs. This can be done using the above flags, like:
3698 \begin{codeexample}[code only]
3699 \robExtConfigure{
3700 if unix={
3701 compile in parallel
3702 },
3703 }
3704 \end{codeexample}
3705 (note that |unix| is understood as ``non windows'', i.e.\ would run in Unix/Linux/MacOs)
3706 \end{pgfmanualentry}
3707
3708 NB: in version smaller than v2.1 (or if you prefer the manual method), you can instead run it in manual mode and use for instance GNU |parallel| (or any tool of you choice) to run all commands in the file |\jobname-robExt-compile-missing-figures.sh| in parallel. To do that:
3709 \begin{itemize}
3710 \item First add |\robExtConfigure{enable manual mode}| in your file
3711 \item Create the cache folder, e.g.\ using |mkdir robustExternalize|
3712 \item Compile your file, with, e.g.\ |pdflatex yourfile.tex| (in my benchmark: 4.2s)
3713 \item This should create a file |yourfile-robExt-compile-missing-figures.sh|, with each line containing a compilation command like this (the command should be compatible with Windows, Mac and Linux, if not, let me know on github):
3714 \begin{verbatim}
3715 cd robustExternalize/ && pdflatex -halt-on-error "robExt-4A806941E86C6B657A0CB3D160CFFF3E.tex
3716 \end{verbatim}
3717 \textbf{IMPORTANT}: \LaTeX{} might render \textbf{multiple times} the same picture if it is inside some particular environments (align, tables\dots), so this file can contain duplicates if you inserted cached data inside. In version 2.1 this is solved, but on older versions, to avoid running the same command twice, \textbf{be sure to remove duplicates!} On Linux, this can be done by piping the file into |sort| and |uniq| (if your files can depend on previously compiled elements as explained in \cref{sec:passOutputToOtherTemplate}, you should additionally preserve \mylink{https://unix.stackexchange.com/questions/194780/remove-duplicate-lines-while-keeping-the-order-of-the-lines}{the order of the lines}). Since this is anyway a rather advanced use case, we will not consider that case for simplicity.
3718 \item Run all these command in parallel, for instance on Linux you can install |parallel|, and run the following command (|--bar| displays a progress bar):
3719 \begin{verbatim}
3720 cat yourfile-robExt-compile-missing-figures.sh | sort | uniq | parallel --bar --jobs 200%
3721 \end{verbatim}
3722 (note that since v2.1, it is not necessary to remove duplicates using |sort| and |uniq| since the file contains no more duplicates) In my benchmark, it ran during 52s, so 1.6x faster than the original compilation without caching)
3723 \item Recompile the original document with |pdflatex yourfile.tex|
3724 \end{itemize}
3725 In my benchmark, the total time is 2x4.2s + 52s = 60s, so 1.5 times faster than a normal command (of course, this depends a lot on the preamble of the file that you compile, since the loading time of the file is the main bottleneck for the first compilation; the advantage here is that it is easy to include only the necessary things in the preamble of cached pictures, possibly creating different presets if it is easier to manage it this way).
3726
3727 \subsubsection{Compile a template to compile even faster}\label{sec:compileFaster}
3728
3729 Long story short: you can compile even faster (at least 1.5x in our tests, but we expect this to be more visible on larger tests due to the loading time of the preamble of the main document that takes most of the time of the compilation) by compiling presets, but beware that you will not be able to modify the placeholders except |add to preamble| with the default compiler we provide. The gain comes from the fact that instead of trying to find all placeholders to replace in the string, we can directly replace a few hard-coded placeholders to save time (yes, \LaTeX{} is not really efficient so it can make a difference\dots).
3730
3731
3732 \begin{pgfmanualentry}
3733 \makeatletter%
3734 \def\extrakeytext{style, }
3735 \extractkey/robExt/new compiled preset=\marg{preset options to compile}\marg{runtime options}\@nil
3736 \extractkey/robExt/compile latex template\@nil
3737 \makeatother%
3738 \pgfmanualbody
3739 Compile a preset by creating a new placeholders that removes all placeholders except |__ROBEXT_MAIN_CONTENT__|, |__ROBEXT_MAIN_CONTENT_ORIG__| and |__ROBEXT_LATEX_PREAMBLE__|. |preset options to compile| should be sure that the template, compilation command and include command placeholders contain the final version: this can be easily done for latex presets by adding |compile latex template| at the end of |preset options to compile|:.
3740 \begin{codeexample}[vbox]
3741 % We create a latex-based preset and compile it
3742 \robExtConfigure{
3743 new preset={templateZX}{
3744 latex,
3745 add to preamble={
3746 \usepackage{tikz}
3747 \usepackage{tikz-cd}
3748 \usepackage{zx-calculus}
3749 },
3750 %% possibly add some dependencies
3751 },
3752 % We compile it into a new preset
3753 new compiled preset={compiled ZX}{templateZX, compile latex template}{},
3754 }
3755
3756 % we use that preset automatically for ZX environments
3757 \cacheEnvironment{ZX}{compiled ZX}
3758 \cacheCommand{zx}{compiled ZX}
3759
3760 % Usage: (you can't use placeholders except for the preamble, trade-off of the compiled template)
3761 \begin{ZX}<add to preamble={\def\sayHey#1{Hey #1!}}>
3762 \zxX{\sayHey{Bob}}
3763 \end{ZX}
3764 \end{codeexample}
3765 \end{pgfmanualentry}
3766
3767
3768 Explanations: in v2.0, we made substantial improvements in order to improve significantly the compilation time (our benchmark went from 20s (v1.0) to only 5.77s (v2.0)), but you might want to make this even faster: with a compiled preset, you can improve it further, experimentation showed an additional improvement factor of 1.4x (final compilation time was 4s in our tests, reminder: without the library it would take 1mn25s). The main bottleneck in term of time is the expansion of the placeholders (that allows great flexibility, but can add a significant time). At a high level, we keep track in a list of all declared placeholders, and loop over them to replace each of them until the string is left unmodified by a full turn. This is simple to implement, does not need to assume any shape for the placeholder\dots{} but not extremely efficient in \LaTeX{} where string and list manipulations are costly.
3769
3770 We can play on multiple parameters to speed up the process:
3771 \begin{itemize}
3772 \item Disable completely the placeholders and only replace a small amount of fixed placeholders in a fixed order and stop expanding the placeholder. This is what we do by default when we compile a preset: it is the quickest solution, but you cannot use arbitrary placeholders.
3773 \item Start the expansion using a fixed (preset-dependent) list of placeholders, check if some templates are still present (assuming that templates must contain at least two consecutive underscores |__|), if not stop, otherwise go to the normal (less efficient) placeholder replacement. It is what we do for instance in the latex preset, and gives a great balance between efficiency and flexibility. Details can be found in \cref{sec:advancedOperations}.
3774 \item Stop iterating over all placeholders, only choose the one meaningful (why would I care about python placeholders in latex?). For this, we introduce an import system, where you can create placeholders that are not added to the ``global'' list of placeholders, and import them where you want. In practice, you should not really need to use it unless you do more advanced stuff as we already take care of setting it properly, but details are in \cref{sec:importSystem}.
3775 \end{itemize}
3776 Another option could be to rewrite the code to search directly the list of placeholders in the string, but it is certainly not trivial to do in latex, would require even more constraints on the shape of placeholders, and would certainly still no more efficient than the compiled stuff. But anyway the already implemented solutions already give fairly good performances.
3777
3778 \subsection{Default presets}\label{sec:presets}
3779
3780 We provide by default some presets for famous languages (for now \LaTeX{} and python).
3781
3782 \subsubsection{All languages}
3783
3784 First, here are a few options that are available irrespective of the used language.
3785
3786 \begin{pgfmanualentry}
3787 \makeatletter%
3788 \def\extrakeytext{style, }
3789 \extractkey/robExt/set includegraphics options=\marg{options}\@nil
3790 \extractkey/robExt/add to includegraphics options=\marg{options}\@nil
3791 \makeatother%
3792 \pgfmanualbody
3793 Set/add options to the |\includegraphics| run when inserting the pdf (by the default include command). By default it is empty, but the |latex| preset sets it to:\\
3794 |trim=__ROBEXT_LATEX_TRIM_LENGTH__ __ROBEXT_LATEX_TRIM_LENGTH__|\\
3795 |__ROBEXT_LATEX_TRIM_LENGTH__ __ROBEXT_LATEX_TRIM_LENGTH__|\\
3796 in order to remove the margin added in the standalone package options, which is needed to display overlay texts.
3797 \end{pgfmanualentry}
3798
3799 \begin{pgfmanualentry}
3800 \makeatletter%
3801 \def\extrakeytext{style, }
3802 \extractkey/robExt/verbatim output\@nil
3803 \makeatother%
3804 \pgfmanualbody
3805 Shortcut for:
3806 \begin{verbatim}
3807 custom include command={%
3808 \evalPlaceholder{%
3809 __ROBEXT_VERBATIM_COMMAND__{%
3810 __ROBEXT_CACHE_FOLDER____ROBEXT_OUTPUT_PREFIX__-out.txt}%
3811 }%
3812 },
3813 \end{verbatim}
3814 i.e.\ instead of printing the pdf we print the content of the file |__ROBEXT_OUTPUT_PREFIX__-out.txt| using the command in |__ROBEXT_VERBATIM_COMMAND__|, that defaults to |\verbatiminput|:
3815 \begin{codeAndResult}
3816 \begin{CacheMeCode}{python, verbatim output}
3817 with open("__ROBEXT_OUTPUT_PREFIX__-out.txt", "w") as f:
3818 for i in range(5):
3819 f.write(f"Hello {i}\n")
3820 \end{CacheMeCode}
3821 \end{codeAndResult}
3822 \end{pgfmanualentry}
3823
3824 \begin{pgfmanualentry}
3825 \makeatletter%
3826 \def\extrakeytext{style, }
3827 \extractkey/robExt/debug\@nil
3828 \extractkey/robExt/print command and source\@nil
3829 \makeatother%
3830 \pgfmanualbody
3831 (new in v2.0) These two (alias) commands allow you to print the compilation command, the dependency file (useful to be sure you tracked all dependencies), and the source file:
3832 \begin{codeexample}[width=0pt,vbox]
3833 \begin{CacheMe}{latex,
3834 add dependencies={common_inputs.tex},
3835 add to preamble={\input{__ROBEXT_WAY_BACK__common_inputs.tex}},
3836 debug
3837 }
3838 The answer is \myValueDefinedInCommonInputs.
3839 \end{CacheMe}
3840 \end{codeexample}
3841
3842 \end{pgfmanualentry}
3843
3844
3845 \subsubsection{\LaTeX{} and \tikzname{}}
3846
3847 The |latex| preset is used to cache any \LaTeX{} content, like tikz pictures. Note that as of today, it supports overlay content out of the box (if the overlay is more than 30cm long, you might want to customize a placeholder), but not images that need to use |remember picture|.
3848
3849 \begin{pgfmanualentry}
3850 \makeatletter%
3851 \def\extrakeytext{style, }
3852 \extractkey/robExt/latex\@nil
3853 \makeatother%
3854 \pgfmanualbody
3855 This style sets the template |__ROBEXT_LATEX__| and the compilation command:\\ |__ROBEXT_LATEX_COMPILATION_COMMAND__|\\
3856 (cf \cref{sec:placeholders} for details), and adds a number of styles described below, to easily configure the most common options. You can use it as follows:
3857 \begin{codeexample}[width=0pt,vbox]
3858 The next picture is cached %
3859 \begin{CacheMe}{latex, add to preamble={\usepackage{tikz}}}
3860 \begin{tikzpicture}[baseline=(A.base)]
3861 \node[fill=red, rounded corners](A){My node that respects baseline.};
3862 \node[fill=red, rounded corners, opacity=.3,overlay] at (A.north east){I am an overlay text};
3863 \end{tikzpicture}
3864 \end{CacheMe} and you can see that overlay and depth works.
3865 \end{codeexample}
3866 \end{pgfmanualentry}
3867
3868 To see how to create your own preset or automatically load a library, see \cref{sec:customize}.
3869
3870 The next options can be used after calling the |latex| style:
3871
3872 \begin{pgfmanualentry}
3873 \makeatletter%
3874 \def\extrakeytext{style, }
3875 \extractkey/robExt/latex/use latexmk\@nil
3876 \extractkey/robExt/latex/use lualatex\@nil
3877 \extractkey/robExt/latex/use xelatex\@nil
3878 \extractkey/robExt/latex/use latex and dvi\@nil
3879 \extractkey/robExt/dvi to ps\@nil
3880 \makeatother%
3881 \pgfmanualbody
3882 The first three styles use latexmk/lualatex/xelatex to compile. It is a shortcut for:\\
3883 |set placeholder={__ROBEXT_LATEX_ENGINE__}{yourfavoriteengine}|\\
3884 |dvi to ps| is called internally in |use latex and dvi|, converts the |.dvi| file into a |.ps| file, and renames it into |.pdf| so that it is automatically included. |use latex and dvi| sets the compiler to |latex|, producing |dvi| files, and call |dvi to ps| to convert them to ps files that can be included. So if your workflow involves dvi, you can call directly:
3885 \begin{codeexample}[code only]
3886 \robExtConfigure{
3887 add to preset={latex}{use latex and dvi},
3888 }
3889 \end{codeexample}
3890 and you can then compile your file as usual with:
3891 \begin{verbatim}
3892 # --shell-escape only needed the first time you compile, see above for alternatives
3893 $ latex --shell-escape yourfile.tex
3894 $ dvips yourfile.dvi
3895 \end{verbatim}
3896 \end{pgfmanualentry}
3897
3898 \begin{pgfmanualentry}
3899 \makeatletter%
3900 \def\extrakeytext{style, }
3901 \extractkey/robExt/latex/set latex options=\marg{latex options}\@nil
3902 \extractkey/robExt/latex/add to latex options=\marg{latex options}\@nil
3903 \makeatother%
3904 \pgfmanualbody
3905 Set/add elements to the set of latex options of the |\documentclass| (it will automatically add a comma before if you add an element). Internally it sets |__ROBEXT_LATEX_OPTIONS__|. By default, it sets:\\
3906 |margin=__ROBEXT_LATEX_TRIM_LENGTH__|
3907 (where |__ROBEXT_LATEX_TRIM_LENGTH__| is defined as 30cm by default) in order to add a margin that will be trimmed later in the |\includegraphics|. This is useful not to cut stuff displayed outside of the bounding box (overlays).
3908 \end{pgfmanualentry}
3909
3910 \begin{pgfmanualentry}
3911 \makeatletter%
3912 \def\extrakeytext{style, }
3913 \extractkey/robExt/latex/set documentclass=\marg{documentclass}\@nil
3914 \makeatother%
3915 \pgfmanualbody
3916 Set the documentclass of the document (defaults to |standalone|). Internally, it sets the placeholder |__ROBEXT_LATEX_DOCUMENT_CLASS__|.
3917 \end{pgfmanualentry}
3918
3919 \begin{pgfmanualentry}
3920 \makeatletter%
3921 \def\extrakeytext{style, }
3922 \extractkey/robExt/latex/set preamble=\marg{code of preamble}\@nil
3923 \extractkey/robExt/latex/add to preamble=\marg{code of preamble}\@nil
3924 \extractkey/robExt/latex/set preamble hyperref=\marg{code of preamble}\@nil
3925 \extractkey/robExt/latex/add to preamble hyperref=\marg{code of preamble}\@nil
3926 \extractkey/robExt/latex/set preamble after hyperref=\marg{code of preamble}\@nil
3927 \extractkey/robExt/latex/add to preamble after hyperref=\marg{code of preamble}\@nil
3928 \makeatother%
3929 \pgfmanualbody
3930 Set/add element to the preamble (defaults to |standalone|). Internally, it sets the placeholder |__ROBEXT_LATEX_PREAMBLE__|. The variations |hyperref| and |after hyperref| are used to put stuff after the preambule, as |hyperref| typically needs to be loaded last (or nearly): packages that must be loaded after |hyperref| like |cref| can be added via |add to preamble after hyperref|.
3931 \end{pgfmanualentry}
3932
3933 \begin{pgfmanualentry}
3934 \makeatletter%
3935 \def\extrakeytext{style, }
3936 \extractkey/robExt/latex/do not wrap code\@nil
3937 \makeatother%
3938 \pgfmanualbody
3939 By default, the main content is wrapped into a box in order to measure its depth to properly set the baseline. If you do not want to do this wrapping, you can set this option. Internally, it is a shortcut for:\\
3940 |set placeholder={__ROBEXT_LATEX_MAIN_CONTENT_WRAPPED__}{__ROBEXT_MAIN_CONTENT__}|
3941 \textbf{IMPORTANT}: note that it means that you might need to adapt your code to take into account the fact that they are inside a box (I don't know of any other solution to compute the depth, but it does not mean that there is none).
3942 \end{pgfmanualentry}
3943
3944 \begin{pgfmanualentry}
3945 \makeatletter%
3946 \def\extrakeytext{style, }
3947 \extractkey/robExt/latex/in command\@nil
3948 \makeatother%
3949 \pgfmanualbody
3950 Sets |__ROBEXT_MAIN_CONTENT| to point to |__ROBEXT_MAIN_CONTENT_ORIG__| to remove any wrapping of the user input, for instance made by tikzpicture.
3951 \end{pgfmanualentry}
3952
3953 \begin{pgfmanualentry}
3954 \makeatletter%
3955 \def\extrakeytext{style, }
3956 \extractkey/robExt/tikz\@nil
3957 \extractkey/robExt/tikzpicture\@nil
3958 \makeatother%
3959 \pgfmanualbody
3960 |tikz| loads |latex| and then adds |tikz| to the preamble. |tikzpicture| first load |tikz| and wraps the main content within |\begin{tikzpicture}| and |\end{tikzpicture}| using:\\
3961 \begin{verbatim}
3962 set placeholder={__ROBEXT_MAIN_CONTENT__}{%
3963 \begin{tikzpicture}__ROBEXT_MAIN_CONTENT_ORIG__\end{tikzpicture}%
3964 }
3965 \end{verbatim}
3966 so that the user does not need to type it. See for instance the introduction for examples of use.
3967 \end{pgfmanualentry}
3968
3969
3970 \subsubsection{Python}
3971
3972 We provide support for python:
3973
3974 \begin{pgfmanualentry}
3975 \makeatletter%
3976 \def\extrakeytext{style, }
3977 \extractkey/robExt/python\@nil
3978 \makeatother%
3979 \pgfmanualbody
3980 Load the |python| preset (inspect |__ROBEXT_PYTHON__|) for details on the exact template, but note that this template might be subject to changes. We also provide a few helper functions:
3981 \begin{itemize}
3982 \item |write_to_out(text)| writes |text| to the |*-out.tex| file that will be loaded automatically before running the include function
3983 \item |parse_args()| is a function that returns a dictionary mapping some keys to values depending on the called arguments: for instance, if you call the python file with |python script key1 value1 key2 value2|, then the dictionary will map |key1| to |value1| and |key2| to |value2|. You might like this in conjunction with commands presented in \cref{sec:configureCompilationCommand}. Note that if you place placeholders in your code, you might not need this, but this is used if you plan to use your script outside of this library.
3984 \item |get_cache_folder()| outputs the cache folder.
3985 \item |get_file_base()| outputs the prefix of all files that should be created by this script, that looks like |robExt-somehash|.
3986 \item |get_current_script()| returns the current script.
3987 \item |get_filename_from_extension(extension)| outputs the prefix |robExt-somehash| concatenated with the extension. You often need this function to get the path of a file that your script is creating, for instance, |get_filename_from_extension("-out.txt")| is the path |*-out.txt| of the file that is read by |verbatim output|.
3988 \item |get_verbatim_output()| returns |get_filename_from_extension("-out.txt")|
3989 \item |finished_with_no_error()| creates the pdf file if it does not exists (to certify that the compilation ran without issues). The template automatically runs this function at the end.
3990 \end{itemize}
3991 We demonstrate its usage on a few examples:
3992 \begin{codeAndResult}
3993 \begin{CacheMeCode}{python, verbatim output}
3994 with open(get_verbatim_output(), "w") as f:
3995 for i in range(5):
3996 f.write(f"Hello {i}\n")
3997 \end{CacheMeCode}
3998 \end{codeAndResult}
3999
4000 Note that if you use a version before 2.6, you cannot indent further the python code (i.e.\ the first line must not start with any space). This is fixed in 2.6 with the addition of |remove leading spaces if not disabled| in the python preset by default, that will remove automatically any unnecessary indentation. If you use automatic indentation in your text editor, you might also like to use |remove spaces until| so that automatically indenting your whole document does not ruin the indentation of the python code.
4001
4002 You can also generate some images. This code will produce the image in \cref{fig:pythonGeneratedImage2}:
4003 \begin{codeexample}[code only]
4004 \begin{CacheMeCode}{python, set includegraphics options={width=.8\linewidth}}
4005 import matplotlib.pyplot as plt
4006 year = [2014, 2015, 2016, 2017, 2018, 2019]
4007 tutorial_count = [39, 117, 111, 110, 67, 29]
4008 plt.plot(year, tutorial_count, color="#6c3376", linewidth=3)
4009 plt.xlabel('Year')
4010 plt.ylabel('Number of futurestud.io Tutorials')
4011 plt.savefig("__ROBEXT_OUTPUT_PDF__")
4012 \end{CacheMeCode}
4013 \end{codeexample}
4014 {\begin{figure}
4015 \centering
4016 \begin{CacheMeCode}{python, set includegraphics options={width=.8\linewidth}}
4017 import matplotlib.pyplot as plt
4018 year = [2014, 2015, 2016, 2017, 2018, 2019]
4019 tutorial_count = [39, 117, 111, 110, 67, 29]
4020 plt.plot(year, tutorial_count, color="#6c3376", linewidth=3)
4021 plt.xlabel('Year')
4022 plt.ylabel('Number of futurestud.io Tutorials')
4023 plt.savefig("__ROBEXT_OUTPUT_PDF__")
4024 \end{CacheMeCode}
4025 \caption{Image generated with python.}
4026 \label{fig:pythonGeneratedImage2}
4027 \end{figure}
4028 }
4029
4030 Note that by default, the executable called |python| is run. It seems like on windows |python3| is not created and only |python| exists, while on linux the user can choose whether |python| should point to |python3| or |python2| (on NixOs, I directly have |python| pointing to |python3|, and in ubuntu, you might need to install |python-is-python3| or create a symlink, as explained \href{https://askubuntu.com/questions/1296790/python-is-python3-package-in-ubuntu-20-04-what-is-it-and-what-does-it-actually}{here}). In any case, you can customize the name of the executable by setting something like:
4031 \begin{verbatim}
4032 \setPlaceholder{__ROBEXT_PYTHON_EXEC__}{python3}
4033 \end{verbatim}
4034 or using the style |force python3| that forces |python3|.
4035 \end{pgfmanualentry}
4036
4037
4038 \begin{pgfmanualentry}
4039 \makeatletter%
4040 \def\extrakeytext{style, }
4041 \extractkey/robExt/python print code and result\@nil
4042 \makeatother%
4043 \pgfmanualbody
4044 (Warning: in 2.7 a bug was introduced (fixed in v2.8) where an empty line was automatically added in front of the code) This is a demo style that can print a python code and its result.
4045 \begin{codeAndResult}
4046 \begin{CacheMeCode}{python print code and result, set title={The for loop}}
4047 for name in ["Alice", "Bob"]:
4048 print(f"Hello {name}")
4049 \end{CacheMeCode}
4050 \end{codeAndResult}
4051 You can set |__ROBEXT_PYTHON_TCOLORBOX_PROPS__| the options of the tcolorbox,\\ |__ROBEXT_PYTHON_CODE_MESSAGE__| and |__ROBEXT_PYTHON_RESULT_MESSAGE__| which are displayed before the corresponding block, |__ROBEXT_PYTHON_LSTINPUT_STYLE__| which contains the default lstinput style and |__MY_TITLE__| (cf |set title|) that contains the title of the box. Make sure to have the following packages to use the default styling:
4052 \begin{verbatim}
4053 \usepackage{pythonhighlight}
4054 \usepackage{tcolorbox}
4055 \end{verbatim}
4056 \end{pgfmanualentry}
4057
4058 \begin{pgfmanualentry}
4059 \makeatletter%
4060 \def\extrakeytext{style, }
4061 \extractkey/robExt/python/add import\@nil
4062 \makeatother%
4063 \pgfmanualbody
4064 (since v2.1) Add an import statement in the first part of the file.
4065 \begin{codeexample}[vbox]
4066 \robExtConfigure{
4067 add to preset={my python}{
4068 python print code and result,
4069 add import={from math import cos},
4070 add import={from math import sin},
4071 },
4072 }
4073 \begin{CacheMeCode}{my python}
4074 print(cos(1)+sin(2))
4075 \end{CacheMeCode}
4076 \end{codeexample}
4077
4078 \end{pgfmanualentry}
4079
4080 \subsubsection{Bash}
4081
4082 We provide a basic bash template, that sets:
4083 \begin{verbatim}
4084 set -e
4085 outputTxt="__ROBEXT_OUTPUT_PREFIX__-out.txt"
4086 outputTex="__ROBEXT_OUTPUT_PREFIX__-out.tex"
4087 outputPdf="__ROBEXT_OUTPUT_PDF__"
4088 \end{verbatim}
4089 in order to quit when an error occurs, and to define two variables containing the path to the |pdf| file and to the file that is read by the |verbatim output| setting (that just apply a |\verbatiminput| on that file). Finally, it also creates the file |outputPdf| with |echo "ok"| in order to notify that the compilation succeeded.
4090
4091 In practice:
4092 \begin{codeAndResult}
4093 \begin{CacheMeCode}{bash, verbatim output}
4094 # $outputTxt contains the path of the file that will be printed via \verbatiminput
4095 uname -srv > "${outputTxt}"
4096 \end{CacheMeCode}
4097 \end{codeAndResult}
4098
4099 \subsubsection{Verbatim text}
4100
4101 Sometimes, it might be handy to write the text to a file and use it somehow. This is possible using |verbatim text|, that defaults to calling |\verbatiminput| on that file:
4102
4103 \begin{codeAndResult}
4104 \begin{CacheMeCode}{verbatim text}
4105 def some_verbatim_fct(a):
4106 # See this is a verbatim code where I can use the % symbol
4107 return a % b
4108 \end{CacheMeCode}
4109 \end{codeAndResult}
4110
4111 You can also call |verbatim text no include|: it will not include the text, but it sets a macro |\robExtPathToInput| containing the path to the input file. Use it the way you like! For instance, we define here a macro |codeAndResult| that prints the code and runs it (we use a pretty printer from pgf, so you need to load |\usepackage{tikz}\input{pgfmanual-en-macros.tex}| to use it). It is what we use right now in this documentation for verbatim blocks like here. You can obtain a simpler version using:
4112
4113 \begin{codeAndResult}
4114 \begin{CacheMeCode}{verbatim text no include}
4115 \NewDocumentCommand{\testVerbatim}{+v}{
4116 \begin{flushleft}\ttfamily%
4117 #1
4118 \end{flushleft}}
4119 \testVerbatim{Demo % with percent}
4120 \end{CacheMeCode}
4121 We will input the file \robExtPathToInput{}:
4122 \input{\robExtPathToInput}
4123 This file contains:
4124 \verbatiminput{\robExtPathToInput}
4125 \end{codeAndResult}
4126
4127 You might also like to use |name output=yourfile| that will create two macros |\yourfile| and |\yourfileInCache|, equal respectively to the prefix |robExt-somehash| and |pathOfCache/robExt-somehash|.
4128
4129 \subsubsection{Online images}
4130
4131 We also provide support for online images since v2.3.
4132 \begin{pgfmanualentry}
4133 \extractcommand\includegraphicsWeb\opt{<robExt options>}\opt{\oarg{includegraphics options}}\marg{url image}\@@
4134 \makeatletter%
4135 \def\extrakeytext{style, }
4136 \extractkey/robExt/web image\@nil
4137 \extractkey/robExt/web image/wget\@nil
4138 \extractkey/robExt/web image/curl\@nil
4139 \makeatother%
4140 \pgfmanualbody
4141 |\includegraphicsWeb| is used in place of |\includegraphics| to download online images:
4142 \begin{codeexample}[width=0pt,vbox]
4143 Here is a bear downloaded online: \includegraphicsWeb[width=3cm]{https://placebear.com/400/300}.
4144 \end{codeexample}
4145 By default, the engine uses |wget| in linux (since it is installed by default) and |curl| on windows (should also be installed by default on recent windows). But you can change it by modifying the |web image| preset (or using the optional robExt options that are loaded after |web image|):
4146 \begin{codeexample}[width=0pt,vbox]
4147 \robExtConfigure{
4148 add to preset={web image}{
4149 curl
4150 },
4151 }
4152
4153 Here is a bear downloaded online: \includegraphicsWeb[width=3cm]{https://placebear.com/400/303}.
4154 \end{codeexample}
4155 By default, the |wget| and |curl| presets are defined as:
4156 \begin{verbatim}
4157 wget/.style={
4158 set compilation command={wget "__ROBEXT_MAIN_CONTENT__" -O "__ROBEXT_OUTPUT_PDF__"},
4159 },
4160 curl/.style={
4161 set compilation command={curl "__ROBEXT_MAIN_CONTENT__" -L -o "__ROBEXT_OUTPUT_PDF__"},
4162 },
4163 \end{verbatim}
4164 \end{pgfmanualentry}
4165
4166 \subsubsection{Gnuplot}
4167
4168 We also provide support for gnuplot since v2.3.
4169
4170 \begin{pgfmanualentry}
4171 \makeatletter%
4172 \def\extrakeytext{style, }
4173 \extractkey/robExt/gnuplot\@nil
4174 \extractkey/robExt/gnuplot/set terminal=\marg{terminal and options}\@nil
4175 \extractkey/robExt/gnuplot/pdf terminal=\opt{pdf terminal options}\@nil
4176 \extractkey/robExt/gnuplot/tikz terminal=\opt{tikz terminal options}\@nil
4177 \makeatother%
4178 \pgfmanualbody
4179 Loads the |gnuplot| preset. By default, it uses the |pdf| terminal:
4180 \begin{codeAndResult}
4181 \begin{CacheMeCode}{gnuplot}
4182 plot sin(x)
4183 \end{CacheMeCode}
4184 \end{codeAndResult}
4185
4186 You can also specify the gnuplot options to the pdf terminal, like the size, using:
4187 \begin{codeAndResult}
4188 \begin{CacheMeCode}{gnuplot,pdf terminal={size 5cm,4cm}}
4189 plot sin(x)
4190 \end{CacheMeCode}
4191 \end{codeAndResult}
4192 You can also change the options of the |includegraphics| command used to include the image, using as usual:
4193 \begin{codeAndResult}
4194 \begin{CacheMeCode}{gnuplot,set includegraphics options={width=5cm,height=4cm}}
4195 plot sin(x)
4196 \end{CacheMeCode}
4197 \end{codeAndResult}
4198 You can also use other terminals using the |set terminal| option. For instance, you can use the png terminal and configure its size using:
4199 \begin{codeAndResult}
4200 \begin{CacheMeCode}{gnuplot,set terminal={png size 400,300}}
4201 plot sin(x)
4202 \end{CacheMeCode}
4203 \end{codeAndResult}
4204 The tikz terminal is a bit special since we do not want to use |\includegraphics| but |\input| to include the file. You can use it like this, just make sure:
4205 \begin{itemize}
4206 \item to have gnuplot installed with lua support. With nix you can get it with:\\
4207 |nix-shell -p '(gnuplot.override { withLua = true; })'|
4208 \item Add |\usepackage{gnuplot-lua-tikz}| after making sure to run\\
4209 |gnuplot -e "set terminal tikz createstyle"| once to create the |.sty| file.
4210 \end{itemize}
4211 \begin{codeAndResult}
4212 % \usepackage{gnuplot-lua-tikz} %% Generate with gnuplot -e "set terminal tikz createstyle"
4213 \begin{CacheMeCode}{gnuplot,tikz terminal={size 5cm,4cm}}
4214 plot sin(x)
4215 \end{CacheMeCode}
4216 \end{codeAndResult}
4217 (Note that if you do not provide any option to |tikz terminal|, it will just use the default value in gnuplot, you can also add any other option to the terminal here.) By default, we only cache the gnuplot compilation, but the |\input| is not cached (so gnuplot will not be run again the next time, but tikz will run every time). But it can also be cached, just add |cache tikz| for that:
4218 \begin{codeAndResult}
4219 \robExtConfigure{
4220 add to preset={tikz}{
4221 % Run gnuplot -e "set terminal tikz createstyle" in the robustExternalize folder first
4222 % to create this file, or, better, run this command in your local folder and use
4223 % "copy file to cache" to copy the 3 generated files.:
4224 add to preamble={\usepackage{gnuplot-lua-tikz}},
4225 },
4226 add to preset={gnuplot}{
4227 tikz terminal/.append style={
4228 cache tikz,
4229 },
4230 },
4231 }
4232 \begin{CacheMeCode}{gnuplot, tikz terminal={size 8cm,5cm}}
4233 plot cos(x)
4234 \end{CacheMeCode}
4235 \end{codeAndResult}
4236 We also automatically add |__ROBEXT_WAY_BACK__| to the |loadpath|, this way you do NOT need to type |plot "__ROBEXT_WAY_BACK__yourfile.dat"`| if the data is in the main folder. Note however that you need to add this file to the list of dependencies, otherwise it will not be recompiled if the file changes:
4237 \begin{codeAndResult}
4238 \begin{CacheMeCode}{gnuplot, dependencies={gnuplot_data.dat}}
4239 plot "gnuplot_data.dat"
4240 \end{CacheMeCode}
4241 \end{codeAndResult}
4242
4243 You can also use the current text width when using the tikz terminal using something like:\\
4244 |tikz terminal/.expanded={size \lenToCm{\textwidth},\lenToCm{.3\textwidth}}|\\
4245 Full example:
4246 \begin{codeAndResult}
4247 % Just to check size:
4248 \noindent\rule{\textwidth}{1mm}\\%
4249 \begin{CacheMeCode}{gnuplot, tikz terminal/.expanded={size \lenToCm{\textwidth},\lenToCm{.3\textwidth}}}
4250 plot cos(x)
4251 \end{CacheMeCode}
4252 \end{codeAndResult}
4253
4254 Similar to the tikz terminal, you can also use the |cairolatex| terminal like this:
4255 \begin{codeAndResult}
4256 \begin{CacheMeCode}{gnuplot,cairolatex terminal}
4257 plot sin(x)
4258 \end{CacheMeCode}
4259 \end{codeAndResult}
4260 As before, you can also specify the size, for instance it term of the current textwidth:
4261 \begin{codeAndResult}
4262 \begin{CacheMeCode}{gnuplot, cairolatex terminal/.expanded={size \lenToCm{\textwidth},\lenToCm{.3\textwidth}}}
4263 plot cos(x)
4264 \end{CacheMeCode}
4265 \end{codeAndResult}
4266 \end{pgfmanualentry}
4267
4268 \begin{pgfmanualentry}
4269 \extractcommand\robExtGpgetvar\marg{variable name}\@@
4270 \extractcommand\robExtGpgetvarNb\opt{*}\opt{\oarg{text, default 404}}\marg{variable name}\@@
4271 \pgfmanualbody
4272 Like |\gpgetvar{}| from |gnuplot-lua-tikz| but does not produce an error if the variable does not exist yet (mostly useful if you compile in parallel as shown \mylink{https://github.com/leo-colisson/robust-externalize/issues/17}{here}). The first time, you will get a message like:
4273
4274 \robExtGpgetvar{test_variable}
4275
4276 and later this will compile fine:
4277 \begin{codeAndResult}
4278 \begin{CacheMeCode}{gnuplot, tikz terminal={providevars test_variable}}
4279 test_variable = 5
4280 plot cos(test_variable * x) title "Test2"
4281 \end{CacheMeCode}
4282 Variable is \robExtGpgetvar{test_variable}.
4283 \end{codeAndResult}
4284 |\robExtGpgetvarNb| is similar, except that it prints a number 404 by default (useful if you use it in siunit) and is expandable (also \mylink{https://github.com/leo-colisson/robust-externalize/issues/17}{needed for siunit}). You can choose another text using the optional argument. The star version prints a warning in the log if the variable does not exist, but can only be used in LuaLaTeX:
4285 \begin{codeAndResult}
4286 Variable is \num[round-mode=figures,round-precision=3]{\robExtGpgetvarNb{non_existing_variable}}.
4287 \end{codeAndResult}
4288 Note that you will get a warning if the variable does not exist (yet?) only in LuaLaTeX as in other engines there is no \mylink{https://tex.stackexchange.com/questions/705299/print-message-in-expandable-macro/705304}{way to write in the log with an expandable function}.
4289 \end{pgfmanualentry}
4290
4291 \subsubsection{TikZit}
4292
4293 \mylink{https://tikzit.github.io/}{TikZit} is a software to produce \tikzname{} images via a graphical interface.
4294
4295 \begin{pgfmanualentry}
4296 \extractcommand\cacheTikzit\opt{\oarg{preset}}\@@
4297 \extractcommand\cacheTikzitWithStyle\opt{\oarg{preset}}\marg{name of style file}\@@
4298 \pgfmanualbody
4299 (since v2.5) These command will automatically cache the |\tikzfig| command (and therefore also |\ctikzfig|). While |\cacheTikzit| will let you create the preset (named |tikzit| preset by default), |\cacheTikzitWithStyle| will automatically create the preset style for you, loading your style given as parameter:
4300 \begin{codeexample}[vbox]
4301 %%%%%%% In your preamble:
4302 \cacheTikzitWithStyle{new_zxstyle.tikzstyles}
4303
4304 %%%%%%% In your document:
4305 \tikzfig{demo} % figures/ is optional
4306 \end{codeexample}
4307 If you prefer to do it manually, you can do instead:
4308 \begin{codeexample}[vbox]
4309 %%%%%%% In your preamble:
4310 \robExtConfigure{
4311 % First, we copy the tikzit-related files to the cache:
4312 copy file to cache={tikzit.sty},
4313 copy file to cache={new_zxstyle.tikzstyles},
4314 % We create the tikzit preset loaded by default:
4315 new preset={tikzit}{
4316 latex,
4317 add to preamble={
4318 \usepackage{tikzit}
4319 \input{new_zxstyle.tikzstyles}
4320 },
4321 },
4322 }
4323 % Cache all tikzit figures:
4324 \cacheTikzit
4325
4326 %%%%%%% In your document:
4327 \tikzfig{figures/demo}
4328 \end{codeexample}
4329 \textbf{WARNING:} since the tikz picture uses |baseline| that relies on the current font size to vertically align the figure, and since we do not yet propagate the current font size to the cached picture (there are so many ways to configure the font in \LaTeX\dots{}), you should make sure that the |tikzit| preset sets the font size like in your main document, for instance via:
4330 \begin{codeexample}[vbox]
4331 %%%%%%% In your preamble:
4332 \cacheTikzitWithStyle{new_zxstyle.tikzstyles}
4333 \robExtConfigure{
4334 add to preset={tikzit}{
4335 add to latex options={12pt},
4336 },
4337 }
4338 %%%%%%% In your document:
4339 \tikzfig{demo} % figures/ is optional
4340 \end{codeexample}
4341 Note that |\tikzfig| accepts an additional optional argument for further options, for instance to forward locally a macro or to disable externalization:
4342 \begin{codeexample}[vbox]
4343 %%%%%%% In your preamble, make sure to load:
4344 %% \usepackage{tikzit}
4345 %% \input{new_zxstyle.tikzstyles}
4346 %% if you want "disable externalization" to work.
4347 \cacheTikzitWithStyle{new_zxstyle.tikzstyles}
4348 %%%%%%% In your document:
4349 \tikzfig<disable externalization>{demo} % figures/ is optional
4350 \end{codeexample}
4351 \end{pgfmanualentry}
4352
4353 \subsubsection{Custom languages}
4354
4355 To add support to new languages, see \cref{sec:otherLanguages} for an example.
4356
4357
4358 \subsection{List of special placeholders and presets}\label{sec:placeholders}
4359
4360 This library defines a number of pre-existing placeholders, or placeholders playing a special role. We list some of them in this section. All placeholders created by this library start with |__ROBEXT_|. Note that you can list all predefined placeholders (at least those globally defined) using |\printImportedPlaceholdersExceptDefaults| (note that some other placeholders might be created directly in the style set right before the command, and may not appear in this list if you call it before setting the style).
4361
4362 \subsubsection{Generic placeholders}
4363
4364 We define two special placeholders that should be defined by the user (possibly indirectly, using presets offered by this library):
4365 \begin{itemize}
4366 \item |__ROBEXT_TEMPLATE__| is a placeholder that should contain the code of the file to compile.
4367 \item |__ROBEXT_MAIN_CONTENT_ORIG__| is a placeholder containing the text typed by the user, automatically set by |CacheMe|, |CacheMeCode| etc. You rarely need to deal with this placeholder directly since |__ROBEXT_MAIN_CONTENT__| will typically point to it and add some necessary wrapping.
4368 \item |__ROBEXT_MAIN_CONTENT__| is a placeholder that might be used inside |__ROBEXT_TEMPLATE__|, that points by default to |__ROBEXT_MAIN_CONTENT_ORIG__| and that contains the content that should be typed inside the document. For instance, this might be a tikz picture, a python function without the import etc. Note that it is often used to wrap the text of the user |__ROBEXT_MAIN_CONTENT_ORIG__|: for instance, the |tikzpicture| preset adds the |\begin{tikzpicture}| around the user code automatically: this way we do not need to edit the command to disable externalization.
4369 \item |__ROBEXT_COMPILATION_COMMAND__| contains the compilation command to run to compile the file (assuming we are in the cache folder).
4370 \end{itemize}
4371
4372 We also provide a number of predefined placeholders in order to get the name of the source file etc... Note that most of these placeholders are defined (and/or expanded inplace) late during the compilation stage as one needs first to obtain the hash of the file, and therefore all dependencies, the content of the template etc.
4373 \begin{itemize}
4374 \item |__ROBEXT_SOURCE_FILE__| contains the path of the file to compile (containing the content of |__ROBEXT_TEMPLATE__|) like |robExt-somehash.tex|, relative to the cache folder (since we always go to this folder before doing any action, you most likely want to use this directly in the compilation command).
4375 \item |__ROBEXT_OUTPUT_PDF__| contains the path of the pdf file produced after the compilation command relative to the cache folder (like |robExt-somehash.pdf|). Even if you do not plan to output a pdf file, you should still create that file at the end of the compilation so that this library can know whether the compilation succeeded.
4376 \item |__ROBEXT_OUTPUT_PREFIX__| contains the prefix that all newly created file should follow, like |robExt-somehash|. If you want to create additional files (e.g. a picture, a video, a console output etc...) make sure to make it start with this string. It will not only help to ensure purity, but it also allows us to garbage collect useless files easily.
4377 \item |__ROBEXT_WAY_BACK__| contains the path to go back to the main project from the cache folder, like |../| (internally it is equals to the expanded value of |\robExtPrefixPathWayBack|).
4378 \item |__ROBEXT_CACHE_FOLDER__| contains the path to the cache folder. Since most commands are run from the cache folder, this should not be really useful to the user.
4379 \end{itemize}
4380
4381 You can also use these placeholders to customize the default include function:
4382 \begin{itemize}
4383 \item |__ROBEXT_INCLUDEGRAPHICS_OPTIONS__| contains the options given to |\includegraphics| when loading the pdf
4384 \item |__ROBEXT_INCLUDEGRAPHICS_FILE__| contains the file loaded by |\includegraphics|, defaults to |\robExtAddCachePathAndName{\robExtFinalHash.pdf}|, that is itself equivalent to |__ROBEXT_CACHE_FOLDER____ROBEXT_OUTPUT_PDF__| or\\|__ROBEXT_CACHE_FOLDER____ROBEXT_OUTPUT_PREFIX__.pdf|.
4385 \end{itemize}
4386
4387 \subsubsection{Placeholders related to \LaTeX{}}
4388 Some placeholders are reserved only when dealing with \LaTeX{} code:
4389 \begin{itemize}
4390 \item |__ROBEXT_LATEX__| is the main entrypoint, containing all the latex template. It internally calls other placeholders listed below.
4391 \item |__ROBEXT_LATEX_OPTIONS__|: contains the options to compile the document, like |a4paper|. Empty by default.
4392 \item |__ROBEXT_LATEX_DOCUMENT_CLASS__|: contains the class of the document. Defaults to |standalone|.
4393 \item |__ROBEXT_LATEX_PREAMBLE__|: contains the preamble. Is empty by default.
4394 \item |__ROBEXT_LATEX_MAIN_CONTENT_WRAPPED__|: content inside the |document| environment. It will wrap the actual content typed by the user |__ROBEXT_MAIN_CONTENT__| around a box to compute its depth. If you do not want this behavior, you can set |__ROBEXT_LATEX_MAIN_CONTENT_WRAPPED__| to be equal to |__ROBEXT_MAIN_CONTENT__|. It calls internally |__ROBEXT_LATEX_CREATE_OUT_FILE__| and |__ROBEXT_LATEX_WRITE_DEPTH_TO_OUT_FILE__| to do this computation.
4395 \item |__ROBEXT_LATEX_CREATE_OUT_FILE__| creates a new file called |\jobname-out.tex| and open it in the handle called |\writeRobExt|
4396 \item |__ROBEXT_LATEX_WRITE_DEPTH_TO_OUT_FILE__| writes the height, depth and width of the box |\boxRobExt| into the filed opened in |\writeRobExt|.
4397 \item |__ROBEXT_LATEX_COMPILATION_COMMAND__| is the command used to compile a \LaTeX{} document. It uses internally other placeholders:
4398 \item |__ROBEXT_LATEX_ENGINE__| is the engine used to compile the document (defaults to |pdflatex|)
4399 \item |__ROBEXT_LATEX_COMPILATION_COMMAND_OPTIONS__| contains the options used to compile the document (defaults to |-shell-escape -halt-on-error|)
4400 \end{itemize}
4401
4402 \subsubsection{Placeholders related to python}
4403
4404 \begin{itemize}
4405 \item |__ROBEXT_PYTHON_EXEC__| contains the python executable (defaults to |python|) used to compile
4406 \item |__ROBEXT_PYTHON__| contains the python template
4407 \item |__ROBEXT_PYTHON_IMPORT__| can contain import statements
4408 \item |__ROBEXT_PYTHON_MAIN_CONTENT_WRAPPED__| is used to add all the above functions. You can set it to |__ROBEXT_MAIN_CONTENT__| if you do not want them
4409 \item |__ROBEXT_PYTHON_FINISHED_WITH_NO_ERROR__| is called at the end to create the pdf file even if it is not created, you can set it to the empty string if you do not want to do that.
4410 \end{itemize}
4411
4412 \subsubsection{Placeholders related to bash}
4413
4414 \begin{itemize}
4415 \item |__ROBEXT_BASH_TEMPLATE__| contains the bash template. By default, it sets |set -e|, creates |outputTxt|, |outputTex| and |outputPdf| pointing to the corresponding files, and it created the pdf file at the end.
4416 \item |__ROBEXT_SHELL__| contains the shell (defaults to |bash|).
4417 \end{itemize}
4418
4419
4420 \subsection{Customize presets and create your own style}\label{sec:customize}
4421
4422 Note that you can define your own presets simply by creating a new pgf style (please refer to tikz-pgf's documentation for more details). For instance, we defined the |tikz| and |tikzpicture| presets using:
4423 \begin{codeexample}[code only]
4424 \robExtConfigure{
4425 new preset={tikz}{
4426 latex,
4427 add to preamble={\usepackage{tikz}},
4428 },
4429 new preset={tikzpicture}{
4430 tikz,
4431 set placeholder={__ROBEXT_MAIN_CONTENT__}{\begin{tikzpicture}__ROBEXT_MAIN_CONTENT_ORIG__\end{tikzpicture}},
4432 },
4433 }
4434 \end{codeexample}
4435 in order to automatically load |tikz| and add the surrounding |tikzpicture| when needed (note that the style is always loaded \textbf{after} the definition of |__ROBEXT_MAIN_CONTENT_ORIG__|, so in theory you could also modify it directly even if it is not recommended). You can also customize an existing style by adding stuff to it using |add to preset| (or |.append style| but make sure to double the hashes). For instance, here, we add the |shadows| library to the |tikz| preset by default:
4436 \begin{codeexample}[width=0pt,vbox]
4437 \robExtConfigure{
4438 add to preset={tikz}{
4439 add to preamble={\usetikzlibrary{shadows}},
4440 },
4441 }
4442 See, tikz's style now packs the |shadows| library by default: %
4443 \begin{CacheMe}{tikzpicture}[even odd rule]
4444 \filldraw [drop shadow,fill=white] (0,0) circle (.5) (0.5,0) circle (.5);
4445 \end{CacheMe}
4446 \end{codeexample}
4447
4448
4449 \subsection{Cache automatically a given environment}\label{sec:wrapAutomatically}
4450
4451 It might be handy to cache automatically a given environment: we already provide:\\ |\cacheTikz|\\
4452 to cache all tikz pictures (unless externalization is disabled), but we also provide tools to handle arbitrary environments.
4453
4454 \begin{pgfmanualentry}
4455 \extractcommand\robExtExternalizeAllTikzpictures\opt{\oarg{preset for tikz}}\opt{\oarg{preset for tikzpicture}}\opt{\oarg{delimiters}}\@@
4456 \extractcommand\cacheTikz\opt{\oarg{preset for tikz}}\opt{\oarg{preset for tikzpicture}}\opt{\oarg{delimiters}}\@@
4457 \extractcommand\robExtDoNotExternalizeAllTikzpictures\@@
4458 \extractcommand\doNotCacheTikz\@@
4459 \makeatletter%
4460 \def\extrakeytext{style, }
4461 \extractkey/robExt/cache tikz\@nil
4462 \extractkey/robExt/cache tikz\@nil
4463 \extractkey/robExt/cache tikz 2 args=\marg{tikz preset}\marg{tikzpicture preset}\@nil
4464 \extractkey/robExt/cache tikz 3 args=\marg{tikz preset}\marg{tikzpicture preset}\marg{delimiters cacheMe options}\@nil
4465 \makeatother%
4466 \pgfmanualbody
4467 (|cache tikz*| from 2.3, simply style alias) This will automatically cache all tikz pictures (the |*ExternalizeAllTikzpicturers| are alias of the |*cacheTikz| which is available from v2.0). Since v2.0, we added the delimiters options and we allow to specify custom presets for |tikz| and |tikzpicture|, and we parse |\tikz| as well (the |tikz| preset is now used by |\tikz| by default while the |tikzpicture| preset is used by |tikzpicture|). Note that we add an additional optional argument to the tikz picture via its first argument delimited by |delimiters| (defaults to |<>|) to specify preset options, which can for instance be practical to disable externalization on individual pictures. Cf.\ \cref{sec:disableExternalization} to see an example of use.
4468 \begin{codeexample}[width=0pt,vbox]
4469 \cacheTikz
4470
4471 \def\whereIAm{(not cached)}
4472 \robExtConfigure{
4473 add to preset={tikz}{
4474 add to preamble={
4475 \def\whereIAm{(cached)}
4476 },
4477 },
4478 }
4479
4480 \tikz \node[fill=pink, rounded corners]{See that this syntax can be safely used. \whereIAm};
4481
4482 \tikz<add to preamble={\def\sayHello#1{Hello #1!}}> \node[fill=green, rounded corners]{\sayHello{Alice} \whereIAm};
4483
4484 \tikz<disable externalization> \node[fill=green, rounded corners]{Foo \whereIAm};
4485 \end{codeexample}
4486 Here is an example to specify arguments via parenthesis:
4487 \begin{codeexample}[width=0pt,vbox]
4488 % the first two arguments are the default presets used by \tikz and \tikzpicture
4489 \cacheTikz[tikz][tikzpicture][()]
4490
4491 \def\whereIAm{(not cached)}
4492 \robExtConfigure{
4493 add to preset={tikz}{
4494 add to preamble={
4495 \def\whereIAm{(cached)}
4496 },
4497 },
4498 }
4499
4500 \tikz \node[fill=pink, rounded corners]{See that this syntax can be safely used. \whereIAm};
4501
4502 \tikz(add to preamble={\def\sayHello#1{Hello #1!}}) \node[fill=green, rounded corners]{\sayHello{Alice} \whereIAm};
4503
4504 \tikz(disable externalization) \node[fill=green, rounded corners]{Foo \whereIAm};
4505 \end{codeexample}
4506 You can also change the default style loaded for tikz and tikzpicture (note that you might prefer to modify |tikz| directly using |add to preset|), but you need v2.1 (buggy in v2.0):
4507
4508 \begin{codeexample}[vbox]
4509 % You might prefer to modify tikz directly using "add to preset"
4510 \cacheTikz[tikz, add to preamble={\def\hello{H}},][tikzpicture,
4511 add to preamble={\def\hello{HH}},
4512 ]
4513
4514 \tikz[baseline=(A.base)] \node(A){In tikz \hello}; %
4515 \begin{tikzpicture}[baseline=(A.base)]
4516 \node(A){In tikzpicture \hello};
4517 \end{tikzpicture}
4518 \end{codeexample}
4519 Note that the |cache tikz| styles (the variation just provide default values) is useful for instance if you only want to locally enable |cache tikz| for the |\input| of a style (this way you can cache the output of a cached thing\dots{}). For instance, |gnuplot| with a tikz terminal will compile into a tex file that will be inputted. But unless |\cacheTikz| is enabled, the inputted picture will not be cached (i.e. tikz will need to run). If you still want to cache it without enabling |\cacheTikz| globally, you can load this style in the |gnuplot| style, or do something like:
4520
4521 |\doNotCacheTikz| just undo |\cacheTikz|:
4522 \begin{codeexample}[width=0pt,vbox]
4523 \def\whereIAm{(not cached)}
4524 \robExtConfigure{
4525 add to preset={tikz}{
4526 add to preamble={
4527 \def\whereIAm{(cached)}
4528 },
4529 },
4530 }
4531
4532 \cacheTikz
4533 \doNotCacheTikz
4534
4535 \tikz \node[fill=pink, rounded corners]{\whereIAm};
4536 \begin{tikzpicture}
4537 \node[fill=pink, rounded corners]{\whereIAm};
4538 \end{tikzpicture}
4539 \end{codeexample}
4540 \end{pgfmanualentry}
4541
4542 \begin{pgfmanualentry}
4543 \extractcommand\robExtDisableTikzpictureOverwrite\@@
4544 \pgfmanualbody
4545 This is useful to temporarily reset the current environment to their original value (since v2.0 it also resets other environments, not just |tikzpicture|). This must typically be called at the beginning of |command if no externalization| to avoid infinite recursion if you redefine it, but expect for this case the user is not expected to use this option.
4546 \end{pgfmanualentry}
4547
4548 Let us say that you want to cache all elements of a given environment, like |minipage| or |zx-calculus| pictures (another package of mine):
4549
4550
4551 \begin{pgfmanualentry}
4552 \extractcommand\cacheEnvironment\opt{\marg{delimiters}}\marg{name environment}\marg{default preset options}\@@
4553 \pgfmanualbody
4554 This will automatically cache the corresponding environment (but note that you still need to define it in the preamble of the cached files, for instance by loading the appropriate package):
4555 \begin{codeexample}[width=0pt,vbox]
4556 \cacheEnvironment{ZX}{latex, add to preamble={\usepackage{zx-calculus}}}
4557 A ZX figure %
4558 \begin{ZX}
4559 \zxX{\alpha} \rar \ar[d,C] & \zxZ*{a\pi} \\
4560 \zxZ{\beta} \rar & \zxX*{b\pi}
4561 \end{ZX} and the same but aligned on the second line %
4562 \begin{ZX}[mbr=2]
4563 \zxX{\alpha} \rar \ar[d,C] & \zxZ*{a\pi} \\
4564 \zxZ{\beta} \rar & \zxX*{b\pi}
4565 \end{ZX}.
4566 \end{codeexample}
4567 You can of course configure them using globally defined configuration, but you can also provide arguments to a single picture using the delimiters |delimiters| that default to |<...>| as the optional argument, like: %
4568 \begin{codeexample}[width=0pt,vbox]
4569 \cacheEnvironment{ZX}{latex, add to preamble={\usepackage{zx-calculus}}}
4570 \begin{ZX}<add to preamble={\usepackage{amsmath}}> % amsmath provides \text
4571 \zxX{\alpha} \rar \ar[d,C] & \zxZ{\text{yes}} \\
4572 \zxZ{\beta} \rar & \zxX*{b\pi}
4573 \end{ZX}
4574 \end{codeexample}
4575 If you do not like |<>| or if your command already have this parameter, you can change it, for instance to get parens as delimiters, use:
4576 \begin{codeexample}[width=0pt,vbox]
4577 \cacheEnvironment[()]{ZX}{latex, add to preamble={\usepackage{zx-calculus}}}
4578 \begin{ZX}(add to preamble={\usepackage{amsmath}}) % amsmath provides \text
4579 \zxX{\alpha} \rar \ar[d,C] & \zxZ{\text{yes}} \\
4580 \zxZ{\beta} \rar & \zxX*{b\pi}
4581 \end{ZX}
4582 \end{codeexample}
4583 otherwise you must provide some presets arguments, possibly empty:\\
4584 |\begin{someweirdenv}<><args to someweirdenv>|
4585
4586 You can also use this argument to disable externalisation on a per-picture basis:
4587 \begin{codeexample}[width=0pt,vbox]
4588 \cacheEnvironment{ZX}{latex, add to preamble={\usepackage{zx-calculus}}}
4589 \begin{ZX}<disable externalization> % amsmath provides \text
4590 \zxX{\alpha} \rar \ar[d,C] & \zxZ*{a\pi} \\
4591 \zxZ{\beta} \rar & \zxX*{b\pi}
4592 \end{ZX}
4593 \end{codeexample}
4594
4595 \end{pgfmanualentry}
4596
4597 \begin{pgfmanualentry}
4598 \extractcommand\cacheCommand\opt{\oarg{delimiter}}\marg{name command}\opt{\oarg{xparse signature}}\marg{default preset options}\@@
4599 \pgfmanualbody
4600 This will automatically cache the corresponding command, in a similar way to environment. It work exactly the same, except that we (usually) need to specify the signature of the command or it is impossible to know where the command stops. If the command is defined using xparse-compatible commands like |\NewDocumentCommand|, this detection is automatically done. Otherwise, you need to specify it in the xparse format: long story short, |O{foo}| is an optional argument with default value foo, |m| is a mandatory argument.
4601
4602 First, let us see an example with a command defined using xparse:
4603 \begin{codeexample}[width=0pt,vbox]
4604 % We cache the command \zx that is defined with NewDocumentCommand: no need to specify the signature
4605 \cacheCommand{zx}{latex, add to preamble={\usepackage{zx-calculus}}}
4606 A ZX figure %
4607 \zx{
4608 \zxX{\alpha} \rar \ar[d,C] & \zxZ*{a\pi} \\
4609 \zxZ{\beta} \rar & \zxX*{b\pi}
4610 } and the same but aligned on the second line %
4611 \zx[mbr=2]{
4612 \zxX{\alpha} \rar \ar[d,C] & \zxZ*{a\pi} \\
4613 \zxZ{\beta} \rar & \zxX*{b\pi}
4614 }.
4615 \end{codeexample}
4616
4617 You can of course configure them using globally defined configuration, but you can also provide arguments to a single picture using the delimiters that default to |<>| as the optional argument, like: %
4618 \begin{codeexample}[width=0pt,vbox]
4619 \cacheCommand{zx}{latex, add to preamble={\usepackage{zx-calculus}\def\hello#1{Hello #1.}}}
4620 \zx<add to preamble={\usepackage{amsmath}\def\bye#1{Bye #1.}}>[mbr=1]{ % amsmath provides \text
4621 \zxX{\alpha} \rar \ar[d,C] & \zxZ{\text{\hello{Alice}}} \\
4622 \zxZ{\beta} \rar & \zxZ{\text{\bye{Bob}}}
4623 }
4624 \end{codeexample}
4625 or with parens as delimiters:
4626 \begin{codeexample}[width=0pt,vbox]
4627 \cacheCommand[()]{zx}{latex, add to preamble={\usepackage{zx-calculus}}}
4628 \zx(add to preamble={\usepackage{amsmath}})[mbr=1]{ % amsmath provides \text
4629 \zxX{\alpha} \rar \ar[d,C] & \zxZ{\text{yes}} \\
4630 \zxZ{\beta} \rar & \zxX*{b\pi}
4631 }
4632 \end{codeexample}
4633
4634 Here is an example with a command not defined with |\NewDocumentCommand| (we also show how you can use the optional argument to disable externalisation on a per-picture basis):
4635 \begin{codeexample}[width=0pt,vbox]
4636 \def\fromWhere{I am not cached}
4637 \newcommand{\myMacroNotDefinedWithNewDocumentCommand}[3][default value]{
4638 Optional argument 1: #1,
4639 Argument 2: #2,
4640 Argument 3: #3 (\fromWhere).
4641 }
4642 \cacheCommand{myMacroNotDefinedWithNewDocumentCommand}[O{default value}mm]{
4643 latex,
4644 add to preamble={%
4645 \def\fromWhere{I am cached}
4646 \newcommand{\myMacroNotDefinedWithNewDocumentCommand}[3][default value]{
4647 Optional argument 1: #1,
4648 Argument 2: #2,
4649 Argument 3: #3 (\fromWhere).
4650 }
4651 }
4652 }
4653
4654 \myMacroNotDefinedWithNewDocumentCommand{second arg}{last arg}\\
4655 \myMacroNotDefinedWithNewDocumentCommand<disable externalization>{second arg}{last arg}
4656 \end{codeexample}
4657
4658 \end{pgfmanualentry}
4659
4660 \paragraph{Defining its own macro without repeating its definition.}
4661 Note that when you define yourself a macro function, the above structure might not be optimal as you need to define the macro in the main document (in case you disable the externalization) and in the template. One option to avoid repeated code is to write the definition in a common input file (see \cref{sec:dependencies}), use |\runHereAndInPreambleOfCachedFiles| or |forward=\macroToExport|. But sometimes, you might need to do more involved operations, for instance to add a file as a dependency etc. So another solution it to wrap yourself your function into |cacheMe| yourself. Say you want your function to draw a circle like, |\tikz \draw[fill=#2] (0,0) circle [radius=#1];|, then wrap in inside |CacheMe|:
4662
4663 \begin{codeexample}[width=0mm,vbox]
4664 % D<>{} is an optional argument enclosed in <>, we use this to pass arguments to CacheMe
4665 \NewDocumentCommand{\drawMyCircle}{D<>{}O{2mm}m}{
4666 \begin{CacheMe}{tikz, #1}
4667 \tikz \draw[fill=#3] (0,0) circle [radius=#2];
4668 \end{CacheMe}
4669 }
4670
4671 You can externalize it \drawMyCircle{pink} %
4672 or disable externalization \drawMyCircle<disable externalization>[4mm]{red}.
4673 \end{codeexample}
4674
4675 \paragraph{Manually wrap a command.} In some more advanced cases, if you do not know the definition of the command and if |\cacheCommand| does not work (e.g. the number of mandatory argument depends on the first argument), you can wrap it manually. To do so, first copy first your command using |\DeclareCommandCopy{\robExtCommandOrigNAMEOFCOMMAND}{\NAMEOFCOMMAND}| and run |\robExtAddToCommandResetList{NAMEOFCOMMAND}| (this is needed to disable externalization), and override the command by wrapping it into a cache. Make sure to add |\def\robExtCommandOrigName{NAMEOFCOMMAND}| at the beginning of the function or |disable externalization| will not work:
4676
4677 \begin{codeAndResult}
4678 Original command: \zx{\zxZ{\alpha} \rar & \zxX{\beta}}. %
4679 \DeclareCommandCopy{\robExtCommandOrigzx}{\zx}% used to recover the original function
4680 \robExtAddToCommandResetList{zx}% let us know that this function should be reset when externalization is disabled
4681 \DeclareDocumentCommand{\zx}{D<>{}O{}m}{%
4682 \def\robExtCommandOrigName{zx}%
4683 \begin{CacheMe}{latex, add to preamble={\usepackage{zx-calculus}}, #1}%
4684 \zx[#2]{#3}%
4685 \end{CacheMe}%
4686 }
4687 This is cached \zx<>{\zxZ{\alpha} \rar & \zxX{\beta}}, you can add options like %
4688 \zx<add to preamble={\usepackage{amsmath}}>{\zxZ{\alpha} \rar & \zxX{\text{Hey}}} %
4689 and we can disable the externalization: %
4690 \zx<disable externalization>{\zxZ{\alpha} \rar & \zxX{\text{Hey}}}.
4691 \end{codeAndResult}
4692
4693 You can do a similar trick for environment, by using instead
4694 \begin{verbatim}
4695 \NewEnvironmentCopy{robExtEnvironmentOrigNAMEENV}{NAMEENV}
4696 \robExtAddToEnvironmentResetList{NAMEENV}
4697 \def\robExtEnvironmentOrigName{NAMEENV}
4698 \end{verbatim}
4699
4700 \subsection{Operations on the cache}\label{sec:operationsCache}
4701
4702 Every time we compile a document, we create automatically a bunch of files:
4703 \begin{itemize}
4704 \item the cache is located by default in the |robustExternalize| folder. Feel free to remove this folder if you want to completely clear the cache (but then you need to recompile everything). See below if you want to clean it in a better way.
4705 \item |\jobname-robExt-all-figures.txt| contains the list of all figures contained in the document. Mostly useful to help the script that remove other figures.
4706 \item |robExt-remove-old-figures.py| is a python script that will remove all cached files that are not used anymore. Just run |python robExt-remove-old-figures.py| to clean it. You will then see the list of files that the script wants to remove: make sure it does not remove any important data, and press ``y''. Note that it will search for all files that look like |*robExt-all-figures.txt| to see the list of pictures that are still in use, and by default it will only remove the images in the |robustExternalize| folder that start with |robExt-|. If you change the path of the cache or the prefix, edit the script (should not be hard to do).
4707 \item |\jobname-robExt-compile-missing-figures.sh| contains a list of commands that you need to run to compile the images not yet compiled in the cache (this list will only be created if you enable the manual compilation mode).
4708 \item |\jobname-robExt-tmp-file-you-can-remove.tmp| is a temporary file. Feel free to remove it.
4709 \end{itemize}
4710
4711 We go over some of these scripts.
4712
4713 \subsubsection{Cleaning the cache}
4714
4715 You might want to clean the cache. Of course you can remove all generated files, but if you want to keep the picture in use in the latest version of the document, we provide a python script (automatically generated in the root folder) to do this. Just install python3 and run:\\
4716
4717 |python3 robExt-remove-old-figures.py|\\
4718
4719 (on windows, the executable might be called |python|) You will then be prompted for a confirmation after providing the list of files that will be removed.
4720
4721 \subsubsection{Listing all figures in use}
4722
4723 After the compilation of the document, a file |robExt-all-figures.txt| is created with the list of the |.tex| file of all figures used in the current document.
4724
4725 \subsubsection{Manually compiling the figures}
4726
4727 When enabling the manual mode (useful if we don't want to enable |-shell-escape|):
4728
4729 \begin{verbatim}
4730 \robExtConfigure{
4731 enable manual mode
4732 }
4733 \end{verbatim}
4734
4735 or the fallback to manual mode (it will only enable the manual mode if |-shell-escape| is disabled):
4736 \begin{verbatim}
4737 \robExtConfigure{
4738 enable fallback to manual mode,
4739 }
4740 \end{verbatim}
4741
4742 the library creates a file |JOBNAME-robExt-compile-missing-figures.sh| that contains the instructions to build the figures that are not yet in the cache (each line contains the compilation command to run). On Linux (or on Windows with bash/cygwin/… installed, it possibly even work out of the box without) you can easily execute them using:
4743
4744 \begin{verbatim}
4745 bash JOBNAME-robExt-compile-missing-figures.sh
4746 \end{verbatim}
4747
4748
4749 \subsection{How to debug}\label{sec:debug}
4750
4751 If for some reasons you are unable to understand why a build fails, first check if you compiled your document with |-shell-escape| (not that this must appear \textbf{before} the filename).
4752
4753 Since v2.3, we provide a more advanced error handling system in order to provide more meaningful errors to the user, and to write the full compilation output in the log in case of an error. We do so by wrapping commands around something like |(my command) > somelog.tex 2>&1|; therefore nothing is printed on screen during the compilation of the cached picture, you only get a message if there is an error.
4754 \begin{pgfmanualentry}
4755 \makeatletter%
4756 \def\extrakeytext{style, }
4757 \extractkey/robExt/do not redirect compilation output\@nil
4758 \makeatother
4759 If you want to come back to the old behavior, that just runs the command is it either set this option, or set |\def\robExtDoNotRedirectOutput{}| and |\def\robExtDoNotRedirectOutputInManuallyCompileMissingFigures{}| (the last one will only concern commands written to the |robExt-compile-missing-figures.sh|, which is used in manual mode and in parallel mode).
4760 \end{pgfmanualentry}
4761
4762 Starting from 2.3, we also automatically print an actual error message like:
4763 \begin{verbatim}
4764 ! Package robExt Error: On line 20: the pdf file
4765 (robExt)
4766 robustExternalize/robExt-F27CD43D192AA2668A16DEAA616591FF.pdf
4767 (robExt) is not present. The compilation command "cd
4768 (robExt) robustExternalize/ && xelatex -halt-on-error
4769 (robExt) "robExt-F27CD43D192AA2668A16DEAA616591FF.tex"" used
4770 (robExt) to compile the environment on line 20 certainly
4771 (robExt) failed with errors:
4772 (robExt) vvvvvv
4773 (robExt) ! Package tikz Error: Giving up on this path. Did
4774 (robExt) you forget a semicolon?.
4775 (robExt)
4776 (robExt) ^^^^^^
4777 (robExt) See full logs below (you might need to press ENTER
4778 (robExt) to go to the next error) or in
4779 (robExt)
4780 robustExternalize/robExt-F27CD43D192AA2668A16DEAA616591FF-compilation.log.
4781 \end{verbatim}
4782 You can see inside the location in the main tex file of the block containing the error, we provide also the compilation command that lead to this error, and the lines of the log containing the word ``error'' (case insensitive), as well as the path to the full log of the compilation of the inner command, that you can also see if you continue the compilation by pressing Enter or by looking at the full log file, for instance in TeXstudio. This smaller message is often good enough in LaTeX, but usually not very good for languages that do not print the word ``error''. In that case, add to your preset:
4783
4784 \begin{pgfmanualentry}
4785 \makeatletter%
4786 \def\extrakeytext{style, }
4787 \extractkey/robExt/print whole file in error message\@nil
4788 \extractkey/robExt/do not print whole file in error message\@nil
4789 \makeatother
4790 (Add this only in preset, do NOT set it globally)
4791 If you want to print the whole file in the small error message because you do not want to inspect the full log file, you can use the style |print whole file in error message|. This is enabled by default on the gnuplot, python and bash presets for instance, but disabled in \LaTeX{} has it makes little sense to print thousands of log lines in the error.
4792 \end{pgfmanualentry}
4793
4794 \begin{pgfmanualentry}
4795 \makeatletter%
4796 \def\extrakeytext{style, }
4797 \extractkey/robExt/texstudio\@nil
4798 \extractkey/robExt/logs should show as errors\@nil
4799 \extractkey/robExt/prefix log message with=\marg{string to prepend to log message}\@nil
4800 \extractkey/robExt/spacing between lines in log=\marg{content to separate lines in log}\@nil
4801 \makeatother
4802 Some IDE like TeXstudio will only print lines starting with an exclamation mark, assuming that they are spaced enough, so to make the compilation errors more visible in the log, we can start every line in the log with a |!| (you can set it globally via |logs should show as errors| that internally calls |prefix log message with|) and separate all lines with enough empty lines using |spacing between lines in log|. For simplicity, we create |texstudio| to automatically configure these values so that errors print nicely in texstudio via:
4803 \begin{verbatim}
4804 \robExtConfigure{texstudio}
4805 \end{verbatim}
4806 This way you will get errors like:
4807 \begin{verbatim}
4808 -------- We print now the full log --------
4809 ! sh: ligne 1: gnuplot : commande introuvable
4810 -------- End of the full log --------
4811 \end{verbatim}
4812 and the line |sh: ligne 1: gnuplot : commande introuvable| will appear in your IDE without going in the log file. Note that this will only be printed for items that enable |print whole file in error message| not to pollute the errors space when the log contains many lines (e.g. \LaTeX{}), but this is automatically enabled on most default presets.
4813 \end{pgfmanualentry}
4814
4815 Then, you can look at the log files\footnote{Either the latex one or the |-compilation.log| file, and sometimes try in a terminal if you really can't see any useful error as it might be the case that the error is not printed in the log file, which occurs for instance if xparse is not installed on Windows and you use the compilation command in parallel.} to get more advices, and run yourself the compilation command printed in the above error message. This way, you can easily check the content of the file and see why it fails to compile. In version before 2.3, or if you use |do not redirect compilation output|, the compilation errors are also displayed directly in the output, and you can read the log file for details.
4816
4817 You might often get an error:
4818 \begin{verbatim}
4819 ! Missing $ inserted.
4820 \end{verbatim}
4821 This is typically when a placeholder was left unreplaced (e.g.\ you forgot to define it, import it, or you forgot to wrap a command in |\evalPlaceholder{}|): since \LaTeX{} is asked to typeset |__something__|, it thinks that you are trying to write a subscript, and asks you to start first the math mode.
4822
4823 To get more advanced info during the compilation command, set the style |more logs| (that does |\def\robExtDebugMessage#1{\message{^^J[robExt] #1}}|) in order to print some messages on the replacement process (there is also |\robExtDebugWarning| for more important messages, but it prints the logs by default.
4824
4825 Then, it is often handy to check the content of the generated template. You can either get the name in the log, via |name output|, or print it directly in the file:
4826
4827 \begin{pgfmanualentry}
4828 \makeatletter%
4829 \def\extrakeytext{style, }
4830 \extractkey/robExt/debug\@nil
4831 \extractkey/robExt/print command and source\@nil
4832 \makeatother%
4833 \pgfmanualbody
4834 You can also use |debug| (or its alias |print command and source|) in order to disable the compilation and print instead the compilation command and the source file:
4835
4836 \begin{codeexample}[width=0pt,vbox]
4837 \begin{tikzpictureC}<debug>[baseline=(A.base)]
4838 \node[fill=red, rounded corners](A){My node that respects baseline \ding{164}.};
4839 \node[fill=red, rounded corners, opacity=.3,overlay] at (A.north east){I am an overlay text};
4840 \end{tikzpictureC}
4841 \end{codeexample}
4842 \begin{codeexample}[width=0pt,vbox]
4843 \end{codeexample}
4844 \end{pgfmanualentry}
4845
4846 \begin{pgfmanualentry}
4847 \extractcommand\robExtShowPlaceholder\opt{*}\marg{placeholder name}\@@
4848 \makeatletter%
4849 \def\extrakeytext{style, }
4850 \extractkey/robExt/show placeholder=\marg{placeholder name}\@nil
4851 \makeatother%
4852 \pgfmanualbody
4853 |\robExtShowPlaceholder{__ROBEXT_MAIN_CONTENT__}| will show in the terminal the content of the placeholder. Use the start not to pause.
4854 \end{pgfmanualentry}
4855
4856 \begin{pgfmanualentry}
4857 \extractcommand\robExtShowPlaceholders\opt{*}\@@
4858 \extractcommand\robExtShowPlaceholdersContents\opt{*}\@@
4859 \makeatletter%
4860 \def\extrakeytext{style, }
4861 \extractkey/robExt/show placeholders\@nil
4862 \extractkey/robExt/show placeholders contents\@nil
4863 \makeatother%
4864 \pgfmanualbody
4865 Show all imported placeholders and their content. Use the start not to pause.
4866 \end{pgfmanualentry}
4867
4868 \begin{pgfmanualentry}
4869 \makeatletter%
4870 \def\extrakeytext{style, }
4871 \extractkey/robExt/nb lines after error to show=\marg{nb lines to keep}\@nil
4872 \extractkey/robExt/remove line number\@nil
4873 \extractkey/robExt/do not remove line number\@nil
4874 \makeatother
4875 In order to make the small error message more meaningful (to avoid getting to the full log), we try to extract some errors automatically, reading lines staring with |!|, or containing |error| or |invalid|. But this line alone is often not enough, so you can use |nb lines after error to show| to determine the number of lines to show after (defaults to 3). |remove line number| will remove in the short error message any |l.| at the beginning of the line, otherwise some editors (at least emacs), will interpret it as a line number in the current file and will jump to a bad position (this is enabled by default). These options would work best if set globally when you use |compile in parallel|.
4876 \end{pgfmanualentry}
4877
4878 \subsection{Advanced optimizations}\label{sec:advancedOperations}
4879
4880 We made a number of optimizations to get near instant feedback on documents having hundreds of pictures, basically by saying which placeholder should be replaced, in which order, when to stop replacing placeholders, and possibly by compiling templates (see \cref{sec:compilePreset}). Most of them are invisible to the end user and pre-configured for presets like |latex| or when compiling a preset, but you might want to also use them on your own.
4881
4882 First note that the order used to import placeholders is important, as it will first replace the first imported placeholders: so if you imported the placeholders in the right order, a single loop should be enough to replace them all, otherwise you might need $n$ loops if you need to replace $n$ placeholders (the basic evaluation procedure just loops over placeholders and replace all occurrences in the string until there is either no remaining placeholders (see below), or if you obtain the same result after two loops).
4883
4884
4885 \begin{pgfmanualentry}
4886 \extractcommand\onlyPlaceholdersInCompilationCommand\marg{list,of,placeholders}\@@
4887 \extractcommand\firstPlaceholdersInCompilationCommand\marg{list,of,placeholders}\@@
4888 \extractcommand\onlyPlaceholdersInTemplate\marg{list,of,placeholders}\@@
4889 \extractcommand\firstPlaceholdersInTemplate\marg{list,of,placeholders}\@@
4890 \pgfmanualbody
4891 Using these commands (possibly inside |/utils/exec={\yourcommand{foo}}| in a style), you will tell to the system to evaluate the compilation/template placeholders (depending on the name of the command) only using the placeholders in the argument, or (for the commands starting with |first|), by starting with the placeholders in argument before continuing with others placeholders.
4892 \end{pgfmanualentry}
4893
4894 \begin{pgfmanualentry}
4895 \makeatletter%
4896 \def\extrakeytext{style, }
4897 \extractkey/robExt/all placeholders have underscores\@nil
4898 \extractkey/robExt/not all placeholders have underscores\@nil
4899 \makeatother%
4900 \pgfmanualbody
4901 In order to know when to stop replacing placeholders earlier (i.e.\ without running until it converges), it is practical to know how placeholders look like in order to stop before. This (enabled by default) says to the library that all placeholders should start with two underscores |__|, allowing us to easily check if a string contains a placeholder. If you want to use placeholders with fancy names and no underscores, disable this feature (but it might be a bit slower).
4902 \end{pgfmanualentry}
4903
4904
4905 \begin{pgfmanualentry}
4906 \makeatletter%
4907 \def\extrakeytext{style, }
4908 \extractkey/robExt/do not load special placeholders\@nil
4909 \extractkey/robExt/load special placeholders\@nil
4910 \makeatother%
4911 \pgfmanualbody
4912 Similarly, to save some time, we do not import some special placeholders and only replace them manually at the end, the list being: |__ROBEXT_OUTPUT_PREFIX__|, |__ROBEXT_SOURCE_FILE__|, |__ROBEXT_OUTPUT_PDF__|, |__ROBEXT_WAY_BACK__|, |__ROBEXT_CACHE_FOLDER__|. If for some reasons you do want to import them earlier, you can do it this way.
4913 \end{pgfmanualentry}
4914
4915 \begin{pgfmanualentry}
4916 \makeatletter%
4917 \def\extrakeytext{style, }
4918 \extractkey/robExt/disable placeholders\@nil
4919 \extractkey/robExt/enable placeholders\@nil
4920 \makeatother%
4921 \pgfmanualbody
4922 To save even more time, you can disable the placeholder system completely, and only replace the following placeholders: |__ROBEXT_MAIN_CONTENT__|, |__ROBEXT_LATEX_PREAMBLE__| and |__ROBEXT_MAIN_CONTENT_ORIG__|. This is done notably inside |new compiled preset| in order to speed up the compilation by maybe a factor of 1.5 or 2, but then you cannot use any other placeholders. Note that the default presets like |latex| enable placeholders, so you should be able to call |latex| inside a compiled template to come back to the uncompiled version.
4923 \end{pgfmanualentry}
4924
4925 \begin{pgfmanualentry}
4926 \makeatletter%
4927 \def\extrakeytext{style, }
4928 \extractkey/robExt/disable import mechanism\@nil
4929 \extractkey/robExt/enable optimizations\@nil
4930 \makeatother%
4931 \pgfmanualbody
4932 If you disable the import mechanism (enabled by default), it will do an |\importAllPlaceholders| while evaluating the template. This is not recommended as it is quite inefficient, it is better to selectively import the group you need.
4933 \end{pgfmanualentry}
4934
4935
4936 \section{Frequent errors}
4937
4938 \subsection{Xelatex and tabs}
4939
4940 It seems that xelatex (I never had issues with pdflatex and lualatex, but if you get this error on other engines you can try the same fix) \mylink{https://tex.stackexchange.com/a/14776/116348}{has a hard time dealing with tabs} if you do not compile with:
4941 \begin{verbatim}
4942 xelatex -8bit yourfile.tex
4943 \end{verbatim}
4944 If you see that tabs in your input file are turned into |^^I| in the source code, you should either add the |-8bit| option\dots{} or simply follow egreg's advice:
4945 \begin{center}
4946 \emph{The strategy is very simple: never use TAB when dealing with TeX. Reserve the TAB key to trigger autocompletion and your life will be happier.}
4947 \end{center}
4948 If you use TeXstudio that uses Tabs by default, you can disable this feature by setting these two options:
4949 \begin{verbatim}
4950 Options > Configure TeXstudio > Editor > Replace indentation tabs with spaces
4951 Options > Configure TeXstudio > Editor > Replace tabs in text with spaces
4952 \end{verbatim}
4953
4954 \section{TODO and known bugs:}
4955
4956 \begin{itemize}
4957 \item See how to deal with label, links and cite inside pictures (without disabling externalization). For label and links, I have a proof of concept, I ``just'' need to write it down. \url{https://tex.stackexchange.com/questions/695277/clickable-includegraphics-for-cross-reference-data}
4958 \item Deal with remember picture
4959 \item Since externalizing is all about speed, it would be nice to do more benchmarks. But overall, it seems fairly optimized, at least when using the compiled presets. One option to gain in term of efficiency and simplicity might be to directly use the fact that the placeholders start and end with two dashes: a more efficient implementation might be doable using something like |\def\findPlaceholders#1__#2__{}| instead of string replacement. I will try to investigate in future releases.
4960 \end{itemize}
4961
4962 \section{Changelog}
4963
4964 \begin{itemize}
4965 \item v3.0:
4966 \begin{itemize}
4967 \item Added |dvi to ps| and |use latex and dvi|
4968 \item Fix bug with |no cache folder|
4969 \item Fix bug with |add to compilation command options| not working
4970 \item Added |forward counter and back| and |forward counter back|
4971 \item Fix infinite compilation time when input does not exist (WARNING:, it will invalidate all previously cached LaTeX documents since this adds a compilation option to LaTeX by default! If you want to use the old buggy behavior to preserve your cache, define |\robExtSetPlaceholder{__ROBEXT_LATEX_COMPILATION_COMMAND_OPTIONS__}{-halt-on-error}|. Anyway, if you want truly reproducible caching, just copy the .sty file in your project)
4972 \item Support |if matches else|
4973 \end{itemize}
4974 \item v2.9 (2024/03/15)
4975 \begin{itemize}
4976 \item Bug that may forbid the package to load has been fixed (you might encounter |ERROR: Missing = inserted for \ifnum|)
4977 \end{itemize}
4978 \item v2.8:
4979 \begin{itemize}
4980 \item Fix a regression bug introduced in 2.7: |python print code and result| was adding a new line above the code printed. This is fixed now.
4981 \end{itemize}
4982 \item v2.7:
4983 \begin{itemize}
4984 \item apply |remove leading spaces| by default also in |placeholderFromCode| and |PlaceholderPathFromCode|, and allow the user to customize the style. This produces a very minor backward incompatibility as it might disturb code where all lines start with a space.
4985 \end{itemize}
4986 \item v2.6:
4987 \begin{itemize}
4988 \item Added |\lenToCmNoUnit|
4989 \item Added |\placeholderPrependAllLines| and alike
4990 \item Added |remove spaces until| and alike
4991 \item Added |placeholderRemoveLeadingSpaces| and alike
4992 \end{itemize}
4993 \item v2.5:
4994 \begin{itemize}
4995 \item Add tikzit support
4996 \item Add support for |--output-directory|
4997 \end{itemize}
4998 \item v2.4:
4999 \begin{itemize}
5000 \item Better error message in wget if file not found
5001 \item Add support for arXiv with |rename backup files for arxiv|, |print source when saving|, |backup source for arxiv|, |forward counter force value|
5002 \item Add |\robExtMv|, |\robExtCp|, |set compilation command create if no error| and |set compilation command move if no error|.
5003 \item Add |copy file to cache|
5004 \end{itemize}
5005 \item v2.3:
5006 \begin{itemize}
5007 \item Fix bug in |more logs| and |less logs|
5008 \item Make |if matches word| more efficient, independent on the number of runs, allowing registration, namespaces, etc.
5009 \item Added |\definecolorAutoForward| and |\colorletAutoForward|
5010 \item Add support for gnuplot
5011 \item Added |\runHereAndInPreambleOfCachedFiles|
5012 \item Clearer and more advanced error handling
5013 \item Add support for online images with |\includegraphicsWeb|
5014 \end{itemize}
5015 \item v2.2
5016 \begin{itemize}
5017 \item v2.1 introduced two important bugs where hashes could not be used in a |\cacheMe| environment, and |auto forward| was not working if the string was containing an environment. This is fixed now.
5018 \item Fix issue with |compile in parallel| on MacOs (xargs there is not GNU xargs and is missing |-a| option)
5019 \item Added |*ExpandableDocumentCommandAutoForward|.
5020 \item Added |\genericAutoForward| to forward arbitrary code.
5021 \item Added |if windows| and |if unix| tests.
5022 \item Added details on the future difference between |if matches| and |if matches word|.
5023 \end{itemize}
5024 \item v2.1:
5025 \begin{itemize}
5026 \item Fix a bug when compiling the main document with lualatex or xelatex
5027 \item Fix a bug when compiling a template that was not exporting dependencies
5028 \item Add |recompile| to recompile a file even if no dependencies changed.
5029 \item Add a hook |robust-externalize/just-before-writing-files|.
5030 \item Fixed a bug in |\cacheTikz| that was not working with a custom argument for tikzpicture
5031 \item Added options |forward*| to forward macros and counters
5032 \item Added |auto forward| and co
5033 \item Added |compile in parallel| and co
5034 \end{itemize}
5035 \item v2.0:
5036 \begin{itemize}
5037 \item \textbf{not backward compatible}: the preset |tikzpicture| should be used instead of |tikz|: |tikz| does not wrap anymore its content into |\begin{tikzpicture}| in order to be usable inside the command version |\tikz| (but |tikzpicture| does load |tikz| first). Moreover, all arguments to |tikzpictureC| or |tikzpicture| (if you loaded |cacheTikz|) should be specified in the first argument, using |<your options>|. This is used to provide a more uniform interface with the new |\cacheEnvironment| command. Hopefully this should \textbf{not cause too much trouble} since the first version of the library has been published on CTAN only a few days ago.
5038 \item not really compatible: Renamed some latex placeholders to prefix all of them with |__ROBEXT_LATEX_|. Should not be a problem if you used the style made to change them.
5039 \item Added an alias to |\robExtExternalizeAllTikzpictures| called |\cacheTikz|. Now, this also configures |\tikz|.
5040 \item You can now use ampersands etc freely thanks to lrbox.
5041 \item You can now automatically cache environments using |\cacheEnvironment| and commands using |\cacheCommand|.
5042 \item We provide |new preset| and |add to preset| to avoid doubling the number of hashes.
5043 \item We provide new functions like |\setPlaceholderRecReplaceFromList| to only expand a subset of placeholders.
5044 \item An error message is given if you forget to set a template.
5045 \item Add |enable fallback to manual mode| to fallback to manual mode only if shell escape is missing.
5046 \item Allow restricted mode
5047 \item |debug| mode available
5048 \item Rename |set subfolder and way back| to |set cache folder and way back| (in a backward compatible way)
5049 \item Waaaaaaay more efficient. Also added a method to compile presets.
5050 \item I added the import system for efficiency reasons (not present in v1.0 at all). Note that I also added some other functions that I forgot to notify as new in the doc...
5051 \end{itemize}
5052 \end{itemize}
5053
5054 \printindex
5055
5056 \end{document}
5057 % Luatex is needed, otherwise quotes ' are turned into another symbol in documentation
5058 % https://github.com/leo-colisson/robust-externalize/issues/11
5059 % Local Variables:
5060 % TeX-command-extra-options: "--shell-escape -halt-on-error"
5061 % TeX-engine: luatex
5062 % jinx-languages: "en"
5063 % End: