1
votes

I use knitr with XeLaTeX within RStudio. I use chunk caching so that I don't have to rerun certain code every time I compile my document. This minimal example shows that the caching appears to be broken if the fontspec package is loaded.

\documentclass{article}
\usepackage{fontspec} % Appears to somehow conflict with caching.

\begin{document}

<<pre_load, cache=TRUE>>=
library(tikzDevice)
options(tikzDefaultEngine="xetex")
@

\section{Test}
<<test_block, dev='tikz', dependson='pre_load'>>=
plot(1:10,main='Test')
@

\end{document}

The first time this document is compiled to PDF, it will work, because caching is not used. However, if a change is made to the test_block chunk, and the code is run a second time, it will fail. For example, after compiling to PDF once, change the test_block chunk to:

<<test_block, dev='tikz', dependson='pre_load'>>=
plot(1:10,main='Test Modified')
@

Now, compiling to PDF fails with the following error:

! 
 ********************************************
 * XeTeX is required to compile this document.
 * Sorry!
 ********************************************.
\RequireXeTeX ...********************************}
                                                  \endgroup \fi 
l.18 \RequireXeTeX

This error indicates that options(tikzDefaultEngine="xetex") has not been set. Interestingly, if the fontspec package is not loaded, then this error does not occur.

My question is: Is this a bug, or is there something wrong with my code?

I am using knitr (1.1) using tikzDevice (0.6.3) on R (R Under development (unstable) (2012-11-10 r61101)) through RStudio (0.97.246) (accessed via browser through RStudio Server) which itself is running on a Ubuntu (12.04.2 LTS). My LaTeX2e is dated <2009/09/24>.

1

1 Answers

2
votes

Do not put options(tikzDefaultEngine="xetex") in a cached chunk because it has a side-effect which cannot be cached, so the second time you compile the document, this option will be skipped. Read the section Important Notes in the cache page on the knitr website.

Note you do not need to library(tikzDevice) either; this package will be automatically loaded when you set dev='tikz'.

In most cases, you should cache the plot chunk instead because it is slow to create TikZ graphics.

\documentclass{article}
\usepackage{fontspec} % Appears to somehow conflict with caching.

\begin{document}

<<pre_load>>=
options(tikzDefaultEngine="xetex")
@

\section{Test}
<<test_block, dev='tikz'>>=
plot(1:10,main='Test')
@

\end{document}