Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add line numbers to text content of a rendered rmarkdown html document

I am writing a report in Rmarkdown which shall be rendered in html because it contains Rshiny chunks. Is there any way I can add line numbers to the file?

Importantly I need line numbers for the text and not for the code chunks as asked here.

I wonder if it is possible to add some CSS to the .Rmd file below but wouldn't know how to do that.

---
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.

Thank you very much,

Paul

like image 767
Paul Avatar asked Jun 16 '16 18:06

Paul


People also ask

How do you make a superscript in R Markdown?

To indicate a superscript, use a single caret character ^ . Note: this can be confusing, because the R Markdown language delimits superscripts with two carets. In LaTeX equations, a single caret indicates the superscript. If the subscript or superscript has just one character, there is no need to delimit with braces.

How do I create an index in R Markdown?

Authoring Books and Technical Documents with R Markdown An index entry can be created via the \index{} command in the book body, e.g., \index{GIT} .

How do you insert a line break in R Markdown PDF?

Add Line Breaks in R Markdown To break a line in R Markdown and have it appear in your output, use two trailing spaces and then hit return .

How do you add a footnote in R Markdown?

To create a footnote in R Markdown, you use the carrot ^ followed immediately by square brackets []. Put the text inside of the [] and it'll print that at the bottom of the page. Code for a footnote will look like this: ^[This sentence will be printed as a footnote.] .


1 Answers

Interesting question and since I like to play around with JS and jQuery inside of RMarkdown documents I gave it a shot.

This solution is not bulletproof. It is only tested with Firefox. Since cross-browser compatibility of jQuery is a mess it will probably only work with Firefox.

Every line is now labeled including normal paragraphs, unordered and ordered lists, source code and output chunks.

Here is the complete working document:

---
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>
  var $elements = $('p:not(:has(>img)), pre,  ul, ol').slice(start=1);

  $(document).ready(function(){
    $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)
```

You can exclude certain parts by just removing the corresponding tag from the line

var $elements = $('p:not(:has(>img)), pre,  ul, ol').slice(start=1);

So if you do not want to label output chunks and lists, change it to

var $elements = $('p:not(:has(>img)), pre.r').slice(start=1);

(Unlike output chunks, source code chunks carry the class .r.)

As I said for complex documents you might stumble over some bugs. Let me know if you do ;)

enter image description here

like image 108
Martin Schmelzer Avatar answered Nov 25 '22 08:11

Martin Schmelzer