Wednesday, June 25, 2014

TexShop engines for Knitr w/ and w/o pstricks

Two years ago, I've posted a link that explains how to set up a painless compilation of Sweave documents in TexShop:

Since I've switched to Knitr last year, I wanted to share a couple of tricks of using a TexShop+Knitr combination.

First, setting up a Knitr engine in TexShop is analogous to the recipe from the above link: create a file Knitr.engine in your ~/Library/TexShop/Engines/ directory with the following content:


export PATH=$PATH:/usr/texbin:/usr/local/bin
Rscript -e "library(knitr); knit('$1')"

Now if you (re-)open TexShop, you should have Knitr in your list of engines located next to the Typeset button on the top. This worked well for me until today, when I needed to combine Knitr code with some old LaTeX code of mine that used "pstricks" package. Since pdflatex does not work with "pstricks" (there something called PDFTricks, but I haven't tried it), I needed to create another engine in my ~/Library/TexShop/Engines/ directory that I called KnitrDviPs:

Rscript -e "library(knitr); knit('$1')"
latex "${1%.*}"
bibtex "${1%.*}"
latex "${1%.*}"
latex "${1%.*}"
dvips -t letter -o "${1%.*}.ps" "${1%.*}"
pstopdf "${1%.*}.ps"

This engine goes through a less efficient "dvi->ps->pdf" route. However, this still doesn't do the trick just yet, because by default Knitr does not produce postscript files of all embedded figures. So you have to add a "postscript" device to your Knitr document using Knitr chunk options. For example, somewhere near the beginning of your Knitr document you can put the following command:

opts_chunk$set(fig.path='figures/', fig.align='center', dev=c('pdf', 'postscript'))

Now you have two Knitr engines: one that goes through pdflatex and another that goes through "dvi->ps->pdf".