Ame*_*aMN 32 css r knitr r-markdown
我希望以不同的颜色(例如红色)突出显示某个代码块,以表明这是不好的做法.如果我正在使用.Rnw
,我可以添加chunk选项background = 'red'
并得到我想要的东西,但这似乎不起作用.Rmd
.我的猜测是我需要制作一个自定义的css样式表(虽然选择器是什么,我不知道),也可能创建一个自定义钩子.我希望它基于每个块,而不是整个文档的整体更改.
Ian*_*tle 29
我们可以使用class.source
代码块头中的选项为R Markdown提供自定义CSS.这在以下帖子中解释:
综合一个例子,我可能会设置一个名为"badCode"的类,然后有一些CSS来改变你想要的背景.这是我的.Rmd
:
---
output: html_document
---
```{css}
.badCode {
background-color: red;
}
```
```{r mtcars}
summary(mtcars)
```
```{r cars, class.source="badCode"}
summary(cars)
```
Run Code Online (Sandbox Code Playgroud)
Jim*_*Jim 27
请记住,markdown支持代码块之外的HTML.
我会用一个带有自定义类的div来包围代码块,这个类可以根据我的需要设置它们.此示例将代码设置为蓝色,输出设置为浅蓝色
<style>
div.blue pre { background-color:lightblue; }
div.blue pre.r { background-color:blue; }
</style>
<div class = "blue">
```{r bluecars}
summary(cars)
```
</div>
```{r normal}
summary(cars)
```
Run Code Online (Sandbox Code Playgroud)
这个解决方案有点黑客,但它确实有效.它的要点是制作两个代码块,用唯一的类名交换{r}指示符.然后添加css代码来设置每个块的样式.
---
output: html_document
---
<style>
pre.bluecars {
background-color: #aabbff !important;
}
pre.redcars {
background-color: #ffbbbb !important;
}
</style>
## chunk-specific bg colors
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
- blue
```{bluecars}
summary(cars)
```
```{r, echo=FALSE}
summary(cars)
```
- normal
```{r}
summary(cars)
```
- red
```{redcars}
summary(cars)
```
```{r, echo=FALSE}
summary(cars)
```
Run Code Online (Sandbox Code Playgroud)
我发现了以下方法来对我编织为 PDF 的 Rmarkdown 文档中的块进行着色(编码):
使用 pandoc 突出显示方案作为基础
pandoc --print-highlight-style pygments > my.theme
Run Code Online (Sandbox Code Playgroud)
然后使用正则表达式编辑 my.theme 来设置所有
"text-color": null
Run Code Online (Sandbox Code Playgroud)
然后,您可以将此属性更改为您喜欢的任何颜色(这里是浅灰色)
"background-color": "#f8f8f8"
Run Code Online (Sandbox Code Playgroud)
在“pdf_document”下的 .Rmd 文档的 YAML 中,输入以下内容
pandoc_args: --highlight-style=my.theme
Run Code Online (Sandbox Code Playgroud)
对于我的用例来说,这就是我所需要的。
归档时间: |
|
查看次数: |
10410 次 |
最近记录: |