Skip to content

Commit

Permalink
add a new chunk option file to read an external file into the chunk
Browse files Browse the repository at this point in the history
  • Loading branch information
yihui committed Dec 2, 2021
1 parent 237cde1 commit 545aed3
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Package: knitr
Type: Package
Title: A General-Purpose Package for Dynamic Report Generation in R
Version: 1.36.7
Version: 1.36.8
Authors@R: c(
person("Yihui", "Xie", role = c("aut", "cre"), email = "xie@yihui.name", comment = c(ORCID = "0000-0003-0645-5666")),
person("Abhraneel", "Sarma", role = "ctb"),
Expand Down
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## NEW FEATURES

- Added a new chunk option named `file` so that the chunk content can be read from an external file. Setting the chunk option `file = "test.R"` is equivalent to using the chunk option `code = xfun::read_utf8("test.R")`.

- For R Markdown documents, code chunks can be embedded in a parent code chunk with more backticks now. For example, a code chunk with four backticks can contain code chunks with three backticks. One application is to conditionally include some verbatim content that contains code chunks via the `asis` engine, e.g.,

`````md
Expand Down
10 changes: 9 additions & 1 deletion R/block.R
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,15 @@ call_block = function(block) {
if (inherits(params$ref.label, 'AsIs') && is.null(params$opts.label))
params$opts.label = ref.label
}
params[["code"]] = params[["code"]] %n% unlist(knit_code$get(ref.label), use.names = FALSE)
# if chunk option 'file' is provided, read the file(s) as the chunk body;
# otherwise if 'code' is provided, use it; if neither 'file' nor 'code' is
# provided, use the chunk body
params[["code"]] = if (is.null(code_file <- params[['file']])) {
params[["code"]] %n% unlist(knit_code$get(ref.label), use.names = FALSE)
} else {
# TODO: use xfun::read_all() so we can read multiple files at once
xfun::read_utf8(code_file)
}

# opts.label = TRUE means inheriting chunk options from ref.label
if (isTRUE(params$opts.label)) params$opts.label = ref.label
Expand Down

2 comments on commit 545aed3

@cderv
Copy link
Collaborator

@cderv cderv commented on 545aed3 Dec 2, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW I have added this feature to the knitr-examples about verbatim engine
yihui/knitr-examples@41baeac

@yihui
Copy link
Owner Author

@yihui yihui commented on 545aed3 Dec 2, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great. Thanks!

Please sign in to comment.