我想将代码行编号添加到 Rmarkdown 文件的 HTML 输出中。我会对任何方法感到满意uniquely标识输出中的每一行代码(例如,在整个文档中递增的连续行号,或者代码块由它们自己的索引标识,并且在这些代码块中行号从 1 开始)。
我一直无法实现这一目标。
使用其他 stackoverflow 答案和这篇博文 https://blog.atusy.net/submodules/rmd-line-num/index.html我已经获得了行号,但它们会随着每个新块而重置。
我有以下 Rmd 文件:
---
output:
html_document:
highlight: kate
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
class.source = "numberLines lineAnchors"
)
```
```{r}
5 + 5
3 * 9
```
```{r}
x <- 5
x * 3
```
编译为:
正如您所看到的,当一个块被输出分割或一个新块开始时,行号会重置。我希望看到的行号为 1, 2, 3, 4,而不是 1, 1, 1, 2。
Anyone know how to get this to work?
我设法通过在 HTML 文档末尾添加一些 jquery 来获取连续的行号Rmd
文档:
---
output:
rmdformats::html_clean:
highlight: kate
toc: true
use_bookdown: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
class.source = "numberLines lineAnchors"
)
```
```{r}
5 + 5
3 * 9
```
```{r}
x <- 5
x * 3
```
<!--
The javascript below will reset the line numbers when
the document loads.
-->
<script>
$(function() {
$(".sourceLine").each( function( index ){
$( this ).attr( "data-line-number", index + 1 );
});
});
</script>
The resulting document has the sequential line numbers, as shown below:
这有点hacky,因为它需要jquery(可能是通过包含一些覆盖现有CSS的方法来实现的),但它可以工作并且看起来很整洁。
截至 2020 年 8 月 4 日更新
他们改变了行编号的工作方式(现在它基于 CSS 计数器)。为了让它在整个文档中按顺序工作,您需要插入一些 CSS。下面是一个完整的工作示例。重要的代码在<style>
堵塞。它重置相关计数器body
(文档)级别,并防止为每个代码块重置计数器。
---
output:
rmdformats::html_clean:
highlight: kate
toc: true
use_bookdown: true
---
<style>
body
{ counter-reset: source-line 0; }
pre.numberSource code
{ counter-reset: none; }
</style>
```{r setup, include=FALSE}
knitr::opts_chunk$set(
class.source = "numberLines lineAnchors"
)
```
```{r}
5 + 5
3 * 9
```
```{r}
x <- 5
x * 3
```
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)