Skip to content

Commit

Permalink
close #2368: wrap code chunk in try() for purl() when the chunk optio…
Browse files Browse the repository at this point in the history
…n `error = TRUE` (#2380)

also close #2338
  • Loading branch information
yihui authored Nov 1, 2024
1 parent 35df6f8 commit 47267f5
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
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

0 comments on commit 47267f5

Please sign in to comment.