Debian Codegraph @

R/hooks-latex.R

raw
1 #' Default plot hooks for different output formats
2 #'
3 #' These hook functions define how to mark up graphics output in different
4 #' output formats.
5 #'
6 #' Depending on the options passed over, \code{hook_plot_tex} may return the
7 #' normal \samp{\\includegraphics{}} command, or \samp{\\input{}} (for tikz
8 #' files), or \samp{\\animategraphics{}} (for animations); it also takes many
9 #' other options into consideration to align plots and set figure sizes, etc.
10 #' Similarly, \code{hook_plot_html}, \code{hook_plot_md} and
11 #' \code{hook_plot_rst} return character strings which are HTML, Markdown, reST
12 #' code.
13 #'
14 #' In most cases we do not need to call these hooks explicitly, and they were
15 #' designed to be used internally. Sometimes we may not be able to record R
16 #' plots using \code{grDevices::\link{recordPlot}()}, and we can make use of
17 #' these hooks to insert graphics output in the output document; see
18 #' \code{\link{hook_plot_custom}} for details.
19 #' @param x Filename for the plot (a character string).
20 #' @param options A list of the current chunk options.
21 #' @rdname hook_plot
22 #' @return A character string of code, with plot filenames wrapped.
23 #' @references \url{https://yihui.org/knitr/hooks/}
24 #' @seealso \code{\link{hook_plot_custom}}
25 #' @export
26 #' @examples # this is what happens for a chunk like this
27 #'
28 #' # <<foo-bar-plot, dev='pdf', fig.align='right'>>=
29 #' hook_plot_tex('foo-bar-plot.pdf', opts_chunk$merge(list(fig.align='right')))
30 #'
31 #' # <<bar, dev='tikz'>>=
32 #' hook_plot_tex('bar.tikz', opts_chunk$merge(list(dev='tikz')))
33 #'
34 #' # <<foo, dev='pdf', fig.show='animate', interval=.1>>=
35 #'
36 #' # 5 plots are generated in this chunk
37 #' hook_plot_tex('foo5.pdf', opts_chunk$merge(list(fig.show='animate',interval=.1,fig.cur=5, fig.num=5)))
38 hook_plot_tex = function(x, options) {
39 # This function produces the image inclusion code for LaTeX.
40 # optionally wrapped in code that resizes it, aligns it, handles it
41 # as a subfigure, and/or wraps it in a float. Here is a road map of
42 # the intermediate variables this function fills in (or leaves empty,
43 # as needed), and an impression of their (possible) contents.
44 #
45 # fig1, # \begin{...}[...]
46 # align1, # {\centering
47 # sub1, # \subfloat[...]{
48 # resize1, # \resizebox{...}{...}{
49 # tikz code # '\\input{chunkname.tikz}'
50 # or animate code # or '\\animategraphics[size]{1/interval}{chunkname}{1}{fig.num}'
51 # or plain code # or '\\includegraphics[size]{chunkname}'
52 # resize2, # }
53 # sub2, # }
54 # align2, # }
55 # fig2 # \caption[...]{...\label{...}}
56 # # \end{...} % still fig2
57
58 rw = options$resize.width
59 rh = options$resize.height
60 rc = options$resize.command
61 resize1 = resize2 = ''
62 if (is.null(rc)) {
63 if (!is.null(rw) || !is.null(rh)) {
64 resize1 = sprintf('\\resizebox{%s}{%s}{', rw %n% '!', rh %n% '!')
65 resize2 = '} '
66 }
67 } else {
68 # users can specify a custom "resize" command (we can use an arbitrary
69 # command, e.g., framebox)
70 resize1 = paste0('\\', rc, '{')
71 resize2 = '} '
72 }
73
74 tikz = is_tikz_dev(options)
75
76 a = options$fig.align
77 fig.cur = options$fig.cur %n% 1L
78 fig.num = options$fig.num %n% 1L
79 animate = options$fig.show == 'animate'
80 fig.ncol = options$fig.ncol %n% fig.num
81 if (is.null(fig.sep <- options$fig.sep)) {
82 fig.sep = character(fig.num)
83 # add \newline after every fig.ncol figures; if the last figure is not the
84 # last on its row, skip adding \newline (not necessary, but may be harmless)
85 if (fig.ncol < fig.num)
86 fig.sep[seq(fig.ncol, fig.num - (fig.num %% fig.ncol > 0), fig.ncol)] = '\\newline'
87 }
88 sep.cur = NULL
89
90 # If this is a non-tikz animation, skip to the last fig.
91 if (!tikz && animate && fig.cur < fig.num) return('')
92
93 usesub = length(subcap <- options$fig.subcap) && fig.num > 1
94 # multiple plots: begin at 1, end at fig.num
95 ai = options$fig.show != 'hold'
96
97 # TRUE if this picture is standalone or first in set
98 plot1 = ai || fig.cur <= 1L
99 # TRUE if this picture is standalone or last in set
100 plot2 = ai || fig.cur == fig.num
101
102 # open align code if this picture is standalone/first in set
103 align1 = if (plot1)
104 switch(a, left = '\n\n', center = '\n\n{\\centering ', right = '\n\n\\hfill{}', '\n')
105 # close align code if this picture is standalone/last in set
106 align2 = if (plot2)
107 switch(a, left = '\\hfill{}\n\n', center = '\n\n}\n\n', right = '\n\n', '')
108
109 # figure environment: caption, short caption, label
110 cap = options$fig.cap
111 scap = options$fig.scap
112 fig1 = fig2 = ''
113 mcap = fig.num > 1L && options$fig.show == 'asis' && !length(subcap)
114 # initialize subfloat strings
115 sub1 = sub2 = ''
116
117 # Wrap in figure environment only if user specifies a caption
118 if (length(cap) && !is.na(cap)) {
119 lab = paste0(options$fig.lp, options$label)
120 # If pic is standalone/first in set: open figure environment
121 if (plot1) {
122 pos = options$fig.pos
123 if (pos != '' && !grepl('^[[{]', pos)) pos = sprintf('[%s]', pos)
124 fig1 = sprintf('\\begin{%s}%s', options$fig.env, pos)
125 }
126 # Add subfloat code if needed
127 if (usesub) {
128 sub1 = sprintf('\\subfloat[%s%s]{', subcap, create_label(lab, '-', fig.cur, latex = TRUE))
129 sub2 = '}'
130 sep.cur = fig.sep[fig.cur]
131 # when there are more separators than plots, add the first separator
132 # before the first plot, then the (i+1)th separator to the i-th plot
133 if (length(fig.sep) > fig.num) {
134 if (plot1) sub1 = paste0(fig.sep[1], sub1)
135 sep.cur = fig.sep[fig.cur + 1]
136 }
137 if (is.na(sep.cur)) sep.cur = NULL
138 }
139
140 # If pic is standalone/last in set:
141 # * place caption with label
142 # * close figure environment
143 if (plot2) {
144 if (is.null(scap) && !grepl('[{].*?[:.;].*?[}]', cap)) {
145 scap = strsplit(cap, '[:.;]( |\\\\|$)')[[1L]][1L]
146 }
147 scap = if (is.null(scap) || is.na(scap)) '' else sprintf('[%s]', scap)
148 cap = if (cap == '') '' else sprintf(
149 '\\caption%s{%s}%s\n', escape_percent(scap), escape_percent(cap),
150 create_label(lab, if (mcap) c('-', fig.cur), latex = TRUE)
151 )
152 fig2 = sprintf('%s\\end{%s}\n', cap, options$fig.env)
153 }
154 } else if (pandoc_to(c('latex', 'beamer'))) {
155 # use alignment environments for R Markdown latex output (\centering won't work)
156 align.env = switch(a, left = 'flushleft', center = 'center', right = 'flushright')
157 align1 = if (plot1) if (a == 'default') '\n' else sprintf('\n\n\\begin{%s}', align.env)
158 align2 = if (plot2) if (a == 'default') '' else sprintf('\\end{%s}\n\n', align.env)
159 }
160
161 ow = options$out.width
162 # maxwidth does not work with animations
163 if (animate && identical(ow, '\\maxwidth')) ow = NULL
164 if (is.numeric(ow)) ow = paste0(ow, 'px')
165 size = paste(c(
166 sprintf('width=%s', ow), sprintf('height=%s', options$out.height),
167 sprintf('alt={%s}', escape_percent(options$fig.alt)), options$out.extra
168 ), collapse = ',')
169
170 paste0(
171 fig1, align1, sub1, resize1,
172 if (tikz) {
173 sprintf('\\input{%s}', x)
174 } else if (animate) {
175 # \animategraphics{} should be inserted only *once*!
176 aniopts = options$aniopts
177 aniopts = if (is.na(aniopts)) NULL else gsub(';', ',', aniopts)
178 size = paste(c(size, sprintf('%s', aniopts)), collapse = ',')
179 if (nzchar(size)) size = sprintf('[%s]', size)
180 sprintf('\\animategraphics%s{%s}{%s}{%s}{%s}', size, 1 / options$interval,
181 sub(sprintf('%d$', fig.num), '', sans_ext(x)), 1L, fig.num)
182 } else {
183 if (nzchar(size)) size = sprintf('[%s]', size)
184 res = sprintf(
185 '\\includegraphics%s{%s} ', size,
186 if (getOption('knitr.include_graphics.ext', FALSE)) x else sans_ext(x)
187 )
188 lnk = options$fig.link
189 if (is.null(lnk) || is.na(lnk)) res else sprintf('\\href{%s}{%s}', lnk, res)
190 },
191
192 resize2, sub2, sep.cur, align2, fig2
193 )
194 }
195
196 # % -> \%, but do not touch \%
197 escape_percent = function(x) gsub('(?<!\\\\)%', '\\\\%', x, perl = TRUE)
198
199 .chunk.hook.tex = function(x, options) {
200 ai = output_asis(x, options)
201 col = if (!ai) paste0(
202 color_def(options$background), if (!is_tikz_dev(options)) '\\color{fgcolor}'
203 )
204 k1 = paste0(col, '\\begin{kframe}\n')
205 k2 = '\\end{kframe}'
206 x = .rm.empty.envir(paste0(k1, x, k2))
207 size = if (options$size == 'normalsize') '' else sprintf('\\%s', options$size)
208 if (!ai) {
209 # if the chunk content starts with \n, don't add \n; similarly, if it ends with \n, don't append \n
210 n1 = n2 = '\n'
211 if (grepl('^\\s*\n', x)) n1 = ''
212 if (grepl('\n\\s*$', x)) n2 = ''
213 x = sprintf('\\begin{knitrout}%s%s%s%s\\end{knitrout}', size, n1, x, n2)
214 }
215 if (options$split) {
216 name = fig_path('.tex', options, NULL)
217 if (!file.exists(dirname(name)))
218 dir.create(dirname(name))
219 write_utf8(x, name)
220 sprintf('\\input{%s}', name)
221 } else x
222 }
223
224 # rm empty kframe and verbatim environments
225 .rm.empty.envir = function(x) {
226 x = gsub('\\\\begin\\{(kframe)\\}\\s*\\\\end\\{\\1\\}', '', x)
227 gsub('\\\\end\\{(verbatim|alltt)\\}\\s*\\\\begin\\{\\1\\}[\n]?', '', x)
228 }
229
230 # inline hook for tex
231 .inline.hook.tex = function(x) {
232 if (is.numeric(x)) {
233 x = format_sci(x, 'latex')
234 i = grep('[}]', x)
235 x[i] = sprintf('\\ensuremath{%s}', x[i])
236 # why \text{}: https://github.com/yihui/knitr/issues/348
237 if (getOption('OutDec') != '.') x = sprintf('\\text{%s}', x)
238 }
239 .inline.hook(x)
240 }
241
242 .verb.hook = function(x)
243 one_string(c('\\begin{verbatim}', sub('\n$', '', x), '\\end{verbatim}', ''))
244 .color.block = function(color1 = '', color2 = '') {
245 function(x, options) {
246 x = gsub('\n*$', '', x)
247 x = escape_latex(x, newlines = TRUE, spaces = TRUE)
248 # babel might have problems with "; see http://stackoverflow.com/q/18125539/559676
249 x = gsub('"', '"{}', x)
250 sprintf('\n\n{\\ttfamily\\noindent%s%s%s}', color1, x, color2)
251 }
252 }
253
254 #' Set or get output hooks for different output formats
255 #'
256 #' The \code{render_*()} functions set built-in output hooks for LaTeX, HTML,
257 #' Markdown, reStructuredText, AsciiDoc, and Textile. The \code{hooks_*()}
258 #' functions return a list of the output hooks for the corresponding format.
259 #'
260 #' There are three variants of Markdown documents: ordinary Markdown
261 #' (\code{render_markdown(strict = TRUE)}, which calls
262 #' \code{hooks_markdown(strict = TRUE)}), extended Markdown (e.g., GitHub
263 #' Flavored Markdown and Pandoc; \code{render_markdown(strict = FALSE)}, which
264 #' calls \code{hooks_markdown(strict = FALSE)}), and Jekyll (a blogging system
265 #' on GitHub; \code{render_jekyll()}, which calls \code{hooks_jekyll()}).
266 #'
267 #' For LaTeX output, there are three variants: \pkg{knitr}'s default style
268 #' (\code{render_latex()}, which calls \code{hooks_latex()} and uses the LaTeX
269 #' \pkg{framed} package), Sweave style (\code{render_sweave()}, which calls
270 #' \code{hooks_sweave()} and uses \file{Sweave.sty}), and listings style
271 #' (\code{render_listings()}, which calls \code{hooks_listings()} and uses LaTeX
272 #' \pkg{listings} package).
273 #'
274 #' Default HTML output hooks are set by \code{render_html()} (which calls
275 #' \code{hooks_html()}); \code{render_rst()} (which calls \code{hooks_rst()}) is
276 #' for reStructuredText; \code{render_textile()} (which calls
277 #' \code{hooks_textile()}) is for Textile, and \code{render_asciidoc()} (which
278 #' calls \code{hooks_asciidoc()}) is AsciiDoc.
279 #'
280 #' The \code{render_*()} functions can be used before \code{knit()} or in the
281 #' first chunk of the input document (ideally this chunk has options
282 #' \code{include = FALSE} and \code{cache = FALSE}) so that all the following
283 #' chunks will be formatted as expected.
284 #'
285 #' You can also use \code{\link{knit_hooks}} to set the format's hooks with the
286 #' \code{hooks_*()} functions; see references for more info on further
287 #' customizing output hooks.
288 #'
289 #' @rdname output_hooks
290 #' @return \code{NULL} for \code{render_*} functions; corresponding hooks are
291 #' set as a side effect. A list of output hooks for \code{hooks_*()}
292 #' functions.
293 #' @export
294 #' @references See output hooks in \url{https://yihui.org/knitr/hooks/}, and
295 #' some examples in
296 #' \url{https://bookdown.org/yihui/rmarkdown-cookbook/output-hooks.html}
297 #'
298 #' Jekyll and Liquid:
299 #' \url{https://github.com/jekyll/jekyll/wiki/Liquid-Extensions}; prettify.js:
300 #' \url{https://code.google.com/archive/p/google-code-prettify}
301 #' @examples
302 #' # below is pretty much what knitr::render_markdown() does:
303 #' knitr::knit_hooks$set(knitr::hooks_markdown())
304 #'
305 #' # you can retrieve a subset of the hooks and set them, e.g.,
306 #' knitr::knit_hooks$set(knitr::hooks_markdown()["source"])
307 #'
308 #' knitr::knit_hooks$restore()
309 render_latex = function() {
310 opts_chunk$set(out.width = '\\maxwidth', dev = 'pdf')
311 opts_knit$set(out.format = 'latex')
312 h = opts_knit$get('header')
313 if (!nzchar(h['framed'])) set_header(framed = .header.framed)
314 if (!nzchar(h['highlight'])) set_header(highlight = .header.hi.tex)
315 knit_hooks$set(hooks_latex())
316 }
317
318 #' @rdname output_hooks
319 #' @export
320 hooks_latex = function() {
321 list(
322 source = function(x, options) {
323 x = hilight_source(x, 'latex', options)
324 if (options$highlight) {
325 if (options$engine == 'R' || x[1] != '\\noindent') {
326 one_string(c('\\begin{alltt}', x, '\\end{alltt}', ''))
327 } else {
328 if ((n <- length(x)) > 4) x[n - 2] = sub('\\\\\\\\$', '', x[n - 2])
329 one_string(c(x, ''))
330 }
331 } else .verb.hook(x)
332 },
333 output = function(x, options) {
334 if (output_asis(x, options)) {
335 paste0('\\end{kframe}', x, '\\begin{kframe}')
336 } else .verb.hook(x)
337 },
338 warning = .color.block('\\color{warningcolor}{', '}'),
339 message = .color.block('\\itshape\\color{messagecolor}{', '}'),
340 error = .color.block('\\bfseries\\color{errorcolor}{', '}'),
341 inline = .inline.hook.tex, chunk = .chunk.hook.tex,
342 plot = function(x, options) {
343 # escape plot environments from kframe
344 paste0('\\end{kframe}', hook_plot_tex(x, options), '\n\\begin{kframe}')
345 }
346 )
347 }
348
349 #' @rdname output_hooks
350 #' @export
351 render_sweave = function() {
352 opts_chunk$set(highlight = FALSE, comment = NA, prompt = TRUE) # mimic Sweave settings
353 opts_knit$set(out.format = 'sweave')
354 test_latex_pkg('Sweave', file.path(R.home('share'), 'texmf', 'tex', 'latex', 'Sweave.sty'))
355 set_header(framed = '', highlight = '\\usepackage{Sweave}')
356 knit_hooks$set(hooks_sweave())
357 }
358
359 #' @param envirs Names of LaTeX environments for code input, output, and chunk.
360 #' @rdname output_hooks
361 #' @export
362 hooks_sweave = function(envirs = c('Sinput', 'Soutput', 'Schunk')) {
363 # wrap source code in the Sinput environment, output in Soutput
364 hook.i = function(x, options) one_string(c(
365 sprintf('\\begin{%s}', envirs[1]), hilight_source(x, 'sweave', options),
366 sprintf('\\end{%s}', envirs[1]), ''
367 ))
368 hook.s = function(x, options) {
369 if (output_asis(x, options)) return(x)
370 sprintf('\\begin{%s}\n%s\\end{%s}\n', envirs[2], x, envirs[2])
371 }
372 hook.c = function(x, options) {
373 if (output_asis(x, options)) return(x)
374 sprintf('\\begin{%s}\n%s\\end{%s}', envirs[3], x, envirs[3])
375 }
376 list(
377 source = hook.i, output = hook.s, warning = hook.s, message = hook.s,
378 error = hook.s, plot = hook_plot_tex, inline = .inline.hook.tex, chunk = hook.c
379 )
380 }
381
382 #' @rdname output_hooks
383 #' @export
384 render_listings = function() {
385 opts_chunk$set(highlight = FALSE, comment = NA, prompt = FALSE) # mimic Sweave settings
386 opts_knit$set(out.format = 'listings')
387 test_latex_pkg('Sweavel', system.file('misc', 'Sweavel.sty', package = 'knitr'))
388 set_header(framed = '', highlight = '\\usepackage{Sweavel}')
389 knit_hooks$set(hooks_listings())
390 }
391
392 #' @rdname output_hooks
393 #' @export
394 hooks_listings = hooks_sweave
395
396 # may add textile, and many other markup languages
397
398 #' Some potentially useful document hooks
399 #'
400 #' A document hook is a function to post-process the output document.
401 #'
402 #' \code{hook_movecode()} is a document hook to move code chunks out of LaTeX
403 #' floating environments like \samp{figure} and \samp{table} when the chunks
404 #' were actually written inside the floats. This function is primarily designed
405 #' for LyX: we often insert code chunks into floats to generate figures or
406 #' tables, but in the final output we do not want the code to float with the
407 #' environments, so we use regular expressions to find out the floating
408 #' environments, extract the code chunks and move them out. To disable this
409 #' behavior, use a comment \code{\% knitr_do_not_move} in the floating
410 #' environment.
411 #' @rdname hook_document
412 #' @param x A character string (the whole output document).
413 #' @return The post-processed document as a character string.
414 #' @note These functions are hackish. Also note \code{hook_movecode()} assumes
415 #' you to use the default output hooks for LaTeX (not Sweave or listings), and
416 #' every figure/table environment must have a label.
417 #' @export
418 #' @references \url{https://yihui.org/knitr/hooks/}
419 #' @examples \dontrun{knit_hooks$set(document = hook_movecode)}
420 #' # see example 103 at https://github.com/yihui/knitr-examples
421 hook_movecode = function(x) {
422 x = split_lines(x)
423 res = split(x, cumsum(grepl('^\\\\(begin|end)\\{figure\\}', x)))
424 x = split_lines(unlist(lapply(res, function(p) {
425 if (length(p) <= 4 || !grepl('^\\\\begin\\{figure\\}', p[1]) ||
426 length(grep('% knitr_do_not_move', p)) ||
427 !any(grepl('\\\\begin\\{(alltt|kframe)\\}', p))) return(p)
428 idx = c(1, grep('\\\\includegraphics', p))
429 if (length(idx) <= 1) return(p) # no graphics
430 if (length(i <- grep('\\{\\\\centering.*\\\\includegraphics', p))) {
431 idx = c(idx, i - 1, j2 <- i + 1)
432 for (j in j2) {
433 while (p[j] != '}') idx = c(idx, j <- j + 1) # find } for {\\centering
434 }
435 }
436 if (length(i <- grep('\\\\hfill\\{\\}.*\\\\includegraphics', p)))
437 idx = c(idx, i - 1, i + 1)
438 if (length(i <- grep('\\\\includegraphics.*\\\\hfill\\{\\}', p)))
439 idx = c(idx, i - 1, i + 1)
440 idx = sort(c(idx, seq(grep('\\\\caption', p), grep('\\\\label', p))))
441 idx = unique(idx)
442 p = one_string(c(p[-idx], p[idx]))
443 gsub('\\\\end\\{(kframe)\\}\\s*\\\\begin\\{\\1\\}', '', p)
444 }), use.names = FALSE))
445
446 res = split(x, cumsum(grepl('^\\\\(begin|end)\\{table\\}', x)))
447 res = one_string(unlist(lapply(res, function(p) {
448 if (length(p) <= 4 || !grepl('^\\\\begin\\{table\\}', p[1]) ||
449 length(grep('% knitr_do_not_move', p)) ||
450 !any(grepl('\\\\begin\\{(alltt|kframe)\\}', p))) return(p)
451 if (!any(grepl('\\\\label\\{.*\\}', p))) return(p)
452 idx = c(1, seq(grep('\\\\caption', p), grep('\\\\label', p)))
453 i0 = grep('\\\\begin\\{tabular\\}', p); i1 = grep('\\\\end\\{tabular\\}', p)
454 for (i in seq_along(i0)) idx = c(idx, i0[i]:i1[i])
455 idx = sort(idx)
456 p = one_string(c(p[-idx], p[idx]))
457 gsub('\\\\end\\{(kframe)\\}\\s*\\\\begin\\{\\1\\}', '', p)
458 }), use.names = FALSE))
459 .rm.empty.envir(res)
460 }