Code folding in bookdown

Viewed 5922

The Code folding option in RMarkdown for html documents is awesome. That option makes the programmatic methodology transparent for those who are interested, without forcing the audience to scroll through miles of code. The tight placement of code with prose and interactive graphical output makes the whole project more accessible to a wider audience, and furthermore it reduces the need for additional documentation.

For a larger project, I'm using bookdown, and it works great. The only problem is that there is no code-folding option. Code folding is not currently enabled in bookdown. (see Enable code folding in bookdown )

I know I don't need an option to make it happen. I just need to paste the right code in the right place or places. But what code and where?

A viable alternative would be to put the code chunk below the chunk's outputs in the page. Or, finally, to put them as an appendix. I could do that with html but not reproducible like rbookdown.

3 Answers

I made the R package rtemps which includes a ready-to-use bookdown template with code-folding buttons among others (largely based on Sébastien Rochette's answer/post). Check it here!

I wrote a filter for pandoc that:

  • wraps all code blocks in HTML5 <details> tags
  • adds a local button to fold/unfold code
  • button text toggles between "Show code" and "Hide code" (feel free to customize) via onclick javascript event

Filter can be found here. Needs python distribution with panflute installed to run.

Add to bookdown via pandoc_args: ["-F", "path/to/collapse_code.py"]

Related