1

When I compile an R Markdown document to an HTML document, the non-R code blocks are formatted nicely. But when I compile the following R Markdown document to pdf, the only added code formatting is in the font. There is no shading, fencing, highlighting, etc.

---
output: pdf_document
---

```
code
```

I don't want to micromanage the output, I just want to add some common-sense formatting to clearly separate the code from the prose. I'm using TeXShop on a MAc with the engine below.

#!/bin/bash
/Library/Frameworks/R.framework/Versions/Current/Resources/bin/Rscript -e "rmarkdown::render(\"$1\", encoding='UTF-8')"
landau
  • 5,636
  • 1
  • 22
  • 50

1 Answers1

3

With ``` you introduce a plain markdown code block but not a knitr code chunk. But the output you expect (fencing, highlighting, shading) is the style knitr adds to its code blocks.

Therefore, use ```{r} to wrap code in knitr chunks (use eval = FALSE if you don't want the code to be evaluated). This can also be used for non-R code blocks: As long as the code is not evaluated, the language doesn't matter.

However, for non-R code this will lead to wrong or missing syntax highlighting. To get the correct syntax highlighting, use the option engine if the language is among the supported language engines.

The example below shows a pain markdown block, an evaluated and and unevaluated R code chunk, a (unevaluated) Python chunk without highlighting and finally two (unevaluated) Python chunks with correct highlighting.

---
output:
  pdf_document
---

```
Plain markdown code block.
```


```{r}
print("This is a knitr code chunk.")
```

```{r, eval = FALSE}
print("This is a knitr code chunk that isn't evaluated.")
```


Chunk with Python code (borrowed from http://stackoverflow.com/q/231767/2706569), *wrong* (no) highlighting:
```{r, eval = FALSE}
if self._leftchild and distance - max_dist < self._median:
      yield self._leftchild
```

Chunk with Python code, *correct* highlighting:
```{r, eval = FALSE, engine = "python"}
if self._leftchild and distance - max_dist < self._median:
      yield self._leftchild
```

Chunk with Python code, *correct* highlighting (alternative notation):
```{python, eval = FALSE}
if self._leftchild and distance - max_dist < self._median:
      yield self._leftchild
```

Output

CL.
  • 14,577
  • 5
  • 46
  • 73