How to syntax highlight inline R code in R Markdown?

南笙酒味 提交于 2019-11-27 11:34:45

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/40252885/how-to-syntax-highlight-inline-r-code-in-r-markdown

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