| 1 |
# process chunks and inline text |
| 2 |
process_group = function(x) { |
| 3 |
if (inherits(x, 'block')) call_block(x) else { |
| 4 |
x = call_inline(x) |
| 5 |
knit_hooks$get('text')(x) |
| 6 |
} |
| 7 |
} |
| 8 |
|
| 9 |
call_block = function(block) { |
| 10 |
# now try eval all options except those in eval.after and their aliases |
| 11 |
af = opts_knit$get('eval.after'); al = opts_knit$get('aliases') |
| 12 |
if (!is.null(al) && !is.null(af)) af = c(af, names(al[af %in% al])) |
| 13 |
|
| 14 |
params = opts_chunk$merge(block$params) |
| 15 |
params = dot_names(params) |
| 16 |
for (o in setdiff(names(params), af)) { |
| 17 |
params[o] = list(eval_lang(params[[o]])) |
| 18 |
# also update original options before being merged with opts_chunk |
| 19 |
if (o %in% names(block$params)) block$params[o] = params[o] |
| 20 |
} |
| 21 |
|
| 22 |
label = ref.label = params$label |
| 23 |
if (!is.null(params$ref.label)) { |
| 24 |
ref.label = sc_split(params$ref.label) |
| 25 |
# ref.label = I() implies opts.label = ref.label |
| 26 |
if (inherits(params$ref.label, 'AsIs') && is.null(params$opts.label)) |
| 27 |
params$opts.label = ref.label |
| 28 |
} |
| 29 |
params[['code']] = get_code(params, label, ref.label) |
| 30 |
|
| 31 |
# opts.label = TRUE means inheriting chunk options from ref.label |
| 32 |
if (isTRUE(params$opts.label)) params$opts.label = ref.label |
| 33 |
# expand chunk options defined via opts_template and reference chunks |
| 34 |
params2 = NULL |
| 35 |
for (lab in params$opts.label) { |
| 36 |
# referenced chunk options (if any) override template options |
| 37 |
params3 = merge_list(opts_template$get(lab), attr(knit_code$get(lab), 'chunk_opts')) |
| 38 |
params2 = merge_list(params2, params3) |
| 39 |
} |
| 40 |
if (length(params2)) { |
| 41 |
# local options override referenced options |
| 42 |
params2 = merge_list(params2, block$params) |
| 43 |
# then override previously merged opts_chunk options |
| 44 |
params = merge_list(params, params2) |
| 45 |
# in case any options are not evaluated |
| 46 |
for (o in setdiff(names(params), af)) params[o] = list(eval_lang(params[[o]])) |
| 47 |
} |
| 48 |
|
| 49 |
# save current chunk options in opts_current |
| 50 |
optc = opts_current$get(); on.exit(opts_current$restore(optc), add = TRUE) |
| 51 |
opts_current$restore(params) |
| 52 |
|
| 53 |
if (opts_knit$get('progress')) print_block(block) |
| 54 |
|
| 55 |
if (!isFALSE(params$ref.chunk)) |
| 56 |
params[['code']] = parse_chunk(params[['code']]) # parse sub-chunk references |
| 57 |
|
| 58 |
ohooks = opts_hooks$get() |
| 59 |
for (opt in names(ohooks)) { |
| 60 |
hook = ohooks[[opt]] |
| 61 |
if (!is.function(hook)) { |
| 62 |
warning("The option hook '", opt, "' should be a function") |
| 63 |
next |
| 64 |
} |
| 65 |
if (!is.null(params[[opt]])) params = as.strict_list(hook(params)) |
| 66 |
if (!is.list(params)) |
| 67 |
stop("The option hook '", opt, "' should return a list of chunk options") |
| 68 |
} |
| 69 |
|
| 70 |
params = fix_options(params) # for compatibility |
| 71 |
|
| 72 |
if (!is.null(params$child)) { |
| 73 |
if (!is_blank(params[['code']]) && getOption('knitr.child.warning', TRUE)) warning( |
| 74 |
"The chunk '", params$label, "' has the 'child' option, ", |
| 75 |
"and this code chunk must be empty. Its code will be ignored." |
| 76 |
) |
| 77 |
if (!params$eval) return('') |
| 78 |
cmds = lapply(sc_split(params$child), knit_child, options = block$params) |
| 79 |
out = one_string(unlist(cmds)) |
| 80 |
return(out) |
| 81 |
} |
| 82 |
|
| 83 |
# Check cache |
| 84 |
if (params$cache > 0) { |
| 85 |
content = c( |
| 86 |
params[if (params$cache < 3) cache1.opts else setdiff(names(params), cache0.opts)], |
| 87 |
75L, if (params$cache == 2) params[cache2.opts] |
| 88 |
) |
| 89 |
if (params$engine == 'R' && isFALSE(params$cache.comments)) { |
| 90 |
content[['code']] = parse_only(content[['code']]) |
| 91 |
} |
| 92 |
hash = paste(valid_path(params$cache.path, label), digest(content), sep = '_') |
| 93 |
params$hash = hash |
| 94 |
if (cache$exists(hash, params$cache.lazy) && |
| 95 |
isFALSE(params$cache.rebuild) && |
| 96 |
params$engine != 'Rcpp') { |
| 97 |
if (opts_knit$get('verbose')) message(' loading cache from ', hash) |
| 98 |
cache$load(hash, lazy = params$cache.lazy) |
| 99 |
cache_engine(params) |
| 100 |
if (!params$include) return('') |
| 101 |
if (params$cache == 3) return(cache$output(hash)) |
| 102 |
} |
| 103 |
if (params$engine == 'R') |
| 104 |
cache$library(params$cache.path, save = FALSE) # load packages |
| 105 |
} else if (label %in% names(dep_list$get()) && !isFALSE(opts_knit$get('warn.uncached.dep'))) |
| 106 |
warning2('code chunks must not depend on the uncached chunk "', label, '"') |
| 107 |
|
| 108 |
params$params.src = block$params.src |
| 109 |
opts_current$restore(params) # save current options |
| 110 |
# prevent users from modifying opts_current (#1798) |
| 111 |
opts_current$lock(); on.exit(opts_current$lock(FALSE), add = TRUE) |
| 112 |
|
| 113 |
# set local options() for the current R chunk |
| 114 |
if (is.list(params$R.options)) { |
| 115 |
op = options(params$R.options); on.exit(options(op), add = TRUE) |
| 116 |
} |
| 117 |
|
| 118 |
block_exec(params) |
| 119 |
} |
| 120 |
|
| 121 |
# if chunk option 'file' is provided, read the file(s) as the chunk body; |
| 122 |
# otherwise if 'code' is provided, use it; if neither 'file' nor 'code' is |
| 123 |
# provided, use the chunk body |
| 124 |
get_code = function(params, label, ref.label) { |
| 125 |
code = params[['code']]; file = params[['file']] |
| 126 |
if (is.null(code) && is.null(file)) |
| 127 |
return(unlist(knit_code$get(ref.label), use.names = FALSE)) |
| 128 |
if (!is.null(file)) code = in_input_dir(xfun::read_all(file)) |
| 129 |
set_code(label, code) |
| 130 |
code |
| 131 |
} |
| 132 |
|
| 133 |
# replace code in knit_code but preserve attributes |
| 134 |
set_code = function(label, code) { |
| 135 |
res = knit_code$get(label) |
| 136 |
attributes(code) = attributes(res) |
| 137 |
knit_code$set(setNames(list(code), label)) |
| 138 |
} |
| 139 |
|
| 140 |
# options that should affect cache when cache level = 1,2 |
| 141 |
cache1.opts = c('code', 'eval', 'cache', 'cache.path', 'cache.globals', 'message', 'warning', 'error') |
| 142 |
# more options affecting cache level 2 |
| 143 |
cache2.opts = c('fig.keep', 'fig.path', 'fig.ext', 'dev', 'dpi', 'dev.args', 'fig.width', 'fig.height') |
| 144 |
# options that should not affect cache |
| 145 |
cache0.opts = c('include', 'out.width.px', 'out.height.px', 'cache.rebuild') |
| 146 |
|
| 147 |
block_exec = function(options) { |
| 148 |
otel_active_span( |
| 149 |
name = 'knit', |
| 150 |
label = options$label, |
| 151 |
attributes = make_chunk_attributes(options), |
| 152 |
scope = environment() |
| 153 |
) |
| 154 |
|
| 155 |
if (options$engine == 'R') return(eng_r(options)) |
| 156 |
|
| 157 |
# when code is not R language |
| 158 |
res.before = run_hooks(before = TRUE, options) |
| 159 |
engine = get_engine(options$engine) |
| 160 |
# special case: quarto-dev/quarto-cli#5994 |
| 161 |
if (is_quarto() && options$engine %in% c('dot', 'mermaid', 'ojs')) { |
| 162 |
options$code = c(options$yaml.code, options$code) |
| 163 |
options$yaml.code = NULL |
| 164 |
} |
| 165 |
output = in_input_dir(engine(options)) |
| 166 |
if (is.list(output)) output = unlist(output) |
| 167 |
res.after = run_hooks(before = FALSE, options) |
| 168 |
output = paste(c(res.before, output, res.after), collapse = '') |
| 169 |
output = knit_hooks$get('chunk')(output, options) |
| 170 |
if (options$cache) { |
| 171 |
cache.exists = cache$exists(options$hash, options$cache.lazy) |
| 172 |
if (options$cache.rebuild || !cache.exists) block_cache(options, output, switch( |
| 173 |
options$engine, |
| 174 |
'stan' = options$output.var, 'sql' = options$output.var, character(0) |
| 175 |
)) |
| 176 |
} |
| 177 |
if (options$include) output else '' |
| 178 |
} |
| 179 |
|
| 180 |
#' Engine for R |
| 181 |
#' |
| 182 |
#' This function handles the execution of R code blocks (when the chunk option |
| 183 |
#' \code{engine} is \code{'R'}) and generates the R output for each code block. |
| 184 |
#' |
| 185 |
#' This engine function has one argument \code{options}: the source code of the |
| 186 |
#' current chunk is in \code{options$code}. It returns a processed output that |
| 187 |
#' can consist of data frames (as tables), graphs, or character output. This |
| 188 |
#' function is intended for advanced use to allow developers to extend R, and |
| 189 |
#' customize the pipeline with which R code is executed and processed within |
| 190 |
#' knitr. |
| 191 |
#' |
| 192 |
#' @param options A list of chunk options. Usually this is just the object |
| 193 |
#' \code{options} associated with the current code chunk. |
| 194 |
#' @noRd |
| 195 |
eng_r = function(options) { |
| 196 |
# eval chunks (in an empty envir if cache) |
| 197 |
env = knit_global() |
| 198 |
obj.before = ls(globalenv(), all.names = TRUE) # global objects before chunk |
| 199 |
|
| 200 |
keep = options$fig.keep |
| 201 |
keep.idx = NULL |
| 202 |
if (is.logical(keep)) keep = which(keep) |
| 203 |
if (is.numeric(keep)) { |
| 204 |
keep.idx = keep |
| 205 |
keep = "index" |
| 206 |
} |
| 207 |
|
| 208 |
if (keep.pars <- opts_knit$get('global.par')) on.exit({ |
| 209 |
opts_knit$set(global.pars = par(no.readonly = TRUE)) |
| 210 |
}, add = TRUE) |
| 211 |
|
| 212 |
tmp.fig = tempfile(); on.exit(unlink(tmp.fig), add = TRUE) |
| 213 |
# open a device to record plots if not using a global device or no device is |
| 214 |
# open, and close this device if we don't want to use a global device |
| 215 |
if (!opts_knit$get('global.device') || is.null(dev.list())) { |
| 216 |
# reset current device if any is open (#2166) |
| 217 |
if (!is.null(dev.list())) { |
| 218 |
dv0 = dev.cur(); on.exit(dev.set(dv0), add = TRUE) |
| 219 |
} |
| 220 |
chunk_device(options, keep != 'none', tmp.fig) |
| 221 |
dv = dev.cur() |
| 222 |
if (!opts_knit$get('global.device')) on.exit(dev.off(dv), add = TRUE) |
| 223 |
showtext(options) # showtext support |
| 224 |
} |
| 225 |
# preserve par() settings from the last code chunk |
| 226 |
if (keep.pars) par2(opts_knit$get('global.pars')) |
| 227 |
|
| 228 |
res.before = run_hooks(before = TRUE, options, env) # run 'before' hooks |
| 229 |
|
| 230 |
code = options$code |
| 231 |
echo = options$echo # tidy code if echo |
| 232 |
if (!isFALSE(echo) && !isFALSE(options$tidy) && length(code)) { |
| 233 |
tidy.method = if (isTRUE(options$tidy)) 'formatR' else options$tidy |
| 234 |
if (is.character(tidy.method)) tidy.method = switch( |
| 235 |
tidy.method, |
| 236 |
formatR = function(code, ...) { |
| 237 |
if (!loadable('formatR')) stop2( |
| 238 |
'The formatR package is required by the chunk option tidy = TRUE but ', |
| 239 |
'not installed; tidy = TRUE will be ignored.' |
| 240 |
) |
| 241 |
formatR::tidy_source(text = code, output = FALSE, ...)$text.tidy |
| 242 |
}, |
| 243 |
styler = function(code, ...) unclass(styler::style_text(text = code, ...)) |
| 244 |
) |
| 245 |
res = try_silent(do.call(tidy.method, c(list(code), options$tidy.opts))) |
| 246 |
|
| 247 |
if (!inherits(res, 'try-error')) code = res else warning( |
| 248 |
"Failed to tidy R code in chunk '", options$label, "'. Reason:\n", res |
| 249 |
) |
| 250 |
} |
| 251 |
# only evaluate certain lines |
| 252 |
if (is.numeric(ev <- options$eval)) { |
| 253 |
# group source code into syntactically complete expressions |
| 254 |
if (isFALSE(options$tidy)) code = sapply(xfun::split_source(code), one_string) |
| 255 |
iss = seq_along(code) |
| 256 |
code = comment_out(code, '##', setdiff(iss, iss[ev]), newline = FALSE) |
| 257 |
} |
| 258 |
# guess plot file type if it is NULL |
| 259 |
if (keep != 'none') options$fig.ext = dev2ext(options) |
| 260 |
|
| 261 |
cache.exists = cache$exists(options$hash, options$cache.lazy) |
| 262 |
evaluate = knit_hooks$get('evaluate') |
| 263 |
# return code with class 'source' if not eval chunks |
| 264 |
res = if (is_blank(code)) list() else if (isFALSE(ev)) { |
| 265 |
as.source(code) |
| 266 |
} else if (cache.exists && isFALSE(options$cache.rebuild)) { |
| 267 |
cache$output(options$hash, 'list') |
| 268 |
} else in_input_dir( |
| 269 |
evaluate( |
| 270 |
code, envir = env, new_device = FALSE, |
| 271 |
keep_warning = if (is.numeric(options$warning)) TRUE else options$warning, |
| 272 |
keep_message = if (is.numeric(options$message)) TRUE else options$message, |
| 273 |
stop_on_error = if (is.numeric(options$error)) options$error else { |
| 274 |
if (options$error && options$include) 0L else 2L |
| 275 |
}, |
| 276 |
output_handler = knit_handlers(options$render, options) |
| 277 |
) |
| 278 |
) |
| 279 |
if (options$cache %in% 1:2 && (!cache.exists || isTRUE(options$cache.rebuild))) { |
| 280 |
# make a copy for cache=1,2; when cache=2, we do not really need plots |
| 281 |
res.orig = if (options$cache == 2) remove_plot(res, keep == 'high') else res |
| 282 |
} |
| 283 |
|
| 284 |
# eval other options after the chunk |
| 285 |
if (!isFALSE(ev)) |
| 286 |
for (o in opts_knit$get('eval.after')) |
| 287 |
options[o] = list(eval_lang(options[[o]], env)) |
| 288 |
|
| 289 |
# remove some components according options |
| 290 |
if (isFALSE(echo)) { |
| 291 |
res = Filter(Negate(evaluate::is.source), res) |
| 292 |
} else if (is.numeric(echo)) { |
| 293 |
# choose expressions to echo using a numeric vector |
| 294 |
res = if (isFALSE(ev)) { |
| 295 |
as.source(code[echo]) |
| 296 |
} else { |
| 297 |
filter_evaluate(res, echo, evaluate::is.source) |
| 298 |
} |
| 299 |
} |
| 300 |
if (options$results == 'hide') res = Filter(Negate(is.character), res) |
| 301 |
if (options$results == 'hold') { |
| 302 |
i = vapply(res, is.character, logical(1)) |
| 303 |
if (any(i)) res = c(res[!i], merge_character(res[i])) |
| 304 |
} |
| 305 |
res = filter_evaluate(res, options$warning, evaluate::is.warning) |
| 306 |
res = filter_evaluate(res, options$message, evaluate::is.message) |
| 307 |
|
| 308 |
# rearrange locations of figures |
| 309 |
res = rearrange_figs(res, keep, keep.idx, options$fig.show) |
| 310 |
|
| 311 |
# number of plots in this chunk |
| 312 |
if (is.null(options$fig.num)) |
| 313 |
options$fig.num = if (length(res)) sum(sapply(res, function(x) { |
| 314 |
if (inherits(x, 'knit_image_paths')) return(length(x)) |
| 315 |
if (is_plot_output(x)) return(1) |
| 316 |
0 |
| 317 |
})) else 0L |
| 318 |
|
| 319 |
# merge neighbor elements of the same class into one element |
| 320 |
for (cls in c('source', 'message', 'warning')) res = merge_class(res, cls) |
| 321 |
|
| 322 |
if (isTRUE(options$fig.beforecode)) res = fig_before_code(res) |
| 323 |
|
| 324 |
on.exit({ |
| 325 |
plot_counter(reset = TRUE) |
| 326 |
shot_counter(reset = TRUE) |
| 327 |
opts_knit$delete('plot_files') |
| 328 |
}, add = TRUE) # restore plot number |
| 329 |
|
| 330 |
output = unlist(sew(res, options)) # wrap all results together |
| 331 |
res.after = run_hooks(before = FALSE, options, env) # run 'after' hooks |
| 332 |
|
| 333 |
output = paste(c(res.before, output, res.after), collapse = '') # insert hook results |
| 334 |
output = knit_hooks$get('chunk')(output, options) |
| 335 |
|
| 336 |
if (options$cache > 0) { |
| 337 |
# if cache.vars has been specifically provided, only cache these vars and no |
| 338 |
# need to look for objects in globalenv() |
| 339 |
obj.new = if (is.null(options$cache.vars)) setdiff(ls(globalenv(), all.names = TRUE), obj.before) |
| 340 |
copy_env(globalenv(), env, obj.new) |
| 341 |
objs = if (isFALSE(ev) || length(code) == 0) character(0) else |
| 342 |
options$cache.vars %n% xfun::find_locals(code) |
| 343 |
# make sure all objects to be saved exist in env |
| 344 |
objs = intersect(c(objs, obj.new), ls(env, all.names = TRUE)) |
| 345 |
if (options$autodep) { |
| 346 |
# you shall manually specify global object names if find_symbols() is not reliable |
| 347 |
cache$objects( |
| 348 |
objs, cache_globals(options$cache.globals, code), options$label, |
| 349 |
options$cache.path |
| 350 |
) |
| 351 |
if (isTRUE(opts_knit$get('autodep.initialized'))) { |
| 352 |
dep_auto(labels = options$label) |
| 353 |
} else { |
| 354 |
dep_auto(labels = all_labels()) |
| 355 |
opts_knit$set(autodep.initialized = TRUE) |
| 356 |
} |
| 357 |
} |
| 358 |
if (options$cache < 3) { |
| 359 |
if (options$cache.rebuild || !cache.exists) block_cache(options, res.orig, objs) |
| 360 |
} else block_cache(options, output, objs) |
| 361 |
} |
| 362 |
|
| 363 |
if (options$include) output else if (is.null(s <- options$indent)) '' else s |
| 364 |
} |
| 365 |
|
| 366 |
block_cache = function(options, output, objects) { |
| 367 |
hash = options$hash |
| 368 |
outname = cache_output_name(hash) |
| 369 |
assign(outname, output, envir = knit_global()) |
| 370 |
purge_cache(options) |
| 371 |
cache$library(options$cache.path, save = TRUE) |
| 372 |
cache$save(objects, outname, hash, lazy = options$cache.lazy) |
| 373 |
} |
| 374 |
|
| 375 |
purge_cache = function(options) { |
| 376 |
# purge my old cache and cache of chunks dependent on me |
| 377 |
cache$purge(paste0(valid_path( |
| 378 |
options$cache.path, c(options$label, dep_list$get(options$label)) |
| 379 |
), '_????????????????????????????????')) |
| 380 |
} |
| 381 |
|
| 382 |
cache_globals = function(option, code) { |
| 383 |
if (is.character(option)) option else { |
| 384 |
if (isFALSE(option)) find_symbols(code) else xfun::find_globals(code, knit_global()) |
| 385 |
} |
| 386 |
} |
| 387 |
|
| 388 |
# open a graphical device for a chunk to record plots |
| 389 |
chunk_device = function(options, record = TRUE, tmp = tempfile()) { |
| 390 |
width = options$fig.width[1L] |
| 391 |
height = options$fig.height[1L] |
| 392 |
dev = fallback_dev(options$dev) |
| 393 |
dev.args = options$dev.args |
| 394 |
dpi = options$dpi |
| 395 |
|
| 396 |
# actually I should adjust the recording device according to dev, but here I |
| 397 |
# have only considered devices like png and tikz (because the measurement |
| 398 |
# results can be very different especially with the latter, see #1066), the |
| 399 |
# cairo_pdf device (#1235), and svg (#1705) |
| 400 |
if (identical(dev, 'png')) { |
| 401 |
do.call(grDevices::png, c(list( |
| 402 |
filename = tmp, width = width, height = height, units = 'in', res = dpi |
| 403 |
), get_dargs(dev.args, 'png'))) |
| 404 |
} else if (identical(dev, 'ragg_png')) { |
| 405 |
do.call(ragg_png_dev, c(list( |
| 406 |
filename = tmp, width = width, height = height, units = 'in', res = dpi |
| 407 |
), get_dargs(dev.args, 'ragg_png'))) |
| 408 |
} else if (identical(dev, 'tikz')) { |
| 409 |
dargs = c(list( |
| 410 |
file = tmp, width = width, height = height |
| 411 |
), get_dargs(dev.args, 'tikz')) |
| 412 |
dargs$sanitize = options$sanitize; dargs$standAlone = options$external |
| 413 |
if (is.null(dargs$verbose)) dargs$verbose = FALSE |
| 414 |
do.call(tikz_dev, dargs) |
| 415 |
} else if (identical(dev, 'cairo_pdf')) { |
| 416 |
do.call(grDevices::cairo_pdf, c(list( |
| 417 |
filename = tmp, width = width, height = height |
| 418 |
), get_dargs(dev.args, 'cairo_pdf'))) |
| 419 |
} else if (identical(dev, 'svg')) { |
| 420 |
do.call(grDevices::svg, c(list( |
| 421 |
filename = tmp, width = width, height = height |
| 422 |
), get_dargs(dev.args, 'svg'))) |
| 423 |
} else if (identical(dev, 'svglite')) { |
| 424 |
do.call(svglite::svglite, c(list( |
| 425 |
filename = tmp, width = width, height = height |
| 426 |
), get_dargs(dev.args, 'svglite'))) |
| 427 |
} else if (identical(getOption('device'), pdf_null)) { |
| 428 |
if (!is.null(dev.args)) { |
| 429 |
dev.args = get_dargs(dev.args, 'pdf') |
| 430 |
dev.args = dev.args[intersect(names(dev.args), names(formals(pdf)))] |
| 431 |
} |
| 432 |
do.call(pdf_null, c(list(width = width, height = height), dev.args)) |
| 433 |
} else dev.new(width = width, height = height) |
| 434 |
dev.control(displaylist = if (record) 'enable' else 'inhibit') |
| 435 |
} |
| 436 |
|
| 437 |
# fall back to a usable device (e.g., during R CMD check) |
| 438 |
fallback_dev = function(dev) { |
| 439 |
if (length(dev) != 1 || !getOption('knitr.device.fallback', is_R_CMD_check())) |
| 440 |
return(dev) |
| 441 |
choices = list( |
| 442 |
svg = c('png', 'jpeg', 'bmp'), cairo_pdf = c('pdf'), cairo_ps = c('postscript'), |
| 443 |
png = c('jpeg', 'svg', 'bmp'), jpeg = c('png', 'svg', 'bmp') |
| 444 |
) |
| 445 |
# add choices provided by users |
| 446 |
choices = merge_list(choices, getOption('knitr.device.choices')) |
| 447 |
if (!dev %in% names(choices)) return(dev) # no fallback devices available |
| 448 |
# first test if the specified device actually works |
| 449 |
if (dev_available(dev)) return(dev) |
| 450 |
for (d in choices[[dev]]) if (dev_available(d)) { |
| 451 |
warning2("The device '", dev, "' is not operational; falling back to '", d, "'.") |
| 452 |
return(d) |
| 453 |
} |
| 454 |
dev # no fallback device found; you'll to run into an error soon |
| 455 |
} |
| 456 |
|
| 457 |
# filter out some results based on the numeric chunk option as indices |
| 458 |
filter_evaluate = function(res, opt, test) { |
| 459 |
if (length(res) == 0 || !is.numeric(opt) || !any(idx <- sapply(res, test))) |
| 460 |
return(res) |
| 461 |
idx = which(idx) |
| 462 |
idx = setdiff(idx, na.omit(idx[opt])) # indices of elements to remove |
| 463 |
if (length(idx) == 0) res else res[-idx] |
| 464 |
} |
| 465 |
|
| 466 |
# find recorded plots in the output of evaluate() |
| 467 |
find_recordedplot = function(x) { |
| 468 |
vapply(x, is_plot_output, logical(1)) |
| 469 |
} |
| 470 |
|
| 471 |
is_plot_output = function(x) { |
| 472 |
evaluate::is.recordedplot(x) || |
| 473 |
inherits(x, c('knit_image_paths', 'html_screenshot', 'knit_other_plot')) |
| 474 |
} |
| 475 |
|
| 476 |
# move plots before source code |
| 477 |
fig_before_code = function(x) { |
| 478 |
s = vapply(x, evaluate::is.source, logical(1)) |
| 479 |
if (length(s) == 0 || !any(s)) return(x) |
| 480 |
s = which(s) |
| 481 |
f = which(find_recordedplot(x)) |
| 482 |
f = f[f >= min(s)] # only move those plots after the first code block |
| 483 |
for (i in f) { |
| 484 |
j = max(s[s < i]) |
| 485 |
tmp = x[i]; x[[i]] = NULL; x = append(x, tmp, j - 1) |
| 486 |
s = which(vapply(x, evaluate::is.source, logical(1))) |
| 487 |
} |
| 488 |
x |
| 489 |
} |
| 490 |
|
| 491 |
rearrange_figs = function(res, keep, idx, show) { |
| 492 |
figs = find_recordedplot(res) |
| 493 |
if (!any(figs)) return(res) # no figures |
| 494 |
if (keep == 'none') return(res[!figs]) # remove all |
| 495 |
|
| 496 |
if (show == 'hold') { |
| 497 |
res = c(res[!figs], res[figs]) # move to the end |
| 498 |
figs = find_recordedplot(res) |
| 499 |
} |
| 500 |
if (sum(figs) <= 1) return(res) # return early if only 1 figure to keep |
| 501 |
switch( |
| 502 |
keep, |
| 503 |
first = res[-tail(which(figs), -1L)], |
| 504 |
last = res[-head(which(figs), -1L)], |
| 505 |
high = merge_low_plot(res, figs), # merge low-level plotting changes |
| 506 |
index = { |
| 507 |
i = which(figs)[-idx] |
| 508 |
if (length(i) > 0) res[-i] else res # keep only selected |
| 509 |
}, |
| 510 |
res |
| 511 |
) |
| 512 |
} |
| 513 |
|
| 514 |
# merge neighbor elements of the same class in a list returned by evaluate() |
| 515 |
merge_class = function(res, class = c('source', 'message', 'warning')) { |
| 516 |
|
| 517 |
class = match.arg(class) |
| 518 |
idx = if (length(res)) which(sapply(res, inherits, what = class)) |
| 519 |
if ((n <- length(idx)) <= 1) return(res) |
| 520 |
|
| 521 |
k1 = idx[1]; k2 = NULL; res1 = res[[k1]] |
| 522 |
el = c(source = 'src', message = 'message', warning = 'message')[class] |
| 523 |
for (i in 1:(n - 1)) { |
| 524 |
idx2 = idx[i + 1]; idx1 = idx[i] |
| 525 |
if (idx2 - idx1 == 1) { |
| 526 |
res2 = res[[idx2]] |
| 527 |
# merge warnings/messages only if next one is identical to previous one |
| 528 |
if (class == 'source' || identical(res1, res2) || |
| 529 |
(class == 'message' && !grepl('\n$', tail(res1[[el]], 1)))) { |
| 530 |
res[[k1]][[el]] = c(res[[k1]][[el]], res2[[el]]) |
| 531 |
k2 = c(k2, idx2) |
| 532 |
} else { |
| 533 |
k1 = idx2 |
| 534 |
res1 = res[[k1]] |
| 535 |
} |
| 536 |
} else k1 = idx2 |
| 537 |
} |
| 538 |
if (length(k2)) res = res[-k2] # remove lines that have been merged back |
| 539 |
res |
| 540 |
|
| 541 |
} |
| 542 |
|
| 543 |
# merge character output for output='hold', if the subsequent character is of |
| 544 |
# the same class(es) as the previous one (e.g. should not merge normal |
| 545 |
# characters with asis_output()) |
| 546 |
merge_character = function(res) { |
| 547 |
if ((n <- length(res)) <= 1) return(res) |
| 548 |
k = NULL |
| 549 |
for (i in 1:(n - 1)) { |
| 550 |
cls = class(res[[i]]) |
| 551 |
if (identical(cls, class(res[[i + 1]]))) { |
| 552 |
res[[i + 1]] = paste0(res[[i]], res[[i + 1]]) |
| 553 |
class(res[[i + 1]]) = cls |
| 554 |
k = c(k, i) |
| 555 |
} |
| 556 |
} |
| 557 |
if (length(k)) res = res[-k] |
| 558 |
res |
| 559 |
} |
| 560 |
|
| 561 |
call_inline = function(block) { |
| 562 |
optc = opts_current$get(); on.exit(opts_current$restore(optc), add = TRUE) |
| 563 |
params = opts_chunk$merge(list(label = unnamed_chunk())) |
| 564 |
opts_current$restore(params) |
| 565 |
if (opts_knit$get('progress')) print_inline(block) |
| 566 |
in_input_dir(inline_exec(block)) |
| 567 |
} |
| 568 |
|
| 569 |
inline_exec = function( |
| 570 |
block, envir = knit_global(), hook = knit_hooks$get('inline'), |
| 571 |
hook_eval = knit_hooks$get('evaluate.inline') |
| 572 |
) { |
| 573 |
|
| 574 |
# run inline code and substitute original texts |
| 575 |
code = block$code; input = block$input |
| 576 |
if ((n <- length(code)) == 0) return(input) # untouched if no code is found |
| 577 |
code.src = block$code.src |
| 578 |
lines = block$lines |
| 579 |
|
| 580 |
ans = character(n) |
| 581 |
for (i in 1:n) { |
| 582 |
knit_concord$set(offset = lines[i, ]) |
| 583 |
tryCatch(parse_only(code[i]), error = function(e) { |
| 584 |
stop2('Failed to parse the inline R code: ', code.src[i], '\nReason: ', e$message) |
| 585 |
}) |
| 586 |
res = hook_eval(code[i], envir) |
| 587 |
if (inherits(res, c('knit_asis', 'knit_asis_url'))) res = sew(res, inline = TRUE) |
| 588 |
tryCatch(as.character(res), error = function(e) { |
| 589 |
stop2("The inline value cannot be coerced to character: ", code[i]) |
| 590 |
}) |
| 591 |
if (length(res)) ans[i] = paste(hook(res), collapse = '') |
| 592 |
} |
| 593 |
# replace with evaluated results |
| 594 |
str_replace(input, block$location, ans) |
| 595 |
} |
| 596 |
|
| 597 |
process_tangle = function(x) { |
| 598 |
if (inherits(x, 'block')) tangle_block(x) else tangle_inline(x) |
| 599 |
} |
| 600 |
|
| 601 |
tangle_block = function(x) { |
| 602 |
params = opts_chunk$merge(x$params) |
| 603 |
for (o in c('purl', 'eval', 'child')) { |
| 604 |
if (inherits(try(params[o] <- list(eval_lang(params[[o]]))), 'try-error')) { |
| 605 |
params[['purl']] = FALSE # if any of these options cannot be determined, don't purl |
| 606 |
} |
| 607 |
} |
| 608 |
if (isFALSE(params$purl)) return('') |
| 609 |
label = params$label; ev = params$eval |
| 610 |
if (params$engine != 'R') return( |
| 611 |
one_string(comment_out(knit_code$get(label), params$comment, newline = FALSE)) |
| 612 |
) |
| 613 |
code = if (!isFALSE(ev) && !is.null(params$child)) { |
| 614 |
cmds = lapply(sc_split(params$child), knit_child) |
| 615 |
one_string(unlist(cmds)) |
| 616 |
} else knit_code$get(label) |
| 617 |
# read external code if exists |
| 618 |
if (!isFALSE(ev) && length(code) && any(grepl('read_chunk\\(.+\\)', code))) { |
| 619 |
eval(parse_only(unlist(str_extract(code, 'read_chunk\\(([^)]+)\\)')))) |
| 620 |
} |
| 621 |
code = parse_chunk(code) |
| 622 |
code = tangle_mask(code, ev, x$params$error) |
| 623 |
if (opts_knit$get('documentation') == 0L) return(one_string(code)) |
| 624 |
# e.g. when documentation 1 or 2 with purl() |
| 625 |
label_code(code, x) |
| 626 |
} |
| 627 |
|
| 628 |
tangle_mask = function(code, eval, error) { |
| 629 |
if (isFALSE(eval)) code = comment_out(code, '#', newline = FALSE) |
| 630 |
if (isTRUE(error)) code = c('try({', code, '})') |
| 631 |
code |
| 632 |
} |
| 633 |
|
| 634 |
tangle_inline = function(x) { |
| 635 |
output = if (opts_knit$get('documentation') == 2L) { |
| 636 |
output = paste("#'", gsub('\n', "\n#' ", x$input, fixed = TRUE)) |
| 637 |
} else '' |
| 638 |
|
| 639 |
code = x$code |
| 640 |
if (length(code) == 0L) return(output) |
| 641 |
|
| 642 |
if (getOption('knitr.purl.inline', FALSE)) output = c(output, code) |
| 643 |
|
| 644 |
idx = grepl('knit_child\\(.+\\)', code) |
| 645 |
if (any(idx)) { |
| 646 |
cout = sapply(code[idx], function(z) eval(parse_only(z))) |
| 647 |
output = c(output, cout, '') |
| 648 |
} |
| 649 |
|
| 650 |
one_string(output) |
| 651 |
} |
| 652 |
|
| 653 |
|
| 654 |
# add a label [and extra chunk options] to a code chunk |
| 655 |
label_code = function(code, options) { |
| 656 |
comments = paste0( |
| 657 |
'## ----', options$params.src, |
| 658 |
strrep('-', max(getOption('width') - 11L - nchar(options$params.src), 0L)), |
| 659 |
'----' |
| 660 |
) |
| 661 |
one_string(c(comments, options$params.chunk, code, '')) |
| 662 |
} |
| 663 |
|
| 664 |
as.source = function(code) { |
| 665 |
list(structure(list(src = code), class = 'source')) |
| 666 |
} |