在渲染的rmarkdown html文档中添加行号到文本内容

8
我正在使用Rmarkdown撰写一份报告,需要在其中嵌入Rshiny代码块,因此需要将其渲染为html格式。请问是否有办法为文件添加行号?
重要的是,我需要为文本而不是代码块添加行号,就像这里所提到的那样。
我想知道是否可以在下面的.Rmd文件中添加一些CSS样式,但不知道该怎么做。
---
title: "Title"
author: "Yourname"
date: "June 16, 2016"
output: html_document
runtime: shiny
---


This R Markdown document is made interactive using Shiny. 
Unlike the more traditional workflow of creating static reports, you can now create documents that allow your 
readers to change the assumptions underlying your analysis and see the results immediately. 

## Inputs and Outputs

You can embed Shiny inputs and outputs in your document. Outputs are automatically updated whenever inputs change.  
This demonstrates how a standard R plot can be made interactive by wrapping it in the Shiny `renderPlot` function. 
The `selectInput` and `sliderInput` functions create the input widgets used to drive the plot.

非常感谢您,
保罗
1个回答

7

这是一个有趣的问题,因为我喜欢在RMarkdown文档中尝试使用JS和jQuery,所以我尝试了一下。

这个解决方案并不完美。它仅在Firefox上进行了测试。由于jQuery的跨浏览器兼容性很混乱,它可能只能在Firefox上正常工作。

现在每行都被标记,包括普通段落、无序和有序列表、源代码和输出块。

以下是完整的可工作文档:

---
title: "Title"
author: "Yourname"
date: "June 16, 2016"
output: html_document
runtime: shiny
---

<style>
/* Style the linenumber div */
  .linenumbers {
    border: 1px solid #ccc;
    border-radius: 4px;
    background-color: #EBEBEB;
    text-align: center;
    padding: 0px 3px;
    font-family: monospace;
    float: left;
    position: absolute;
    transform:translate(-125%);
    font-size: inherit !important;
  }

  .main-container {
    margin-left: 8% !important;
  }

  /* fixes the problem with inline code 
     that makes the line spacing bigger: */
  p > code {
    line-height: 90% !important;
  }
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

<script>
  $(document).ready(function(){
  var $elements = $('p:not(:has(>img)), pre,  ul, ol');
    $elements.wrap('<numbering/>');
    $('numbering').prepend('<div class=\"linenumbers\"/>');

    updateLines = function(elmts) {
      var counter = 1; // counts total number of lines
      $(elmts).each(function() {       

        if($(this).is('pre')) {
          var $elmt = $(this).children('code');
          var styles = $(this).css([ "padding-top", "padding-bottom", "line-height"]);
          $(this).siblings('.linenumbers').css(styles);
        } else {
          var $elmt = $(this);
        }

        var h  = $elmt.outerHeight();  // get the height
        var nl = Math.round(h /parseFloat($elmt.css('line-height'))); 
        var text = '';
        for(var i=counter; i < counter + nl; ++i) {
          text += i + '</br>';
        }
        counter += nl;
        $(this).siblings('.linenumbers').html(text);
      });
    };
    updateLines($elements);

  });

  $(window).resize(function() {
    updateLines($elements);
  });
</script>

This R Markdown document has the ability to interactively number 
the lines of text content. It might not be perfect but it sure 
looks nice. If you find a bug or have a tip for how to further improve 
the code, please let me know. I am no professional JavaScript 
programmer so  this was made by an amateur ;)


What if I leave some space here?


## Inputs and Outputs

Here starts another paragraph. Look how the line numbers jump over to 
this one! This is amazing! For demonstrating purposes I have to write 
some more lines. So I bore you a bit more with my nonsense. NONSENSE! 
Ok let us try out some inline code and see whether the line numbers 
still align. `library(ggplot2)` And a second `time()`. Looks ok I 
guess. 
Here starts another paragraph. Look how the line numbers jump over to 
this one! This is amazing! For demonstrating purposes I have to write 
some more lines.    
So I bore you a bit more with my nonsense. NONSENSE! Ok let us try out 
some inline code and see whether the line numbers still align.
`library(ggplot2)` And a second `time()`. Looks ok I guess.
 
```{r}
x <- 1:5
B <- 'Martin'
head(mtcars)
```

```{r}
plot(1)
```

您可以通过从该行中删除相应的标记来排除某些部分。
var $elements = $('p:not(:has(>img)), pre,  ul, ol');

所以,如果您不想标记输出块和列表,请将其更改为:
var $elements = $('p:not(:has(>img)), pre.r');

与输出块不同,源代码块带有类.r

正如我所说,对于复杂的文档,您可能会遇到一些错误。如果您遇到了,请让我知道;)

enter image description here


Martin,非常感谢你!这是向会议论文写作中加入带有Shiny元素的rmarkdown迈出的一大步。我注意到两件事。它在Firefox 47.0上可以运行,但在我的电脑上Chrome 51.0上不行。此外,如果在<textcontent> </ textcontent>标签内存在空行,则会停止编号。有什么想法吗? - Paul
1
Paul和@Ben:谢谢和不客气。我已经研究了这些问题。首先,我可以说的是,这些jQuery机制不是跨浏览器兼容的,所以你必须坚持使用Firefox。明天我会更新答案,提供一些支持源代码块的新代码。 - Martin Schmelzer
Paul和@Ben:嗯,我等不及明天了 ;) - Martin Schmelzer
@MartinSchmelzer 有没有其他方法可以做到这一点?我不知道我做错了什么,但这对我没有用?我发现其他方法是用1 2 3 4 ... 1 2 3 4 .. 1为每行编号。但是,每当有一个新的块时,我不希望它从1开始..我只想让它从1开始然后继续。所以,你的方法就是我想要的,但它对我来说不起作用。 - rr19
@MartinSchmelzer 我正在使用Rmarkdown(即安装版本的Rstudio,而不是云端),我真的希望从上到下所有行都有编号(类似于这篇帖子中的图片)。我不知道Quarto是什么..但它可能与R编码有关,因为你问了。我会看一下的。即使我不擅长编程,但听到关于编程的新事物也很有趣 :) - rr19
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接