r - 如何在 R Markdown 中突出显示内联 R 代码?

标签 r syntax-highlighting knitr r-markdown

这个问题类似于 consistent code html inline and in chunks with knitr .而不是 .Rhtml 文档,我想突出显示 R Markdown 文档中的内联 R 代码,例如,在 `r "plot(cars, main = 'A scatterplot.')"` 之后通过编译 Markdown , 像 plot 这样的标记应突出显示。默认情况下,R 代码块会突出显示语法,但无法突出显示内联 R 代码。

最佳答案

这是使用 development version 的一种解决方案的更高 包(devtools::install_github('yihui/highr'))。基本上,您只需定义自定义 LaTeX 命令以突出显示标记。 highr:::cmd_pandoc_latex是 Pandoc 用来进行语法高亮的 LaTeX 命令的数据框。

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

然后你可以重新定义inline 的钩子(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()作为一个方便的标记,告诉字符串是从普通字符串中突出显示的语法。这只是一个随意的选择。 PDF输出:

syntax highlighted inline code

不过,这不是一个完美的解决方案。在某些情况下,您需要对其进行调整。例如,大多数特殊的 LaTeX 字符都不会转义,例如 ~ .您可能需要处理 hi_pandoc() 返回的 LaTeX 代码通过 gsub() .

就我个人而言,我发现内联输出中的多种颜色会分散注意力,所以我不会在语法上突出显示它,但这完全是个人喜好。

关于r - 如何在 R Markdown 中突出显示内联 R 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40252885/

相关文章:

syntax-highlighting - 如何在VI编辑器中交互式设置语法突出显示

r - 对于每一行,返回非 NA 值的列索引和名称

r - 编织 RMarkdown 文件时遇到问题

python - 相当于R中的python dict

emacs - 在所有编程模式中突出显示 TODO

r - rMarkdown 中是否可以有可排序(交互式)表格?

r - R : argument is not numeric or logical: returning NA, as.integer()

c++ - Visual Studio 2010 中好的 C++ 主题的集合?

r - 在 R Markdown PDF 输出中更改绘图图表大小的输出宽度

r - knitr - 更改代码缩进