Here is one solution using the highr package development version ( devtools::install_github('yihui/highr') ). Basically, you simply define your custom LaTeX commands to highlight tokens. highr:::cmd_pandoc_latex is a data frame of LaTeX commands that Pandoc uses to highlight syntax.
head(highr:::cmd_pandoc_latex) ## cmd1 cmd2 ## COMMENT \\CommentTok{ } ## FUNCTION \\NormalTok{ } ## IF \\NormalTok{ } ## ELSE \\NormalTok{ } ## WHILE \\NormalTok{ } ## FOR \\NormalTok{ }
Then you can override the inline knitr hook:
--- output: pdf_document: keep_tex: yes --- ```{r include=FALSE} local({ hi_pandoc = function(code) { if (knitr:::pandoc_to() != 'latex') return(code) if (packageVersion('highr') < '0.6.1') stop('highr >= 0.6.1 is required') res = highr::hi_latex(code, markup = highr:::cmd_pandoc_latex) sprintf('\\texttt{%s}', res) } hook_inline = knitr::knit_hooks$get('inline') knitr::knit_hooks$set(inline = function(x) { if (is.character(x) && inherits(x, 'AsIs')) hi_pandoc(x) else hook_inline(x) }) }) ``` Test inline R code: `r I("plot(cars, main = 'A scatterplot.')")`. Normal inline code `r pi`. A code block: ```r plot(cars, main = 'A scatterplot.') 1 + 2
I used I() as a convenient marker to indicate character strings as syntax extracted from normal character strings. This is just an arbitrary choice. PDF output:

This is not an ideal solution. In some cases, you will need to configure it. For example, most LaTeX special characters are not escaped, for example ~ . You may need to process the LaTeX code returned by hi_pandoc() on gsub() .
Personally, I find several colors in the built-in distracting effect, so I would not highlight the syntax, but this is a completely personal taste.
Yihui xie
source share