How can syntax highlight inline R code in R Markdown?

This question is similar to the consistent html inline code and in pieces with knitr . Instead of .Rhtml documents, I want to highlight the embedded R-code in R Markdown documents, for example, after `r "plot(cars, main = 'A scatterplot.')"` Compiled with rmarkdown , tokens such as plot , should be highlighted. By default, R code fragments are syntax highlighted, but there is no way to isolate inline R code.

+8
r syntax-highlighting knitr r-markdown
source share
2 answers

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 # a comment ``` 

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:

syntax highlighted inline code

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.

+17
source share

Present time:

 Here is some 'plot(cars, main = 'A scatterplot.')'{.R} inline R code 

Well, I don’t know specifically about R and how you use it, but for most languages ​​(pandoc uses highlighted pkg for this), you can create inline code blocks with the above syntax.

0
source share

All Articles