Before reading

1 Number Pandoc’s fenced code

Pandoc has an official support to number lines on fenced code by giving a class attribute numberLines (https://www.pandoc.org/MANUAL.html#extension-fenced_code_attributes). The document also introduces that lineAnchors class makes line numbers be clickable, and startFrom arugment supports specify starting number.

Note that class attributes require . before the class name.

becomes

This is enough for rmarkdown::pdf_document.

For html_document, we also need to specify highlight other than default in YAML front matter1, 2. See ?rmarkdown::html_document for available highlight options.

2 Number Rmarkdown’s chunks and outputs

The above success infers a success in chunks of Rmarkdown.

2.1 Numbering chunks

For code chunks of Rmarkdown documents, numberLines class can be given by assigning class.source = "numberLines" as a chunk option3. You may also add lineAnchors demilited by space ("numberLines lineAnchors") or as another element of vector (c("numberLines", "lineAnchors")) 4. Unfortunately, I find no way to add startFrom="integer".

Again, you need to specify highlight for html_document.

Thus,

becomes

## [1] 5.5

Great again!!

Unfortunately, line numbering does not work on rmarkdown::word_document.

It does not work properly on rmarkdown::html_notebook and blogdown::html_page as well. I guess some tricks required in CSS or JS.

2.2 Numbering outputs

You may also want to number lines on outputs by class.output = "numberLines" with or without lineAnchors just like input. However, this changes background colors to gray.

If output format is html, css will help.

Before adding class.output = "numberLines", an output in html is

After adding it, the output in html becomes

When chunkout class is further added, the output in html becomes

You can see chunkout class is added to pre tag.

So, lets modify css with

and you’ll be happy, right?

Sorry I do not support pdf because \(LaTeX\) kills me.

4 Enjoy !


  1. “Chunk numberLines hook]” on Rpubs figured out requirement of pygment (https://rpubs.com/Thell/numberLines).

  2. @niszet0 mentioned that not only pygment but also highlight other than default are acceptable (https://niszet.hatenablog.com/entry/2019/04/18/194246 in Japanese).

  3. See “Tex Results” section of “Chunk options and package options” by Yi Hui (https://yihui.name/knitr/options/#text-results)

  4. @niszet mentioned me on Twitter https://twitter.com/niszet0/status/1118837863200591872

  5. The document indicates a following YAML front matter should work, but doesn’t (https://www.pandoc.org/MANUAL.html#reader-options).