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

Wrap code chunk in try() for purl() when the chunk option error = TRUE #2380

Merged
merged 4 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

- Unbalanced chunk delimiters (fences) in R Markdown documents are strictly prohibited now.

- For code chunks with `error = TRUE`, `purl()` and `hook_purl()` will wrap the code in `try({...})` (thanks, @bastistician #2338, @jeroen #2368).

## MINOR CHANGES

- Changed the format of the reference card from PDF to HTML so building this package will not require LaTeX. See `vignette('knitr-refcard', package = 'knitr')`.
Expand Down
8 changes: 7 additions & 1 deletion R/block.R
Original file line number Diff line number Diff line change
Expand Up @@ -605,12 +605,18 @@ tangle_block = function(x) {
eval(parse_only(unlist(str_extract(code, 'read_chunk\\(([^)]+)\\)'))))
}
code = parse_chunk(code)
if (isFALSE(ev)) code = comment_out(code, params$comment, newline = FALSE)
code = tangle_mask(code, ev, x$params$error)
if (opts_knit$get('documentation') == 0L) return(one_string(code))
# e.g. when documentation 1 or 2 with purl()
label_code(code, x)
}

tangle_mask = function(code, eval, error) {
if (isFALSE(eval)) code = comment_out(code, '#', newline = FALSE)
if (isTRUE(error)) code = c('try({', code, '})')
code
}

tangle_inline = function(x) {
output = if (opts_knit$get('documentation') == 2L) {
output = paste("#'", gsub('\n', "\n#' ", x$input, fixed = TRUE))
Expand Down
6 changes: 4 additions & 2 deletions R/hooks-extra.R
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,10 @@ hook_purl = function(before, options, ...) {
.knitEnv$tangle.params = NULL
}

code = options$code
if (isFALSE(options$eval)) code = comment_out(code, '# ', newline = FALSE)
# `options` contains merged chunk options, but we need to check if
# `error=TRUE` in local chunk options, so retrieve options from knit_code
error = attr(knit_code$get(options$label), 'chunk_opts')[['error']]
code = tangle_mask(options$code, options$eval, error)
if (is.character(output)) {
code = c(
if (file.exists(output)) read_utf8(output),
Expand Down
Loading