Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button to hide/fold code in revealjs Quarto

I would like to use a code-fold option in a revealjs Quarto presentation, or something similar. When we use this option in a code chunk like this:

---
title: "Code-fold in revealjs"
format: revealjs
code-fold: true
---

## Graph

```{r}
#| code-fold: true
#| code-summary: "expand for full code"
library(ggplot2)
dat <- data.frame(cond = rep(c("A", "B"), each=10),
                  xvar = 1:20 + rnorm(20,sd=3),
                  yvar = 1:20 + rnorm(20,sd=3))

ggplot(dat, aes(x=xvar, y=yvar)) +
  geom_point(shape=1) + 
  geom_smooth() 
```

Output:

enter image description here

We can see there is no code-fold button. So I was wondering if anyone knows if there is an option like that in revealjs?

like image 651
Quinten Avatar asked Sep 12 '25 03:09

Quinten


1 Answers

Update

Just use echo: true, No need to use that Lua filter.

Quarto revealjs format by default uses echo: false for every chunk. That's code-folding will not work by default (because there is no code block to fold in the rendered slide).

---
title: "Code-fold in revealjs"
format: revealjs
---

## Graph

```{r}
#| echo: true
#| code-fold: true
#| code-summary: "expand for full code"
library(ggplot2)
dat <- data.frame(cond = rep(c("A", "B"), each=10),
                  xvar = 1:20 + rnorm(20,sd=3),
                  yvar = 1:20 + rnorm(20,sd=3))

ggplot(dat, aes(x=xvar, y=yvar)) +
  geom_point(shape=1) + 
  geom_smooth() 
```

code folding in revealjs


You can use the following Lua filter to add code folding

---
title: "Code-fold in revealjs"
format: revealjs
filters: 
  - code-fold.lua
---

## Graph

```{r}
#| echo: true
#| code-fold: true
#| code-summary: "expand for full code"
library(ggplot2)
dat <- data.frame(cond = rep(c("A", "B"), each=10),
                  xvar = 1:20 + rnorm(20,sd=3),
                  yvar = 1:20 + rnorm(20,sd=3))

ggplot(dat, aes(x=xvar, y=yvar)) +
  geom_point(shape=1) + 
  geom_smooth() 
```

code-fold.lua

local str = pandoc.utils.stringify

local template_fold_p1 = [[
<details>
  <summary>
  %s
  </summary>
]]

local template_fold_p2 = [[
%s
</details>
]]

function Div(el)
  if el.attributes['code-fold'] then
    local code_summary = str(el.attributes['code-summary'])
    local fold = string.format(template_fold_p1, code_summary)
    local fold_rb1 = pandoc.RawBlock('html', fold)
    local fold_rb2 = pandoc.RawBlock('html', template_fold_p2)
    el.content:insert(1, fold_rb1)
    el.content:insert(fold_rb1)
    return el
  end
end
like image 68
Shafee Avatar answered Sep 13 '25 16:09

Shafee