关于r:使用knitr / rmarkdown突出显示bash代码

Highlighting bash code with knitr / rmarkdown

我正在尝试使用RStudio,R Markdown和knitr生成HTML报告。在报告中,我想显示一些bash代码。我不想运行代码,但希望突出显示它。

在另一个问题中已经提到它,但是那里的建议对我不起作用。到目前为止,这是我尝试过的操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
---
title:"bash highlighting?"
output: html_document
---
```{r, engine = 'bash', eval = FALSE}
for foo in (ls bar)
do
  echo $foo
done
```

```{bash, eval = FALSE}
for foo in (ls bar)
do
  echo $foo
done
```

这些都不使我在HTML文档中突出显示。我知道这是有可能的,因为我记得一周左右前在某处看到过它,但现在找不到了!有谁知道我怎么能做到?

感谢阅读,

汤姆

编辑:我刚刚找到了这个答案,它建议在.Rmd

中使用以下代码块

1
2
3
4
5
6
7
<link rel="stylesheet" href="http://yandex.st/highlightjs/7.3/styles/default.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
<script src="http://yandex.st/highlightjs/7.3/highlight.min.js">

$(document).ready(function() {
  $('pre code').each(function(i, e) {hljs.highlightBlock(e)});
});

这适用于文档中的bash代码,但会杀死R代码的突出显示!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
## R version 3.2.0 (2015-04-16)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 14.04.2 LTS
##
## locale:
##  [1] LC_CTYPE=en_AU.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_AU.UTF-8        LC_COLLATE=en_AU.UTF-8    
##  [5] LC_MONETARY=en_AU.UTF-8    LC_MESSAGES=en_AU.UTF-8  
##  [7] LC_PAPER=en_AU.UTF-8       LC_NAME=C                
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=en_AU.UTF-8 LC_IDENTIFICATION=C      
##
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base    
##
## loaded via a namespace (and not attached):
## [1] formatR_1.2     tools_3.2.0     htmltools_0.2.6 yaml_2.1.13    
## [5] rmarkdown_0.5.1 knitr_1.10      stringr_0.6.2   digest_0.6.8  
## [9] evaluate_0.7


默认语法突出显示主题不适用于非R代码块,您可以使用其他主题,例如pygments

1
2
3
4
5
6
7
8
9
10
11
12
13
---
title:"Bash Highlighting"
output:
  html_document:
    highlight: pygments
---

```{r, engine = 'bash', eval = FALSE}
for foo in (ls bar)
do
  echo $foo
done
```


好的,感谢您的评论。看来RStudio与突出显示效果不佳。当我将中间降价文件保留为in.md

1
2
3
4
5
6
7
8
9
10
11
12
13
---
title:"Bash Highlighting"
output:
  html_document:
    keep_md: true
---

```{r, engine = 'bash', eval = FALSE}
for foo in (ls bar)
do
  echo $foo
done
```

然后使用pandoc转换为html,例如来自BioConductor的CSS:

1
2
3
pandoc -s in.md \\
    -c https://hedgehog.fhcrc.org/bioconductor/branches/RELEASE_3_1/madman/Rpacks/BiocStyle/inst/resources/html/bioconductor.css \\
    -t html -o out.html

我为Rbash突出显示了不错的代码。

谢谢!