Skip to main content

Using RMarkdown, knitr, and pandoc in TexShop on Mac

Most people will use RStudio for this sort of workflow, but I use TeXShop because I prefer the side-by-side editing view with plain text on the left and the formatted version on the right. I don’t think RStudio supports it. Also, TeXShop feels like a native OS X application. RStudio can’t really shed its Qt roots no matter how hard it tries.

Here’s how to get TexShop working with your RMarkdown workflow.

I assume you’ve already installed pandoc and MacTeX. If you don’t already have RMarkdown installed, load up an R session:

devtools::install_github("rstudio/rmarkdown", dependencies=TRUE)

First, you’ll need to add a custom RMarkdown engine for TexShop. These are located in ~/Library/TeXShop/Engines and are simple executable script files with the extension .engine. Let’s add an rmarkdown engine. Open up the Terminal:

vim ~/Library/TeXShop/Engines/rmarkdown.engine        # or nano, etc.
chmod a+x ~/Library/TeXShop/Engines/rmarkdown.engine

Inside that rmarkdown.engine file you can just paste in these contents:


Rscript -e "rmarkdown::render(\"$1\", encoding='UTF-8')"

TeXShop will pass in the name of your Rmarkdown file as the first argument to your script, so you can pass it to R inside the variable $1. Note that you might have to change the encoding argument to rmarkdown::render if you have TeXShop saving files in something other than UTF8. It’s important to get this right, otherwise non-ASCII characters will cause random paragraphs to turn into NAs. (Fixing this bug is Someone Else’s Problem because the workaround is adequate and there are only so many hours in the day.)

Finally you need to get TeXShop to recognize .Rmd files. By default TeXShop will refuse to let you “typeset” files with extensions that it doesn’t recognize. Though TeXShop does support plain .md files, the RMarkdown package will not knit these and will bypass any R code found in plain Markdown files. So you must write with the .Rmd extension. Fortunately there’s a hidden preference that you can tweak. Simply open Terminal and type:

defaults write TeXShop OtherTeXExtensions -array-add "Rmd"
defaults write TeXShop OtherTeXExtensions -array-add "rmd"

Now when you open .Rmd files, simply select the “rmarkdown” engine from the drop down list in the toolbar and type away.

Other hidden preferences can be found in TeXShop’s extensive help files. I actually started grepping the source code to hack in this functionality until I figured out that the documentation for TeXShop was actually quite good. I’ve been spoiled by scientific software for too long.