Skip to main content

R Markdown Cookbook Practical Tips and Tricks for R Markdown

Section 5.7 Line numbers for code blocks

You can add line numbers to either source code blocks, via the chunk option attr.source = ".numberLines", or text output blocks, via attr.output = ".numberLines" (see Sectionย 11.13 for more information on these options), e.g.,
```{r, attr.source='.numberLines'}
if (TRUE) {
  x <- 1:10
  x + 1
}
```
Note that for HTML output, you have to choose a syntax highlighting theme provided by Pandoc, which means the highlight option of the output format should not be default or textmate. You can use other values for this option listed on the help page ?rmarkdown::html_document, e.g.,
output:
  html_document:
    highlight: tango
For bookdownโ€™s gitbook output format, you may need to adjust the CSS a little bit for the line numbers to be displayed properly on the left side of the code. Below is what we used for this book:
pre.numberSource code > span > a:first-child::before {
  left: -0.3em;
}
For revealjsโ€™s [49] revealjs_presentation output format, you may also need to adjust the CSS:
.reveal pre code {
  overflow: visible;
}
See Sectionย 7.1 if you do not know how to apply custom CSS styles to HTML output.
You can also specify the starting number via the startFrom attribute, e.g.,
```{r, attr.source='.numberLines startFrom="5"'}
if (TRUE) {
  1:10
}
```
Line numbers are not supported for Word output at the moment.