From adebd6a794f0f95fb48e89a8c64bda3cf90ede9b Mon Sep 17 00:00:00 2001 From: jgabry Date: Thu, 17 Dec 2020 10:38:20 -0700 Subject: [PATCH] fix r cmd check NOTE about assignment to global env the idea for this fix comes from https://github.com/yihui/knitr/issues/1824#issuecomment-647333232 --- R/knitr.R | 2 +- R/zzz.R | 29 ++++++++++++++++++++--------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/R/knitr.R b/R/knitr.R index 201374e1e..21c4fc55e 100644 --- a/R/knitr.R +++ b/R/knitr.R @@ -80,7 +80,7 @@ eng_cmdstan <- function(options) { } file <- write_stan_file(options$code, dir = dir) mod <- cmdstan_model(file) - assign(output_var, mod, envir = knitr::knit_global()) + assign(output_var, mod, envir = cmdstanr_knitr_env()) } options$engine <- "stan" # for syntax highlighting code <- paste(options$code, collapse = "\n") diff --git a/R/zzz.R b/R/zzz.R index a656a2eb4..6147d4f2d 100644 --- a/R/zzz.R +++ b/R/zzz.R @@ -1,12 +1,3 @@ -.onAttach <- function(...) { - startup_messages() -} - -.onLoad <- function(...) { - cmdstanr_initialize() -} - - startup_messages <- function() { packageStartupMessage("This is cmdstanr version ", utils::packageVersion("cmdstanr")) packageStartupMessage("- Online documentation and vignettes at mc-stan.org/cmdstanr") @@ -65,3 +56,23 @@ cmdstanr_initialize <- function() { } invisible(TRUE) } + +cmdstanr_knitr_env_function_generator <- function(env1) { + function(env2 = NULL) { + if (!is.null(env2)) { + env1 <<- env2 + } + invisible(env1) + } +} +cmdstanr_knitr_env <- cmdstanr_knitr_env_function_generator(new.env()) + + +.onAttach <- function(...) { + startup_messages() +} + +.onLoad <- function(...) { + cmdstanr_knitr_env(knitr::knit_global()) + cmdstanr_initialize() +}