Skip to content

Commit

Permalink
restore opts_current after each code chunk, and also after knit()
Browse files Browse the repository at this point in the history
… exits (#2292)

also add labels to `opts_current` for inline code to fix #1988
  • Loading branch information
yihui committed Oct 26, 2023
1 parent 8725408 commit c0dcdef
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 8 deletions.
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

- Improved the error message to contain more specific information when YAML chunk options could not be parsed (thanks, @pedropark99, #2294).

## MAJOR CHANGES

- The object `opts_current` will be restored after each code chunk has finished executing. Previously, it would not be restored, which means even for inline R expressions, `opts_current$get()` will inherit chunk options from a previous code chunk (thanks, @rundel, #1988). Besides, `opts_current$get('label')` will return a unique label for inline expressions. One possible application is to construct unique figure paths via `fig_path()` (e.g., ropensci/magick#310).

## BUG FIXES

- Special characters in the chunk option `fig.alt` are properly escaped now (thanks, @jay-sf, #2290).
Expand Down
4 changes: 4 additions & 0 deletions R/block.R
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ call_block = function(block) {
}

# save current chunk options in opts_current
optc = opts_current$get(); on.exit(opts_current$restore(optc), add = TRUE)
opts_current$restore(params)

if (opts_knit$get('progress')) print(block)
Expand Down Expand Up @@ -545,6 +546,9 @@ merge_character = function(res) {
}

call_inline = function(block) {
optc = opts_current$get(); on.exit(opts_current$restore(optc), add = TRUE)
params = opts_chunk$merge(list(label = unnamed_chunk()))
opts_current$restore(params)
if (opts_knit$get('progress')) print(block)
in_input_dir(inline_exec(block))
}
Expand Down
12 changes: 4 additions & 8 deletions R/output.R
Original file line number Diff line number Diff line change
Expand Up @@ -151,14 +151,10 @@ knit = function(
useFancyQuotes = FALSE, device = pdf_null, knitr.in.progress = TRUE
)
on.exit(options(oopts), add = TRUE)
# restore chunk options after parent exits
optc = opts_chunk$get(); ocode = knit_code$get(); optk = opts_knit$get()
on.exit({
opts_chunk$restore(optc)
knit_code$restore(ocode)
opts_current$restore()
opts_knit$restore(optk)
}, add = TRUE)
# restore objects like chunk options after parent exits
opta = list(opts_chunk, opts_current, knit_code, opts_knit)
optv = lapply(opta, function(o) o$get())
on.exit(for (i in seq_along(opta)) opta[[i]]$restore(optv[[i]]), add = TRUE)
opts_knit$set(
output.dir = getwd(), # record working directory in 1st run
tangle = tangle, progress = opts_knit$get('progress') && !quiet
Expand Down

0 comments on commit c0dcdef

Please sign in to comment.