Set code background colour in R markdown to PDF

邮差的信 提交于 2019-12-05 05:07:02

Since you're already set up with Pandoc, you should be able to achieve this using Pandoc's --highlight-style argument. From the docs:

--highlight-style=STYLE Specifies the coloring style to be used in highlighted source code. Options are pygments (the default), kate, monochrome, espresso, zenburn, haddock, and tango.

If you're not specifying the language that each code block contains within the markdown file, you might also have to set the --indented-code-classes argument:

--indented-code-classes=CLASSES Specify classes to use for indented code blocks–for example, perl,numberLines or haskell. Multiple classes may be separated by spaces or commas.

From memory, I think this might require a latex package like fancyvrb, so you might have to install that before it works.

Marius' answer is exactly what I was after. Since comments can't take images, I'm pasting a few screenshots here in case others are curious about this.

To get code backgrounds in the PDF generated from the md, I adjusted my code like so:

# Load packages
require(knitr)
require(markdown)

setwd("C:/Users/.../Desktop/")

# Create .md and .pdf files
filen <- "test"
knit(paste0(filen,".md"))
system(paste0("pandoc -s ", paste0(filen,"-out.md"), " -t latex -o ", paste0(filen,".pdf"), " --highlight-style=tango -S"))

In testing the seven pandoc highlighting options, I found that only three give code backgrounds. Here are screenshots of the PDFs generated with each of the three options, for future reference.

This is tango, the one that best matches what I'm after with the light grey:

And this is zenburn:

And this is espresso

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