Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to syntax highlight inline R code in R Markdown?

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.

like image 768
Yihui Xie Avatar asked Oct 26 '16 02:10

Yihui Xie


People also ask

How is inline code embedded in R Markdown?

Code results can be inserted directly into the text of a . Rmd file by enclosing the code with `r ` .

Can I highlight code in r?

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

How do you write inline code in Markdown?

You can either use inline code, by putting backticks (`) around parts of a line, or you can use a code block, which some renderers will apply syntax highlighting to.


2 Answers

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:

syntax highlighted inline code

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.

like image 75
Yihui Xie Avatar answered Oct 12 '22 16:10

Yihui Xie


Now-a-days:

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

Well, I don't know specifically about R and the way you're using it, but for most languages (pandoc uses the skylighting pkg to do this), you can do inline code blocks with the above syntax.

like image 14
dylnmc Avatar answered Oct 12 '22 18:10

dylnmc