Skip to content

Instantly share code, notes, and snippets.

@zross
Last active November 28, 2018 02:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zross/edb5d1e42998da286e17 to your computer and use it in GitHub Desktop.
Save zross/edb5d1e42998da286e17 to your computer and use it in GitHub Desktop.
Not completely finished hook to add fragment tags to RMarkdown code chunks (slidify, revealjs, R) v2

I wanted to have code in Rmarkdown/slidify treated like a reveal.js fragment (moving in on click) but had trouble getting this to work without going to the HTML output and doing it manually. So these knitr hooks add the 'fragment' class to the pre tags if you include class="fragment in the knitr heading. This also solves an issue I was having with slidify where I would try and globally set the opts_chunk$set(collapse=TRUE) but many of my code fragments were not getting collapsed. This was not an issue in Rmarkdown but seemed to be an issue with slidify.

I run the hooks.R code using source() in my Rmarkdown/slidify doc. Then in a knitr chunk I can include a class like this:

x <-1:100

Known issue: adding class="fragment" does not work with code chunks that have plots.

library(knitr)
opts_chunk$set(collapse=TRUE, echo=TRUE,
error=FALSE, message=FALSE,
warning=FALSE, cache=FALSE)
s0 <- knitr::knit_hooks$get('source')
o0 <- knitr::knit_hooks$get('output')
p0 <- knitr::knit_hooks$get('plot')
knitr::knit_hooks$set(
list(
source=function(x,options){
if (is.null(options$class) & options$fig.num!=0) s0(x, options)
else if (is.null(options$class) & options$fig.num==0)
paste0("<pre><code class='r'>",paste0(x, collapse="\n"))
else
paste0("<pre class='", options$class, "'><code class='r'>",paste0(x, collapse="\n"))
},
output = function(x,options){
if (is.null(options$class) & options$fig.num!=0) o0(x, options)
else if (is.null(options$class))
paste0('\n',x,'</code></pre>')
else
#print(x)
paste0('\n',x,'</code></pre>')
},
# plot = function(x, options){
# print(p0(x, options))
# },
chunk=function(x,options){
if (is.null(options$class) & options$fig.num!=0){return(x)}
else{
if(grepl('</code></pre>',x)==1){return(x)}
if(grepl('</code></pre>',x)!=1){return(paste0(x,'</code></pre>'))}
}
return(x)
}
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment