Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow user to not stop on inline errors when knitting Rmd #50

Open
kalenkovich opened this issue Dec 9, 2024 · 0 comments
Open

allow user to not stop on inline errors when knitting Rmd #50

kalenkovich opened this issue Dec 9, 2024 · 0 comments

Comments

@kalenkovich
Copy link
Contributor

In some cases, it is useful to temporarily ignore inline code errors (e.g., "We had `r N` participants" called before N was defined). One way to do that is to redefine knitr's evaluate.inline knitting hook. Here is one possible implementation

#' Evaluate Inline Code Without Stopping on Errors
#' 
#' A custom knitr hook for inline code evaluation that captures errors and formats them gracefully.
#'
#' @note Based on https://stackoverflow.com/a/62041765/3042770
#'
#' @param code The inline code to evaluate.
#' @param envir The environment in which to evaluate the code.
#' @return The evaluated result or an error message for rendering.
#' 
#' @export
#' 
#' @examples
#' knitr::opts_knit$set(evaluate.inline = blabr::no_stop_inline)
no_stop_inline <- function(code, envir = knitr::knit_global()) {
  result <- tryCatch(
    withVisible(eval(xfun::parse_only(code), envir = envir)),
    error = function(e) {
      list(value = sprintf("`<<<` ERROR in: `%s`: %s `>>>`", code, e$message), is_error = TRUE)
    }
  )
  
  if (!is.null(result$is_error) && isTRUE(result$is_error)) {
    # Print the error message in the console
    cat(result$value)
    warning(result$value)
    # Return the error message for rendering in the document
    knitr::asis_output(result$value)
  } else {
    if (result$visible)
      knitr::knit_print(result$value, inline = TRUE, options = knitr::opts_chunk$get())
  }
}

Which can be used with knitr::opts_knit$set(evaluate.inline = blabr::no_stop_inline) in Rmd.

Alternatively (or in addition), we can provide a function that will set this hook so that the user can skip the whole knitr::opts_knit$set(evaluate.inline = xxx) part.

#' Set the Custom Inline Code Evaluation Hook
#' 
#' This function sets the `no_stop_inline` hook as the evaluate.inline hook for knitr.
#' 
#' @export
#' 
#' @return Invisibly returns NULL after setting the hook.
#' @examples
#' set_no_stop_inline()
set_no_stop_inline <- function() {
  knitr::opts_knit$set(evaluate.inline = no_stop_inline)
  invisible(NULL)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant