From 9bf0910ad02c15a1099b860688382481a5c1838d Mon Sep 17 00:00:00 2001 From: Christophe Dervieux Date: Fri, 13 Sep 2024 10:01:16 +0200 Subject: [PATCH] Add support for `child=c("child.Rmd")` in find_external_resources() (#2575) --- NEWS.md | 1 + R/html_resources.R | 2 +- tests/testthat/test-resources.R | 21 +++++++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index c0f1361ea6..ba8fefa3a5 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,6 +1,7 @@ rmarkdown 2.29 ================================================================================ +- `find_external_resources()` now correctly detects knitr child document provided with option like `child = c("child.Rmd")` (thanks, @rempsyc, #2574). rmarkdown 2.28 ================================================================================ diff --git a/R/html_resources.R b/R/html_resources.R index c4aa4f68d0..e7005c56e4 100644 --- a/R/html_resources.R +++ b/R/html_resources.R @@ -316,7 +316,7 @@ discover_rmd_resources <- function(rmd_file, discover_single_resource) { rmd_content[idx], chunk_start, chunk_start + attr(chunk_line, "capture.length", exact = TRUE) - 2 ) - for (child_expr in c("\\bchild\\s*=\\s*'([^']+)'", "\\bchild\\s*=\\s*\"([^\"]+)\"")) { + for (child_expr in c("\\bchild\\s*=\\s*(?:c\\()?'([^']+)'\\)?", "\\bchild\\s*=\\s*(?:c\\()?\"([^\"]+)\"\\)?")) { child_match <- gregexpr(child_expr, chunk_text, perl = TRUE)[[1]] if (child_match > 0) { child_start <- attr(child_match, "capture.start", exact = TRUE) diff --git a/tests/testthat/test-resources.R b/tests/testthat/test-resources.R index 65c7891434..50d5beaf44 100644 --- a/tests/testthat/test-resources.R +++ b/tests/testthat/test-resources.R @@ -263,3 +263,24 @@ test_that("multiple resources in the includes option can be discovered", { expect_equal(resources, expected) }) + +test_that("knitr child are correctly discovered as resources from chunk options", { + expect_child_resource_found <- function(child_opts, child) { + dir <- withr::local_tempdir("find-child") + withr::local_dir(dir) + rmd <- "test.Rmd" + xfun::write_utf8( + text = knitr::knit_expand(text = c("```{r,<>}", "```"), delim = c("<<", ">>")), + rmd + ) + xfun::write_utf8(c("Content"), child) + expect_contains(find_external_resources(!!rmd)$path, !!child) + } + child <- "child.Rmd" + expect_child_resource_found('child="child.Rmd"', child) + expect_child_resource_found(' child = "child.Rmd"', child) + expect_child_resource_found('child=c("child.Rmd")', child) + expect_child_resource_found("child='child.Rmd'", child) + expect_child_resource_found(" child = 'child.Rmd'", child) + expect_child_resource_found("child=c('child.Rmd')", child) +})