Debian Codegraph @

R/parser.R

raw
1 ## adapted from Hadley's decumar: https://github.com/hadley/decumar
2
3 # split input document into groups containing chunks and other texts
4 # (may contain inline R code)
5 split_file = function(lines, set.preamble = TRUE, patterns = knit_patterns$get()) {
6 n = length(lines)
7 chunk.begin = patterns$chunk.begin; chunk.end = patterns$chunk.end
8 if (is.null(chunk.begin) || is.null(chunk.end))
9 return(list(parse_inline(lines, patterns)))
10
11 if (!child_mode() && set.preamble) {
12 set_preamble(lines, patterns) # prepare for tikz option 'standAlone'
13 }
14
15 markdown_mode = identical(patterns, all_patterns$md)
16 groups = divide_chunks(lines, chunk.begin, chunk.end, markdown_mode)
17
18 if (set.preamble)
19 knit_concord$set(inlines = sapply(groups, length)) # input line numbers for concordance
20
21 # parse 'em all
22 lapply(seq_along(groups), function(i) {
23 knit_concord$set(block = i)
24 g = groups[[i]]
25 block = grepl(chunk.begin, g[1])
26 if (!set.preamble && !parent_mode()) {
27 return(if (block) '' else g) # only need to remove chunks to get pure preamble
28 }
29 if (block) {
30 n = length(g)
31 # remove the optional chunk footer
32 if (n >= 2 && grepl(chunk.end, g[n])) g = g[-n]
33 # remove the optional prefix % in code in Rtex mode
34 g = strip_block(g, patterns$chunk.code)
35 params.src = if (group_pattern(chunk.begin)) {
36 extract_params_src(chunk.begin, g[1])
37 } else ''
38 parse_block(g[-1], g[1], params.src, markdown_mode)
39 } else parse_inline(g, patterns)
40 })
41 }
42
43 # divide lines of input into code/text chunks
44 divide_chunks = function(x, begin, end, md = TRUE) {
45 i = group_indices(grepl(begin, x), grepl(end, x), x, md)
46 unname(split(x, i))
47 }
48
49 extract_params_src = function(chunk.begin, line) {
50 trimws(gsub(chunk.begin, '\\1', line))
51 }
52
53 #' The code manager to manage code in all chunks
54 #'
55 #' This object provides methods to manage code (as character vectors) in all
56 #' chunks in \pkg{knitr} source documents. For example,
57 #' \code{knitr::knit_code$get()} returns a named list of all code chunks (the
58 #' names are chunk labels), and \code{knitr::knit_code$get('foo')} returns the
59 #' character vector of the code in the chunk with the label \code{foo}.
60 #' @note The methods on this object include the \code{set()} method (i.e., you
61 #' could do something like \code{knitr::knit_code$set(foo = "'my precious new
62 #' code'")}), but we recommend that you do not use this method to modify the
63 #' content of code chunks, unless you are
64 #' \href{https://emitanaka.rbind.io/post/knitr-knitr-code/}{as creative as Emi
65 #' Tanaka} and know what you are doing.
66 #' @export
67 knit_code = new_defaults()
68
69 # strip the pattern in code
70 strip_block = function(x, prefix = NULL) {
71 if (!is.null(prefix) && (length(x) > 1)) {
72 x[-1L] = sub(prefix, '', x[-1L])
73 spaces = min(attr(regexpr("^ *", x[-1L]), "match.length"))
74 if (spaces > 0) x[-1L] = substring(x[-1L], spaces + 1)
75 }
76 x
77 }
78
79 # an object to store chunk dependencies; dep_list$get() is of the form list(foo
80 # = c('chunk', 'labels', 'that', 'depend', 'on', 'chunk', 'foo'))
81 dep_list = new_defaults()
82
83 # separate params and R code in code chunks
84 parse_block = function(code, header, params.src, markdown_mode = out_format('markdown')) {
85 params = params.src
86 engine = 'r'
87 # consider the syntax ```{engine, opt=val} for chunk headers
88 if (markdown_mode) {
89 engine = get_chunk_engine(params)
90 params = get_chunk_params(params)
91 }
92 params = clean_empty_params(params) # rm empty options
93 # turn ```{engine} into ```{r, engine="engine"}
94 if (tolower(engine) != 'r') {
95 params = sprintf('%s, engine="%s"', params, engine)
96 params = gsub('^\\s*,\\s*', '', params)
97 }
98
99 # for quarto, preserve the actual original params.src and do not remove the engine
100 if (!is_quarto() || opts_knit$get('tangle')) params.src = params
101 params = xfun::csv_options(params)
102
103 # remove indent (and possibly markdown blockquote >) from code
104 if (nzchar(spaces <- get_chunk_indent(header))) {
105 params$indent = spaces
106 code = gsub(sprintf('^%s', spaces), '', code)
107 # in case the trailing spaces of the indent string are trimmed on certain
108 # lines (e.g. in blockquotes https://github.com/yihui/knitr/issues/1446)
109 code = gsub(sprintf('^%s', gsub('\\s+$', '', spaces)), '', code)
110 }
111
112 # merge with possible chunk options written as (YAML or CSV) metadata in
113 # chunk, and remove metadata from code body
114 parts = partition_chunk(engine, code)
115 dup = intersect(names(params), names(parts$options))
116 params = merge_list(params, parts$options)
117 if (is.null(params$label)) params$label = unnamed_chunk()
118 label = params$label
119 if (length(dup)) warning(
120 "Duplicated chunk option(s) ", paste0("'", dup, "'", collapse = ', '),
121 " in both chunk header and pipe comments of the chunk '", label, "'.", call. = FALSE
122 )
123
124 code = parts$code
125 .knitEnv$labels = c(.knitEnv$labels, label)
126 if (length(code) || length(params[['file']]) || length(params[['code']])) {
127 if (label %in% names(knit_code$get())) {
128 if (identical(getOption('knitr.duplicate.label'), 'allow')) {
129 params$label = label = unnamed_chunk(label)
130 } else stop(
131 "Duplicate chunk label '", label, "', which has been used for the chunk:\n",
132 one_string(knit_code$get(label))
133 )
134 }
135 code = as.character(code)
136 knit_code$set(setNames(list(structure(code, chunk_opts = params)), label))
137 }
138
139 # store dependencies
140 if (!is.null(deps <- params$dependson)) {
141 deps = sc_split(deps)
142 if (is.numeric(deps)) {
143 deps[deps < 0] = length(.knitEnv$labels) + deps[deps < 0]
144 deps = .knitEnv$labels[deps[deps > 0]]
145 }
146 if (is.character(deps)) {
147 for (i in deps) dep_list$set(setNames(list(c(dep_list$get(i), label)), i))
148 } else warning2("Invalid chunk option 'dependson' (must be character or numeric)")
149 }
150
151 # for quarto only
152 if (is_quarto()) {
153 params$original.params.src = params.src
154 params$chunk.echo = isTRUE(params[['echo']])
155 params$yaml.code = parts$src
156 attr(params, 'quarto_options') = c('original.params.src', 'chunk.echo', 'yaml.code')
157 # alias 'warning' explicitly set in chunk metadata to the 'message' option
158 if (!is.null(parts$options[['warning']])) {
159 params$message = parts$options[['warning']]
160 }
161 }
162
163 structure(class = 'block', list(
164 params = params, params.src = params.src, params.chunk = parts$src)
165 )
166 }
167
168 get_chunk_indent = function(header) {
169 gsub('^([\t >]*).*', '\\1', header)
170 }
171
172 get_chunk_engine = function(params) {
173 sub('^([a-zA-Z0-9_]+).*$', '\\1', params)
174 }
175
176 get_chunk_params = function(params) {
177 sub('^([a-zA-Z0-9_]+)', '', params)
178 }
179
180 clean_empty_params = function(params) {
181 gsub('^\\s*,*\\s*|\\s*,*\\s*$', '', params) # rm empty options
182 }
183
184 # autoname for unnamed chunk
185 unnamed_chunk = function(prefix = NULL, i = chunk_counter()) {
186 if (is.null(prefix)) prefix = opts_knit$get('unnamed.chunk.label')
187 paste(prefix, i, sep = '-')
188 }
189
190 # this internal function is still used in RStudio IDE, otherwise can be removed
191 parse_params = function(params, label = TRUE) {
192 res = xfun::csv_options(params)
193 if (label && (!is.character(res$label) || identical(res$label, '')))
194 res$label = unnamed_chunk()
195 res
196 }
197
198 #' Partition chunk options from the code chunk body
199 #'
200 #' This is a wrapper function calling \code{xfun::\link[xfun]{divide_chunk}()}
201 #' under the hood.
202 #' @export
203 #' @keywords internal
204 partition_chunk = function(engine, code) {
205 opts = options(xfun.handle_error.loc_fun = get_loc)
206 on.exit(options(opts))
207 # the code has been moved to the xfun package
208 xfun::divide_chunk(engine, code, strict = is_quarto())
209 }
210
211 print_block = function(x) {
212 params = x$params
213 if (opts_knit$get('verbose')) {
214 code = knit_code$get(params$label)
215 if (length(code) && !is_blank(code)) {
216 cat('\n')
217 cat(one_string(' | ', code), '\n')
218 }
219 }
220 }
221
222 # extract inline R code fragments (as well as global options)
223 parse_inline = function(input, patterns) {
224 inline.code = patterns$inline.code; inline.comment = patterns$inline.comment
225 if (!is.null(inline.comment)) {
226 idx = grepl(inline.comment, input)
227 # strip off inline code
228 input[idx] = gsub(inline.code, '\\1', input[idx])
229 }
230 input = one_string(input) # merge into one line
231
232 loc = cbind(start = numeric(0), end = numeric(0))
233 if (group_pattern(inline.code)) loc = str_locate(input, inline.code)[[1]]
234 code1 = code2 = character()
235 lines = integer()
236 if (nrow(loc)) {
237 code = t(str_match(input, inline.code))
238 if (NCOL(code) >= 2L) {
239 code1 = code[, 1L]
240 code2 = apply(code[, -1L, drop = FALSE], 1, paste, collapse = '')
241 nl = gregexpr('\n', input, fixed = TRUE)[[1]]
242 lines = if (length(nl) > 1 || nl > -1) findInterval(loc, nl) else 0L
243 }
244 }
245
246 structure(list(
247 input = input, location = loc, code = code2, code.src = code1,
248 lines = matrix(lines, ncol = 2, nrow = nrow(loc))
249 ), class = 'inline')
250 }
251
252 print_inline = function(x) {
253 if (opts_knit$get('verbose')) {
254 cat('\n')
255 if (nrow(x$location)) {
256 cat(sprintf(' | %s #%s:%s', x$code, x$location[, 1], x$location[, 2]), sep = '\n')
257 }
258 }
259 }
260
261 #' Read chunks from an external script
262 #'
263 #' Chunks can be put in an external script, and this function reads chunks into
264 #' the current \pkg{knitr} session; \code{read_demo()} is a convenience function
265 #' to read a demo script from a package.
266 #'
267 #' There are two approaches to read external code into the current session: (1)
268 #' Use a special separator of the from \code{## ---- chunk-label} (at least four
269 #' dashes before the chunk label) in the script; (2) Manually specify the
270 #' labels, starting and ending positions of code chunks in the script.
271 #'
272 #' The second approach will be used only when \code{labels} is not \code{NULL}.
273 #' For this approach, if \code{from} is \code{NULL}, the starting position is 1;
274 #' if \code{to} is \code{NULL}, each of its element takes the next element of
275 #' \code{from} minus 1, and the last element of \code{to} will be the length of
276 #' \code{lines} (e.g. when \code{from = c(1, 3, 8)} and the script has 10 lines
277 #' in total, \code{to} will be \code{c(2, 7, 10)}). Alternatively, \code{from}
278 #' and \code{to} can be character vectors as regular expressions to specify the
279 #' positions; when their length is 1, the single regular expression will be
280 #' matched against the \code{lines} vector, otherwise each element of
281 #' \code{from}/\code{to} is matched against \code{lines} and the match is
282 #' supposed to be unique so that the numeric positions returned from
283 #' \code{grep()} will be of the same length of \code{from}/\code{to}. Note
284 #' \code{labels} always has to match the length of \code{from} and \code{to}.
285 #' @param path Path to the R script.
286 #' @param lines Character vector of lines of code. By default, this is read from
287 #' \code{path}.
288 #' @param labels Character vector of chunk labels (default \code{NULL}).
289 #' @param from,to Numeric vector specifying the starting/ending line numbers of
290 #' code chunks, or a character vector; see Details.
291 #' @param from.offset,to.offset Offsets to be added to \code{from}/\code{to}.
292 #' @param roxygen_comments Logical dictating whether to keep trailing
293 #' roxygen-style comments from code chunks in addition to whitespace
294 #' @return As a side effect, code chunks are read into the current session so
295 #' that future chunks can (re)use the code by chunk label references. If an
296 #' external chunk has the same label as a chunk in the current session, chunk
297 #' label references by future chunks will refer to the external chunk.
298 #' @references \url{https://yihui.org/knitr/demo/externalization/}
299 #' @note This function can only be used in a chunk which is \emph{not} cached
300 #' (chunk option \code{cache = FALSE}), and the code is read and stored in the
301 #' current session \emph{without} being executed (to actually run the code,
302 #' you have to use a chunk with a corresponding label).
303 #' @author Yihui Xie; the idea of the second approach came from Peter
304 #' Ruckdeschel (author of the \pkg{SweaveListingUtils} package)
305 #' @export
306 #' @examples ## put this in foo.R and read_chunk('foo.R')
307 #'
308 #' ## ---- my-label ----
309 #' 1+1
310 #' lm(y~x, data=data.frame(x=1:10,y=rnorm(10)))
311 #'
312 #' ## later you can use <<my-label>>= to reference this chunk
313 #'
314 #' ## the 2nd approach
315 #' code = c("#@@a", '1+1', "#@@b", "#@@a", 'rnorm(10)', "#@@b")
316 #' read_chunk(lines = code, labels = 'foo') # put all code into one chunk named foo
317 #' read_chunk(lines = code, labels = 'foo', from = 2, to = 2) # line 2 into chunk foo
318 #' read_chunk(lines = code, labels = c('foo', 'bar'), from = c(1, 4), to = c(3, 6))
319 #' # automatically figure out 'to'
320 #' read_chunk(lines = code, labels = c('foo', 'bar'), from = c(1, 4))
321 #' read_chunk(lines = code, labels = c('foo', 'bar'), from = "^#@@a", to = "^#@@b")
322 #' read_chunk(lines = code, labels = c('foo', 'bar'), from = "^#@@a", to = "^#@@b", from.offset = 1, to.offset = -1)
323 #'
324 #' ## later you can use, e.g., <<foo>>=
325 #' knitr::knit_code$get() # use this to check chunks in the current session
326 #' knitr::knit_code$restore() # clean up the session
327 read_chunk = function(
328 path, lines = read_utf8(path), labels = NULL, from = NULL, to = NULL,
329 from.offset = 0L, to.offset = 0L, roxygen_comments = TRUE
330 ) {
331 if (!length(lines)) {
332 warning('code is empty')
333 return(invisible())
334 }
335 lab = .sep.label
336 if (is.null(labels)) {
337 if (!group_pattern(lab)) return(invisible())
338 } else {
339 if (is.null(from)) from = 1L
340 if (!is.numeric(from)) from = pattern_index(from, lines)
341 if (is.null(to)) to = c(from[-1L] - 1L, length(lines))
342 if (!is.numeric(to)) to = pattern_index(to, lines)
343 stopifnot(length(labels) == length(from), length(from) == length(to))
344 from = from + from.offset; to = to + to.offset
345 code = list()
346 for (i in seq_along(labels)) {
347 code[[labels[i]]] = strip_white(lines[from[i]:to[i]])
348 }
349 knit_code$set(code)
350 return(invisible())
351 }
352 idx = cumsum(grepl(lab, lines))
353 if (idx[1] == 0) {
354 idx = c(0, idx); lines = c('', lines) # no chunk header in the beginning
355 }
356 groups = unname(split(lines, idx))
357 labels = trimws(gsub(lab, '\\3', sapply(groups, `[`, 1)))
358 labels = gsub(',.*', '', labels) # strip off possible chunk options
359 code = lapply(groups, strip_chunk, roxygen_comments)
360 for (i in which(!nzchar(labels))) labels[i] = unnamed_chunk()
361 knit_code$set(setNames(code, labels))
362 }
363
364 #' @rdname read_chunk
365 #' @param topic,package Name of the demo and the package. See
366 #' \code{utils::\link{demo}}.
367 #' @param ... Arguments passed to \code{\link{read_chunk}}.
368 #' @export
369 read_demo = function(topic, package = NULL, ...) {
370 paths = list.files(file.path(find.package(package), 'demo'), full.names = TRUE)
371 read_chunk(paths[sans_ext(basename(paths)) == topic], ...)
372 }
373
374 # convert patterns to numeric indices in a character vector
375 pattern_index = function(pattern, text) {
376 if (length(pattern) == 1L) {
377 idx = grep(pattern, text)
378 if (length(idx) == 0L) stop('pattern ', pattern, ' not found')
379 return(idx)
380 }
381 sapply(pattern, function(p) {
382 idx = grep(p, text)
383 if (length(idx) != 1L) stop('non-unique matches of ', p)
384 idx
385 })
386 }
387
388 strip_chunk = function(x, roxygen_comments = TRUE) {
389 x = x[-1]
390 strip_white(x, if (roxygen_comments) is_blank else function(line) {
391 is_blank(line) || grepl("^#+'[ ]?", line)
392 })
393 }
394
395 # strip lines that are pure white spaces or
396 # that match the test_strip condition(s)
397 strip_white = function(x, test_strip = is_blank) {
398 if (!length(x)) return(x)
399 while (test_strip(x[1])) {
400 x = x[-1]; if (!length(x)) return(x)
401 }
402 while (test_strip(x[(n <- length(x))])) {
403 x = x[-n]; if (n < 2) return(x)
404 }
405 x
406 }
407
408 # (recursively) parse chunk references inside a chunk
409 parse_chunk = function(x, rc = knit_patterns$get('ref.chunk')) {
410 if (length(x) == 0L) return(x)
411 x = c(x) # drop attributes of code (e.g. chunk_opts)
412 if (!group_pattern(rc) || length(idx <- grep(rc, x)) == 0) return(x)
413
414 labels = sub(rc, '\\1', x[idx])
415 code = knit_code$get()
416 i = labels %in% names(code)
417 idx = idx[i]; code = code[labels[i]]
418 indent = gsub('^(\\s*).*', '\\1', x[idx])
419 code = mapply(indent_block, code, indent, SIMPLIFY = FALSE, USE.NAMES = FALSE)
420
421 x = as.list(x)
422 x[idx] = lapply(code, function(z) parse_chunk(z, rc))
423 unlist(x, use.names = FALSE)
424 }
425
426 # split text lines into groups of code and text chunks
427 group_indices = function(chunk.begin, chunk.end, lines = NA, is.md = FALSE) {
428 in.chunk = FALSE # whether inside a chunk now
429 pattern.end = NA # the expected chunk end pattern (derived from header)
430 b = NA # the last found chunk header
431 g = NA # group index: odd - text; even - chunk
432 fun = function(is.begin, is.end, line, i) {
433 if (i == 1) {
434 g <<- if (is.begin) {
435 in.chunk <<- TRUE
436 b <<- i
437 0
438 } else 1
439 return(g)
440 }
441 # begin of another chunk is found while the previous chunk is not complete yet
442 if (in.chunk && is.begin) {
443 if (!is.md || match_chunk_begin(pattern.end, line)) {
444 g <<- g + 2 # same amount of ` as previous chunk, so should be a new chunk
445 if (is.md) b <<- i
446 } # otherwise ignore the chunk header
447 return(g)
448 }
449 if (in.chunk && is.end && match_chunk_end(pattern.end, line, i, b, lines)) {
450 in.chunk <<- FALSE
451 g <<- g + 1
452 return(g - 1) # don't use incremented g yet; use it in the next step
453 }
454 if (!in.chunk && is.begin) {
455 in.chunk <<- TRUE
456 if (is.md) {
457 pattern.end <<- sub('(^[\t >]*```+).*', '^\\1\\\\s*$', line)
458 b <<- i
459 }
460 g <<- g + 2 - g%%2 # make sure g is even
461 }
462 g
463 }
464 mapply(fun, chunk.begin, chunk.end, lines, seq_along(chunk.begin))
465 }
466
467 match_chunk_begin = function(pattern.end, x, pattern = '^\\1\\\\{') {
468 grepl(gsub('^([^`]*`+).*', pattern, pattern.end), x)
469 }
470
471 match_chunk_end = function(pattern, line, i, b, lines) {
472 if (is.na(pattern) || grepl(pattern, line)) return(TRUE)
473 n = length(lines)
474 # if the exact match was not found, look ahead to see if there is another
475 # chunk end that is an exact match before the next chunk begin
476 if (i < n && length(k <- grep(pattern, lines[(i + 1):n]))) {
477 k = k[1]
478 if (k == 1) return(FALSE) # the next line is real chunk end
479 # no other chunk headers before the new next exact chunk end
480 if (!any(match_chunk_begin(pattern, lines[i + 1:(k - 1)], '^\\1`*\\\\{')))
481 return(FALSE)
482 }
483 stop2(
484 'The closing fence on line ', i, ' ("', line, '") in ', current_input(),
485 ' does not match the opening fence "',
486 gsub('\\^(\\s*`+).*', '\\1', pattern), '" on line ', b, '. You are recommended to ',
487 'fix either the opening or closing fence of the code chunk to use exactly ',
488 'the same numbers of backticks and same level of indentation (or blockquote). ',
489 'See https://yihui.org/en/2021/10/unbalanced-delimiters/ for more info.'
490 )
491 }
492
493 #' Get all chunk labels in a document
494 #'
495 #' The function \code{all_labels()} returns all chunk labels as a character
496 #' vector. Optionally, you can specify a series of conditions to filter the
497 #' labels. The function `all_rcpp_labels()` is a wrapper function for
498 #' \code{all_labels(engine == 'Rcpp')}.
499 #'
500 #' For example, suppose the condition expression is \code{engine == 'Rcpp'}, the
501 #' object \code{engine} is the local chunk option \code{engine}. If an
502 #' expression fails to be evaluated (e.g. when a certain object does not exist),
503 #' \code{FALSE} is returned and the label for this chunk will be filtered out.
504 #' @param ... A vector of R expressions, each of which should return \code{TRUE}
505 #' or \code{FALSE}. The expressions are evaluated using the \emph{local} chunk
506 #' options of each code chunk as the environment, which means global chunk
507 #' options are not considered when evaluating these expressions. For example,
508 #' if you set the global chunk option \code{opts_chunk$set(purl = TRUE)},
509 #' \code{all_labels(purl == TRUE)} will \emph{not} return the labels of all
510 #' code chunks, but will only return the labels of those code chunks that have
511 #' local chunk options \code{purl = TRUE}.
512 #' @note Empty code chunks are always ignored, including those chunks that are
513 #' empty in the original document but filled with code using chunk options
514 #' such as \code{ref.label} or \code{code}.
515 #' @return A character vector.
516 #' @export
517 #' @examples # the examples below are meaningless unless you put them in a knitr document
518 #' all_labels()
519 #' all_labels(engine == 'Rcpp')
520 #' all_labels(echo == FALSE && results != 'hide')
521 #' # or separate the two conditions
522 #' all_labels(echo == FALSE, results != 'hide')
523 all_labels = function(...) {
524 cond = as.list(match.call())[-1]
525 code = knit_code$get()
526 labels = names(code)
527
528 if (length(cond) == 0) return(labels)
529
530 params = lapply(code, attr, 'chunk_opts')
531 idx = rep_len(TRUE, length(labels))
532 for (i in seq_along(cond)) {
533 for (j in seq_along(params)) {
534 # need tryCatch() because the expression cond[[i]] may trigger an error
535 # when any variable is not found, e.g. not all chunks have the engine
536 # option when the condition is engine == 'Rcpp'
537 try_eval = function(expr) tryCatch(
538 eval(expr, envir = params[[j]], enclos = knit_global()),
539 error = function(e) FALSE
540 )
541 if (idx[j]) {
542 res = try_eval(cond[[i]])
543 # the condition could be evaluated to an expression; see all_rcpp_labels()
544 if (is.expression(res)) res = try_eval(res)
545 idx[j] = res
546 }
547 }
548 }
549
550 labels[idx]
551 }
552
553 #' @rdname all_labels
554 #' @export
555 all_rcpp_labels = function(...) all_labels(expression(engine == 'Rcpp'), ...)
556
557 #' Wrap code using the inline R expression syntax
558 #'
559 #' This is a convenience function to write the "source code" of inline R
560 #' expressions. For example, if you want to write \samp{`r 1+1`} literally in an
561 #' R Markdown document, you may write \samp{`` `r knitr::inline_expr('1+1')`
562 #' ``}; for Rnw documents, this may be
563 #' \samp{\verb|\Sexpr{knitr::inline_expr{'1+1'}}|}.
564 #' @param code Character string of the inline R source code.
565 #' @param syntax A character string to specify the syntax, e.g. \code{rnw},
566 #' \code{html}, or \code{md}. If not specified, this will be guessed from
567 #' the knitting context.
568 #' @return A character string marked up using the inline R code syntax.
569 #' @export
570 #' @examples library(knitr)
571 #' inline_expr('1+1', 'rnw'); inline_expr('1+1', 'html'); inline_expr('1+1', 'md')
572 inline_expr = function(code, syntax) {
573 if (!is.character(code) || length(code) != 1)
574 stop('The inline code must be a character string')
575 if (!missing(syntax)) pat = syntax else {
576 inline = knit_patterns$get('inline.code')
577 if (is.null(inline)) stop('inline_expr() must be called in a knitting process')
578 pat = NULL
579 for (i in names(all_patterns)) {
580 if (inline == all_patterns[[i]][['inline.code']]) {
581 pat = i; break
582 }
583 }
584 }
585 if (is.null(pat)) stop('Unknown document format')
586 sprintf(switch(
587 pat, rnw = '\\Sexpr{%s}', tex = '\\rinline{%s}', html = '<!--rinline %s -->',
588 md = '`r %s`', rst = ':r:`%s`', asciidoc = '`r %s`', textile = '@r %s@',
589 stop('Unknown syntax ', pat)
590 ), code)
591 }
592
593
594 #' Convert the in-header chunk option syntax to the in-body syntax
595 #'
596 #' This is a helper function for moving chunk options from the chunk header to
597 #' the chunk body using the new syntax.
598 #' @param input File path to the document with code chunks to convert.
599 #' @param output The default \code{NULL} will output to console. Other values
600 #' can be a file path to write the converted content into or a function which
601 #' takes \code{input} as argument and returns a file path to write into (e.g.,
602 #' \code{output = identity} to overwrite the input file).
603 #' @param type This determines how the in-body options will be formatted.
604 #' \code{"mutiline"} (the default, except for \file{qmd} documents, for which
605 #' the default is \code{"yaml"}) will write each chunk option on a separate
606 #' line. Long chunk option values will be wrapped onto several lines, and you
607 #' can use \code{width = 0} to keep one line per option only. \code{"wrap"}
608 #' will wrap all chunk options together using
609 #' \code{\link[base:strwrap]{base::strwrap}()}. \code{"yaml"} will convert
610 #' chunk options to YAML.
611 #' @param width An integer passed to \code{base::strwrap()} for \code{type =
612 #' "wrap"} and \code{type = "multiline"}. If set to \code{0}, deactivate the
613 #' wrapping (for \code{type = "multiline"} only).
614 #' @return A character vector of converted \code{input} when \code{output =
615 #' NULL}. The output file path with converted content otherwise.
616 #' @note Learn more about the new chunk option syntax in
617 #' \url{https://yihui.org/en/2022/01/knitr-news/}
618 #' @section About \pkg{knitr} option syntax:
619 #'
620 #' Historical chunk option syntax have chunk option in the chunk header using
621 #' valid R syntax. This is an example for \verb{.Rmd} document
622 #' \preformatted{
623 #' ```\{r, echo = FALSE, fig.width: 10\}
624 #' ```
625 #' }
626 #'
627 #' New syntax allows to pass option inside the chunk using several variants
628 #' \itemize{
629 #' \item Passing options one per line using valid R syntax. This corresponds to \code{convert_chunk_header(type = "multiline")}.
630 #' \preformatted{
631 #' ```\{r\}
632 #' #| echo = FALSE,
633 #' #| fig.width = 10
634 #' ```
635 #' }
636 #'
637 #' \item Passing option part from header in-chunk with several line if wrapping is
638 #' needed. This corresponds to \code{convert_chunk_header(type = "wrap")}
639 #' \preformatted{
640 #' ```\{r\}
641 #' #| echo = FALSE, fig.width = 10
642 #' ```
643 #' }
644 #' \item Passing options key value pairs in-chunk using YAML syntax. Values are no
645 #' more R expression but valid YAML syntax. This corresponds to
646 #' \code{convert_chunk_header(type = "yaml")} (not implement yet).
647 #' \preformatted{```\{r\}
648 #' #| echo: false,
649 #' #| fig.width: 10
650 #' ```
651 #' }
652 #' }
653 #' @examples
654 #' knitr_example = function(...) system.file('examples', ..., package = 'knitr')
655 #' # Convert a document for multiline type
656 #' convert_chunk_header(knitr_example('knitr-minimal.Rmd'))
657 #' # Convert a document for wrap type
658 #' convert_chunk_header(knitr_example('knitr-minimal.Rmd'), type = "wrap")
659 #' # Reduce default wrapping width
660 #' convert_chunk_header(knitr_example('knitr-minimal.Rmd'), type = "wrap", width = 0.6 * getOption('width'))
661 #' \dontrun{
662 #' # Explicitly name the output
663 #' convert_chunk_header('test.Rmd', output = 'test2.Rmd')
664 #' # Overwrite the input
665 #' convert_chunk_header('test.Rmd', output = identity)
666 #' # Use a custom function to name the output
667 #' convert_chunk_header('test.Rmd', output = \(f) sprintf('%s-new.%s', xfun::sans_ext(f), xfun::file_ext(f)))
668 #' }
669 #' @export
670 convert_chunk_header = function(
671 input, output = NULL, type = c('multiline', 'wrap', 'yaml'),
672 width = 0.9 * getOption('width')
673 ) {
674
675 # extract fenced header information
676 text = xfun::read_utf8(input)
677 ext = xfun::file_ext(input)
678 if (missing(type) && ext == 'qmd') type = 'yaml' # default to yaml for Quarto
679 type = match.arg(type)
680 pattern = detect_pattern(text, ext)
681 # no code chunk in brew file
682 if (pattern == 'brew') return()
683 markdown_mode = pattern == 'md'
684 chunk_begin = all_patterns[[pattern]]$chunk.begin
685
686 # counter for inserted lines
687 nb_added = 0L
688 new_text = text
689 for (i in grep(chunk_begin, text)) {
690 # transform each chunk one by one
691 indent = get_chunk_indent(text[i])
692 header = extract_params_src(chunk_begin, text[i])
693 engine = if (markdown_mode) get_chunk_engine(header) else 'r'
694 params = if (markdown_mode) get_chunk_params(header) else header
695 # if no params nothing to format
696 if (params == '') next
697 params2 = clean_empty_params(params)
698 params2 = trimws(clean_empty_params(params2))
699
700 # select the correct prefix char (e.g `#|`)
701 opt_chars = xfun:::get_option_comment(engine)
702 prefix = paste0(indent, opt_chars$start)
703
704 # clean old chunk keeping only engine
705 new_text[i + nb_added] = gsub(params, '', text[i], fixed = TRUE)
706
707 # format new chunk
708 if (type == 'wrap') {
709 # simple line wrapping of R code
710 params3 = strwrap(params2, width, prefix = prefix)
711 } else if (type == 'multiline') {
712 # one option per line of the form `key = value,`
713 res = xfun::csv_options(params2)
714 params3 = sprintf('%s = %s,', names(res), deparsed_string(res))
715
716 # remove trailing for last element
717 last = length(params3)
718 params3[last] = gsub(',$', '', params3[last])
719
720 # wrap long single line and add prefix
721 params3 = if (width <= 0) paste0(prefix, params3) else {
722 strwrap(params3, width, prefix = prefix)
723 }
724 } else {
725 params3 = xfun::csv_options(params2)
726
727 # fix un-evaluated options for yaml by transforming to !expr val
728 params3 = lapply(params3, function(x) {
729 if (is.symbol(x) || is.language(x)) {
730 x = deparse(x, 500L)
731 attr(x, 'tag') = '!expr'
732 }
733 x
734 })
735 # transform dot option to dash option
736 params3 = dash_names(params3)
737 # convert to yaml and add prefix
738 params3 = strsplit(yaml::as.yaml(
739 params3, handlers = list(
740 # true / false instead of no
741 logical = function(x) {
742 x = tolower(x)
743 class(x) = 'verbatim'
744 x
745 },
746 # use character with verbatim for no quotes
747 # so that integers as kept unchanged (without changing precision)
748 # fig.width = 10, should not be fig-width: 10.0
749 numeric = function(x) {
750 if (length(x) != 1) return(x)
751 x2 = as.integer(x)
752 if (x2 == x) x2 else x
753 }), line.sep = '\n'), '\n')[[1]]
754 params3 = paste0(prefix, params3)
755 }
756
757 if (nzchar(opt_chars$end)) params3 = paste0(params3, opt_chars$end)
758
759 # insert new chunk header
760 new_text = append(new_text, params3, after = i + nb_added)
761 nb_added = nb_added + length(params3)
762 }
763
764 if (is.null(output)) return(new_text)
765 # otherwise write to file
766 if (is.function(output)) output = output(input)
767 xfun::write_utf8(new_text, output)
768 invisible(output)
769 }
770
771 # TODO: when R 4.0.0 is minimal version, switch to deparse1()
772 deparsed_string = function(exprs) {
773 unlist(lapply(exprs, function(x) paste(deparse(x, 500), collapse = ' ')))
774 }