Debian Codegraph @

R/util.R

raw
1 #' @import stats utils
2
3 createUniqueId <- function(bytes) {
4 paste(as.hexmode(sample(256, bytes) - 1), collapse = "")
5 }
6
7 is_windows <- function() {
8 identical(.Platform$OS.type, "windows")
9 }
10
11 is_osx <- function() {
12 Sys.info()["sysname"] == "Darwin"
13 }
14
15 `%||%` <- function(x, y) {
16 if (is.null(x)) y else x
17 }
18
19 # a la shiny:::is_available
20 is_available <- function(package, version = NULL) {
21 installed <- nzchar(system.file(package = package))
22 if (is.null(version)) {
23 return(installed)
24 }
25 installed && isTRUE(utils::packageVersion(package) >= version)
26 }
27
28 # determine the output file for a pandoc conversion
29 pandoc_output_file <- function(input, pandoc_options) {
30 to <- strsplit(pandoc_options$to, "[+-]")[[1]][[1]]
31 ext <- pandoc_output_ext(pandoc_options$ext, to, input)
32 output <- paste0(xfun::sans_ext(input), ext)
33 basename(output)
34 }
35
36 pandoc_output_ext <- function(ext, to, input) {
37 if (!is.null(ext)) return(ext)
38 if (to %in% c("latex", "beamer")) return(".pdf")
39 if (to %in% c("html", "html4", "html5", "s5", "slidy", "slideous", "dzslides", "revealjs"))
40 return(".html")
41 if (to == "markdown" && tolower(xfun::file_ext(input)) != "md") return(".md")
42 paste0(".", to)
43 }
44
45 # needs to handle the case when this function is used in a package loaded with
46 # devtools or pkgload load_all(). Required for testing with testthat also.
47 # From pkgdown:
48 # https://github.com/r-lib/pkgdown/blob/04d3a76892320ac4bd918b39604c157e9f83507a/R/utils-fs.R#L85
49 pkg_file <- function(..., package = "rmarkdown", mustWork = FALSE) {
50 if (devtools_loaded(package)) {
51 # used only if package has been loaded with devtools or pkgload
52 file.path(find.package(package), "inst", ...)
53 } else {
54 system.file(..., package = package, mustWork = mustWork)
55 }
56 }
57
58 pkg_file_arg <- function(..., package = "rmarkdown") {
59 pandoc_path_arg(pkg_file(..., package = package))
60 }
61
62 #' Get the full paths of Lua filters in an R package
63 #'
64 #' Lua filters stored in a source package in the \file{inst/rmarkdown/lua}
65 #' directory will be installed to the \file{rmarkdown/lua} directory in the
66 #' package path. This function finds the full paths of the Lua filters in the
67 #' installed packages.
68 #' @param filters A character vector of filenames for Lua filters to be
69 #' retrieved in \file{rmarkdown/lua} folder of the package. By default
70 #' (\code{NULL}), if none is provided, it returns all filters in that folder.
71 #' @param package The name of the package in which to look for the filters.
72 #' @return A character vector of absolute file paths for the Lua filter from the
73 #' package. The returned paths have been processed by
74 #' \code{\link{pandoc_path_arg}()}, so they are ready to be used by Pandoc.
75 #' @export
76 #' @examples
77 #' # list all Lua filters stored in the rmarkdown package
78 #' pkg_file_lua()
79 #' # get a specific filter
80 #' pkg_file_lua(c("pagebreak.lua", "latex_div.lua"))
81 pkg_file_lua <- function(filters = NULL, package = "rmarkdown") {
82 files <- pkg_file(
83 "rmarkdown", "lua", if (is.null(filters)) '.' else filters,
84 package = package, mustWork = TRUE
85 )
86 if (is.null(filters)) {
87 files <- list.files(dirname(files), "[.]lua$", full.names = TRUE)
88 }
89 pandoc_path_arg(files)
90 }
91
92 pkg_file_highlight <- function(...) {
93 pkg_file("rmarkdown", "highlight", ..., mustWork = TRUE)
94 }
95
96 #' @rdname rmarkdown_format
97 #' @export
98 from_rmarkdown <- function(implicit_figures = TRUE, extensions = NULL) {
99
100 # paste extensions together and remove whitespace
101 extensions <- paste0(extensions, collapse = "")
102 extensions <- gsub(" ", "", extensions)
103
104 # exclude implicit figures unless the user has added them back
105 if (!implicit_figures && !grepl("implicit_figures", extensions))
106 extensions <- paste0("-implicit_figures", extensions)
107
108 rmarkdown_format(extensions)
109 }
110
111 is_null_or_string <- function(text) {
112 is.null(text) || (is.character(text) && (length(text) == 1))
113 }
114
115 read_utf8 <- function(file) {
116 if (inherits(file, 'connection')) con <- file else {
117 con <- base::file(file, encoding = 'UTF-8'); on.exit(close(con), add = TRUE)
118 }
119 enc2utf8(readLines(con, warn = FALSE))
120 }
121
122 write_utf8 <- function(text, con, ...) {
123 opts <- options(encoding = "native.enc"); on.exit(options(opts), add = TRUE)
124 writeLines(enc2utf8(text), con, ..., useBytes = TRUE)
125 }
126
127 file_string <- function(path) one_string(read_utf8(path))
128
129 one_string <- function(x) paste(x, collapse = '\n')
130
131 # in a future version of yaml, it will disable the evaluation of !expr but we
132 # still need it (https://github.com/rstudio/rmarkdown/issues/1387)
133 yaml_load <- function(...) yaml::yaml.load(..., eval.expr = TRUE)
134
135 yaml_load_file <- function(input, ...) yaml_load(read_utf8(input), ...)
136
137 file_name_without_shell_chars <- function(file) {
138 name <- gsub(.shell_chars_regex, '-', basename(file))
139 dir <- dirname(file)
140 if (nzchar(dir) && !identical(dir, "."))
141 file.path(dir, name)
142 else
143 name
144 }
145
146 # make sure the tempdir exists
147 tempfile <- function(pattern = 'file', tmpdir = tempdir(), ...) {
148 dir.create(tmpdir, showWarnings = FALSE, recursive = TRUE)
149 base::tempfile(pattern = pattern, tmpdir = tmpdir, ...)
150 }
151
152 tmpfile_pattern <- "rmarkdown-str"
153
154 # return a string as a tempfile
155 as_tmpfile <- function(str) {
156 if (length(str) == 0) return()
157 f <- tempfile(tmpfile_pattern, fileext = ".html")
158 write_utf8(str, f)
159 f
160 }
161
162 # temp files created by as_tmpfile() cannot be immediately removed because they
163 # are needed later by the pandoc conversion; we have to clean up the temp files
164 # that have the pattern specified in `tmpfile_pattern` when render() exits
165 clean_tmpfiles <- function() {
166 unlink(list.files(
167 tempdir(), sprintf("^%s[0-9a-f]+[.]html$", tmpfile_pattern), full.names = TRUE
168 ))
169 }
170
171 # test if all paths in x are directories
172 dir_exists <- function(x) {
173 length(x) > 0 && utils::file_test('-d', x)
174 }
175
176 file_with_ext <- function(file, ext) {
177 paste(xfun::sans_ext(file), ".", ext, sep = "")
178 }
179
180
181 file_with_meta_ext <- function(file, meta_ext, ext = xfun::file_ext(file)) {
182 paste(xfun::sans_ext(file),
183 ".", meta_ext, ".", ext, sep = "")
184 }
185
186 knitr_files_dir <- function(file) {
187 suffix <- getOption("rmarkdown.files.suffix", "_files")
188 paste(xfun::sans_ext(file), suffix, sep = "")
189 }
190
191 knitr_root_cache_dir <- function(file) {
192 paste(xfun::sans_ext(file), "_cache", sep = "")
193 }
194
195 knitr_cache_dir <- function(file, pandoc_to) {
196 paste(xfun::sans_ext(file), "_cache/", pandoc_to, "/", sep = "")
197 }
198
199 get_knitr_hook_list <- function(hook_names = NULL) {
200 if (is.null(hook_names))
201 hook_names <- c("knit_hooks", "opts_chunk", "opts_hooks", "opts_knit")
202 knitr_ns <- asNamespace("knitr")
203 hook_list <- lapply(hook_names, function(hook_name) {
204 hooks <- get(hook_name, envir = knitr_ns, inherits = FALSE)
205 hooks$get()
206 })
207 names(hook_list) <- hook_names
208 hook_list
209 }
210
211 set_knitr_hook_list <- function(hook_list) {
212 knitr_ns <- asNamespace("knitr")
213 enumerate(hook_list, function(hook_name, hook_value) {
214 hook <- get(hook_name, envir = knitr_ns, inherits = FALSE)
215 hook$set(hook_value)
216 })
217 }
218
219 highlighters <- function() {
220 c("default",
221 "tango",
222 "pygments",
223 "kate",
224 "monochrome",
225 "espresso",
226 "zenburn",
227 "haddock",
228 "breezedark")
229 }
230
231 merge_lists <- function(base_list, overlay_list, recursive = TRUE) {
232 if (length(base_list) == 0)
233 overlay_list
234 else if (length(overlay_list) == 0)
235 base_list
236 else {
237 merged_list <- base_list
238 for (name in names(overlay_list)) {
239 base <- base_list[[name]]
240 overlay <- overlay_list[[name]]
241 if (is.list(base) && is.list(overlay) && recursive)
242 merged_list[[name]] <- merge_lists(base, overlay)
243 else {
244 merged_list[[name]] <- NULL
245 merged_list <- append(merged_list,
246 overlay_list[which(names(overlay_list) %in% name)])
247 }
248 }
249 merged_list
250 }
251 }
252
253 trim_trailing_ws <- function(x) {
254 sub("\\s+$", "", x)
255 }
256
257
258 # Find common base directory, throw error if it doesn't exist
259 base_dir <- function(x) {
260 base <- unique(dirname(x))
261 if (length(base) > 1) {
262 stop2("Input files not all in same directory, please supply explicit wd")
263 }
264 base
265 }
266
267 move_dir <- function(from, to) {
268 dir.create(dirname(to), showWarnings = FALSE)
269 suppressWarnings(file.rename(from, to)) || {
270 file.copy(from, dirname(to), recursive = TRUE) && unlink(from, recursive = TRUE)
271 }
272 }
273
274 # Check if two paths are the same after being normalized
275 same_path <- function(path1, path2, ...) {
276 if (length(path1) * length(path2) != 1)
277 stop('The two paths must be both of length 1')
278 normalize_path(path1, ...) == normalize_path(path2, ...)
279 }
280
281 # normalizePath() doesn't work if the path contains Unicode characters that
282 # cannot be represented in the current system locale, even if the file exists
283 abs_path <- function(x) {
284 if (!file.exists(x)) stop("The file '", x, "' does not exist.")
285 res <- normalize_path(x, must_work = FALSE)
286 if (file.exists(res)) return(res)
287 if (!requireNamespace('fs', quietly = TRUE)) warning(
288 'normalizePath() cannot make the path(s) absolute. The fs package is required.'
289 )
290 as.character(fs::path_abs(x))
291 }
292
293 # Regular expression representing characters likely to be considered special by
294 # the shell (require quoting/escaping)
295 .shell_chars_regex <- '[ <>()|\\:&;#?*\']'
296
297 # Find a program within the PATH. On OSX we need to explictly call
298 # /usr/bin/which with a forwarded PATH since OSX Yosemite strips
299 # the PATH from the environment of child processes
300 find_program <- function(program) {
301 if (is_osx()) {
302 res <- suppressWarnings({
303 # Quote the path (so it can contain spaces, etc.) and escape any quotes
304 # and escapes in the path itself
305 sanitized_path <- gsub("\\", "\\\\", Sys.getenv("PATH"), fixed = TRUE)
306 sanitized_path <- gsub("\"", "\\\"", sanitized_path, fixed = TRUE)
307 system(paste0("PATH=\"", sanitized_path, "\" /usr/bin/which ", program),
308 intern = TRUE)
309 })
310 if (length(res) == 0)
311 ""
312 else
313 res
314 } else {
315 Sys.which(program)
316 }
317 }
318
319 has_crop_tools <- function(...) knitr:::has_crop_tools(...)
320
321 # given a string, escape the regex metacharacters it contains:
322 # regex metas are these,
323 # . \ | ( ) [ { ^ $ * + ?
324 # as defined here:
325 # http://stat.ethz.ch/R-manual/R-devel/library/base/html/regex.html
326 escape_regex_metas <- function(in_str) {
327 gsub("([.\\|()[{^$+?])", "\\\\\\1", in_str)
328 }
329
330 latexmk <- function(file, engine, biblatex = FALSE) {
331 tinytex::latexmk(file, engine, if (biblatex) 'biber' else 'bibtex')
332 }
333
334 n_bytes <- function(string) {
335 nchar(string, type = "bytes")
336 }
337
338 starts_with_bytes <- function(string, bytes) {
339 Encoding(string) <- Encoding(bytes) <- "bytes"
340 if (n_bytes(bytes) > n_bytes(string))
341 return(FALSE)
342 substring(string, 1, n_bytes(bytes)) == bytes
343 }
344
345 ends_with_bytes <- function(string, bytes) {
346 Encoding(string) <- Encoding(bytes) <- "bytes"
347 if (n_bytes(bytes) > n_bytes(string))
348 return(FALSE)
349 substring(string, n_bytes(string) - n_bytes(bytes) + 1, n_bytes(string)) == bytes
350 }
351
352 base64_encode_object <- function(object) {
353 object <- rapply(object, unclass, how = "list")
354 json <- charToRaw(jsonlite::toJSON(object, auto_unbox = TRUE))
355 xfun::base64_encode(json)
356 }
357
358 base64_decode_object <- function(encoded) {
359 json <- rawToChar(xfun::base64_decode(encoded))
360 jsonlite::fromJSON(json)
361 }
362
363 read_file <- function(path, binary = FALSE) {
364 n <- file.info(path)$size
365 if (binary) {
366 readBin(path, raw(), n)
367 } else {
368 readChar(path, n, TRUE)
369 }
370 }
371
372 surround <- function(string, with) {
373 paste(with, string, with, sep = "")
374 }
375
376 to_html_attributes <- function(data, on_empty = "", prefix = " ") {
377
378 if (inherits(data, "html"))
379 return(data)
380
381 if (!length(data))
382 return(on_empty)
383
384 # escape attribute contents
385 escaped <- unlist(lapply(data, function(el) {
386 htmltools::htmlEscape(join(as.character(el), collapse = " "), attribute = TRUE)
387 }))
388
389 # generate html attributes as string
390 quoted <- surround(escaped, with = "\"")
391 result <- join(names(data), quoted, sep = "=", collapse = " ")
392
393 # add prefix if necessary
394 if (nzchar(prefix))
395 result <- join(prefix, result)
396
397 # mark as html and return
398 class(result) <- "html"
399 result
400
401 }
402
403 to_css <- function(data, on_empty = "", prefix = "") {
404
405 if (inherits(data, "html"))
406 return(data)
407
408 if (!length(data))
409 return(on_empty)
410
411 # collapse vectors in data list
412 collapsed <- unlist(lapply(data, function(el) {
413 join(el, collapse = " ")
414 }))
415
416 # paste into single string
417 joined <- join(names(data), collapsed, sep = ": ", collapse = "; ")
418
419 # add prefix
420 if (nzchar(prefix))
421 joined <- join(prefix, joined)
422
423 # return with trailing semi-colon
424 result <- join(joined, ";", sep = "")
425 class(result) <- "html"
426 result
427 }
428
429 rbind_list <- function(data) {
430 result <- do.call(mapply, c(c, data, USE.NAMES = FALSE, SIMPLIFY = FALSE))
431 names(result) <- names(data[[1]])
432 as.data.frame(result, stringsAsFactors = FALSE)
433 }
434
435 enumerate <- function(data, f, ...) {
436 lapply(seq_along(data), function(i) {
437 f(names(data)[[i]], data[[i]], ...)
438 })
439 }
440
441 insert <- function(vector, index, ...) {
442
443 dots <- list(...)
444 mode(dots) <- mode(vector)
445 n <- length(vector)
446
447 result <- if (index == 0) {
448 c(dots, vector)
449 } else if (index == n) {
450 c(vector, dots)
451 } else {
452 c(vector[1:index], dots, vector[(index + 1):n])
453 }
454
455 result
456 }
457
458 replace_binding <- function(binding, package, override) {
459 # override in namespace
460 if (!requireNamespace(package, quietly = TRUE))
461 stop(sprintf("Failed to load namespace for package '%s'", package))
462
463 namespace <- asNamespace(package)
464
465 # get reference to original binding
466 original <- get(binding, envir = namespace)
467
468 # replace the binding
469 if (is.function(override))
470 environment(override) <- namespace
471
472 do.call("unlockBinding", list(binding, namespace))
473 assign(binding, override, envir = namespace)
474 do.call("lockBinding", list(binding, namespace))
475
476 # if package is attached, override there as well
477 search_name <- paste("package", package, sep = ":")
478 if (search_name %in% search()) {
479 env <- as.environment(search_name)
480 do.call("unlockBinding", list(binding, env))
481 assign(binding, override, envir = env)
482 do.call("lockBinding", list(binding, env))
483 }
484
485 # return original
486 original
487 }
488
489 join <- function(..., sep = "", collapse = "") {
490 paste(..., sep = sep, collapse = collapse)
491 }
492
493 shell_exec <- function(cmd, intern = FALSE, wait = TRUE, ...) {
494 if (Sys.info()[["sysname"]] == "Windows")
495 shell(cmd, intern = intern, wait = wait, ...)
496 else
497 system(cmd, intern = intern, wait = wait, ...)
498 }
499
500 # Adjust the graphical device in chunk options: if the device from the output
501 # format is png but knitr's global chunk option is not png, respect knitr's
502 # option, because (1) users may knitr::opts_chunk$set(dev) (which usually means
503 # they know what they are doing) before rmarkdown::render(), and we probably
504 # should not override the user's choice; (2) the png device does not work on
505 # certain platforms (e.g. headless servers without X11), in which case knitr
506 # will set the device to svg instead of png by default in knitr:::set_html_dev,
507 # and rmarkdown should also respect this setting, otherwise we will run into
508 # issues like https://github.com/rstudio/rmarkdown/issues/1100
509 adjust_dev <- function(opts) {
510 dev <- knitr::opts_chunk$get('dev')
511 if (identical(opts$dev, 'png') && length(dev) == 1 && dev != 'png') {
512 opts$dev <- dev
513 }
514 opts
515 }
516
517 xfun_session_info <- function() {
518 paste('Pandoc version:', pandoc_version())
519 }
520
521 # given a path of a file (or dir) in a potential project (e.g., an R package),
522 # figure out the project root
523 proj_root <- function(path, file = '^DESCRIPTION$', pattern = '^Package: ', stop_when = NULL) {
524 dir <- if (dir_exists(path)) path else dirname(path)
525 if (same_path(dir, file.path(dir, '..'))) return()
526 for (f in list.files(dir, file, full.names = TRUE)) {
527 if (length(grep(pattern, read_utf8(f)))) return(dir)
528 }
529 if (is.function(stop_when) && stop_when(dir)) return()
530 dir <- normalize_path(dir)
531 proj_root(dirname(dir), file, pattern, stop_when)
532 }
533
534
535 # retrieve package version without fear of error
536 # loading namespace is ok as these packages have been or will be used
537 get_package_version_string <- function(package) {
538 tryCatch(
539 as.character(getNamespaceVersion(package)),
540 error = function(e) {
541 NULL
542 }
543 )
544 }
545 # find all loaded packages.
546 # May contain extra packages, but will contain all packages used while knitting
547 get_loaded_packages <- function() {
548 packages <- sort(loadedNamespaces())
549 version <- vapply(packages, get_package_version_string, character(1))
550
551 data.frame(
552 packages = packages,
553 version = version,
554 row.names = NULL, stringsAsFactors = FALSE
555 )
556 }
557
558 warning2 = function(...) warning(..., call. = FALSE)
559 stop2 = function(...) stop(..., call. = FALSE)
560
561 # devtools metadata -------------------------------------------------------
562
563 # from pkgdown & downlit
564 # https://github.com/r-lib/pkgdown/blob/77f909b0138a1d7191ad9bb3cf95e78d8e8d93b9/R/utils.r#L52
565
566 devtools_loaded <- function(x) {
567 if (!x %in% loadedNamespaces()) {
568 return(FALSE)
569 }
570 ns <- .getNamespace(x)
571 !is.null(ns$.__DEVTOOLS__)
572 }