I'm writing a knitr chunk hook and would like to check whether the user has explicitly set the results
chunk option.
For "non-standard" chunk options, I can use knitr::opts_current$get("new_option")
to determine whether or not the user explicitly provided the chunk option. If they did, opts_current$get()
returns the value; if they did not, opts_current$get()
returns NULL
.
rmd_new_option <- paste(
"```{r new_option = 'hello'}",
"knitr::opts_current$get(\"new_option\")",
"```",
"",
"```{r}",
"knitr::opts_current$get(\"new_option\")",
"```",
"",
sep = "\n"
)
writeLines(knitr::knit(text = rmd_new_option))
#>
#> ```r
#> knitr::opts_current$get("new_option")
#> #> [1] "hello"
#> ```
#>
#>
#> ```r
#> knitr::opts_current$get("new_option")
#> #> NULL
#> ```
Unfortunately, the default value of the results
chunk option is propagated to opts_current$get()
, so this approach doesn't work. Instead it returns the default value:
rmd_results <- paste(
"```{r}",
"knitr::opts_chunk$get(\"results\")",
"knitr::opts_current$get(\"results\")",
"```",
"",
sep = "\n"
)
writeLines(knitr::knit(text = rmd_results))
#>
#> ```r
#> knitr::opts_chunk$get("results")
#> #> [1] "markup"
#> knitr::opts_current$get("results")
#> #> [1] "markup"
#> ```
Is there another approach that directly returns the exact user-provided chunk options?