| 1 |
# copy objects in one environment to the other |
| 2 |
copy_env = function(from, to, keys = ls(envir = from, all.names = TRUE)) { |
| 3 |
if (identical(from, to)) return() |
| 4 |
for (i in keys) assign(i, get(i, envir = from, inherits = FALSE), envir = to) |
| 5 |
} |
| 6 |
|
| 7 |
|
| 8 |
knit_counter = function(init = 0L) { |
| 9 |
n = init |
| 10 |
function(reset = FALSE) { |
| 11 |
if (reset) return(n <<- init) |
| 12 |
n <<- n + 1L |
| 13 |
n - 1L |
| 14 |
} |
| 15 |
} |
| 16 |
|
| 17 |
plot_counter = knit_counter(1L) |
| 18 |
shot_counter = knit_counter(1L) |
| 19 |
chunk_counter = knit_counter(1L) |
| 20 |
|
| 21 |
# a vectorized and better version than evaluate:::line_prompt |
| 22 |
line_prompt = function(x, prompt = getOption('prompt'), continue = getOption('continue')) { |
| 23 |
# match a \n, then followed by any character (use zero width assertion) |
| 24 |
paste0(prompt, gsub('(?<=\n)(?=.|\n)', continue, x, perl = TRUE)) |
| 25 |
} |
| 26 |
|
| 27 |
# add a prefix to output |
| 28 |
comment_out = function(x, prefix = '##', which = TRUE, newline = TRUE) { |
| 29 |
x = gsub('[\n]{2,}$', '\n', x) |
| 30 |
if (newline) x = gsub('([^\n]|^)$', '\\1\n', x) # add \n if not exists |
| 31 |
if (is.null(prefix) || !nzchar(prefix) || is.na(prefix)) return(x) |
| 32 |
prefix = paste(prefix, '') |
| 33 |
x = gsub(' +([\n]*)$', '\\1', x) |
| 34 |
x[which] = line_prompt(x[which], prompt = prefix, continue = prefix) |
| 35 |
x |
| 36 |
} |
| 37 |
|
| 38 |
# assign string in comments to a global variable |
| 39 |
comment_to_var = function(x, varname, pattern, envir) { |
| 40 |
if (grepl(pattern, x)) { |
| 41 |
assign(varname, sub(pattern, '', x), envir = envir) |
| 42 |
return(TRUE) |
| 43 |
} |
| 44 |
FALSE |
| 45 |
} |
| 46 |
|
| 47 |
is_blank = function(x) { |
| 48 |
if (length(x)) all(grepl('^\\s*$', x)) else TRUE |
| 49 |
} |
| 50 |
|
| 51 |
attr = function(...) base::attr(..., exact = TRUE) |
| 52 |
|
| 53 |
valid_path = function(prefix, label) { |
| 54 |
if (length(prefix) == 0L || is.na(prefix) || prefix == 'NA') prefix = '' |
| 55 |
paste0(prefix, label) |
| 56 |
} |
| 57 |
|
| 58 |
# define a color variable in TeX |
| 59 |
color_def = function(col, variable = 'shadecolor') { |
| 60 |
if (all(is.na(col))) return('') # no LaTeX code when color is NA |
| 61 |
x = if (length(col) == 1L) sc_split(col) else col |
| 62 |
if ((n <- length(x)) != 3L) { |
| 63 |
if (n == 1L) x = drop(col2rgb(x) / 255) else { |
| 64 |
x = switch(variable, shadecolor = rep(.97, 3), fgcolor = rep(0, 3)) |
| 65 |
warning("the color '", col, "' is invalid;", |
| 66 |
'using default color...', |
| 67 |
'see https://yihui.org/knitr/options/') |
| 68 |
} |
| 69 |
} |
| 70 |
if (length(x) != 3L) stop('invalid color:', col) |
| 71 |
if (is.numeric(x)) x = round(x, 3L) |
| 72 |
xfun::decimal_dot( |
| 73 |
sprintf('\\definecolor{%s}{rgb}{%s, %s, %s}', variable, x[1], x[2], x[3]) |
| 74 |
) |
| 75 |
} |
| 76 |
|
| 77 |
# split by semicolon or colon |
| 78 |
sc_split = function(string) { |
| 79 |
if (is.call(string)) string = eval(string) |
| 80 |
if (is.numeric(string) || length(string) != 1L) return(string) |
| 81 |
trimws(strsplit(string, ';|,')[[1]]) |
| 82 |
} |
| 83 |
|
| 84 |
# extract LaTeX packages for tikzDevice |
| 85 |
set_preamble = function(input, patterns = knit_patterns$get()) { |
| 86 |
if (!out_format('latex')) return() |
| 87 |
.knitEnv$tikzPackages = .knitEnv$bibliography = NULL |
| 88 |
if (length(db <- patterns$document.begin) != 1L) return() # no \begin{document} pattern |
| 89 |
if (length(hb <- patterns$header.begin) != 1L) return() # no \documentclass{} pattern |
| 90 |
idx2 = grep(db, input)[1] |
| 91 |
if (is.na(idx2) || idx2 < 2L) return() |
| 92 |
idx1 = grep(hb, input)[1] |
| 93 |
if (is.na(idx1) || idx1 >= idx2) return() |
| 94 |
txt = one_string(input[idx1:(idx2 - 1L)]) # rough preamble |
| 95 |
idx = str_locate(txt, hb, FALSE) # locate documentclass |
| 96 |
options(tikzDocumentDeclaration = substr(txt, idx[, 1L], idx[, 2L])) |
| 97 |
preamble = pure_preamble(split_lines(substr(txt, idx[, 2L] + 1L, nchar(txt))), patterns) |
| 98 |
.knitEnv$tikzPackages = c(.header.sweave.cmd, preamble, '\n') |
| 99 |
.knitEnv$bibliography = grep('^\\\\bibliography.+', input, value = TRUE) |
| 100 |
} |
| 101 |
# filter out code chunks from preamble if they exist (they do in LyX/Sweave) |
| 102 |
pure_preamble = function(preamble, patterns) { |
| 103 |
res = split_file(lines = preamble, set.preamble = FALSE, patterns) # should avoid recursion |
| 104 |
if (!parent_mode()) { |
| 105 |
# when not in parent mode, just return normal texts and skip code |
| 106 |
return(unlist(res)) |
| 107 |
} |
| 108 |
owd = setwd(input_dir()); on.exit(setwd(owd)) |
| 109 |
progress = opts_knit$get('progress') # suppress printing of blocks and texts |
| 110 |
opts_knit$set(progress = FALSE); on.exit(opts_knit$set(progress = progress), add = TRUE) |
| 111 |
# run the code in the preamble |
| 112 |
sapply(res, if (opts_knit$get('tangle')) process_tangle else process_group) |
| 113 |
} |
| 114 |
|
| 115 |
#' Specify the parent document of child documents |
| 116 |
#' |
| 117 |
#' This function extracts the LaTeX preamble of the parent document to use for |
| 118 |
#' the child document, so that the child document can be compiled as an |
| 119 |
#' individual document. |
| 120 |
#' |
| 121 |
#' When the preamble of the parent document also contains code chunks and inline |
| 122 |
#' R code, they will be evaluated as if they were in this child document. For |
| 123 |
#' examples, when \pkg{knitr} hooks or other options are set in the preamble of |
| 124 |
#' the parent document, it will apply to the child document as well. |
| 125 |
#' @param parent Path to the parent document, relative to the current child |
| 126 |
#' document. |
| 127 |
#' @return The preamble is extracted and stored to be used later when the |
| 128 |
#' complete output is written. |
| 129 |
#' @note Obviously this function is only useful when the output format is LaTeX. |
| 130 |
#' This function only works when the child document is compiled in a |
| 131 |
#' standalone mode using \code{\link{knit}()} (instead of being called in |
| 132 |
#' \code{\link{knit_child}()}); when the parent document is compiled, this |
| 133 |
#' function in the child document will be ignored. |
| 134 |
#' @references \url{https://yihui.org/knitr/demo/child/} |
| 135 |
#' @export |
| 136 |
#' @examples ## can use, e.g. \Sexpr{set_parent('parent_doc.Rnw')} or |
| 137 |
#' |
| 138 |
#' # <<setup-child, include=FALSE>>= |
| 139 |
#' |
| 140 |
#' # set_parent('parent_doc.Rnw') |
| 141 |
#' |
| 142 |
#' # @@ |
| 143 |
set_parent = function(parent) { |
| 144 |
if (child_mode()) return(invisible(NULL)) # quit if in child mode |
| 145 |
opts_knit$set(parent = TRUE) |
| 146 |
set_preamble(read_utf8(parent)) |
| 147 |
invisible(NULL) |
| 148 |
} |
| 149 |
|
| 150 |
# whether to write results as-is? |
| 151 |
output_asis = function(x, options) { |
| 152 |
is_blank(x) || identical(options$results, 'asis') |
| 153 |
} |
| 154 |
|
| 155 |
# the working directory: use root.dir if specified, otherwise the dir of the |
| 156 |
# input file unless knitr.use.cwd = TRUE |
| 157 |
input_dir = function() { |
| 158 |
root = opts_knit$get('root.dir') |
| 159 |
root %n% (if (!getOption('knitr.use.cwd', FALSE)) .knitEnv$input.dir) %n% '.' |
| 160 |
} |
| 161 |
|
| 162 |
# eval expr under the input dir |
| 163 |
in_input_dir = function(expr) in_dir(input_dir(), expr) |
| 164 |
|
| 165 |
# detect if running on CRAN (assuming that CRAN does not set CI or |
| 166 |
# NOT_CRAN=true); or set R_CRANDALF=true (is cran) or false (not cran) |
| 167 |
is_cran = function() { |
| 168 |
x = Sys.getenv('R_CRANDALF', NA) |
| 169 |
if (!is.na(x)) tolower(x) == 'true' else { |
| 170 |
!any(tolower(Sys.getenv(c('CI', 'NOT_CRAN'))) == 'true') |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
is_cran_check = function() { |
| 175 |
is_cran() && is_R_CMD_check() |
| 176 |
} |
| 177 |
|
| 178 |
is_R_CMD_build = function() Sys.getenv('R_BUILD_TEMPLIB') != '' |
| 179 |
is_bioc = function() Sys.getenv('BBS_HOME') != '' |
| 180 |
|
| 181 |
# round a number to getOption('digits') decimal places by default, and format() |
| 182 |
# it using significant digits if the option knitr.digits.signif = TRUE |
| 183 |
round_digits = function(x) { |
| 184 |
if (getOption('knitr.digits.signif', FALSE)) format(x) else { |
| 185 |
as.character(round(x, getOption('digits'))) |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
# scientific notation in TeX, HTML and reST |
| 190 |
format_sci_one = function( |
| 191 |
x, format = 'latex', times = getOption('knitr.inline.times', '\\times ') |
| 192 |
) { |
| 193 |
|
| 194 |
if (!(class(x)[1] == 'numeric') || is.na(x) || x == 0) return(as.character(x)) |
| 195 |
|
| 196 |
if (is.infinite(x)) { |
| 197 |
return( |
| 198 |
switch(format, latex = { |
| 199 |
sprintf("%s\\infty{}", ifelse(x < 0, "-", "")) |
| 200 |
}, html = { |
| 201 |
sprintf("%s∞", ifelse(x < 0, "-", "")) |
| 202 |
}, as.character(x))) |
| 203 |
} |
| 204 |
|
| 205 |
if (abs(lx <- floor(log10(abs(x)))) < getOption('scipen') + 4L) |
| 206 |
return(round_digits(x)) # no need sci notation |
| 207 |
|
| 208 |
b = round_digits(x / 10^lx) |
| 209 |
|
| 210 |
switch(format, latex = { |
| 211 |
sci_notation('%s%s10^{%s}', b, times, lx) |
| 212 |
}, |
| 213 |
html = sci_notation('%s%s10<sup>%s</sup>', b, ' × ', lx), |
| 214 |
md = sci_notation('%s%s10^%s^', b, '× ', lx), |
| 215 |
rst = { |
| 216 |
# if AsIs, use the :math: directive |
| 217 |
if (inherits(x, 'AsIs')) { |
| 218 |
s = sci_notation('%s%s10^{%s}', b, times, lx) |
| 219 |
sprintf(':math:`%s`', s) |
| 220 |
} else { |
| 221 |
# This needs the following line at the top of the file to define |times| |
| 222 |
# .. include <isonum.txt> |
| 223 |
sci_notation('%s%s10 :sup:`%s`', b, ' |times| ', lx) |
| 224 |
} |
| 225 |
}, as.character(x)) |
| 226 |
} |
| 227 |
|
| 228 |
sci_notation = function(format, base, times, power) { |
| 229 |
if (base %in% c('1', '-1')) { |
| 230 |
times = '' |
| 231 |
base = if (base == '1') '' else '-' |
| 232 |
} |
| 233 |
sprintf(format, base, times, power) |
| 234 |
} |
| 235 |
|
| 236 |
# vectorized version of format_sci_one() |
| 237 |
format_sci = function(x, ...) { |
| 238 |
if (inherits(x, 'roman')) return(as.character(x)) |
| 239 |
vapply(x, format_sci_one, character(1L), ..., USE.NAMES = FALSE) |
| 240 |
} |
| 241 |
|
| 242 |
# is tikz device without externalization? |
| 243 |
is_tikz_dev = function(options) { |
| 244 |
'tikz' %in% options$dev && !options$external |
| 245 |
} |
| 246 |
|
| 247 |
tikz_dict = function(path) { |
| 248 |
paste(sans_ext(basename(path)), 'tikzDictionary', sep = '-') |
| 249 |
} |
| 250 |
|
| 251 |
# convert dashes in option names with dots (e.g., `fig-height` to `fig.height`), |
| 252 |
# and vice versa (dots work for knitr, and dashes for Quarto) |
| 253 |
fix_names = function(x, char1, char2, aliases) { |
| 254 |
name1 = grep(char1, names(x), value = TRUE, fixed = TRUE) |
| 255 |
name2 = gsub(char1, char2, name1, fixed = TRUE) |
| 256 |
name3 = c(names(opts_chunk_attr), names(opts_chunk$get())) |
| 257 |
# only convert names that are known to knitr |
| 258 |
i = (if (char1 == '.') name1 else name2) %in% name3 |
| 259 |
if (any(i)) { |
| 260 |
x[name2[i]] = x[name1[i]] # move values to to new names |
| 261 |
x[name1[i]] = NULL # delete old names |
| 262 |
} |
| 263 |
for (j in intersect(names(x), names(aliases))) { |
| 264 |
x[[aliases[j]]] = x[[j]] |
| 265 |
x[[j]] = NULL |
| 266 |
} |
| 267 |
x |
| 268 |
} |
| 269 |
|
| 270 |
dot_names = function(x) { |
| 271 |
fix_names(x, '-', '.', c(fig.format = 'dev', fig.dpi = 'dpi')) |
| 272 |
} |
| 273 |
|
| 274 |
dash_names = function(x) { |
| 275 |
fix_names(x, '.', '-', c(dev = 'fig-format', dpi = 'fig-dpi', tab.cap = 'tbl-cap')) |
| 276 |
} |
| 277 |
|
| 278 |
# initially for compatibility with Sweave and old beta versions of knitr |
| 279 |
# but now also place to tweak default options |
| 280 |
fix_options = function(options) { |
| 281 |
options = as.strict_list(options) |
| 282 |
|
| 283 |
# message/warning take logical or numeric values; if character, convert to logical |
| 284 |
for (i in c('message', 'warning')) { |
| 285 |
if (is.character(options[[i]])) options[[i]] = as.logical(options[[i]]) |
| 286 |
} |
| 287 |
# if you want to use subfloats, fig.show must be 'hold' |
| 288 |
if (length(options$fig.subcap)) options$fig.show = 'hold' |
| 289 |
# if the animation hook has been set, fig.show must be 'animate' |
| 290 |
if (!is.null(options$animation.hook)) options$fig.show = 'animate' |
| 291 |
# the default device NULL is not valid; use pdf is not set |
| 292 |
if (is.null(options$dev)) options$dev = 'pdf' |
| 293 |
# FALSE means hide for options$results |
| 294 |
if (isFALSE(options$results)) options$results = 'hide' |
| 295 |
|
| 296 |
# the figure/cache filenames may contain UTF-8 chars, which won't work on |
| 297 |
# Windows, e.g. png() fails if filename contains UTF-8 chars (must use native |
| 298 |
# encoding); in rmarkdown::render(input), basename(input) may implicitly |
| 299 |
# convert the encoding of the filename `input` to UTF-8 |
| 300 |
options$fig.path = native_encode(options$fig.path) |
| 301 |
options$cache.path = native_encode(options$cache.path) |
| 302 |
|
| 303 |
# cache=TRUE -> 3; FALSE -> 0 |
| 304 |
if (is.logical(options$cache)) options$cache = options$cache * 3 |
| 305 |
if (options$engine != 'R') { |
| 306 |
# non-R code should not use cache = 1, 2 |
| 307 |
options$cache = (options$cache > 0) * 3 |
| 308 |
# error numbers only make sense to R engine, so 0 -> TRUE; 1, 2 -> FALSE |
| 309 |
if (is.numeric(options$error)) options$error = options$error == 0 |
| 310 |
} |
| 311 |
|
| 312 |
options$eval = unname(options$eval) |
| 313 |
|
| 314 |
# handle aspect ratio/figure dimensions; give priority to fig.dim, with |
| 315 |
# warning (seems relatively more likely as user's intention in case when both |
| 316 |
# present) if aspect ratio is specified, calculate figure height |
| 317 |
fix_asp = is.numeric(options$fig.asp) |
| 318 |
if (length(options$fig.dim) == 2L) { |
| 319 |
if (fix_asp) warning('The chunk option fig.asp is ignored since fig.dim is provided.') |
| 320 |
options$fig.width = options$fig.dim[1L]; options$fig.height = options$fig.dim[2L] |
| 321 |
} else { |
| 322 |
if (fix_asp) options$fig.height = options$fig.width * options$fig.asp |
| 323 |
} |
| 324 |
|
| 325 |
# out.[width|height].px: unit in pixels for sizes |
| 326 |
for (i in c('width', 'height')) { |
| 327 |
options[[sprintf('out.%s.px', i)]] = options[[o <- sprintf('out.%s', i)]] %n% |
| 328 |
(options[[sprintf('fig.%s', i)]] * options$dpi) |
| 329 |
# turn x% to x/100\linewidth or \textheight |
| 330 |
if (is_latex_output()) options[o] = list(latex_percent_size(options[[o]], i)) |
| 331 |
} |
| 332 |
# for Retina displays, increase physical size, and decrease output size |
| 333 |
if (is.numeric(r <- options$fig.retina) && r != 1) { |
| 334 |
if (is.null(options[['out.width']])) { |
| 335 |
options$out.width = options$fig.width * options$dpi |
| 336 |
} |
| 337 |
options$dpi = options$dpi * r |
| 338 |
} else { |
| 339 |
options$fig.retina = 1 |
| 340 |
} |
| 341 |
|
| 342 |
# deal with aliases: a1 is real option; a0 is alias |
| 343 |
if (length(a1 <- opts_knit$get('aliases')) && length(a0 <- names(a1))) { |
| 344 |
for (i in seq_along(a1)) { |
| 345 |
# use alias only if the name exists in options |
| 346 |
if (a0[i] %in% names(options)) options[[a1[i]]] = options[[a0[i]]] |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
# adjust some options when collapse is TRUE |
| 351 |
if (options$collapse) { |
| 352 |
options[unlist(lapply( |
| 353 |
c('class.', 'attr.'), paste0, c('output', 'message', 'warning', 'error') |
| 354 |
))] = NULL |
| 355 |
} |
| 356 |
|
| 357 |
# change default of value conditionally |
| 358 |
if (identical(options$strip.white, I(TRUE))) |
| 359 |
options$strip.white = !options$collapse |
| 360 |
|
| 361 |
options |
| 362 |
} |
| 363 |
|
| 364 |
#' Check the current input and output type |
| 365 |
#' |
| 366 |
#' The function \code{is_latex_output()} returns \code{TRUE} when the output |
| 367 |
#' format is LaTeX; it works for both \file{.Rnw} and R Markdown documents (for |
| 368 |
#' the latter, the two Pandoc formats \code{latex} and \code{beamer} are |
| 369 |
#' considered LaTeX output). The function \code{is_html_output()} only works for |
| 370 |
#' R Markdown documents and will test for several Pandoc HTML based output |
| 371 |
#' formats (by default, these formats are considered as HTML formats: |
| 372 |
#' \code{c('markdown', 'epub', 'epub2', 'html', 'html4', 'html5', 'revealjs', 's5', |
| 373 |
#' 'slideous', 'slidy', 'gfm')}). |
| 374 |
#' |
| 375 |
#' The function \code{pandoc_to()} returns the Pandoc output format, and |
| 376 |
#' \code{pandoc_from()} returns Pandoc input format. \code{pandoc_to(fmt)} |
| 377 |
#' allows to check the current output format against a set of format names. Both |
| 378 |
#' are to be used with R Markdown documents. |
| 379 |
#' |
| 380 |
#' These functions may be useful for conditional output that depends on the |
| 381 |
#' output format. For example, you may write out a LaTeX table in an R Markdown |
| 382 |
#' document when the output format is LaTeX, and an HTML or Markdown table when |
| 383 |
#' the output format is HTML. Use \code{pandoc_to(fmt)} to test a more specific |
| 384 |
#' Pandoc format. |
| 385 |
#' |
| 386 |
#' Internally, the Pandoc output format of the current R Markdown document is |
| 387 |
#' stored in \code{knitr::\link{opts_knit}$get('rmarkdown.pandoc.to')}, and the |
| 388 |
#' Pandoc input format in |
| 389 |
#' \code{knitr::\link{opts_knit}$get('rmarkdown.pandoc.from')} |
| 390 |
#' |
| 391 |
#' @note See available Pandoc formats, in |
| 392 |
#' \href{https://pandoc.org/MANUAL.html}{Pandoc's Manual} |
| 393 |
#' @rdname output_type |
| 394 |
#' @export |
| 395 |
#' @examples |
| 396 |
#' # check for output formats type |
| 397 |
#' knitr::is_latex_output() |
| 398 |
#' knitr::is_html_output() |
| 399 |
#' knitr::is_html_output(excludes = c('markdown', 'epub')) |
| 400 |
#' # Get current formats |
| 401 |
#' knitr::pandoc_from() |
| 402 |
#' knitr::pandoc_to() |
| 403 |
#' # Test if current output format is 'docx' |
| 404 |
#' knitr::pandoc_to('docx') |
| 405 |
is_latex_output = function() { |
| 406 |
out_format(c('latex', 'sweave', 'listings')) || pandoc_to(c('latex', 'beamer')) |
| 407 |
} |
| 408 |
|
| 409 |
#' @param fmt A character vector of output formats to be checked against. If not |
| 410 |
#' provided, \code{is_html_output()} uses \code{pandoc_to()}, and |
| 411 |
#' \code{pandoc_to()} returns the output format name. |
| 412 |
#' @param excludes A character vector of output formats that should not be |
| 413 |
#' considered as HTML format. Options are: markdown, epub, epub2, html, html4, html5, |
| 414 |
#' revealjs, s5, slideous, slidy, and gfm. |
| 415 |
#' @rdname output_type |
| 416 |
#' @export |
| 417 |
is_html_output = function(fmt = pandoc_to(), excludes = NULL) { |
| 418 |
fmt = fmt %n% out_format() |
| 419 |
if (length(fmt) == 0) return(FALSE) |
| 420 |
if (grepl('^markdown', fmt)) fmt = 'markdown' |
| 421 |
if (fmt == 'epub3') fmt = 'epub' |
| 422 |
fmts = c('markdown', 'epub', 'epub2', 'html', 'html4', 'html5', 'revealjs', 's5', 'slideous', 'slidy', 'gfm') |
| 423 |
fmt %in% setdiff(fmts, excludes) |
| 424 |
} |
| 425 |
|
| 426 |
#' @param exact Whether to return or use the exact format name. If not, Pandoc |
| 427 |
#' extensions will be removed from the format name, e.g., \samp{latex-smart} |
| 428 |
#' will be treated as \samp{latex}. |
| 429 |
#' @rdname output_type |
| 430 |
#' @export |
| 431 |
pandoc_to = function(fmt, exact = FALSE) { |
| 432 |
# rmarkdown sets an option for the Pandoc output format from markdown |
| 433 |
to = fmt_name(opts_knit$get('rmarkdown.pandoc.to'), exact) |
| 434 |
if (missing(fmt)) to else !is.null(to) && (to %in% fmt) |
| 435 |
} |
| 436 |
|
| 437 |
#' @rdname output_type |
| 438 |
#' @export |
| 439 |
pandoc_from = function(exact = FALSE) { |
| 440 |
# rmarkdown's input format, obtained from a package option set by rmarkdown |
| 441 |
fmt_name(opts_knit$get('rmarkdown.pandoc.from'), exact) %n% 'markdown' |
| 442 |
} |
| 443 |
|
| 444 |
# pandoc format name: if not exact, return base name (remove extensions), e.g., |
| 445 |
# latex-smart -> latex |
| 446 |
fmt_name = function(x, exact = FALSE) { |
| 447 |
if (exact || is.null(x)) x else gsub('[-+].*', '', x) |
| 448 |
} |
| 449 |
|
| 450 |
# turn percent width/height to LaTeX unit, e.g. out.width = 30% -> .3\linewidth |
| 451 |
latex_percent_size = function(x, which = c('width', 'height')) { |
| 452 |
if (!is.character(x)) return(x) |
| 453 |
i = grep('^[0-9.]+%$', x) |
| 454 |
if (length(i) == 0) return(x) |
| 455 |
xi = as.numeric(sub('%$', '', x[i])) |
| 456 |
if (any(is.na(xi))) return(x) |
| 457 |
which = match.arg(which) |
| 458 |
x[i] = paste0( |
| 459 |
formatC(xi / 100, decimal.mark = '.'), |
| 460 |
if (which == 'width') '\\linewidth' else '\\textheight' |
| 461 |
) |
| 462 |
x |
| 463 |
} |
| 464 |
|
| 465 |
# eval options as symbol/language objects |
| 466 |
eval_lang = function(x, envir = knit_global()) { |
| 467 |
if (!is.symbol(x) && !is.language(x)) return(x) |
| 468 |
in_input_dir(eval(x, envir = envir)) |
| 469 |
} |
| 470 |
|
| 471 |
# check latex packages; if not exist, copy them over to ./ |
| 472 |
test_latex_pkg = function(name, path) { |
| 473 |
res = try_silent(system(sprintf('%s %s.sty', kpsewhich(), name), intern = TRUE)) |
| 474 |
if (inherits(res, 'try-error') || !length(res)) { |
| 475 |
warning("unable to find LaTeX package '", name, "'; will use a copy from knitr") |
| 476 |
file.copy(path, '.') |
| 477 |
} |
| 478 |
} |
| 479 |
|
| 480 |
# get child and parent mode |
| 481 |
child_mode = function() opts_knit$get('child') |
| 482 |
parent_mode = function() opts_knit$get('parent') |
| 483 |
|
| 484 |
# return the output format, or if current format is in specified formats |
| 485 |
out_format = function(x) { |
| 486 |
fmt = opts_knit$get('out.format') |
| 487 |
if (missing(x)) fmt else !is.null(fmt) && (fmt %in% x) |
| 488 |
} |
| 489 |
|
| 490 |
# tempfile under the current working directory |
| 491 |
wd_tempfile = function(...) basename(tempfile(tmpdir = '.', ...)) |
| 492 |
|
| 493 |
pandoc_fragment = function(text, to = pandoc_to(), from = pandoc_from()) { |
| 494 |
if (length(text) == 0) return(text) |
| 495 |
f1 = wd_tempfile('pandoc', '.md'); f2 = wd_tempfile('pandoc') |
| 496 |
on.exit(unlink(c(f1, f2)), add = TRUE) |
| 497 |
write_utf8(text, f1) |
| 498 |
rmarkdown::pandoc_convert(f1, to, from, f2, options = if (is_html_output(to)) '--mathjax') |
| 499 |
file_string(f2) |
| 500 |
} |
| 501 |
|
| 502 |
#' Path for figure files |
| 503 |
#' |
| 504 |
#' The filename of figure files is the combination of options \code{fig.path} |
| 505 |
#' and \code{label}. This function returns the path of figures for the current |
| 506 |
#' chunk by default. |
| 507 |
#' @param suffix A filename suffix; if it is non-empty and does not |
| 508 |
#' contain a dot \code{.}, it will be treated as the filename extension (e.g. |
| 509 |
#' \code{png} will be used as \code{.png}) |
| 510 |
#' @param options A list of options; by default the options of the current chunk. |
| 511 |
#' @param number The current figure number. The default is the internal chunk option |
| 512 |
#' \code{fig.cur}, if this is available. |
| 513 |
#' @return A character vector of the form \file{fig.path-label-i.suffix}. |
| 514 |
#' @note When there are special characters (not alphanumeric or \samp{-} or |
| 515 |
#' \samp{_}) in the path, they will be automatically replaced with \samp{_}. |
| 516 |
#' For example, \file{a b/c.d-} will be sanitized to \file{a_b/c_d-}. This |
| 517 |
#' makes the filenames safe to LaTeX. |
| 518 |
#' @export |
| 519 |
#' @examples fig_path('.pdf', options = list(fig.path='figure/abc-', label='first-plot')) |
| 520 |
#' fig_path('.png', list(fig.path='foo-', label='bar'), 1:10) |
| 521 |
fig_path = function(suffix = '', options = opts_current$get(), number) { |
| 522 |
suffix = sub('^([^.])', '.\\1', suffix) |
| 523 |
if (missing(number)) number = options$fig.cur %n% 1L |
| 524 |
if (!is.null(number)) suffix = paste0('-', number, suffix) |
| 525 |
path = valid_path(options$fig.path, options$label) |
| 526 |
if (getOption('knitr.sanitize.paths', out_format(c('latex', 'sweave', 'listings')))) |
| 527 |
path = sanitize_fn(path) |
| 528 |
paste0(path, suffix) |
| 529 |
} |
| 530 |
# sanitize filename for LaTeX |
| 531 |
sanitize_fn = function(path, warn = TRUE) { |
| 532 |
p = gsub('[^~:_./\\[:alnum:]-]', '_', path) |
| 533 |
if (warn && (p != path)) warning( |
| 534 |
"Replaced special characters in figure filename '", path, "' -> '", p, "'" |
| 535 |
) |
| 536 |
p |
| 537 |
} |
| 538 |
|
| 539 |
#' Obtain the figure filenames for a chunk |
| 540 |
#' |
| 541 |
#' Given a chunk label, the figure file extension, the figure number(s), and the |
| 542 |
#' chunk option \code{fig.path}, return the filename(s). |
| 543 |
#' |
| 544 |
#' This function can be used in an inline R expression to write out the figure |
| 545 |
#' filenames without hard-coding them. For example, if you created a plot in a |
| 546 |
#' code chunk with the label \code{foo} and figure path \file{my-figure/}, you |
| 547 |
#' are not recommended to use hard-coded figure paths like |
| 548 |
#' \samp{\includegraphics{my-figure/foo-1.pdf}} (in \file{.Rnw} documents) or |
| 549 |
#' \samp{} (R Markdown) in your document. Instead, you |
| 550 |
#' should use \samp{\\Sexpr{fig_chunk('foo', 'pdf')}} or \samp{`)}. |
| 552 |
#' |
| 553 |
#' You can generate plots in a code chunk but not show them inside the code |
| 554 |
#' chunk by using the chunk option \code{fig.show = 'hide'}. Then you can use |
| 555 |
#' this function if you want to show them elsewhere. |
| 556 |
#' @param label The chunk label. |
| 557 |
#' @param ext The figure file extension, e.g. \code{png} or \code{pdf}. |
| 558 |
#' @param number The figure number (by default \code{1}). |
| 559 |
#' @param fig.path Passed to \code{\link{fig_path}}. By default, the chunk |
| 560 |
#' option \code{fig.path} is used. |
| 561 |
#' @return A character vector of filenames. |
| 562 |
#' @export |
| 563 |
#' @examples library(knitr) |
| 564 |
#' fig_chunk('foo', 'png') |
| 565 |
#' fig_chunk('foo', 'pdf') |
| 566 |
#' fig_chunk('foo', 'svg', 2) # the second plot of the chunk foo |
| 567 |
#' fig_chunk('foo', 'png', 1:5) # if the chunk foo produced 5 plots |
| 568 |
fig_chunk = function(label, ext = '', number, fig.path = opts_chunk$get('fig.path')) { |
| 569 |
fig_path(ext, list(fig.path = fig.path, label = label), number) |
| 570 |
} |
| 571 |
|
| 572 |
#' The global environment for evaluating code |
| 573 |
#' |
| 574 |
#' Get or set the environment in which code chunks are evaluated. |
| 575 |
#' |
| 576 |
#' @param envir If \code{NULL}, the function returns the \code{envir} argument |
| 577 |
#' of \code{\link{knit}}, otherwise it should be a new environment for |
| 578 |
#' evaluating code, in which case the function returns the old environment |
| 579 |
#' after setting the new environment. |
| 580 |
#' @export |
| 581 |
knit_global = function(envir = NULL) { |
| 582 |
old = .knitEnv$knit_global %n% globalenv() |
| 583 |
if (!is.null(envir)) .knitEnv$knit_global = envir |
| 584 |
old |
| 585 |
} |
| 586 |
|
| 587 |
# Indents a Block |
| 588 |
# Input |
| 589 |
# "library(ggplot2)\nqplot(wt, mpg, data = mtcars)" |
| 590 |
# Output |
| 591 |
# library(ggplot2) |
| 592 |
# qplot(wt, mpg, data = mtcars) |
| 593 |
indent_block = function(block, spaces = ' ') { |
| 594 |
if (is.null(block) || !any(nzchar(block))) return(rep(spaces, length(block))) |
| 595 |
if (spaces == '') return(block) |
| 596 |
line_prompt(block, spaces, spaces) |
| 597 |
} |
| 598 |
|
| 599 |
# print knitr logs |
| 600 |
print_knitlog = function() { |
| 601 |
if (!opts_knit$get('verbose') || child_mode() || !length(klog <- knit_log$get(drop = FALSE))) |
| 602 |
return() |
| 603 |
|
| 604 |
for (i in unlist(klog, use.names = FALSE)) { |
| 605 |
cat(sub('\n+$', '', i), '\n\n') |
| 606 |
if (length(code <- knit_code$get(sub('^Chunk ([^:]+):\n.*', '\\1', i)))) |
| 607 |
cat(code, sep = '\n') |
| 608 |
} |
| 609 |
cat('\nNumber of messages:\n') |
| 610 |
print(sapply(klog, length)) |
| 611 |
} |
| 612 |
|
| 613 |
# count the number of lines |
| 614 |
line_count = function(x) { |
| 615 |
n = lengths(strsplit(x, '\n', fixed = TRUE)) |
| 616 |
i = grep('\n$', x) |
| 617 |
n[i] = n[i] + 1L # add an extra count for lines ending with \n |
| 618 |
n[n == 0] = 1L # should be at least one line |
| 619 |
n |
| 620 |
} |
| 621 |
|
| 622 |
has_package = function(pkg) loadable(pkg, FALSE) |
| 623 |
has_packages = function(pkgs) { |
| 624 |
for (p in pkgs) if (!has_package(p)) return(FALSE) |
| 625 |
TRUE |
| 626 |
} |
| 627 |
|
| 628 |
# if LHS is NULL, return the RHS |
| 629 |
`%n%` = function(x, y) if (is.null(x)) y else x |
| 630 |
|
| 631 |
# merge elements of y into x with the same names |
| 632 |
merge_list = function(x, y) { |
| 633 |
x[names(y)] = y |
| 634 |
x |
| 635 |
} |
| 636 |
|
| 637 |
# find a token in a template, and replace it with a value |
| 638 |
insert_template = function(text, token, value, ignore = FALSE) { |
| 639 |
if (is.null(value)) return(text) |
| 640 |
i = grep(token, text); n = length(i) |
| 641 |
if (n > 1) stop("There are multiple tokens in the template: '", token, "'") |
| 642 |
if (n == 0) { |
| 643 |
if (ignore) return(text) |
| 644 |
stop("Couldn't find the token '", token, "' in the template.") |
| 645 |
} |
| 646 |
append(text, value, i) |
| 647 |
} |
| 648 |
|
| 649 |
# paths of all figures |
| 650 |
all_figs = function(options, ext = options$fig.ext, num = options$fig.num) { |
| 651 |
unlist(lapply(ext, fig_path, options = options, number = seq_len(num))) |
| 652 |
} |
| 653 |
|
| 654 |
# evaluate an expression in a diretory and restore wd after that |
| 655 |
in_dir = function(dir, expr) { |
| 656 |
if (!is.null(dir)) { |
| 657 |
owd = setwd(dir); on.exit(setwd(owd)) |
| 658 |
} |
| 659 |
wd1 = getwd() |
| 660 |
res = expr |
| 661 |
wd2 = getwd() |
| 662 |
if (wd1 != wd2) warning( |
| 663 |
'You changed the working directory to ', wd2, ' (probably via setwd()). ', |
| 664 |
'It will be restored to ', wd1, '. See the Note section in ?knitr::knit' |
| 665 |
) |
| 666 |
res |
| 667 |
} |
| 668 |
|
| 669 |
# evaluate under the base.dir |
| 670 |
in_base_dir = function(expr) { |
| 671 |
d = opts_knit$get('base.dir') |
| 672 |
if (is.character(d) && !file_test('-d', d)) dir.create(d, recursive = TRUE) |
| 673 |
in_dir(d, expr) |
| 674 |
} |
| 675 |
|
| 676 |
# escape special LaTeX characters |
| 677 |
escape_latex = function(x, newlines = FALSE, spaces = FALSE) { |
| 678 |
x = gsub('\\\\', '\\\\textbackslash', x) |
| 679 |
x = gsub('([#$%&_{}])', '\\\\\\1', x) |
| 680 |
x = gsub('\\\\textbackslash', '\\\\textbackslash{}', x) |
| 681 |
x = gsub('~', '\\\\textasciitilde{}', x) |
| 682 |
x = gsub('\\^', '\\\\textasciicircum{}', x) |
| 683 |
if (newlines) x = gsub('(?<!\n)\n(?!\n)', '\\\\\\\\', x, perl = TRUE) |
| 684 |
# when there are consecutive spaces, escape each of them except the first one |
| 685 |
if (spaces) x = gsub('(?<= ) ', '\\\\ ', x, perl = TRUE) |
| 686 |
x |
| 687 |
} |
| 688 |
|
| 689 |
escape_html = function(x) { |
| 690 |
.Deprecated('xfun::html_escape()', old = 'knitr:::escape_html()') |
| 691 |
xfun::html_escape(x) |
| 692 |
} |
| 693 |
|
| 694 |
split_lines = function(x) xfun::split_lines(x) |
| 695 |
|
| 696 |
# if a string is encoded in UTF-8, convert it to native encoding |
| 697 |
native_encode = function(x, to = '') { |
| 698 |
from = if (any(Encoding(x) == 'UTF-8')) 'UTF-8' else '' |
| 699 |
x2 = iconv(x, from, to) |
| 700 |
if (!any(is.na(x2))) return(x2) # use conversion only if it succeeds |
| 701 |
warning('some characters may not work under the current locale') |
| 702 |
x |
| 703 |
} |
| 704 |
|
| 705 |
is_native_enc = function(x) { |
| 706 |
x == 'native.enc' || x == '' |
| 707 |
} |
| 708 |
|
| 709 |
is_utf8 = function(x) { |
| 710 |
!any(is.na(iconv(x, 'UTF-8', 'UTF-8'))) |
| 711 |
} |
| 712 |
|
| 713 |
#' Wrap long lines in Rmd files |
| 714 |
#' |
| 715 |
#' This function wraps long paragraphs in an R Markdown file. Other elements are |
| 716 |
#' not wrapped: the YAML preamble, fenced code blocks, section headers and |
| 717 |
#' indented elements. The main reason for wrapping long lines is to make it |
| 718 |
#' easier to review differences in version control. |
| 719 |
#' @param file The input Rmd file. |
| 720 |
#' @param width The expected line width. |
| 721 |
#' @param text A character vector of text lines, as an alternative to \code{file}. If |
| 722 |
#' \code{text} is not \code{NULL}, \code{file} is ignored. |
| 723 |
#' @param backup Path to back up the original file in case anything goes |
| 724 |
#' wrong. If set to \code{NULL}, no backup is made. The default value is constructed |
| 725 |
#' from \code{file} by adding \code{__} before the base filename. |
| 726 |
#' @return If \code{file} is provided, it is overwritten; if \code{text} is |
| 727 |
#' provided, a character vector is returned. |
| 728 |
#' @note Currently it does not wrap blockquotes or lists (ordered or unordered). |
| 729 |
#' This feature may or may not be added in the future. |
| 730 |
#' @export |
| 731 |
#' @examples wrap_rmd(text = c('```', '1+1', '```', '- a list item', '> a quote', '', |
| 732 |
#' paste(rep('this is a normal paragraph', 5), collapse = ' '))) |
| 733 |
wrap_rmd = function(file, width = 80, text = NULL, backup) { |
| 734 |
x = if (is.null(text)) read_utf8(file) else split_lines(text) |
| 735 |
x = strip_white(x) # strip blank lines in the beginning and end |
| 736 |
if ((n <- length(x)) <= 1L) return(x) # are you kidding? |
| 737 |
idx = NULL # collect the lines to exclude from wrapping |
| 738 |
i = grep('^---$', x) # yaml preamble |
| 739 |
if (length(i) > 1 && i[1L] == 1L) idx = c(idx, i[1L]:i[2L]) |
| 740 |
i = grep('^(```|\\{% (end|)highlight [a-z ]*%\\}|</?script.*>)', x) # code blocks |
| 741 |
if (length(i)) { |
| 742 |
if (length(i) %% 2L != 0L) stop('markers for code blocks must be paired up') |
| 743 |
idx = c(idx, unlist(apply(matrix(i, ncol = 2L, byrow = TRUE), 1L, |
| 744 |
function(z) z[1L]:z[2L]))) |
| 745 |
} |
| 746 |
# section headers, indented code blocks and latex math |
| 747 |
idx = c(idx, grep('^(#|===|---| |\t)', x)) |
| 748 |
# blank lines |
| 749 |
idx = c(idx, grep('^\\s*$', x)) |
| 750 |
# TODO: this is naive -- I treat a line as (a part of) a normal paragraph if |
| 751 |
# it does not start with a space, or > (blockquotes) or -, *, 1. (lists), and |
| 752 |
# only wrap paragraphs |
| 753 |
idx = c(idx, grep('^\\s*( |> |- |\\* |\\d+ )', x)) |
| 754 |
idx = unique(idx) |
| 755 |
if (length(idx) == n) return(x) # no need to wrap anything |
| 756 |
|
| 757 |
i = logical(n); i[idx] = TRUE; r = rle(i) |
| 758 |
n = length(r$lengths); txt = vector('list', n); j = c(0L, cumsum(r$lengths)) |
| 759 |
for (i in seq_len(n)) { |
| 760 |
block = x[seq(j[i] + 1L, j[i + 1])] |
| 761 |
txt[[i]] = if (r$value[i]) { |
| 762 |
# those lines not to be wrapped |
| 763 |
gsub('\\s+$', '', block) # strip pending spaces |
| 764 |
} else { |
| 765 |
strwrap(one_string(block), width) |
| 766 |
} |
| 767 |
} |
| 768 |
txt = unlist(txt) |
| 769 |
if (is.null(text)) { |
| 770 |
if (missing(backup)) backup = file.path(dirname(file), paste0('__', basename(file))) |
| 771 |
if (!is.null(backup)) file.copy(file, backup, overwrite = TRUE) |
| 772 |
write_utf8(txt, file) |
| 773 |
} else txt |
| 774 |
} |
| 775 |
|
| 776 |
# change the default device to an appropriate device when the output is html |
| 777 |
# (e.g. markdown, reST, AsciiDoc) |
| 778 |
set_html_dev = function() { |
| 779 |
# only change if device has not been set |
| 780 |
if (!is.null(opts_chunk$get('dev'))) return() |
| 781 |
# in some cases, png() does not work (e.g. options('bitmapType') == 'Xlib' on |
| 782 |
# headless servers); use svg then |
| 783 |
opts_chunk$set(dev = if (dev_available('png')) 'png' else 'svg') |
| 784 |
} |
| 785 |
|
| 786 |
# locate kpsewhich especially for Mac OS because /usr/texbin may not be in PATH |
| 787 |
kpsewhich = function() { |
| 788 |
if (Sys.info()['sysname'] != 'Darwin' || !file.exists(x <- '/usr/texbin/kpsewhich') |
| 789 |
|| nzchar(Sys.which('kpsewhich'))) |
| 790 |
'kpsewhich' else x |
| 791 |
} |
| 792 |
|
| 793 |
# check if a utility exists; if it does, save its availability in opts_knit |
| 794 |
has_utility = function(name, package = name) { |
| 795 |
name2 = paste0('util_', name) # e.g. util_pdfcrop |
| 796 |
if (is.logical(yes <- opts_knit$get(name2))) return(yes) |
| 797 |
# a special case: use tools::find_gs_cmd() to find ghostscript |
| 798 |
if (name == 'pdfcrop') yes = has_crop_tools() else { |
| 799 |
yes = nzchar(Sys.which(name)) |
| 800 |
if (!yes) warning(package, ' not installed or not in PATH') |
| 801 |
} |
| 802 |
opts_knit$set(setNames(list(yes), name2)) |
| 803 |
yes |
| 804 |
} |
| 805 |
|
| 806 |
# check if pdfcrop and ghostscript are available |
| 807 |
has_crop_tools = function(warn = TRUE) { |
| 808 |
if (Sys.which('pdfcrop') == '') { |
| 809 |
if (warn) warning("'pdfcrop' is required but not found") |
| 810 |
return(FALSE) |
| 811 |
} |
| 812 |
if (is_windows() && Sys.which('tlmgr') != '') { |
| 813 |
# assuming users know what this env var means (rstudio/tinytex#391) |
| 814 |
if (Sys.getenv('TEXLIVE_WINDOWS_EXTERNAL_GS') != '') return(TRUE) |
| 815 |
year = tinytex::tlmgr_version('list')$texlive |
| 816 |
if (year < 2023 && warn) warning( |
| 817 |
'TeX Live version too low. Please consider upgrading, e.g., via tinytex::reinstall_tinytex().' |
| 818 |
) |
| 819 |
return(year >= 2023) |
| 820 |
} |
| 821 |
gs = tools::find_gs_cmd() != '' |
| 822 |
if (warn && !gs) warning("'ghostscript' is required but not found") |
| 823 |
gs |
| 824 |
} |
| 825 |
|
| 826 |
#' Query the current input filename |
| 827 |
#' |
| 828 |
#' Returns the name of the input file passed to \code{\link{knit}()}. |
| 829 |
#' @param dir Boolean; whether to prepend the current working directory to the file path, |
| 830 |
#' i.e. whether to return an absolute path or a relative path. |
| 831 |
#' @return A character string, if this function is called inside an input |
| 832 |
#' document. Otherwise \code{NULL}. |
| 833 |
#' @export |
| 834 |
current_input = function(dir = FALSE) { |
| 835 |
input = knit_concord$get('infile') |
| 836 |
outwd = opts_knit$get('output.dir') |
| 837 |
if (is.null(input)) return() |
| 838 |
if (dir) { |
| 839 |
if (is.null(outwd)) { |
| 840 |
warning('Cannot determine the directory of the input document') |
| 841 |
dir = FALSE |
| 842 |
} |
| 843 |
} |
| 844 |
if (!dir) return(basename(input)) |
| 845 |
if (is_abs_path(input)) input else file.path(outwd, input) |
| 846 |
} |
| 847 |
|
| 848 |
# cache output handlers from evaluate; see .onLoad |
| 849 |
default_handlers = NULL |
| 850 |
# use rlang handler for error only if available; see .onLoad |
| 851 |
rlang_entrace_handler = NULL |
| 852 |
# change the value handler in evaluate default handlers |
| 853 |
knit_handlers = function(fun, options) { |
| 854 |
if (!is.function(fun)) fun = function(x, ...) { |
| 855 |
res = withVisible(knit_print(x, ...)) |
| 856 |
# indicate the htmlwidget result with a special class so we can attach |
| 857 |
# the figure caption to it later in sew.knit_asis |
| 858 |
if (inherits(x, 'htmlwidget')) |
| 859 |
class(res$value) = c(class(res$value), 'knit_asis_htmlwidget') |
| 860 |
if (res$visible) res$value else invisible(res$value) |
| 861 |
} |
| 862 |
if (length(formals(fun)) < 2) |
| 863 |
stop("the chunk option 'render' must be a function of the form ", |
| 864 |
"function(x, options) or function(x, ...)") |
| 865 |
merge_list(default_handlers, list( |
| 866 |
value = function(x, visible) { |
| 867 |
if (visible) fun(x, options = options) |
| 868 |
}, |
| 869 |
calling_handlers = c(options$calling.handlers, rlang_entrace_handler) |
| 870 |
)) |
| 871 |
} |
| 872 |
|
| 873 |
# is the inst dir under . or ..? differs in R CMD build/INSTALL and devtools/roxygen2 |
| 874 |
inst_dir = function(...) { |
| 875 |
p = file.path(c('..', '.'), 'inst', ...) |
| 876 |
p[file.exists(p)] |
| 877 |
} |
| 878 |
|
| 879 |
# a restricted version of is.numeric (e.g. do not treat chron::chron() as |
| 880 |
# numeric since their behavior may be somewhat unpredictable, e.g. through |
| 881 |
# round(), #1118); see #1396 for difftime |
| 882 |
is_numeric = function(x) { |
| 883 |
class(x)[1] %in% c('numeric', 'integer', 'difftime', 'complex') |
| 884 |
} |
| 885 |
|
| 886 |
# create \label{x} or (\#x); the latter is current an internal hack for bookdown |
| 887 |
create_label = function(..., latex = FALSE) { |
| 888 |
if (isTRUE(opts_knit$get('bookdown.internal.label'))) { |
| 889 |
lab1 = '(\\#'; lab2 = ')' |
| 890 |
} else if (latex) { |
| 891 |
lab1 = '\\label{'; lab2 = '}' |
| 892 |
} else { |
| 893 |
return('') # we don't want the label at all |
| 894 |
} |
| 895 |
paste(c(lab1, ..., lab2), collapse = '') |
| 896 |
} |
| 897 |
|
| 898 |
#' Combine multiple words into a single string |
| 899 |
#' |
| 900 |
#' This is a wrapper function of \code{xfun::join_words()}. |
| 901 |
#' @param ... Arguments passed to \code{xfun::\link[xfun]{join_words}()}. |
| 902 |
#' @export |
| 903 |
combine_words = function(...) xfun::join_words(...) |
| 904 |
|
| 905 |
warning2 = function(...) warning(..., call. = FALSE) |
| 906 |
stop2 = function(...) stop(..., call. = FALSE) |
| 907 |
|
| 908 |
warn_options_unsupported = function(option, to) { |
| 909 |
warning2('Chunk option ', option, ' is not supported for ', to, ' output') |
| 910 |
} |
| 911 |
|
| 912 |
raw_markers = c('!!!!!RAW-KNITR-CONTENT', 'RAW-KNITR-CONTENT!!!!!') |
| 913 |
|
| 914 |
#' @export |
| 915 |
#' @rdname raw_output |
| 916 |
extract_raw_output = function(text, markers = raw_markers) { |
| 917 |
r = sprintf('%s(.*?)%s', markers[1], markers[2]) |
| 918 |
x = one_string(text) |
| 919 |
m = gregexpr(r, x) |
| 920 |
s = regmatches(x, m) |
| 921 |
n = length(s[[1]]) |
| 922 |
if (n == 0) return(list(value = text, chunks = character())) |
| 923 |
|
| 924 |
chunks = tokens = character(n) |
| 925 |
for (i in seq_len(n)) { |
| 926 |
chunks[i] = sub(r, '\\1', s[[1]][i]) |
| 927 |
tokens[i] = digest(chunks[i]) |
| 928 |
s[[1]][i] = gsub(r, paste0(markers[1], tokens[i], markers[2]), s[[1]][i]) |
| 929 |
} |
| 930 |
regmatches(x, m) = s |
| 931 |
|
| 932 |
list(value = x, chunks = setNames(chunks, tokens)) |
| 933 |
} |
| 934 |
|
| 935 |
#' @export |
| 936 |
#' @rdname raw_output |
| 937 |
restore_raw_output = function(text, chunks, markers = raw_markers) { |
| 938 |
if ((n <- length(chunks)) == 0) return(text) |
| 939 |
text = enc2utf8(text); chunks = enc2utf8(chunks); tokens = names(chunks) |
| 940 |
for (i in seq_len(n)) { |
| 941 |
r = paste0(markers[1], tokens[i], markers[2]) |
| 942 |
text = gsub(r, chunks[i], text, fixed = TRUE, useBytes = TRUE) |
| 943 |
} |
| 944 |
Encoding(text) = 'UTF-8' |
| 945 |
text |
| 946 |
} |
| 947 |
|
| 948 |
#' Mark character strings as raw output that should not be converted |
| 949 |
#' |
| 950 |
#' These functions provide a mechanism to protect the character output of R code |
| 951 |
#' chunks. The output is annotated with special markers in \code{raw_output}; |
| 952 |
#' \code{extract_raw_output()} will extract raw output wrapped in the markers, |
| 953 |
#' and replace the raw output with its MD5 digest; \code{restore_raw_output()} |
| 954 |
#' will restore the MD5 digest with the original raw output. |
| 955 |
#' |
| 956 |
#' This mechanism is designed primarily for R Markdown pre/post-processors. In |
| 957 |
#' an R code chunk, you generate \code{raw_output()} to the Markdown output. In |
| 958 |
#' the pre-processor, you can \code{extract_raw_output()} from the Markdown |
| 959 |
#' file, store the raw output and MD5 digests, and remove the actual raw output |
| 960 |
#' from Markdown so Pandoc will never see it. In the post-processor, you can |
| 961 |
#' read the Pandoc output (e.g., an HTML or RTF file), and restore the raw |
| 962 |
#' output. |
| 963 |
#' @param x The character vector to be protected. |
| 964 |
#' @param markers A length-2 character vector to be used to wrap \code{x}; |
| 965 |
#' see \code{knitr:::raw_markers} for the default value. |
| 966 |
#' @param ... Arguments to be passed to \code{\link{asis_output}()}. |
| 967 |
#' @param text For \code{extract_raw_output()}, the content of the input file |
| 968 |
#' (e.g. Markdown); for \code{restore_raw_output()}, the content of the output |
| 969 |
#' file (e.g. HTML generated by Pandoc from Markdown). |
| 970 |
#' @param chunks A named character vector returned from |
| 971 |
#' \code{extract_raw_output()}. |
| 972 |
#' @return For \code{extract_raw_output()}, a list of two components: |
| 973 |
#' \code{value} (the \code{text} with raw output replaced by MD5 digests) and |
| 974 |
#' \code{chunks} (a named character vector, of which the names are MD5 digests |
| 975 |
#' and values are the raw output). For \code{restore_raw_output()}, the |
| 976 |
#' restored \code{text}. |
| 977 |
#' @export |
| 978 |
#' @examples library(knitr) |
| 979 |
#' out = c('*hello*', raw_output('<special>content</special> *protect* me!'), '*world*') |
| 980 |
#' pre = extract_raw_output(out) |
| 981 |
#' str(pre) |
| 982 |
#' pre$value = gsub('[*]([^*]+)[*]', '<em>\\1</em>', pre$value) # think this as Pandoc conversion |
| 983 |
#' pre$value |
| 984 |
#' # raw output was protected from the conversion (e.g. *protect* was not converted) |
| 985 |
#' restore_raw_output(pre$value, pre$chunks) |
| 986 |
raw_output = function(x, markers = raw_markers, ...) { |
| 987 |
asis_output(paste(c(markers[1], x, markers[2]), collapse = ''), ...) |
| 988 |
} |
| 989 |
|
| 990 |
|
| 991 |
#' Mark character strings as raw blocks in R Markdown |
| 992 |
#' |
| 993 |
#' Wraps content in a raw attribute block, which protects it from being escaped |
| 994 |
#' by Pandoc. See \url{https://pandoc.org/MANUAL.html#generic-raw-attribute}. |
| 995 |
#' Functions \code{raw_latex()} and \code{raw_html()} are shorthands of |
| 996 |
#' \code{raw_block(x, 'latex')} and \code{raw_block(x, 'html')}, respectively. |
| 997 |
#' @param x The character vector to be protected. |
| 998 |
#' @param type The type of raw blocks (i.e., the Pandoc output format). If you |
| 999 |
#' are not sure about the Pandoc output format of your document, insert a code |
| 1000 |
#' chunk \code{knitr:::pandoc_to()} and see what it returns after the document |
| 1001 |
#' is compiled. |
| 1002 |
#' @param ... Arguments to be passed to \code{\link{asis_output}()}. |
| 1003 |
#' @export |
| 1004 |
#' @examples |
| 1005 |
#' knitr::raw_latex('\\emph{some text}') |
| 1006 |
raw_block = function(x, type = 'latex', ...) { |
| 1007 |
if (!rmarkdown::pandoc_available('2.0.0')) warning('raw_block() requires Pandoc >= 2.0.0') |
| 1008 |
x = fenced_block(x, attr = paste0('=', type)) |
| 1009 |
x = gsub('^\n|\n$', '', x) |
| 1010 |
asis_output(x, ...) |
| 1011 |
} |
| 1012 |
|
| 1013 |
#' @rdname raw_block |
| 1014 |
#' @export |
| 1015 |
raw_latex = function(x, ...) raw_block(x, 'latex', ...) |
| 1016 |
|
| 1017 |
#' @rdname raw_block |
| 1018 |
#' @export |
| 1019 |
raw_html = function(x, ...) raw_block(x, 'html', ...) |
| 1020 |
|
| 1021 |
optipng = function(...) { |
| 1022 |
warning2('knitr:::optipng() has been deprecated; please use xfun::optipng()') |
| 1023 |
xfun::optipng(...) |
| 1024 |
} |
| 1025 |
|
| 1026 |
digest = function(x) { |
| 1027 |
if (loadable('digest')) digest::digest(x) else digest2(x) |
| 1028 |
} |
| 1029 |
|
| 1030 |
# compatible with digest::digest() but definitely slower because of file I/O |
| 1031 |
digest2 = function(x) { |
| 1032 |
s = serialize(x, NULL, ascii = FALSE) |
| 1033 |
if (length(s) > 14) s = s[-(1:14)] # https://d.cosx.org/d/419804 |
| 1034 |
writeBin(s, f <- tempfile()) |
| 1035 |
on.exit(unlink(f), add = TRUE) |
| 1036 |
unname(tools::md5sum(f)) |
| 1037 |
} |
| 1038 |
|
| 1039 |
# not removing the serialize() header (first few bytes) |
| 1040 |
digest3 = function(x) { |
| 1041 |
f = tempfile(); on.exit(unlink(f), add = TRUE) |
| 1042 |
s = file(f, open = 'wb') |
| 1043 |
serialize(x, s, ascii = FALSE) |
| 1044 |
close(s) |
| 1045 |
unname(tools::md5sum(f)) |
| 1046 |
} |
| 1047 |
|
| 1048 |
# collapse by \n |
| 1049 |
one_string = function(x, ...) paste(x, ..., collapse = '\n') |
| 1050 |
|
| 1051 |
# double quote a vector and combine by "; " |
| 1052 |
quote_vec = function(x, sep = '; ') paste0(sprintf('"%s"', x), collapse = sep) |
| 1053 |
|
| 1054 |
#' Encode an image file to a data URI |
| 1055 |
#' |
| 1056 |
#' This function is the same as \code{xfun::\link[xfun]{base64_uri}()} (only with a |
| 1057 |
#' different function name). It can encode an image file as a base64 string, |
| 1058 |
#' which can be used in the \code{img} tag in HTML. |
| 1059 |
#' @param f Path to the image file. |
| 1060 |
#' @return The data URI as a character string. |
| 1061 |
#' @author Wush Wu and Yihui Xie |
| 1062 |
#' @export |
| 1063 |
#' @references \url{https://en.wikipedia.org/wiki/Data_URI_scheme} |
| 1064 |
#' @examples uri = image_uri(file.path(R.home('doc'), 'html', 'logo.jpg')) |
| 1065 |
#' if (interactive()) {cat(sprintf('<img src="%s" />', uri), file = 'logo.html') |
| 1066 |
#' browseURL('logo.html') # you can check its HTML source |
| 1067 |
#' } |
| 1068 |
image_uri = function(f) xfun::base64_uri(f) |
| 1069 |
|
| 1070 |
# Change all "[label](url)" to "label" except leave "`[label](url)`" as is |
| 1071 |
remove_urls = function(x) { |
| 1072 |
# regex adapted from https://dev.to/mattkenefick/regex-convert-markdown-links-to-html-anchors-f7j |
| 1073 |
gsub("(?<!`)\\[([^]]+)\\]\\(([^)]+)\\)(?!`)", "\\1", x, perl = TRUE) |
| 1074 |
} |
| 1075 |
|
| 1076 |
# patch strsplit() to split '' into '' instead of character(0) |
| 1077 |
str_split = function(x, split, ...) { |
| 1078 |
y = strsplit(x, split, ...) |
| 1079 |
y[x == ''] = list('') |
| 1080 |
y |
| 1081 |
} |
| 1082 |
|
| 1083 |
# default progress bar function in knitr: create a text progress bar, and return |
| 1084 |
# methods to update/close it |
| 1085 |
txt_pb = function(total, labels) { |
| 1086 |
if (getOption('knitr.progress.linenums', FALSE)) { |
| 1087 |
nums = sapply(seq_along(labels), current_lines) |
| 1088 |
labels = sprintf( |
| 1089 |
'%s%s%s:%s', labels, ifelse(labels == '', '', ' @ '), |
| 1090 |
knit_concord$get('infile'), nums |
| 1091 |
) |
| 1092 |
} |
| 1093 |
s = ifelse(labels == '', '', sprintf(' [%s]', labels)) # chunk labels in [] |
| 1094 |
w = nchar(s) # widths of labels |
| 1095 |
n = max(w) |
| 1096 |
# right-pad spaces for same width of all labels so a wider label of the |
| 1097 |
# progress bar in a previous step could be completely wiped (by spaces) |
| 1098 |
s = paste0(s, strrep(' ', n - w)) |
| 1099 |
w2 = getOption('width') |
| 1100 |
con = getOption('knitr.progress.output', '') |
| 1101 |
cat_line = function(...) cat(..., sep = '', file = con) |
| 1102 |
# test if it is a "terminal" connection (whether \r is supported) |
| 1103 |
simple = (function() { |
| 1104 |
# a global option to decide whether to use the simple progress output |
| 1105 |
if (!is.null(res <- getOption('knitr.progress.simple'))) return(res) |
| 1106 |
if (identical(con, '')) con = stdout() |
| 1107 |
if (!inherits(con, 'connection')) return(TRUE) |
| 1108 |
if (isatty(con)) return(FALSE) |
| 1109 |
# when in RStudio, return FALSE |
| 1110 |
Sys.getenv('RSTUDIO') != '1' |
| 1111 |
})() |
| 1112 |
# use simple progress output without the bar but only progress and labels |
| 1113 |
if (simple) return(list( |
| 1114 |
update = function(i) cat_line(i, '/', total, s[i], '\n') |
| 1115 |
)) |
| 1116 |
pb = txtProgressBar( |
| 1117 |
0, total, 0, '.', width = max(w2 - 10 - n, 10), style = 3, file = con |
| 1118 |
) |
| 1119 |
list( |
| 1120 |
update = function(i) { |
| 1121 |
setTxtProgressBar(pb, i) |
| 1122 |
cat_line(s[i]) # append chunk label to the progress bar |
| 1123 |
}, |
| 1124 |
interrupt = function() message('\n'), |
| 1125 |
done = function() { |
| 1126 |
# wipe the progress bar |
| 1127 |
cat_line('\r', strrep(' ', max(w2, 10) + 10 + n)) |
| 1128 |
close(pb) |
| 1129 |
} |
| 1130 |
) |
| 1131 |
} |
| 1132 |
|
| 1133 |
is_quarto = function() isTRUE(.knitEnv$is_quarto) |
| 1134 |
|
| 1135 |
with_options = function(expr, opts_list) { |
| 1136 |
local_options(opts_list) |
| 1137 |
expr |
| 1138 |
} |
| 1139 |
|
| 1140 |
local_options <- function(opts_list, .local_envir = parent.frame()) { |
| 1141 |
old = options(opts_list) |
| 1142 |
defer(options(old), .local_envir) |
| 1143 |
} |
| 1144 |
|
| 1145 |
defer = function(expr, frame = parent.frame(), after = FALSE) { |
| 1146 |
thunk = as.call(list(function() expr)) |
| 1147 |
do.call(on.exit, list(thunk, add = TRUE, after = after), envir = frame) |
| 1148 |
} |