Skip to content

Instantly share code, notes, and snippets.

@stephenturner
Created February 16, 2016 20:09
Show Gist options
  • Save stephenturner/530ac4d3523e8094ebea to your computer and use it in GitHub Desktop.
Save stephenturner/530ac4d3523e8094ebea to your computer and use it in GitHub Desktop.
# The hook
```{r}
library(knitr)
knitr::knit_hooks$set(source = function(x, options){
if (!is.null(options$verbatim) && options$verbatim){
opts = gsub(",\\s*verbatim\\s*=\\s*TRUE\\s*", "", options$params.src)
bef = sprintf('\n\n ```{r %s}\n', opts, "\n")
stringr::str_c(
bef,
knitr:::indent_block(paste(x, collapse = '\n'), " "),
"\n ```\n"
)
} else {
stringr::str_c("\n\n```", tolower(options$engine), "\n",
paste(x, collapse = '\n'), "\n```\n\n"
)
}
})
```
# Just embedding a chunk
## Works as expected
```{r chunkName, verbatim=TRUE, eval=FALSE}
head(mtcars)
```
## This doesn't
With an unnamed chunk, the `, verbatim=TRUE` still shows up.
```{r, verbatim=TRUE, eval=FALSE}
head(mtcars)
```
# What I'm really after
I want to be able to demonstrate how to write RMarkdown. Not just the chunk.
So, for example, I'm teaching, and "here's an example of an RMarkdown document!"
Something like this:
```
---
title: "whatever"
author: "whoever"
---
# Major heading
Here's some text in your RMarkdown document.
```{r, verbatim=TRUE, eval=FALSE}
head(mtcars)
```
Now we're back into regular markdown in our embedded document.
Here's inline code; mean of mpg is `r mean(mtcars$mpg)`.
```
Now we're back in our "top level" document. But we've got problems:
1. The `verbatim=TRUE` is still present in the unnamed chunk
2. The chunk is unnecessarily indented, since it was in a fenced block anyway.
3. The inline code was evaluated instead of printed.
4. The closing fence is not printed, and messes up later formatting if we add more chunks.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment