Cross-reference code chunks in `bookdown` similar to figures, tables, and equations

Cross-posted on stackoverflow

When I am writing with bookdown, I would like to be able to refer to a code chunk in the text.
Presumably, this would require a two-fold solution:

  • Index each target code chunks numerically
  • Add href anchors to the indices so that I can refer to them in the text

With the help from this SO thread and this SO thread,
I was able to piece together a solution for the first part.

Inside style.css:

.book .book-body .page-wrapper .page-inner section.normal {
  counter-reset: counter-rchunks;

.book .book-body .page-wrapper .page-inner section.normal div.section div.sourceCode {
  padding-right: 5em;

.book .book-body .page-wrapper .page-inner section.normal div.section div.sourceCode pre.demor {
  counter-increment: counter-rchunks;
  position: relative;
  overflow: visible;

.book .book-body .page-wrapper .page-inner section.normal div.section div.sourceCode pre.demor::after {
  content: '[' counter(counter-rchunks) ']';
  display: inline-block;
  position: absolute;
  right: -5em;
  color: rgb(48, 63, 159);

Inside one of the bookdown chapters:

    ```{r class.source = "demor"}

    cars |>
      dplyr::slice_head(n = 3)


The result, once knitted, would look like this:

enter image description here

I would really appreciate if someone could help me complete the solution
so that I could cross-reference code chunks within the text.
For example,

As shown in chunk 1, ...

in which the "1" would be a hyperlink to where the actual chunk is located on the page.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.