fenced code blocks when converting R Markdown to pdf

走远了吗. 提交于 2019-12-11 10:24:30

问题


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')"

回答1:


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
```



来源:https://stackoverflow.com/questions/34815357/fenced-code-blocks-when-converting-r-markdown-to-pdf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!