bookdown icon indicating copy to clipboard operation
bookdown copied to clipboard

Reference and caption code chunk

Open coatless opened this issue 7 years ago • 13 comments

I'm interested in being able to reference code listings alongside a caption in a manner similar to figures. For example, if I had a code chunk called dobootstrap

It might look like so:

```{r dobootstrap, code.cap = "Illustrates the overall procedure for writing a simple random sample with replacement bootstrap."}
bootstrap = function(xt, B = 100, func = mean, ...) {
  results = rep(NA, B)   # Storage Vector
  n = length(xt)             # Length of Data
  
  for (i in seq_len(B)) {   # Begin Bootstrap
    xt_star  = xt[sample(n, n, replace = T)] # Generate new data
  results[i] = func(xt_star, ...) # Obtain statistic
  }
  
  results                         # Return bootstrapped test distribution
}
```

Then the reference would be \@ref(code:dobootstrap).

Presently, the only way to reference a chunk seems to be to have it generate a figure and apply a caption with fig.cap.

coatless avatar Nov 08 '16 05:11 coatless

This is not possible at the moment. If I try hard enough, I can probably implement it, but I tend not to do it: https://bookdown.org/yihui/bookdown/faq.html

I guess I'm well-known to be opinionated, and here is my opinion on cross-references: I don't like them. As an author, I find it very convenient to refer readers to different parts of the document. As a reader, I find it more of a mess. Each cross-reference potentially means the reader has to flip some pages through the book. A lot of cross-references will make the book a tangled hairball. So I'll remind myself not to abuse cross-references when I write something lengthy. I admit I often fail, though. I succeeded in avoiding footnotes and parentheses as much as possible somehow, so readers don't have to move their eyes up and down, or be interrupted by a side note. Personally I find it helpful to explain things in a structure as linear as possible and not to connect all the dots explicitly. When I read a Sherlock Holmes story, I find I can connect the dots in my brain without the author telling me to go to Section 3.4 or see Figure 5.7, even if the story is quite complicated. I do admire authors of detective stories. It may not be fair to compare academic/technical writing with novels, but I'd ask myself time and time again if I could avoid redirecting readers when I write, in other words, can I make it clear in the first place so readers can just remember it?

Okay, I have digressed far enough :) Back to your request: I'm not saying a hard no. If it turns out the gain overweighs the pain, I'll certainly be happy to reconsider it (e.g. your request #152 was a good one, since theorems can make the logic more clear in math books).

yihui avatar Nov 08 '16 06:11 yihui

I would very much like to see this feature implemented. I'm generally in agreement about excessive cross-referencing but in the case of code blocks I often find you want to be able to point to some code you have included in an appendix from a methods section, where you explain in board terms what the code does in the methods for non-coding types and then point to the specifics for those interested in the implementation.

RichardJActon avatar May 10 '18 13:05 RichardJActon

I just wanted to add my voice here - it would be great to be able to reference code chunks in text, as I would like to draw the readers attention to the way that the code is written in a paper - so the feature is the code, rather than its output.

I have asked myself the question "Do I really need this?", and I think that the answer is yes - although I would also be very happy with an alternative, such as making the code into an algorithm format, or something similar.

I'm happy to try and work on this, if that would be helpful?

njtierney avatar Jun 13 '18 23:06 njtierney

Okay, I think I have got enough votes for this feature. I still don't have time for it, but anyone please feel free to try. Note that you will have to make it work for at least PDF and HTML output. It will be great if it also works for EPUB and Word, but personally I don't care much about these formats.

yihui avatar Jun 14 '18 04:06 yihui

OK great, I'm happy to give this a shot - I have been looking for an excuse to get into the internals of bookdown/rmarkdown, so let's see how I go - I don't think that I will get this feature done in time for the paper, so it might be a while - anyone reading this please feel free to have a go!

njtierney avatar Jun 14 '18 04:06 njtierney

I would also be interested in this feature! Let me know if there is a way I can help!

ihrke avatar Sep 27 '18 07:09 ihrke

Hi -- has this feature been implemented? Some publishers specifically require code chunks to be structured as captioned tables that can be referenced in the text, with proper sourcing information etc. I do think it would be very helpful to be able to use it.

spegmb avatar Feb 24 '20 13:02 spegmb

For those who interested, you may find this post on SO useful:

https://stackoverflow.com/questions/50702942/does-rmarkdown-allow-captions-and-references-for-code-chunks

Unfortunately, it only works for PDF output

hongyuanjia avatar Mar 05 '20 05:03 hongyuanjia

I am also interested in this feature. I am currently working on a methods textbook. I totally agree with Yihui's points above (tangled hairball etc.), i.e., one should not reference things that are far away. However, atm I am using "see code below/above" (or something similar) to refer to code chunks and it would be much more exact to ref the chunk with an identifier.

paulcbauer avatar May 12 '20 10:05 paulcbauer

It would be great to see this feature!

mattnolan001 avatar Jul 17 '20 10:07 mattnolan001

It is worth noting that when using the listings package (by passing --listings to pandoc to generate the alternate LaTeX), the package itself supports captions and labels being passed in to its arguments (i.e. \begin{lstlisting}[caption={Useless code},label=useless]). Looking at Pandoc's source, it will export label at least if it is specified, but I don't see a way to do that...

At least I would likely make use of this on "plain" code blocks (i.e. not evaluated ones), too.

augustin avatar Sep 14 '22 04:09 augustin

Thanks a lot for sharing this @augustin. I did not notice --listings option before as a non expert LaTeX users. However, I know my way around Pandoc. Here is how you can add label and caption to a plain code block

---
title: "Untitled"
author: "Unauthored"
date: "1/1/2020"
output:
    pdf_document:
      pandoc_args: --listings
---

```{.r #lst:id caption="My Code Chunk"}
1 + 1
```

See Listing \ref{lst:id} for details

image

With evaluated code, you can leverage attr.source knitr options

---
title: "Untitled"
author: "Unauthored"
date: "1/1/2020"
output:
    pdf_document:
      pandoc_args: --listings
      keep_tex: true
---

```{r collapse = TRUE, attr.source="#lst:id caption='My Code Chunk'"}
1 + 1
```

See Listing \ref{lst:id} for details

image

However, I don't know what feature are lost by loosing listing code chunk; I am not sure highlighting is still working.

The hard part for such feature is bookdown is making sure that it works for HTML and PDF, and that it works with other feature too.

But for PDF only output, you should be able to use the above.

cderv avatar Sep 14 '22 08:09 cderv

I am not sure highlighting is still working.

Using listings means highlighting is provided by the LaTeX package and not by Pandoc, and indeed the LaTeX package seems to have more limited highlight definitions. In my testing things seem to still be at least "acceptable", but the extra features are for the time being nicer.

Thanks very much for this!

augustin avatar Sep 14 '22 19:09 augustin