如何语法中的R降价亮点内嵌R代码里面?

问题描述 投票:9回答:2

这个问题类似于consistent code html inline and in chunks with knitr。取而代之的.rhtml文件,我想强调R中降价文件,例如内嵌R代码里面,`r "plot(cars, main = 'A scatterplot.')"`通过rmarkdown编译后,像plot令牌应突出。默认情况下,R代码块是语法高亮,但是没有办法,突出内嵌R代码里面。

r syntax-highlighting knitr r-markdown
2个回答
19
投票

下面是使用highr包(development version)的devtools::install_github('yihui/highr')一个解决方案。基本上你只定义自定义LaTeX命令以突出的标记。 highr:::cmd_pandoc_latex是胶乳的数据帧命令,Pandoc用来做语法高亮。

head(highr:::cmd_pandoc_latex)
##                   cmd1 cmd2
## COMMENT  \\CommentTok{    }
## FUNCTION  \\NormalTok{    }
## IF        \\NormalTok{    }
## ELSE      \\NormalTok{    }
## WHILE     \\NormalTok{    }
## FOR       \\NormalTok{    }

然后,你可以重新定义knitr的inline钩:

---
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()作为一种方便的标记告诉字符串是语法与正常字符串突出。这仅仅是一个任意选择。 PDF输出:

syntax highlighted inline code

这不是一个完美的解决方案,虽然。您将需要调整它在某些情况下。例如,最特别的LaTeX的字符没能逃脱,如~。您可能需要处理由hi_pandoc()gsub()回到LaTeX的代码。

我个人觉得在直列输出分心多种颜色,所以我不会语法高亮,但是这完全是个人喜好。


6
投票

如今:

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

好了,我不知道具体是对R和你使用它的方式,但对于大多数语言(pandoc使用skylighting PKG这样做),你可以做内联代码块上述语法。

© www.soinside.com 2019 - 2024. All rights reserved.