How to syntax highlight inline R code in R Markdown?
knitr, r, r-markdown, syntax-highlighting
Solution
Here is one solution using the development version of the highr package (`devtools::install_github('yihui/highr')`). Basically you just define your custom LaTeX commands to highlight the tokens. `highr:::cmd_pandoc_latex` is a data frame of LaTeX commands that Pandoc uses to do syntax highlighting.
head(highr:::cmd_pandoc_latex)
## cmd1 cmd2
## COMMENT \\CommentTok{ }
## FUNCTION \\NormalTok{ }
## IF \\NormalTok{ }
## ELSE \\NormalTok{ }
## WHILE \\NormalTok{ }
## FOR \\NormalTok{ }
Then you can redefine the `inline` hook of knitr:
---
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 # a comment
`
I used `I()` as a convenient marker to tell the character strings to be syntax highlighted from normal character strings. It is just an arbitrary choice. PDF output:
This is not a perfect solution, though. You will need to tweak it in some cases. For example, most special LaTeX characters are not escaped, such as `~`. You may need to process the LaTeX code returned by `hi_pandoc()` by `gsub()`.
Personally I find multiple colors in inline output distracting, so I would not syntax highlighting it, but this is entirely personal taste.
Problem
This question is similar to consistent code html inline and in chunks with knitr. Instead of .Rhtml documents, I want to highlight inline R code in R Markdown documents, e.g., after ``r "plot(cars, main = 'A scatterplot.')"`` is compiled through rmarkdown, the tokens like `plot` should be highlighted. By default, R code chunks are syntax highlighted, but there is no way to highlight inline R code.