Debian Codegraph @

R/output.R

raw
1 #' Knit a document
2 #'
3 #' This function takes an input file, extracts the R code in it according to a
4 #' list of patterns, evaluates the code and writes the output in another file.
5 #' It can also tangle R source code from the input document (\code{purl()} is a
6 #' wrapper to \code{knit(..., tangle = TRUE)}). The \code{knitr.purl.inline}
7 #' option can be used to also tangle the code of inline expressions (disabled by
8 #' default).
9 #'
10 #' For most of the time, it is not necessary to set any options outside the
11 #' input document; in other words, a single call like
12 #' \code{knit('my_input.Rnw')} is usually enough. This function will try to
13 #' determine many internal settings automatically. For the sake of
14 #' reproducibility, it is better practice to include the options inside the
15 #' input document (to be self-contained), instead of setting them before
16 #' knitting the document.
17 #'
18 #' First the filename of the output document is determined in this way:
19 #' \file{foo.Rnw} generates \file{foo.tex}, and other filename extensions like
20 #' \file{.Rtex}, \file{.Rhtml} (\file{.Rhtm}) and \file{.Rmd}
21 #' (\file{.Rmarkdown}) will generate \file{.tex}, \file{.html} and \file{.md}
22 #' respectively. For other types of files, if the filename contains
23 #' \samp{_knit_}, this part will be removed in the output file, e.g.,
24 #' \file{foo_knit_.html} creates the output \file{foo.html}; if \samp{_knit_} is
25 #' not found in the filename, \file{foo.ext} will produce \file{foo.txt} if
26 #' \code{ext} is not \code{txt}, otherwise the output is \file{foo-out.txt}. If
27 #' \code{tangle = TRUE}, \file{foo.ext} generates an R script \file{foo.R}.
28 #'
29 #' We need a set of syntax to identify special markups for R code chunks and R
30 #' options, etc. The syntax is defined in a pattern list. All built-in pattern
31 #' lists can be found in \code{all_patterns} (call it \code{apat}). First
32 #' \pkg{knitr} will try to decide the pattern list based on the filename
33 #' extension of the input document, e.g. \samp{Rnw} files use the list
34 #' \code{apat$rnw}, \samp{tex} uses the list \code{apat$tex}, \samp{brew} uses
35 #' \code{apat$brew} and HTML files use \code{apat$html}; for unkown extensions,
36 #' the content of the input document is matched against all pattern lists to
37 #' automatically determine which pattern list is being used. You can also
38 #' manually set the pattern list using the \code{\link{knit_patterns}} object or
39 #' the \code{\link{pat_rnw}} series functions in advance and \pkg{knitr} will
40 #' respect the setting.
41 #'
42 #' According to the output format (\code{opts_knit$get('out.format')}), a set of
43 #' output hooks will be set to mark up results from R (see
44 #' \code{\link{render_latex}}). The output format can be LaTeX, Sweave and HTML,
45 #' etc. The output hooks decide how to mark up the results (you can customize
46 #' the hooks).
47 #'
48 #' The name \code{knit} comes from its counterpart \samp{weave} (as in Sweave),
49 #' and the name \code{purl} (as \samp{tangle} in Stangle) comes from a knitting
50 #' method `knit one, purl one'.
51 #'
52 #' If the input document has child documents, they will also be compiled
53 #' recursively. See \code{\link{knit_child}}.
54 #'
55 #' See the package website and manuals in the references to know more about
56 #' \pkg{knitr}, including the full documentation of chunk options and demos,
57 #' etc.
58 #' @param input Path to the input file.
59 #' @param output Path to the output file for \code{knit()}. If \code{NULL}, this
60 #' function will try to guess a default, which will be under the current
61 #' working directory.
62 #' @param tangle Boolean; whether to tangle the R code from the input file (like
63 #' \code{utils::\link{Stangle}}).
64 #' @param text A character vector. This is an alternative way to provide the
65 #' input file.
66 #' @param quiet Boolean; suppress the progress bar and messages?
67 #' @param envir Environment in which code chunks are to be evaluated, for
68 #' example, \code{\link{parent.frame}()}, \code{\link{new.env}()}, or
69 #' \code{\link{globalenv}()}).
70 #' @param encoding Encoding of the input file; always assumed to be UTF-8 (i.e.,
71 #' this argument is effectively ignored).
72 #' @return The compiled document is written into the output file, and the path
73 #' of the output file is returned. If the \code{text} argument is not
74 #' \code{NULL}, the compiled output is returned as a character vector. In
75 #' other words, if you provide a file input, you get an output filename; if
76 #' you provide a character vector input, you get a character vector output.
77 #' @note The working directory when evaluating R code chunks is the directory of
78 #' the input document by default, so if the R code involves external files
79 #' (like \code{read.table()}), it is better to put these files under the same
80 #' directory of the input document so that we can use relative paths. However,
81 #' it is possible to change this directory with the package option
82 #' \code{\link{opts_knit}$set(root.dir = ...)} so all paths in code chunks are
83 #' relative to this \code{root.dir}. It is not recommended to change the
84 #' working directory via \code{\link{setwd}()} in a code chunk, because it may
85 #' lead to terrible consequences (e.g. figure and cache files may be written
86 #' to wrong places). If you do use \code{setwd()}, please note that
87 #' \pkg{knitr} will always restore the working directory to the original one.
88 #' Whenever you feel confused, print \code{getwd()} in a code chunk to see
89 #' what the working directory really is.
90 #'
91 #' If the \code{output} argument is a file path, it is strongly recommended to
92 #' be in the current working directory (e.g. \file{foo.tex} instead of
93 #' \file{somewhere/foo.tex}), especially when the output has external
94 #' dependencies such as figure files. If you want to write the output to a
95 #' different directory, it is recommended to set the working directory to that
96 #' directory before you knit a document. For example, if the source document
97 #' is \file{foo.Rmd} and the expected output is \file{out/foo.md}, you can
98 #' write \code{setwd('out/'); knit('../foo.Rmd')} instead of
99 #' \code{knit('foo.Rmd', 'out/foo.md')}.
100 #'
101 #' N.B. There is no guarantee that the R script generated by \code{purl()} can
102 #' reproduce the computation done in \code{knit()}. The \code{knit()} process
103 #' can be fairly complicated (special values for chunk options, custom chunk
104 #' hooks, computing engines besides R, and the \code{envir} argument, etc). If
105 #' you want to reproduce the computation in a report generated by
106 #' \code{knit()}, be sure to use \code{knit()}, instead of merely executing
107 #' the R script generated by \code{purl()}. This seems to be obvious, but some
108 #' people
109 #' \href{https://stat.ethz.ch/pipermail/r-devel/2014-May/069113.html}{do not
110 #' get it}.
111 #' @export
112 #' @references Package homepage: \url{https://yihui.org/knitr/}. The \pkg{knitr}
113 #' \href{https://yihui.org/knitr/demo/manual/}{main manual}: and
114 #' \href{https://yihui.org/knitr/demo/graphics/}{graphics manual}.
115 #'
116 #' See \code{citation('knitr')} for the citation information.
117 #' @examples library(knitr)
118 #' (f = system.file('examples', 'knitr-minimal.Rnw', package = 'knitr'))
119 #' knit(f) # compile to tex
120 #'
121 #' purl(f) # tangle R code
122 #' purl(f, documentation = 0) # extract R code only
123 #' purl(f, documentation = 2) # also include documentation
124 #'
125 #' unlink(c('knitr-minimal.tex', 'knitr-minimal.R', 'figure'), recursive = TRUE)
126 knit = function(
127 input, output = NULL, tangle = FALSE, text = NULL, quiet = FALSE,
128 envir = parent.frame(), encoding = 'UTF-8'
129 ) {
130
131 in.file = !missing(input) && is.character(input) # is input provided?
132 oconc = knit_concord$get(); on.exit(knit_concord$set(oconc), add = TRUE)
133
134 if (child_mode()) {
135 setwd(opts_knit$get('output.dir') %n% '.') # always restore original working dir
136 # in child mode, input path needs to be adjusted
137 if (in.file && !is_abs_path(input)) {
138 input = paste0(opts_knit$get('child.path'), input)
139 input = file.path(input_dir(), input)
140 }
141 # respect the quiet argument in child mode (#741)
142 optk = opts_knit$get(); on.exit(opts_knit$restore(optk), add = TRUE)
143 opts_knit$set(progress = opts_knit$get('progress') && !quiet)
144 quiet = !opts_knit$get('progress')
145 } else {
146 knit_log$restore()
147 on.exit(chunk_counter(reset = TRUE), add = TRUE) # restore counter
148 adjust_opts_knit()
149 # turn off fancy quotes, use a null pdf device to record graphics
150 oopts = options(
151 useFancyQuotes = FALSE, device = pdf_null, knitr.in.progress = TRUE
152 )
153 on.exit(options(oopts), add = TRUE)
154 # restore objects like chunk options after parent exits
155 opta = list(opts_chunk, opts_current, knit_code, opts_knit)
156 optv = lapply(opta, function(o) o$get())
157 on.exit(for (i in seq_along(opta)) opta[[i]]$restore(optv[[i]]), add = TRUE)
158 opts_knit$set(
159 output.dir = getwd(), # record working directory in 1st run
160 tangle = tangle, progress = opts_knit$get('progress') && !quiet
161 )
162 }
163 # store the evaluation environment and restore on exit
164 oenvir = .knitEnv$knit_global; .knitEnv$knit_global = envir
165 on.exit({.knitEnv$knit_global = oenvir}, add = TRUE)
166
167 ext = 'unknown'
168 if (in.file) {
169 input.dir = .knitEnv$input.dir; on.exit({.knitEnv$input.dir = input.dir}, add = TRUE)
170 .knitEnv$input.dir = dirname(input) # record input dir
171 ext = tolower(file_ext(input))
172 if ((is.null(output) || is.na(output)) && !child_mode())
173 output = basename(auto_out_name(input, ext))
174 # do not run purl() when the output is newer than input (the output might
175 # have been generated by hook_purl)
176 if (is.character(output) && !child_mode()) {
177 out.purl = with_ext(input, 'R')
178 if (xfun::same_path(output, out.purl) && tangle && file_test('-nt', out.purl, input))
179 return(out.purl)
180 otangle = .knitEnv$tangle.file # the tangled R script
181 .knitEnv$tangle.file = normalizePath(out.purl, mustWork = FALSE)
182 .knitEnv$tangle.start = FALSE
183 on.exit({.knitEnv$tangle.file = otangle; .knitEnv$tangle.start = NULL}, add = TRUE)
184 }
185 if (is.null(getOption('tikzMetricsDictionary'))) {
186 options(tikzMetricsDictionary = tikz_dict(input)) # cache tikz dictionary
187 on.exit(options(tikzMetricsDictionary = NULL), add = TRUE)
188 }
189 knit_concord$set(infile = input, outfile = output)
190 }
191
192 # we need some special treatment for chunks in Quarto document
193 .knitEnv$is_quarto = !is.null(opts_knit$get('quarto.version')) || ext == 'qmd'
194
195 text = if (is.null(text)) xfun::read_utf8(input) else split_lines(text)
196 if (!length(text)) {
197 if (is.character(output)) file.create(output)
198 return(output) # a trivial case: create an empty file and exit
199 }
200
201 apat = all_patterns; opat = knit_patterns$get()
202 on.exit(knit_patterns$restore(opat), add = TRUE)
203 if (length(opat) == 0 || all(vapply(opat, is.null, logical(1)))) {
204 # use ext if cannot auto detect pattern
205 if (is.null(pattern <- detect_pattern(text, ext))) {
206 # nothing to be executed; just return original input
207 if (is.null(output)) {
208 return(if (tangle) '' else one_string(text))
209 } else {
210 write_utf8(if (tangle) '' else text, output)
211 return(output)
212 }
213 }
214 if (!(pattern %in% names(apat))) stop(
215 "a pattern list cannot be automatically found for the file extension '",
216 ext, "' in built-in pattern lists; ",
217 'see ?knit_patterns on how to set up customized patterns'
218 )
219 set_pattern(pattern)
220 if (pattern == 'rnw' && length(sweave_lines <- which_sweave(text)) > 0)
221 remind_sweave(if (in.file) input, sweave_lines)
222 opts_knit$set(out.format = switch(
223 pattern, rnw = 'latex', tex = 'latex', html = 'html', md = 'markdown',
224 rst = 'rst', brew = 'brew', asciidoc = 'asciidoc', textile = 'textile'
225 ))
226 }
227
228 if (is.null(out_format())) auto_format(ext)
229
230 otel_active_span(
231 name = 'knitr processing',
232 label = get_knitr_concord('infile'),
233 attributes = make_knitr_attributes()
234 )
235
236 params = NULL # the params field from YAML
237 if (out_format('markdown')) {
238 if (child_mode()) {
239 # in child mode, strip off the YAML metadata in Markdown if exists
240 if (grepl('^---\\s*$', text[1])) {
241 i = grep('^---\\s*$', text)
242 if (length(i) >= 2) text[1:i[2]] = ''
243 }
244 } else {
245 params = knit_params(text)
246 params = if (length(params))
247 c('params <-', capture.output(dput(flatten_params(params), '')), '')
248 .knitEnv$tangle.params = params # for hook_purl()
249 }
250 }
251 # change output hooks only if they are not set beforehand
252 if (identical(knit_hooks$get(names(.default.hooks)), .default.hooks) && !child_mode()) {
253 getFromNamespace(paste('render', out_format(), sep = '_'), 'knitr')()
254 on.exit(knit_hooks$set(.default.hooks), add = TRUE)
255 }
256
257 progress = opts_knit$get('progress')
258 if (in.file && !quiet) message(ifelse(progress, '\n\n', ''), 'processing file: ', input)
259 on.exit(run_hook('after.knit'), add = TRUE)
260 run_hook('before.knit')
261 res = process_file(text, output)
262 res = one_string(knit_hooks$get('document')(res))
263 if (tangle) res = c(params, res)
264 if (!is.null(output)) write_utf8(res, output)
265 if (!child_mode()) {
266 dep_list$restore() # empty dependency list
267 .knitEnv$labels = NULL
268 }
269
270 if (in.file && is.character(output) && file.exists(output)) {
271 concord_gen(input, output)
272 if (!quiet) message('output file: ', output, ifelse(progress, '\n', ''))
273 }
274
275 otel_active_span(
276 name = 'knitr output',
277 label = get_knitr_concord('outfile'),
278 attributes = make_knitr_attributes()
279 )
280
281 output %n% res
282 }
283 #' @rdname knit
284 #' @param documentation An integer specifying the level of documentation to add to
285 #' the tangled script. \code{0} means to output pure code, discarding all text chunks);
286 #' \code{1} (the default) means to add the chunk headers to the code; \code{2} means to
287 #' add all text chunks to code as roxygen comments.
288 #' @param ... arguments passed to \code{\link{knit}()} from \code{purl()}
289 #' @export
290 purl = function(..., documentation = 1L) {
291 doc = opts_knit$get('documentation'); on.exit(opts_knit$set(documentation = doc))
292 opts_knit$set(documentation = documentation)
293 knit(..., tangle = TRUE)
294 }
295
296 process_file = function(text, output) {
297 groups = split_file(lines = text)
298 n = length(groups); res = character(n)
299 tangle = opts_knit$get('tangle')
300
301 # when in R CMD check, turn off the progress bar (R-exts said the progress bar
302 # was not appropriate for non-interactive mode, and I don't want to argue)
303 progress = opts_knit$get('progress') && !is_R_CMD_check()
304 labels = unlist(lapply(groups, function(g) {
305 if (is.list(g$params)) g[[c('params', 'label')]] else ''
306 }))
307 if (progress) {
308 pb_fun = getOption('knitr.progress.fun', txt_pb)
309 pb = if (is.function(pb_fun)) pb_fun(n, labels)
310 on.exit(if (is.function(pb$done)) pb$done(), add = TRUE)
311 }
312 wd = getwd()
313 for (i in 1:n) {
314 if (!is.null(.knitEnv$terminate)) {
315 if (!child_mode() || !.knitEnv$terminate_fully) {
316 # reset the internal variable `terminate` in the top parent
317 res[i] = one_string(.knitEnv$terminate)
318 knit_exit(NULL, NULL)
319 }
320 break # must have called knit_exit(), so exit early
321 }
322 if (progress && is.function(pb$update)) pb$update(i)
323 group = groups[[i]]
324 knit_concord$set(block = i)
325 error = NULL
326 res[i] = xfun:::handle_error(
327 with_options(
328 withCallingHandlers(
329 if (tangle) process_tangle(group) else process_group(group),
330 error = function(e) {
331 if (progress && is.function(pb$interrupt)) pb$interrupt()
332 if (is_R_CMD_build() || is_R_CMD_check()) error <<- format(e)
333 }
334 ),
335 list(rlang_trace_top_env = knit_global())
336 ),
337 function(loc) {
338 setwd(wd)
339 write_utf8(res, output %n% stdout())
340 paste0(
341 '\nQuitting from ', loc,
342 if (!is.null(error)) paste0('\n', rule(), error, '\n', rule())
343 )
344 },
345 if (labels[i] != '') sprintf(' [%s]', labels[i]), get_loc
346 )
347 knit_concord$set(offset = NULL)
348 }
349
350 if (!tangle) res = insert_header(res) # insert header
351 # output line numbers
352 if (concord_mode()) knit_concord$set(outlines = line_count(res))
353 print_knitlog()
354 if (tangle) res = strip_white(res)
355
356 res
357 }
358
359 rule = function() {
360 # Used by pkgbuild; please don't change without letting us know
361 paste0(strrep('~', getOption('width')), '\n')
362 }
363
364 # return a string to point out the current location in the doc
365 get_loc = function(label = '') {
366 paste0(knit_concord$get('infile'), ':', current_lines(), label)
367 }
368
369 auto_out_name = function(input, ext = tolower(file_ext(input))) {
370 base = sans_ext(input)
371 name = if (opts_knit$get('tangle')) c(base, '.R') else
372 if (ext %in% c('rnw', 'snw')) c(base, '.tex') else
373 if (ext %in% c('rmd', 'rmarkdown', 'qmd', 'rhtml', 'rhtm', 'rtex', 'stex', 'rrst', 'rtextile'))
374 c(base, '.', substring(ext, 2L)) else
375 if (grepl('_knit_', input)) sub('_knit_', '', input) else
376 if (ext != 'txt') c(base, '.txt') else c(base, '-out.', ext)
377 paste(name, collapse = '')
378 }
379
380 # determine output format based on file extension
381 ext2fmt = c(
382 rnw = 'latex', snw = 'latex', tex = 'latex', rtex = 'latex', stex = 'latex',
383 htm = 'html', html = 'html', rhtml = 'html', rhtm = 'html',
384 md = 'markdown', markdown = 'markdown', rmd = 'markdown', rmarkdown = 'markdown',
385 qmd = 'markdown', brew = 'brew', rst = 'rst', rrst = 'rst'
386 )
387
388 auto_format = function(ext) {
389 fmt = ext2fmt[ext]
390 if (is.na(fmt)) fmt = {
391 warning('cannot automatically decide the output format')
392 'unknown'
393 }
394 opts_knit$set(out.format = fmt)
395 invisible(fmt)
396 }
397
398 #' Knit a child document
399 #'
400 #' This function knits a child document and returns a character string to input
401 #' the result into the main document. It is designed to be used in the chunk
402 #' option \code{child} and serves as the alternative to the
403 #' \command{SweaveInput} command in Sweave.
404 #' @param ... Arguments passed to \code{\link{knit}}.
405 #' @param options A list of chunk options to be used as global options inside
406 #' the child document. When one uses the \code{child}
407 #' option in a parent chunk, the chunk options of the parent chunk will be
408 #' passed to the \code{options} argument here. Ignored if not a list.
409 #' @inheritParams knit
410 #' @return A character string of the content of the compiled child document is
411 #' returned as a character string so it can be written back to the parent
412 #' document directly.
413 #' @references \url{https://yihui.org/knitr/demo/child/}
414 #' @note This function is not supposed be called directly like
415 #' \code{\link{knit}()}; instead it must be placed in a parent document to let
416 #' \code{\link{knit}()} call it indirectly.
417 #'
418 #' The path of the child document is determined relative to the parent document.
419 #' @export
420 #' @examples # you can write \Sexpr{knit_child('child-doc.Rnw')} in an Rnw file 'main.Rnw'
421 #' # to input results from child-doc.Rnw in main.tex
422 #'
423 #' # comment out the child doc by \Sexpr{knit_child('child-doc.Rnw', eval = FALSE)}
424 knit_child = function(..., options = NULL, envir = knit_global()) {
425 child = child_mode()
426 opts_knit$set(child = TRUE) # yes, in child mode now
427 on.exit(opts_knit$set(child = child)) # restore child status
428 if (is.list(options)) {
429 options$label = options$child = NULL # do not need to pass the parent label on
430 if (length(options)) {
431 optc = opts_chunk$get(names(options), drop = FALSE); opts_chunk$set(options)
432 # if user did not touch opts_chunk$set() in child, restore the chunk option
433 on.exit({
434 for (i in names(options)) if (identical(options[[i]], opts_chunk$get(i)))
435 opts_chunk$set(optc[i])
436 }, add = TRUE)
437 }
438 }
439 res = knit(..., tangle = opts_knit$get('tangle'), envir = envir)
440 one_string(c('', res))
441 }
442
443 #' Exit knitting early
444 #'
445 #' Sometimes we may want to exit the knitting process early, and completely
446 #' ignore the rest of the document. This function provides a mechanism to
447 #' terminate \code{\link{knit}()}.
448 #' @param append A character vector to be appended to the results from
449 #' \code{knit()} so far. By default, this is \samp{\end{document}} for LaTeX
450 #' output, and \samp{</body></html>} for HTML output, to make the output
451 #' document complete. For other types of output, it is an empty string.
452 #' @param fully Whether to fully exit the knitting process if \code{knit_exit()}
453 #' is called from a child document. If \code{FALSE}, only exit the knitting
454 #' process of the child document.
455 #' @return Invisible \code{NULL}. An internal signal is set up (as a side
456 #' effect) to notify \code{knit()} to quit as if it had reached the end of the
457 #' document.
458 #' @export
459 #' @examples # see https://github.com/yihui/knitr-examples/blob/master/096-knit-exit.Rmd
460 knit_exit = function(append, fully = TRUE) {
461 if (missing(append)) append = if (out_format(c('latex', 'sweave', 'listings')))
462 '\\end{document}' else if (out_format('html')) '</body>\n</html>' else ''
463 .knitEnv$terminate = append # use this terminate variable to notify knit()
464 .knitEnv$terminate_fully = fully
465 invisible()
466 }
467
468 knit_log = new_defaults() # knitr log for errors, warnings and messages
469
470 #' Wrap evaluated results for output
471 #'
472 #' This function is mainly for internal use: it is called on each part of the
473 #' output of the code chunk (code, messages, text output, and plots, etc.) after
474 #' all statements in the code chunk have been evaluated, and will sew these
475 #' pieces of output together into a character vector.
476 #' @param x Output from \code{evaluate::\link[evaluate]{evaluate}()}.
477 #' @param options A list of chunk options used to control output.
478 #' @param ... Other arguments to pass to methods.
479 #' @export
480 sew = function(x, options = list(), ...) {
481 UseMethod('sew', x)
482 }
483
484 #' @export
485 sew.list = function(x, options = list(), ...) {
486 if (length(x) == 0L) return(x)
487 lapply(x, sew, options, ...)
488 }
489
490 # ignore unknown classes
491 #' @export
492 sew.default = function(x, options, ...) return()
493
494 #' @export
495 sew.character = function(x, options, ...) {
496 if (options$results == 'hide') return()
497 if (output_asis(x, options)) {
498 if (!out_format('latex')) return(x) # latex output still need a tweak
499 } else x = comment_out(x, options$comment)
500 knit_hooks$get('output')(x, options)
501 }
502
503 asis_token = '<!-- KNITR_ASIS_OUTPUT_TOKEN -->'
504 wrap_asis = function(x, options) {
505 # do nothing when inside quarto as it is not needed
506 # https://github.com/yihui/knitr/pull/2212#pullrequestreview-1292924523
507 if (is_quarto()) return(x)
508
509 x = as.character(x)
510 if ((n <- length(x)) == 0 || !out_format('markdown') || missing(options) || !isTRUE(options$collapse))
511 return(x)
512 x[1] = paste0(asis_token, x[1])
513 x[n] = paste0(x[n], asis_token)
514 x
515 }
516
517 # If you provide a custom print function that returns a character object of
518 # class 'knit_asis', it will be written as is.
519 #' @export
520 sew.knit_asis = function(x, options, inline = FALSE, ...) {
521 m = attr(x, 'knit_meta')
522 knit_meta_add(m, if (missing(options)) '' else options$label)
523 if (!missing(options)) {
524 if (options$cache > 0 && isFALSE(attr(x, 'knit_cacheable'))) stop(
525 "The code chunk '", options$label, "' is not cacheable; ",
526 "please use the chunk option cache=FALSE on this chunk"
527 )
528 # store metadata in an object named of the form .hash_meta when cache=TRUE
529 if (length(m) && options$cache == 3)
530 assign(cache_meta_name(options$hash), m, envir = knit_global())
531 if (inherits(x, 'knit_asis_htmlwidget')) {
532 options$fig.cur = plot_counter()
533 options = reduce_plot_opts(options)
534 # TODO: remove this when quarto > 1.3.353 is widely used
535 if (is_quarto()) return(add_html_caption(options, wrap_asis(x, options)))
536 # look for attribute 'aria-labelledby="label"' in the first HTML tag and
537 # use the label to provide alt text if found
538 return(add_html_caption(
539 options, wrap_asis(x, options),
540 xfun::grep_sub('^[^<]*<[^>]+aria-labelledby[ ]*=[ ]*"([^"]+)".*$', '\\1', x)
541 ))
542 }
543 }
544 x = wrap_asis(x, options)
545 if (inline) return(x)
546 options$results = 'asis'
547 knit_hooks$get('output')(x, options)
548 }
549
550 #' @export
551 sew.source = function(x, options, ...) {
552 if (isFALSE(options$echo)) return()
553 src = sub('\n$', '', x$src)
554 if (options$strip.white) src = strip_white(src)
555 if (is_blank(src)) return() # an empty chunk
556 knit_hooks$get('source')(src, options)
557 }
558
559 msg_wrap = function(message, type, options) {
560 # when the output format is LaTeX, do not wrap messages (let LaTeX deal with wrapping)
561 if (!length(grep('\n', message)) && !out_format(c('latex', 'listings', 'sweave')))
562 message = xfun::str_wrap(message, width = getOption('width'))
563 knit_log$set(setNames(
564 list(c(knit_log$get(type), paste0('Chunk ', options$label, ':\n ', message))),
565 type
566 ))
567 message = msg_sanitize(message, type)
568 knit_hooks$get(type)(comment_out(message, options$comment), options)
569 }
570
571 # set options(knitr.sanitize.errors = TRUE) to hide error messages, etc
572 msg_sanitize = function(message, type) {
573 type = match.arg(type, c('error', 'warning', 'message'))
574 opt = getOption(sprintf('knitr.sanitize.%ss', type), FALSE)
575 if (isTRUE(opt)) message = switch(
576 type, error = 'An error occurred', warning = 'A warning was emitted',
577 message = 'A message was emitted'
578 ) else if (is.character(opt)) message = opt
579 message
580 }
581
582 #' @export
583 sew.warning = function(x, options, ...) {
584 call = if (is.null(x$call)) '' else {
585 call = deparse(x$call)[1]
586 if (call == 'eval(expr, envir, enclos)') '' else paste(' in', call)
587 }
588 msg_wrap(sprintf('Warning%s: %s', call, conditionMessage(x)), 'warning', options)
589 }
590
591 #' @export
592 sew.message = function(x, options, ...) {
593 msg_wrap(paste(conditionMessage(x), collapse = ''), 'message', options)
594 }
595
596 #' @export
597 sew.error = function(x, options, ...) {
598 msg_wrap(as.character(x), 'error', options)
599 }
600
601 #' @export
602 sew.recordedplot = function(x, options, ...) {
603 # figure number sequence for multiple plots
604 fig.cur = plot_counter()
605 options$fig.cur = fig.cur # put fig num in options
606 name = fig_path('', options, number = fig.cur)
607 in_base_dir(
608 # automatically creates dir for plots
609 if (!file_test('-d', dirname(name)))
610 dir.create(dirname(name), recursive = TRUE)
611 )
612 # vectorize over dev, ext and dpi: save multiple versions of the plot
613 files = mapply(
614 save_plot, width = options$fig.width, height = options$fig.height,
615 dev = options$dev, ext = options$fig.ext, dpi = options$dpi,
616 MoreArgs = list(plot = x, name = name, options = options), SIMPLIFY = FALSE
617 )
618 opts_knit$append(plot_files = unlist(files))
619 if (options$fig.show == 'hide') return('')
620 in_base_dir(run_hook_plot(files[[1]], reduce_plot_opts(options)))
621 }
622
623 #' @export
624 sew.knit_image_paths = function(x, options = opts_chunk$get(), inline = FALSE, ...) {
625 if (options$fig.show == 'hide') return('')
626 # remove the automatically set out.width when fig.retina is set, otherwise the
627 # size of external images embedded via include_graphics() will be set to
628 # fig.width * dpi in fix_options()
629 if (is.numeric(r <- options$fig.retina)) {
630 w1 = options$out.width
631 w2 = options$fig.width * options$dpi / r
632 if (length(w1) * length(w2) == 1 && is.numeric(w1) && w1 == w2)
633 options['out.width'] = list(NULL)
634 }
635 options$fig.num = options$fig.num %n% length(x)
636 dpi = attr(x, 'dpi') %n% options$dpi
637 hook = knit_hooks$get('plot')
638 paste(unlist(lapply(seq_along(x), function(i) {
639 options$fig.cur = plot_counter()
640 if (is.null(options[['out.width']]))
641 options['out.width'] = list(raster_dpi_width(x[i], dpi))
642 hook(x[i], reduce_plot_opts(options))
643 })), collapse = '')
644 }
645
646 #' @export
647 sew.html_screenshot = function(x, options = opts_chunk$get(), inline = FALSE, ...) {
648 ext = x$extension
649 in_base_dir({
650 i = plot_counter()
651 if (is.null(f <- x$file)) {
652 f = fig_path(ext, options, i)
653 dir.create(dirname(f), recursive = TRUE, showWarnings = FALSE)
654 writeBin(x$image, f, useBytes = TRUE)
655 }
656 options$fig.cur = i
657 options = reduce_plot_opts(options)
658 if (!is.null(x$url) && is.null(options$fig.link)) options$fig.link = x$url
659 run_hook_plot(f, options)
660 })
661 }
662
663 # record plot filenames in opts_knit$get('plot_files'), including those from R
664 # code and auto screenshots of HTML widgets, etc. Then run the plot hook.
665 run_hook_plot = function(x, options) {
666 opts_knit$append(plot_files = x)
667 hook = knit_hooks$get('plot')
668 hook(x, options)
669 }
670
671 #' @export
672 sew.knit_embed_url = function(x, options = opts_chunk$get(), inline = FALSE, ...) {
673 options$fig.cur = plot_counter()
674 options = reduce_plot_opts(options)
675 if (length(extra <- options$out.extra)) extra = paste('', extra, collapse = '')
676 add_html_caption(options, sprintf(
677 '<iframe src="%s" width="%s" height="%s" data-external="1"%s></iframe>',
678 html_escape(x$url), options$out.width %n% '100%', x$height %n% '400px',
679 extra %n% ''
680 ))
681 }
682
683 add_html_caption = function(options, code, id = NULL) {
684 cap = .img.cap(options)
685 if (cap == '' && !length(id)) return(code)
686
687 if (length(id)) {
688 alt = .img.cap(options, alt = TRUE, escape = TRUE)
689 if (cap == alt && cap != '') {
690 # both are the same, so insert cap with id
691 alttext = sprintf('<p class="caption" id="%s">%s</p>\n', id, cap)
692 # prevent a second insertion
693 cap = ''
694 } else {
695 alttext = sprintf('<p id="%s" hidden>%s</p>\n', id, alt)
696 }
697 } else alttext = ''
698
699 captext = if (cap == '') '' else sprintf('<p class="caption">%s</p>\n', cap)
700
701 sprintf(
702 '<div class="figure"%s>\n%s\n%s%s</div>',
703 css_text_align(options$fig.align), code, captext, alttext
704 )
705 }
706
707 #' A custom printing function
708 #'
709 #' The S3 generic function \code{knit_print} is the default printing function in
710 #' \pkg{knitr}. The chunk option \code{render} uses this function by default.
711 #' The main purpose of this S3 generic function is to customize printing of R
712 #' objects in code chunks. We can fall back to the normal printing behavior by
713 #' setting the chunk option \code{render = normal_print}.
714 #'
715 #' Users can write custom methods based on this generic function. For example,
716 #' if we want to print all data frames as tables in the output, we can define a
717 #' method \code{knit_print.data.frame} that turns a data.frame into a table (the
718 #' implementation may use other R packages or functions, e.g. \pkg{xtable} or
719 #' \code{\link{kable}()}).
720 #' @param x An R object to be printed
721 #' @param ... Additional arguments passed to the S3 method. Currently ignored,
722 #' except two optional arguments \code{options} and \code{inline}; see
723 #' the references below.
724 #' @return The value returned from the print method should be a character vector
725 #' or can be converted to a character value. You can wrap the value in
726 #' \code{\link{asis_output}()} so that \pkg{knitr} writes the character value
727 #' as is in the output.
728 #' @note It is recommended to leave a \code{...} argument in your method, to
729 #' allow future changes of the \code{knit_print()} API without breaking your
730 #' method.
731 #' @references See \code{vignette('knit_print', package = 'knitr')}.
732 #' @export
733 #' @examples library(knitr)
734 #' # write tables for data frames
735 #' knit_print.data.frame = function(x, ...) {
736 #' res = paste(c('', '', kable(x, output = FALSE)), collapse = '\n')
737 #' asis_output(res)
738 #' }
739 #' # register the method
740 #' registerS3method("knit_print", "data.frame", knit_print.data.frame)
741 #' # after you define and register the above method, data frames will be printed
742 #' # as tables in knitr, which is different with the default print() behavior
743 knit_print = function(x, ...) {
744 if (getOption('knitr.in.progress', FALSE)) {
745 current_env = parent.frame()
746 local_options(list(rlang_trace_top_env = current_env))
747 }
748 if (need_screenshot(x, ...)) {
749 html_screenshot(x)
750 } else {
751 UseMethod('knit_print')
752 }
753 }
754
755 #" the default print method is just print()/show()
756 #' @export
757 knit_print.default = function(x, ..., inline = FALSE) {
758 if (inline) x else normal_print(x)
759 }
760
761 #' @export
762 knit_print.knit_asis = function(x, ...) x
763
764 #' @export
765 knit_print.knit_asis_url = function(x, ...) x
766
767 #' @rdname knit_print
768 #' @export
769 normal_print = function(x, ...) {
770 if (isS4(x)) methods::show(x) else print(x)
771 }
772
773 #' Mark an R object with a special class
774 #'
775 #' This is a convenience function that assigns the input object a class named
776 #' \code{knit_asis}, so that \pkg{knitr} will treat it as is (the effect is the
777 #' same as the chunk option \code{results = 'asis'}) when it is written to the
778 #' output.
779 #'
780 #' This function is normally used in a custom S3 method based on the printing
781 #' function \code{\link{knit_print}()}.
782 #'
783 #' For the \code{cacheable} argument, you need to be careful when printing the
784 #' object involves non-trivial side effects, in which case it is strongly
785 #' recommended to use \code{cacheable = FALSE} to instruct \pkg{knitr} that this
786 #' object should not be cached using the chunk option \code{cache = TRUE},
787 #' otherwise the side effects will be lost the next time the chunk is knitted.
788 #' For example, printing a \pkg{shiny} input element or an HTML widget in an R
789 #' Markdown document may involve registering metadata about some JavaScript
790 #' libraries or stylesheets, and the metadata may be lost if we cache the code
791 #' chunk, because the code evaluation will be skipped the next time. This
792 #' particular issue has been solved in \pkg{knitr} after v1.13 (the metadata
793 #' will be saved and loaded automatically when caching is enabled), but not all
794 #' metadata can be saved and loaded next time and still works in the new R
795 #' session.
796 #' @param x An R object. Typically a character string, or an object which can
797 #' be converted to a character string via \code{\link{as.character}()}.
798 #' @param meta Additional metadata of the object to be printed. The metadata
799 #' will be collected when the object is printed, and accessible via
800 #' \code{knit_meta()}.
801 #' @param cacheable Boolean indicating whether this object is cacheable. If
802 #' \code{FALSE}, \pkg{knitr} will stop when caching is enabled on code chunks
803 #' that contain \code{asis_output()}.
804 #' @note This function only works in top-level R expressions, and it will not
805 #' work when it is called inside another expression, such as a for-loop. See
806 #' \url{https://github.com/yihui/knitr/issues/1137} for a discussion.
807 #' @export
808 #' @examples # see ?knit_print
809 asis_output = function(x, meta = NULL, cacheable = NA) {
810 structure(x, class = 'knit_asis', knit_meta = meta, knit_cacheable = cacheable)
811 }
812
813 #' Metadata about objects to be printed
814 #'
815 #' As an object is printed, \pkg{knitr} will collect metadata about it (if
816 #' available). After knitting is done, all the metadata is accessible via this
817 #' function. You can manually add metadata to the \pkg{knitr} session via
818 #' \code{knit_meta_add()}.
819 #' @param class Optionally return only metadata entries that inherit from the
820 #' specified class. The default, \code{NULL}, returns all entries.
821 #' @param clean Whether to clean the collected metadata. By default, the
822 #' metadata stored in \pkg{knitr} is cleaned up once retrieved, because we may
823 #' not want the metadata to be passed to the next \code{knit()} call; to be
824 #' defensive (i.e. not to have carryover metadata), you can call
825 #' \code{knit_meta()} before \code{knit()}.
826 #' @export
827 #' @return \code{knit_meta()} returns the matched metadata specified by
828 #' \code{class}; \code{knit_meta_add()} returns all current metadata.
829 knit_meta = function(class = NULL, clean = TRUE) {
830 if (is.null(class)) {
831 if (clean) on.exit({.knitEnv$meta = list()}, add = TRUE)
832 return(.knitEnv$meta)
833 }
834 # if a class was specified, match the items belonging to the class
835 matches = if (length(.knitEnv$meta)) {
836 vapply(.knitEnv$meta, inherits, logical(1), what = class)
837 }
838 if (!any(matches)) return(list())
839 if (clean) on.exit({
840 .knitEnv$meta[matches] = NULL
841 id = attr(.knitEnv$meta, 'knit_meta_id')
842 if (length(id)) attr(.knitEnv$meta, 'knit_meta_id') = id[!matches]
843 }, add = TRUE)
844 .knitEnv$meta[matches]
845 }
846
847 #' @param meta A metadata object to be added to the session.
848 #' @param label A chunk label to indicate which chunk the metadata belongs to.
849 #' @rdname knit_meta
850 #' @export
851 knit_meta_add = function(meta, label = '') {
852 if (length(meta)) {
853 meta_id = attr(.knitEnv$meta, 'knit_meta_id')
854 .knitEnv$meta = c(.knitEnv$meta, meta)
855 attr(.knitEnv$meta, 'knit_meta_id') = c(meta_id, rep_len(label, length(meta)))
856 }
857 .knitEnv$meta
858 }