Debian Codegraph @

R/defaults.R

raw
1 #' @include utils.R
2
3 new_defaults = function(value = list()) {
4 defaults = value
5 locked = FALSE
6
7 get = function(name, default = FALSE, drop = TRUE) {
8 if (default) defaults = value # this is only a local version
9 if (missing(name)) defaults else {
10 if (drop && length(name) == 1) defaults[[name]] else {
11 setNames(defaults[name], name)
12 }
13 }
14 }
15 resolve = function(...) {
16 dots = list(...)
17 if (length(dots) == 0) return()
18 if (is.null(names(dots)) && length(dots) == 1 && is.list(dots[[1]]))
19 if (length(dots <- dots[[1]]) == 0) return()
20 dots
21 }
22 set2 = function(values) {
23 old = get(names(values), drop = FALSE)
24 if (length(values)) {
25 # TODO: change warning() to stop() and no longer whitelist JuliaCall
26 if (locked && !identical(names(values), 'Jfig.cur')) warning(
27 'The object is read-only and cannot be modified. If you have to modify it ',
28 'for a legitimate reason, call the method $lock(FALSE) on the object before $set(). ',
29 'Using $lock(FALSE) to modify the object will be enforced in future versions of knitr ',
30 'and this warning will become an error.',
31 immediate. = TRUE
32 )
33 defaults <<- merge(values)
34 }
35 invisible(old)
36 }
37 set = function(...) {
38 set2(resolve(...))
39 }
40 delete = function(keys) {
41 for (k in keys) defaults[[k]] <<- NULL
42 }
43 merge = function(values) merge_list(defaults, values)
44 restore = function(target = value) defaults <<- target
45 append = function(...) {
46 dots = resolve(...)
47 for (i in names(dots)) dots[[i]] <- c(defaults[[i]], dots[[i]])
48 set2(dots)
49 }
50 lock = function(status = TRUE) locked <<- status
51
52 list(
53 get = get, set = set, delete = delete, append = append, merge = merge,
54 restore = restore, lock = lock
55 )
56 }
57
58 #' Default and current chunk options
59 #'
60 #' Options for R code chunks. When running R code, the object \code{opts_chunk}
61 #' (default options) is not modified by chunk headers (local chunk options are
62 #' merged with default options), whereas \code{opts_current} (current options)
63 #' changes with different chunk headers and it always reflects the options for
64 #' the current chunk.
65 #'
66 #' Normally we set up the global options once in the first code chunk in a
67 #' document using \code{opts_chunk$set()}, so that all \emph{latter} chunks will
68 #' use these options. Note the global options set in one chunk will not affect
69 #' the options in this chunk itself, and that is why we often need to set global
70 #' options in a separate chunk.
71 #'
72 #' See \code{str(knitr::opts_chunk$get())} for a list of default chunk options.
73 #' @references Usage: \url{https://yihui.org/knitr/objects/}
74 #'
75 #' A list of available options:
76 #' \url{https://yihui.org/knitr/options/#chunk-options}
77 #' @note \code{opts_current} should be treated as read-only and you are supposed
78 #' to only query its values via \code{opts_current$get()}. Calling
79 #' \code{opts_current$set()} will throw an error.
80 #' @export
81 #' @examples opts_chunk$get('prompt'); opts_chunk$get('fig.keep')
82 opts_chunk = new_defaults(list(
83 eval = TRUE, echo = TRUE, results = 'markup', tidy = FALSE, tidy.opts = NULL,
84 collapse = FALSE, prompt = FALSE, comment = '##', highlight = TRUE,
85 size = 'normalsize', background = '#F7F7F7',
86
87 # value wrapped in I() means a change in default option later
88 # (e.g in fix_options, conditionally to other argument)
89 strip.white = I(TRUE),
90
91 cache = FALSE, cache.path = 'cache/', cache.vars = NULL, cache.lazy = TRUE,
92 dependson = NULL, autodep = FALSE, cache.rebuild = FALSE,
93
94 fig.keep = 'high', fig.show = 'asis', fig.align = 'default', fig.path = 'figure/',
95 dev = NULL, dev.args = NULL, dpi = 72, fig.ext = NULL, fig.width = 7, fig.height = 7,
96 fig.env = 'figure', fig.cap = NULL, fig.scap = NULL, fig.lp = 'fig:', fig.subcap = NULL,
97 fig.pos = '', out.width = NULL, out.height = NULL, out.extra = NULL, fig.retina = 1,
98 external = TRUE, sanitize = FALSE, interval = 1, aniopts = 'controls,loop',
99
100 warning = TRUE, error = TRUE, message = TRUE,
101
102 render = NULL,
103
104 ref.label = NULL, child = NULL, engine = 'R', split = FALSE, include = TRUE, purl = TRUE
105
106 ))
107
108 #' @rdname opts_chunk
109 #' @export
110 opts_current = new_defaults()
111 opts_current$restore(opts_chunk$get())
112
113 #' @include plot.R
114
115 # a list of options attributes for RStudio
116 opts_chunk_attr = local({
117 opts = lapply(opts_chunk$get(), class)
118 opts[opts == 'NULL'] = 'character'
119 opts$results = list('markup', 'asis', 'hold', 'hide')
120 opts$fig.show = list('asis', 'hold', 'animate', 'hide')
121 opts$fig.keep = list('high', 'none', 'all', 'first', 'last')
122 opts$fig.align = list('default', 'left', 'right', 'center')
123 opts$fig.showtext = 'logical'
124 # quartz_ devices are for OS X only
125 opts$dev = names(auto_exts)
126 if (Sys.info()[['sysname']] != 'Darwin')
127 opts$dev = grep('^quartz_', opts$dev, value = TRUE, invert = TRUE)
128 if (.Platform$OS.type != 'windows')
129 opts$dev = setdiff(opts$dev, 'win.metafile')
130 opts$dev = opts$fig.format = as.list(opts$dev)
131 opts$fig.dpi = 'numeric'
132 opts$fig.ext = as.list(unique(auto_exts))
133 opts$external = opts$sanitize = NULL # hide these two rare options
134 opts$fig.process = 'function'
135 opts[c('fig.asp', 'fig.ncol')] = 'numeric'
136 opts$fig.dim = 'list'
137 opts$fig.id = 'logical'
138 opts[c(
139 'opts.label', 'resize.width', 'resize.height', 'fig.alt', 'fig.link', 'fig.sep',
140 'tab.cap', 'ffmpeg.bitrate', 'ffmpeg.format'
141 )] = 'character'
142 opts$lang = 'list'
143 opts$R.options = 'list'
144 opts$cache.comments = 'logical'
145 opts$cache.globals = 'list'
146 opts$animation.hook = list('ffmpeg', 'gifski')
147 for (i in c('class', 'attr')) {
148 for (j in c('source', 'output', 'message', 'warning', 'error', 'chunk')) {
149 opts[[paste(i, j, sep = '.')]] = 'character'
150 }
151 }
152 # for R Markdown paged tables
153 opts[paste0(c(
154 'max', 'sql.max', 'paged', 'rows', 'cols', 'cols.min', 'pages', 'paged', 'rownames'
155 ), '.print')] = 'numeric'
156 opts
157 })
158
159 #' Set aliases for chunk options
160 #'
161 #' We do not have to use the chunk option names given in \pkg{knitr}; we can set
162 #' aliases for them. The aliases are a named character vector; the names are
163 #' aliases and the elements in this vector are the real option names.
164 #' @param ... Named arguments. Argument names are aliases, and argument values
165 #' are real option names.
166 #' @return \code{NULL}. \code{opts_knit$get('aliases')} is modified as the side effect.
167 #' @export
168 #' @examples set_alias(w = 'fig.width', h = 'fig.height')
169 #' # then we can use options w and h in chunk headers instead of fig.width and fig.height
170 set_alias = function(...) {
171 opts_knit$set(aliases = c(...))
172 }
173
174 #' Options for the knitr package
175 #'
176 #' Options including whether to use a progress bar when knitting a document, and
177 #' the base directory of images, etc.
178 #'
179 #' Besides the standard usage (\code{opts_knit$set()}), we can also set package
180 #' options prior to loading \code{knitr} or calling \code{knit()} using
181 #' \code{\link{options}()} in base R. A global option \code{knitr.package.foo}
182 #' in \code{options()} will be set as an option \code{foo} in \code{opts_knit},
183 #' i.e. global options in base R with the prefix \code{knitr.package.}
184 #' correspond to options in \code{opts_knit}. This can be useful to set package
185 #' options in \file{~/.Rprofile} without loading \pkg{knitr}.
186 #'
187 #' See \code{str(knitr::opts_knit$get())} for a list of default package options.
188 #' @references Usage: \url{https://yihui.org/knitr/objects/}
189 #'
190 #' A list of available options:
191 #' \url{https://yihui.org/knitr/options/#package-options}
192 #' @export
193 #' @examples opts_knit$get('verbose'); opts_knit$set(verbose = TRUE) # change it
194 #' if (interactive()) {
195 #' # for unnamed chunks, use 'fig' as the figure prefix
196 #' opts_knit$set(unnamed.chunk.label='fig')
197 #' knit('001-minimal.Rmd') # from https://github.com/yihui/knitr-examples
198 #' }
199 #' @include hooks-html.R
200 opts_knit = new_defaults(list(
201 progress = TRUE, verbose = FALSE, eval.after = c('fig.cap', 'fig.scap', 'fig.alt'),
202 base.dir = NULL, base.url = NULL, root.dir = NULL, child.path = '',
203 upload.fun = identity, global.device = FALSE, global.par = FALSE,
204 concordance = FALSE, documentation = 1L, self.contained = TRUE,
205 unnamed.chunk.label = 'unnamed-chunk', highr.opts = NULL,
206 label.prefix = c(table = 'tab:'), latex.tilde = NULL,
207
208 # internal options; users should not touch them
209 out.format = NULL, child = FALSE, parent = FALSE, tangle = FALSE, aliases = NULL,
210 header = c(highlight = '', tikz = '', framed = ''), global.pars = NULL
211 ))
212 # tangle: whether I'm in tangle mode; child: whether I'm in child document mode;
213 # parent: whether I need to add parent preamble to the child output
214
215 # adjust opts_chunk and opts_knit according to options(), e.g.
216 # options(knitr.package.progress = FALSE) --> opts_knit$set(progress = FALSE),
217 # and options(knitr.chunk.tidy) --> opts_chunk$set(tidy = TRUE); this makes it
218 # possible to set options in ~/.Rprofile without loading knitr
219 adjust_opts_knit = function() {
220 # begin_hack: R CMD build does not evaluate .Rprofile, but I need a way to
221 # modify opts_chunk just for myself
222 if (nzchar(opts <- Sys.getenv('R_KNITR_OPTIONS')))
223 eval(parse_only(sprintf('base::options(%s)', opts)), envir = globalenv())
224 # end_hack
225 opts = options()
226 nms = names(opts)
227 if (length(nms <- grep('^knitr[.]', nms, value = TRUE)) == 0) return()
228 opts = opts[nms]
229 # strip off knitr.chunk from option names and set chunk options
230 i = grep('^knitr[.]chunk[.]', nms)
231 opts_chunk$set(setNames(opts[i], sub('^knitr[.]chunk[.]', '', nms[i])))
232 # similarly for knitr.package.options
233 i = grep('^knitr[.]package[.]', nms)
234 opts_knit$set(setNames(opts[i], sub('^knitr[.]package[.]', '', nms[i])))
235 }
236
237 #' Template for creating reusable chunk options
238 #'
239 #' Creates a template binding a label to a set of chunk options. Every chunk
240 #' that references the template label will have the specified set of options
241 #' applied to it.
242 #' @export
243 #' @examples opts_template$set(myfigures = list(fig.height = 4, fig.width = 4))
244 #' # later you can reuse these chunk options by 'opts.label', e.g.
245 #'
246 #' # <<foo, opts.label='myfigures'>>=
247 #'
248 #' # the above is equivalent to <<foo, fig.height=4, fig.width=4>>=
249 opts_template = new_defaults()