Search code examples
r-markdownreveal.jsslidify

Incrementally reveal code, revealjs, slidify, Rmarkdown


I'm working with the R package slidify to create revealjs slides. I'd like to reveal code fragments incrementally using the RMarkdown (rather than edit the resulting HTML) but can't seem to figure out a way.

In the example below I have two code chunks and I'd like the second to occur only after the preceding paragraph. I can go in to the resulting HTML and add class=fragment to the pre tag, but this is very inefficient!

Suggestions

---
title       : RevealJS with Bootstrap
framework   : revealjs
---

```{r}
mean(1:3)
```

<div class="fragment">
This works fine, the div does not appear until you click forward in the deck. But you can't put the div tags around a code fragment.
</div>


```{r}
mean(1:3)
```

Solution

  • You might have already answered for yourself by now, but one solution would be using knitr hooks. Here is a simple example:

    ---
    title       : RevealJS with Bootstrap
    framework   : revealjs
    ---
    
    ```{r cache=F,echo=F}
    s0 <- knitr::knit_hooks$get('source')
    o0 <- knitr::knit_hooks$get('output')
    
    knitr::knit_hooks$set(
      list(
        source=function(x,options){
          if (is.null(options$class)) s0(x, options)
          else
            paste0(
              paste0("<div class='", options$class, "'><pre><code>")
              ,x
              ,'</code></pre>\n'
            )
        }
        ,output = function(x,options){
          if (is.null(options$class)) o0(x, options)
          else 
            paste0(
              "<pre><code>"
              ,x
              ,'</code></pre></div>\n'
            )
        }
      )
    )
    ```
    
    ```{r class="fragment"}
    mean(1:3)
    ```
    
    <div class="fragment">
      This works fine, the div does not appear until you click forward in the deck. But you can't put the div tags around a code fragment.
    </div>
    
    
    ```{r class="fragment"}
    mean(1:3)
    ```