3

In my document, I want to show some info, using ``` block, such as:

```
bruin@c7 ~ $ cat /etc/centos-release
CentOS Linux release 7.4.1708 (Core)
bruin@c7 ~ $
```

For large output chunks, I want to fold them. How to do that? Searching the web it seems all related topics are about code folding, but what I want to fold is not any type of code, just simple text...

Thanks!

Ralf Stubner
  • 26,263
  • 3
  • 40
  • 75
bruin
  • 979
  • 1
  • 10
  • 30

1 Answers1

4

Here is a very easy way to implement the following yourself:

enter image description here

You can find all the code you need in the following reproducible RMD document:

---
title: "Hide Verbatim Blocks"
author: "Martin Schmelzer"
date: "June 22, 2018"
output: html_document
---

<style>
.fold-btn { float: right; }
</style>

<script type="text/javascript">
$(document).ready(function() {
  $(".fold").prepend("<button class=\"fold-btn\">Unfold</button>");
  $(".fold").children("code").toggle();
  $(".fold-btn").on("click", function() {
    if($(this).text() === "Fold") {
      $(this).text("Unfold");
    } else {
      $(this).text("Fold");
    }
    $(this).next("code").toggle("linear");
  })
});
</script>

# Rmd file

```{fold}
bruin@c7 ~ $ cat /etc/centos-release
CentOS Linux release 7.4.1708 (Core)
bruin@c7 ~ $
```

In the JS part we simply add a button to every chunk that is marked with the class fold. Afterwards we add the onClick event to all those buttons. When a button is clicked, its text should toggle between Fold and Unfold. And the corresponding code container should toggle its visibility state as well. Every chunk marked with fold is folded when the document is opened. How you style the button using CSS is up to you.

Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
  • Thanks, Martin. I had a quick test in my existing project, it does not work, don't know why... Let me create a minimum project and try it again. Thanks again. – bruin Jun 29 '18 at 11:03
  • Update all packages. Post your YAML options or a minimum reproducible document that has the same characteristics. – Martin Schmelzer Jun 29 '18 at 11:05
  • It works now. I was using "bookdown::gitbook" output, after I change to "bookdown::html_document2", it works as expected. Thanks! – bruin Jun 29 '18 at 13:45
  • Actually it also works for gitbook, after several tests. I put your script into a "fold.js" file, and for gitbook output, add "includes: in_header: fold.js"; also put the ".fold-btn {float: right;}" into my existing css file. It just works as I wanted. Many thanks! – bruin Jun 29 '18 at 14:18
  • @bruin Do you know if it's possible to fold all chunks by default? thanks! – Luis Jul 24 '19 at 19:13