BergelsonLab / BergelsonLab/blabr

allow user to not stop on inline errors when knitting Rmd

Open
#50 0 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
R
Stars
1
Forks
3
PR merge metrics
No merged PRs in 30d

Description

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

```r
#' 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.

```r
#' 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)
}
```

Contributor guide

Open the contributing guide

Research direction

Start with the proposed no_stop_inline and set_no_stop_inline functions and knitr's evaluate.inline hook. Check the package's existing R entry points and tests, if present, before integrating the functions. Done means inline errors render as messages without stopping knitting, while successful inline expressions retain normal output.

Written by the indexing model from the issue text.

Assessment

Tech stack
r
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.