Skip to content

Commit

Permalink
fix #2360: don't resolve <<label>> references when label is not f…
Browse files Browse the repository at this point in the history
…ound in the document
  • Loading branch information
yihui committed Sep 17, 2024
1 parent f3248f7 commit 49f8793
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 4 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.48.1
Version: 1.48.2
Authors@R: c(
person("Yihui", "Xie", role = c("aut", "cre"), email = "[email protected]", comment = c(ORCID = "0000-0003-0645-5666")),
person("Abhraneel", "Sarma", role = "ctb"),
Expand Down
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# CHANGES IN knitr VERSION 1.49

## BUG FIXES

- In-chunk references of the form `<<label>>` should not be resolved if `label` is not found in the document (thanks, @jennybc @gadenbuie, #2360).

# CHANGES IN knitr VERSION 1.48

Expand Down
7 changes: 4 additions & 3 deletions R/parser.R
Original file line number Diff line number Diff line change
Expand Up @@ -399,12 +399,13 @@ strip_white = function(x, test_strip = is_blank) {
parse_chunk = function(x, rc = knit_patterns$get('ref.chunk')) {
if (length(x) == 0L) return(x)
x = c(x) # drop attributes of code (e.g. chunk_opts)
if (!group_pattern(rc) || !any(idx <- grepl(rc, x))) return(x)
if (!group_pattern(rc) || length(idx <- grep(rc, x)) == 0) return(x)

labels = sub(rc, '\\1', x[idx])
code = knit_code$get(labels)
code = knit_code$get()
i = labels %in% names(code)
idx = idx[i]; code = code[labels[i]]
indent = gsub('^(\\s*).*', '\\1', x[idx])
if (length(labels) <= 1L) code = list(code)
code = mapply(indent_block, code, indent, SIMPLIFY = FALSE, USE.NAMES = FALSE)

x = as.list(x)
Expand Down
5 changes: 5 additions & 0 deletions tests/testit/test-parser.R
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@ assert('parse_chunk() preserves indentation', {
(pc('<<d>>') %==% c('function() {', ' if (T)', ' 1+1', '}'))
})

assert('parse_chunk() ignores labels not found in knit_code', {
# chunk 'e' doesn't exist
(pc(c('3*3', '<<a>>', ' <<e>>', '<<b>> ')) %==% c("3*3", "1+1", " <<e>>", "2-2"))
})

knit_code$restore()

# duplication of labels
Expand Down

0 comments on commit 49f8793

Please sign in to comment.