forked from yihui/knitr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hooks.R
487 lines (459 loc) · 19.6 KB
/
hooks.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
#' Default plot hooks for different output formats
#'
#' These hook functions define how to mark up graphics output in different
#' output formats.
#'
#' Depending on the options passed over, \code{hook_plot_tex} may return the
#' normal \samp{\\includegraphics{}} command, or \samp{\\input{}} (for tikz
#' files), or \samp{\\animategraphics{}} (for animations); it also takes many
#' other options into consideration to align plots and set figure sizes, etc.
#' Similarly, \code{hook_plot_html} and \code{hook_plot_md} return character
#' strings which are HTML or Markdown code.
#'
#' In most cases we do not need to call these hooks explicitly, and it was
#' designed to be used internally. Sometimes we may not be able to record R
#' plots using \code{\link[grDevices]{recordPlot}}, and we can make use of these
#' hooks to insert graphics output in the output document; see
#' \code{\link{hook_plot_custom}} for details.
#' @param x a character vector of length 2 ; \code{x[1]} is the plot base
#' filename, and \code{x[2]} is the file extension
#' @param options a list of the current chunk options
#' @rdname hook_plot
#' @return A character string (code with plot filenames wrapped)
#' @references \url{http://yihui.name/knitr/hooks}
#' @seealso \code{\link{hook_plot_custom}}
#' @export
#' @examples ## this is what happens for a chunk like this
#' ## <<foo-bar-plot, dev='pdf', fig.align='right'>>=
#' hook_plot_tex(c('foo-bar-plot', 'pdf'), opts_chunk$merge(list(fig.align='right')))
#'
#' ## <<bar, dev='tikz'>>=
#' hook_plot_tex(c('bar', 'tikz'), opts_chunk$merge(list(dev='tikz')))
#'
#' ## <<foo, dev='pdf', fig.show='animate', interval=.1>>=
#' ## 5 plots are generated in this chunk
#' hook_plot_tex(c('foo5', 'pdf'), opts_chunk$merge(list(fig.show='animate',interval=.1,fig.cur=5, fig.num=5)))
hook_plot_tex = function(x, options) {
if (!options$include) return('')
rw = options$resize.width; rh = options$resize.height
resize1 = resize2 = ''
if (!is.null(rw) || !is.null(rh)) {
resize1 = sprintf('\\resizebox{%s}{%s}{', ifelse(is.null(rw), '!', rw),
ifelse(is.null(rh), '!', rh))
resize2 = '} '
}
tikz = is_tikz_dev(options)
a = options$fig.align; fig.cur = options$fig.cur; fig.num = options$fig.num
if (is.null(fig.cur)) fig.cur = 0L; if (is.null(fig.num)) fig.num = 1L
animate = options$fig.show == 'animate'
if (!tikz && animate && fig.cur < fig.num) return('')
align1 = align2 = ''
## multiple plots: begin at 1, end at fig.num
ai = options$fig.show != 'hold'
plot1 = ai || fig.cur <= 1L; plot2 = ai || fig.cur == 0L || fig.cur == fig.num
if (plot1) align1 = switch(a, left = '\n\n', center = '\n\n{\\centering ',
right = '\n\n\\hfill{}', '')
if (plot2) align2 = switch(a, left = '\\hfill{}\n\n', center = '\n\n}\n\n',
right = '\n\n', '')
## figure environment: caption, short caption, label
cap = options$fig.cap; scap = options$fig.scap; fig1 = fig2 = ''
mcap = fig.num > 1L && options$fig.show == 'asis'
if (mcap) {
cap = rep(cap, length.out = fig.num)[fig.cur] # multiple captions
scap = rep(scap, length.out = fig.num)[fig.cur]
} else {
cap = cap[1L]; scap = scap[1L]
}
if(length(cap) && !is.na(cap)) {
if (plot1) {
fig1 = sprintf('\\begin{figure}[%s]\n', options$fig.pos)
}
if (plot2) {
lab = str_c(options$fig.lp, options$label, ifelse(mcap, fig.cur, ''))
if (is.null(scap)) scap = str_split(cap, '\\.|;|:')[[1L]][1L]
scap = if(is.na(scap)) '' else str_c('[', scap, ']')
fig2 = sprintf('\\caption%s{%s\\label{%s}}\n\\end{figure}\n', scap, cap, lab)
}
}
size = paste(c(sprintf('width=%s', options$out.width),
sprintf('height=%s', options$out.height)), collapse = ',')
paste(fig1, align1, resize1,
if (tikz) {
sprintf('\\input{%s.tikz}', x[1])
} else if (animate) {
## \animategraphics{} should be inserted only *once*!
aniopts = options$aniopts
aniopts = if (is.na(aniopts)) NULL else gsub(';', ',', aniopts)
if (nzchar(size)) size = paste(size, sprintf('%s', aniopts), sep = ',')
if (nzchar(size)) size = sprintf('[%s]', size)
sprintf('\\animategraphics%s{%s}{%s}{%s}{%s}', size, 1/options$interval,
sub(str_c(fig.num, '$'), '', x[1]), 1L, fig.num)
} else {
if (nzchar(size)) size = sprintf('[%s]', size)
sprintf('\\includegraphics%s{%s} ', size, x[1])
},
resize2, align2, fig2, sep = '')
}
#' @rdname hook_plot
#' @export
hook_plot_html = function(x, options) {
## TODO: output size not implemented for HTML yet
if(options$fig.show == 'animate') {
.ani.plot.hook.html(x, options)
} else {
## TODO: output size not implemented for HTML yet
a = options$fig.align
sprintf('<img src="%s" class="plot" %s/>\n', .upload.url(x),
switch(a, default = '', left = 'style="float: left"',
right = 'style="float: right"',
center = 'style="margin: auto; display: block"'))
}
}
#' @rdname hook_plot
#' @export
hook_plot_md = function(x, options) {
if(options$fig.show == 'animate') {
.ani.plot.hook.html(x, options)
} else {
base = opts_knit$get('base.url')
if (is.null(base)) base = ''
cap = if (is.null(fig.cap <- options$fig.cap)) {
sprintf('plot of chunk %s', options$label)
} else {
if (options$fig.num == 1L) fig.cap[1] else fig.cap[options$fig.cur]
}
sprintf('![%s](%s%s) ', cap, base, .upload.url(x))
}
}
## a wrapper to imgur_upload to get the URL of images when option upload==TRUE
.upload.url = function(x) {
file = paste(x, collapse = '.')
opts_knit$get('upload.fun')(file)
}
.chunk.hook.tex = function(x, options) {
col = if (ai <- output_asis(x, options)) '' else
str_c(color_def(options$background), ifelse(is_tikz_dev(options), '', '\\color{fgcolor}'))
k1 = str_c(col, '\\begin{kframe}\n')
k2 = '\\end{kframe}'
x = str_c(k1, x, k2)
## rm empty kframe and verbatim environments
x = gsub('\\\\begin\\{(kframe)\\}\\s*\\\\end\\{\\1\\}', '', x)
x = gsub('\\\\end\\{(verbatim)\\}\\s*\\\\begin\\{\\1\\}[\n]?', '', x)
if (!ai) x = str_c('\\begin{knitrout}\n', x, '\n\\end{knitrout}')
if (options$split) {
name = fig_path('.tex', options)
if (!file.exists(dirname(name)))
dir.create(dirname(name))
cat(x, file = name)
sprintf('\\input{%s}', name)
} else x
}
.chunk.hook.html = function(x, options) {
if (output_asis(x, options)) return(x)
x = sprintf('<pre class="knitr">%s</pre>', x)
if (options$split) {
name = fig_path('.html', options)
if (!file.exists(dirname(name)))
dir.create(dirname(name))
cat(x, file = name)
sprintf('<iframe src="%s" class="knitr" width="100%%"></iframe>', name)
} else x
}
.ani.plot.hook.html = function(x, options) {
# pull out all the relevant plot options
fig.num = options$fig.num
fig.cur = options$fig.cur
if(is.null(fig.cur)) fig.cur = 0
# Don't print out intermediate plots if we're animating
if(fig.cur < fig.num) return('')
# set up the ffmpeg run
ffmpeg.opts = options$aniopts
fig.fname = str_c(sub(str_c(fig.num, '$'), '%d', x[1]), x[2])
mov.fname = str_c(sub(paste(fig.num, '$',sep = ''), '', x[1]), ".mp4")
if(is.na(ffmpeg.opts)) ffmpeg.opts = NULL
ffmpeg.cmd = paste("ffmpeg", "-y", "-r", 1/options$interval,
"-i", fig.fname, mov.fname)
system(ffmpeg.cmd, ignore.stdout = TRUE)
# figure out the options for the movie itself
mov.opts = sc_split(options$aniopts)
opt.str = paste(sprintf('width=%s', options$out.width),
sprintf('height=%s', options$out.height),
if('controls' %in% mov.opts) 'controls="controls"',
if('loop' %in% mov.opts) 'loop="loop"')
sprintf('<video %s><source src="%s" type="video/mp4" />video of chunk %s</video>',
opt.str, mov.fname, options$label)
}
## format a single inline object
.inline.hook = function(x) {
paste(as.character(x), collapse = ', ')
}
## inline hook for tex
.inline.hook.tex = function(x) {
if (is.numeric(x)) x = format_sci(x, 'latex')
.inline.hook(x)
}
## single param hook: a function of one argument
.param.hook = function(before, options, envir) {
if (before) {
'do something before the code chunk'
} else {
'do something after the code chunk'
}
}
.out.hook = function(x, options) x
.verb.hook = function(x, options) str_c('\\begin{verbatim}\n', x, '\\end{verbatim}\n')
.default.hooks = list(source = .out.hook, output = .out.hook, warning = .out.hook,
message = .out.hook, error = .out.hook, plot = hook_plot_tex,
inline = .inline.hook, chunk = function(x, options) x)
#' Hooks for R code chunks, inline R code and output
#'
#' A hook is a function of a pre-defined form (arguments) that takes values of
#' arguments and returns desired output. The object \code{knit_hooks} is used to
#' access or set hooks in this package.
#' @export
#' @references Usage: \url{http://yihui.name/knitr/objects}
#'
#' Components in \code{knit_hooks}: \url{http://yihui.name/knitr/hooks}
#' @examples knit_hooks$get('source'); knit_hooks$get('inline')
knit_hooks = new_defaults(.default.hooks)
## hooks that return character values will be inserted into final output
run_hooks = function(before, options, envir) {
## default and user-defined new hooks
hooks.d = knit_hooks$get(default = TRUE); hooks.n = knit_hooks$get()
hooks.a = hooks.n[setdiff(names(hooks.n), names(hooks.d))] # a list of hooks to run
out = NULL
for (i in names(hooks.a)) {
if (!is.null(options[[i]])) {
## run only when option is not NULL
res = hooks.a[[i]](before = before, options = options, envir = envir)
if (is.character(res)) out = c(out, res)
}
}
out
}
#' Set output hooks for different output formats
#'
#' These functions set built-in output hooks for LaTeX, HTML and Markdown.
#'
#' There are three variants of markdown documents: ordinary markdown
#' (\code{render_markdown()}), GFM (GitHub Flavored Markdown;
#' \code{render_gfm()}) and Jekyll (a blogging system on GitHub;
#' \code{render_jekyll()}). For LaTeX output, there are three variants as well:
#' \pkg{knitr}'s default style (\code{render_latex()}; use the LaTeX
#' \pkg{framed} package), Sweave style (\code{render_sweave()}; use
#' \file{Sweave.sty}) and listings style (\code{render_listings()}; use LaTeX
#' \pkg{listings} package). Default HTML output hooks are set by
#' \code{render_html()}.
#'
#' These functions can be used before \code{knit()} or in the first chunk of the
#' input document (ideally this chunk has options \code{include = FALSE} and
#' \code{cache = FALSE}) so that all the following chunks will be formatted as
#' expected.
#'
#' You can use \code{\link{knit_hooks}} to further customize output hooks; see
#' references.
#' @rdname output_hooks
#' @return \code{NULL}; corresponding hooks are set as a side effect
#' @export
#' @references See output hooks in \url{http://yihui.name/knitr/hooks}
render_latex = function() {
if (child_mode()) return()
test_latex_pkg('framed', system.file('misc', 'framed.sty', package = 'knitr'))
h = opts_knit$get('header')
if (!nzchar(h['framed'])) set_header(framed = .header.framed)
if (!nzchar(h['highlight'])) {
# header for Latex Syntax Highlighting
.header.hi.tex = paste(theme_to_header_latex('edit-eclipse')$highlight,
collapse = '\n')
set_header(highlight = .header.hi.tex)
}
knit_hooks$restore()
knit_hooks$set(source = function(x, options) {
if (options$highlight) {
## gsub() makes sure " will not produce an umlaut
str_c('\\begin{flushleft}\n', gsub('"', '"{}', x, fixed = TRUE),
'\\end{flushleft}\n')
} else .verb.hook(x, options)
}, output = function(x, options) {
if (output_asis(x, options)) {
str_c('\\end{kframe}\n', x, '\n\\begin{kframe}')
} else .verb.hook(x, options)
}, warning = .verb.hook, message = .verb.hook, error = .verb.hook,
inline = .inline.hook.tex, chunk = .chunk.hook.tex,
plot = function(x, options) {
## escape plot environments from kframe
str_c('\\end{kframe}', hook_plot_tex(x, options), '\\begin{kframe}')
})
}
#' @rdname output_hooks
#' @export
render_sweave = function() {
if (child_mode()) return()
opts_chunk$set(highlight = FALSE, comment = NA, prompt = TRUE) # mimic Sweave settings
test_latex_pkg('Sweave', file.path(R.home("share"), "texmf", "tex", "latex", "Sweave.sty"))
set_header(framed = '', highlight = '\\usepackage{Sweave}')
knit_hooks$restore()
## wrap source code in the Sinput environment, output in Soutput
hook.i = function(x, options) str_c('\\begin{Sinput}\n', x, '\\end{Sinput}\n')
hook.s = function(x, options) str_c('\\begin{Soutput}\n', x, '\\end{Soutput}\n')
hook.o = function(x, options) if (output_asis(x, options)) x else hook.s(x, options)
hook.c = function(x, options) str_c('\\begin{Schunk}\n', x, '\\end{Schunk}\n')
knit_hooks$set(source = hook.i, output = hook.o, warning = hook.s,
message = hook.s, error = hook.s, inline = .inline.hook.tex,
plot = hook_plot_tex, chunk = hook.c)
}
#' @rdname output_hooks
#' @export
render_listings = function() {
if (child_mode()) return()
render_sweave()
opts_chunk$set(prompt = FALSE)
test_latex_pkg('Sweavel', system.file('misc', 'Sweavel.sty', package = 'knitr'))
set_header(framed = '', highlight = '\\usepackage{Sweavel}')
invisible(NULL)
}
#' @rdname output_hooks
#' @export
render_html = function() {
knit_hooks$restore()
## use div with different classes
html.hook = function(name) {
force(name)
function (x, options) sprintf('<div class="%s">%s</div>', name, x)
}
h = opts_knit$get('header')
if (!nzchar(h['highlight'])) {
# CSS for html syntax highlighting
.header.hi.html = paste(theme_to_header_html('default')$highlight,
collapse = '\n')
set_header(highlight = .header.hi.html)
}
z = list()
for (i in c('source', 'output', 'warning', 'message', 'error'))
z[[i]] = html.hook(i)
knit_hooks$set(z)
knit_hooks$set(inline = function(x) {
sprintf(if (inherits(x, 'AsIs')) '%s' else '<code class="knitr inline">%s</code>',
.inline.hook(format_sci(x, 'html')))
}, plot = hook_plot_html, chunk = .chunk.hook.html)
}
#' @rdname output_hooks
#' @export
render_markdown = function() {
knit_hooks$restore()
## four spaces lead to <pre></pre>
hook.t = function(x, options) str_c('\n\n', line_prompt(x, ' ', ' '), '\n')
hook.o = function(x, options) if (output_asis(x, options)) x else hook.t(x, options)
knit_hooks$set(source = hook.t, output = hook.o, warning = hook.t,
error = hook.t, message = hook.t,
inline = function(x) sprintf('`%s`', .inline.hook(format_sci(x, 'html'))),
plot = hook_plot_md)
}
#' @rdname output_hooks
#' @export
render_gfm = function() {
## gfm and jekyll are derived from markdown
render_markdown()
hook.r = function(x, options) str_c('\n\n```r\n', x, '```\n\n')
hook.t = function(x, options) str_c('\n\n```\n', x, '```\n\n')
hook.o = function(x, options) if (output_asis(x, options)) x else hook.t(x, options)
knit_hooks$set(source = hook.r, output = hook.o, warning = hook.t,
error = hook.t, message = hook.t)
}
#' @rdname output_hooks
#' @export
render_jekyll = function() {
render_markdown()
hook.r = function(x, options) str_c('\n\n{% highlight r %}\n', x, '{% endhighlight %}\n\n')
hook.t = function(x, options) str_c('\n\n{% highlight text %}\n', x, '{% endhighlight %}\n\n')
hook.o = function(x, options) if (output_asis(x, options)) x else hook.t(x, options)
knit_hooks$set(source = hook.r, output = hook.o, warning = hook.t,
error = hook.t, message = hook.t)
}
## may add textile, ReST and many other markup languages
#' Built-in chunk hooks to extend knitr
#'
#' Hook functions are called when the corresponding chunk options are
#' \code{TRUE} to do additional jobs beside the R code in chunks. This package
#' provides a few useful hooks, which can also serve as examples of how to
#' define chunk hooks in \pkg{knitr}.
#'
#' The function \code{hook_rgl} can be set as a hook in \pkg{knitr} to save
#' plots produced by the \pkg{rgl} package. According to the chunk option
#' \samp{dev} (graphical device), plots can be save to different formats
#' (\samp{postscript}: \samp{eps}; \samp{pdf}: \samp{pdf}; other devices
#' correspond to the default PNG format). The plot window will be adjusted
#' according to chunk options \samp{width} and \samp{height}. Filenames are
#' derived from chunk labels and the prefix string.
#'
#' The function \code{hook_pdfcrop} can use the program \command{pdfcrop} to
#' crop the extra white margin in order to make better use of the space in the
#' output document, otherwise we often have to struggle with
#' \code{\link[graphics]{par}} to set appropriate margins. Note
#' \command{pdfcrop} often comes with a LaTeX distribution such as MiKTeX or
#' TeXLive, and you may not need to install it separately (use
#' \code{Sys.which('pdfcrop')} to check it; if it not empty, you are able to use
#' it).
#'
#' When the plots are not recordable via \code{\link[grDevices]{recordPlot}} and
#' we save the plots to files manually via other functions (e.g. \pkg{rgl}
#' plots), we can use the chunk hook \code{hook_plot_custom} to help write code
#' for graphics output into the output document.
#' @rdname chunk_hook
#' @param before,options,envir see references
#' @references \url{http://yihui.name/knitr/hooks#chunk_hooks}
#' @seealso \code{\link[rgl]{rgl.snapshot}}, \code{\link[rgl]{rgl.postscript}}
#' @export
#' @examples knit_hooks$set(rgl = hook_rgl)
#' ## then in code chunks, use the option rgl=TRUE
hook_rgl = function(before, options, envir) {
## after a chunk has been evaluated
if (before || !require('rgl') || rgl.cur() == 0) return() # no active device
name = fig_path()
par3d(windowRect = 100 + options$dpi * c(0, 0, options$fig.width, options$fig.height))
Sys.sleep(.05) # need time to respond to window size change
fmt = opts_knit$get('out.format')
if (fmt %in% c('html', 'markdown', 'gfm', 'jekyll')) options$dev = 'png'
## support 3 formats: eps, pdf and png (default)
switch(options$dev,
postscript = rgl.postscript(str_c(name, '.eps'), fmt = 'eps'),
pdf = rgl.postscript(str_c(name, '.pdf'), fmt = 'pdf'),
rgl.snapshot(str_c(name, '.png'), fmt = 'png'))
hook_plot_custom(before, options, envir)
}
#' @export
#' @rdname chunk_hook
hook_pdfcrop = function(before, options, envir) {
## crops PDF after a chunk is evaluated and PDF files produced
ext = options$fig.ext
if (options$dev == 'tikz' && options$external) ext = 'pdf'
if (before || (fig.num <- options$fig.num) == 0L || ext != 'pdf')
return()
paths = paste(valid_path(options$fig.path, options$label),
if (fig.num == 1L) '' else seq_len(fig.num), ".pdf", sep = "")
lapply(paths, function(x) {
message('cropping ', x)
x = shQuote(x)
system(paste("pdfcrop", x, x, sep = " "))
})
return()
}
#' @export
#' @rdname chunk_hook
hook_plot_custom = function(before, options, envir){
if(before) return() # run hook after the chunk
ext = options$fig.ext
if(is.null(ext)) ext = dev2ext(options$dev)
name = fig_path()
fmt = opts_knit$get('out.format')
if (fmt %in% c('sweave', 'listings')) fmt = 'latex'
hook = switch(fmt, latex = hook_plot_tex, html = hook_plot_html, hook_plot_md)
n = options$fig.num
if (n <= 1L) hook(c(name, ext), options) else {
res = unlist(lapply(seq_len(n), function(i) {
options$fig.cur = i
hook(c(str_c(name, i), ext), options)
}), use.names = FALSE)
str_c(res, collapse = '')
}
}