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

  1. ```{r, attr.source='.numberLines'}
  2. if (TRUE) {
  3. x <- 1:10
  4. x + 1
  5. }
  6. ```

The output is:

  1. if (TRUE) {
  2. x <- 1:10
  3. x + 1
  4. }

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

  1. output:
  2. html_document:
  3. 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 (if you find the line numbers too close to the left margin, increase the left value to, say, -0.2em):

  1. pre.numberSource code > span > a:first-child::before {
  2. left: -0.3em;
  3. }

For revealjs’s revealjs_presentation output format (El Hattab and Allaire 2017), you may also need to adjust the CSS.

  1. .reveal pre code {
  2. overflow: visible;
  3. }

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

  1. ```{r, attr.source='.numberLines startFrom="5"'}
  2. if (TRUE) {
  3. 1:10
  4. }
  5. ```

Line numbers are not supported for Word output at the moment.

References

El Hattab, Hakim, and JJ Allaire. 2017. Revealjs: R Markdown Format for Reveal.js Presentations. https://github.com/rstudio/revealjs.