Debian Codegraph @

R/hooks.R

raw
1 # format a single inline object
2 .inline.hook = function(x) {
3 if (is.numeric(x)) x = round_digits(x)
4 paste(as.character(x), collapse = ', ')
5 }
6 .out.hook = function(x, options) x
7 .plot.hook = function(x, options) paste(x, collapse = '.')
8
9 .default.hooks = list(
10 source = .out.hook, output = .out.hook, warning = .out.hook,
11 message = .out.hook, error = .out.hook, plot = .plot.hook,
12 inline = .inline.hook, chunk = .out.hook, text = identity,
13 evaluate.inline = function(code, envir = knit_global()) {
14 v = withVisible(eval(parse_only(code), envir = envir))
15 if (v$visible) knit_print(v$value, inline = TRUE, options = opts_chunk$get())
16 },
17 evaluate = function(...) evaluate::evaluate(...), document = identity
18 )
19
20 #' Hooks for R code chunks, inline R code and output
21 #'
22 #' A hook is a function of a pre-defined form (arguments) that takes values of
23 #' arguments and returns desired output. The object \code{knit_hooks} is used to
24 #' access or set hooks in this package.
25 #' @export
26 #' @references Usage: \url{https://yihui.org/knitr/objects/}
27 #'
28 #' Components in \code{knit_hooks}: \url{https://yihui.org/knitr/hooks/}
29 #' @examples knit_hooks$get('source'); knit_hooks$get('inline')
30 knit_hooks = new_defaults(.default.hooks)
31
32 run_hook = function(.name, ...) {
33 fun = knit_hooks$get(.name)
34 if (is.function(fun)) fun(...)
35 }
36
37 render_brew = function() NULL
38
39 # the chunk option out.lines = n (first n rows), -n (last n rows), or c(n1, n2)
40 # (first n1 and last n2 rows)
41 hook_suppress = function(x, options) {
42 n = options$out.lines
43 if (length(n) == 0 || !is.numeric(n) || length(n) > 2) return(x)
44 x = split_lines(x)
45 m = length(x)
46 if (length(n) == 1) {
47 if (m > abs(n)) {
48 x = if (n >= 0) c(head(x, n), '....') else c('....', tail(x, -n))
49 }
50 } else {
51 if (m > sum(n)) x = c(head(x, n[1]), '....', tail(x, n[2]))
52 }
53 one_string(x)
54 }
55
56 #' Hooks for code chunk options
57 #'
58 #' Like \code{\link{knit_hooks}}, this object can be used to set hook functions
59 #' to manipulate chunk options.
60 #'
61 #' For every code chunk, if the chunk option named, say, \code{FOO}, is not
62 #' \code{NULL}, and a hook function with the same name has been set via
63 #' \code{opts_hooks$set(FOO = function(options) { options })} (you can manipuate
64 #' the \code{options} argument in the function and return it), the hook function
65 #' will be called to update the chunk options.
66 #' @references \url{https://yihui.org/knitr/hooks/}
67 #' @export
68 #' @examples # make sure the figure width is no smaller than fig.height
69 #' opts_hooks$set(fig.width = function(options) {
70 #' if (options$fig.width < options$fig.height) {
71 #' options$fig.width = options$fig.height
72 #' }
73 #' options
74 #' })
75 #' # remove all hooks
76 #' opts_hooks$restore()
77 opts_hooks = new_defaults(list())