Debian Codegraph @

R/pdf_document.R

raw
1 #' Convert to a PDF/LaTeX document
2 #'
3 #' Formats for converting from R Markdown to a PDF or LaTeX document.
4 #'
5 #' See the \href{https://yihui.org/rmarkdown/pdf-document.html}{online
6 #' documentation} for additional details on using the \code{pdf_document}
7 #' format.
8 #'
9 #' Creating PDF output from R Markdown requires that LaTeX be installed.
10 #'
11 #' R Markdown documents can have optional metadata that is used to generate a
12 #' document header that includes the title, author, and date. For more details
13 #' see the documentation on R Markdown \link[=rmd_metadata]{metadata}.
14 #'
15 #' R Markdown documents also support citations. You can find more information on
16 #' the markdown syntax for citations in the
17 #' \href{https://pandoc.org/MANUAL.html#citations}{Bibliographies
18 #' and Citations} article in the online documentation.
19 #'
20 #' Many aspects of the LaTeX template used to create PDF documents can be
21 #' customized using metadata. For example:
22 #'
23 #' \tabular{l}{
24 #' \code{---} \cr
25 #' \code{title: "Crop Analysis Q3 2013"} \cr
26 #' \code{fontsize: 11pt} \cr
27 #' \code{geometry: margin=1in} \cr
28 #' \code{---}
29 #' }
30 #'
31 #' Available metadata variables include:
32 #'
33 #' \describe{
34 #' \item{\code{lang}}{Document language code (e.g. "es", "fr", "pt-BR")}
35 #' \item{\code{fontsize}}{Font size (e.g. 10pt, 11pt, 12pt)}
36 #' \item{\code{documentclass}}{LaTeX document class (e.g. article)}
37 #' \item{\code{classoption}}{Option for \code{documentclass} (e.g. oneside); may be repeated}
38 #' \item{\code{geometry}}{Options for geometry class (e.g. margin=1in); may be repeated}
39 #' \item{\code{mainfont, sansfont, monofont, mathfont}}{Document fonts (works only with xelatex and lualatex, see the \code{latex_engine} option)}
40 #' \item{\code{linkcolor, urlcolor, citecolor}}{Color for internal, external, and citation links (red, green, magenta, cyan, blue, black)}
41 #' \item{\code{linestretch}}{Options for line spacing (e.g. 1, 1.5, 3)}
42 #' }
43 #' @inheritParams html_document
44 #' @param fig_crop Whether to crop PDF figures with the command
45 #' \command{pdfcrop}. This requires the tools \command{pdfcrop} and
46 #' \command{ghostscript} to be installed. By default, \code{fig_crop = TRUE}
47 #' if these two tools are available.
48 #' @param dev Graphics device to use for figure output (defaults to pdf)
49 #' @param highlight Syntax highlighting style passed to Pandoc.
50 #'
51 #' Supported built-in styles include "default", "tango", "pygments", "kate",
52 #' "monochrome", "espresso", "zenburn", "haddock", and "breezedark".
53 #'
54 #' Two custom styles are also included, "arrow", an accessible color scheme,
55 #' and "rstudio", which mimics the default IDE theme. Alternatively, supply a
56 #' path to a \samp{.theme} file to use
57 #' \href{https://pandoc.org/MANUAL.html#syntax-highlighting}{a custom Pandoc
58 #' style}. Note that custom theme requires Pandoc 2.0+.
59 #'
60 #' Pass \code{NULL} to prevent syntax highlighting.
61 #' @param keep_tex Keep the intermediate tex file used in the conversion to PDF.
62 #' Note that this argument does not control whether to keep the auxiliary
63 #' files (e.g., \file{.aux}) generated by LaTeX when compiling \file{.tex} to
64 #' \file{.pdf}. To keep these files, you may set \code{options(tinytex.clean =
65 #' FALSE)}.
66 #' @param latex_engine LaTeX engine for producing PDF output. Options are
67 #' "pdflatex", "lualatex", "xelatex" and "tectonic".
68 #' @param citation_package The LaTeX package to process citations, \code{natbib}
69 #' or \code{biblatex}. Use \code{default} if neither package is to be used,
70 #' which means citations will be processed via the command
71 #' \command{pandoc-citeproc}.
72 #' @param template Pandoc template to use for rendering. Pass "default" to use
73 #' the rmarkdown package default template; pass \code{NULL} to use pandoc's
74 #' built-in template; pass a path to use a custom template that you've
75 #' created. See the documentation on
76 #' \href{https://pandoc.org/MANUAL.html}{pandoc online documentation} for
77 #' details on creating custom templates.
78 #' @param output_extensions Pandoc extensions to be added or removed from the
79 #' output format, e.g., \code{"-smart"} means the output format will be
80 #' \code{latex-smart}.
81 #' @param extra_dependencies A LaTeX dependency \code{latex_dependency()}, a
82 #' list of LaTeX dependencies, a character vector of LaTeX package names (e.g.
83 #' \code{c("framed", "hyperref")}), or a named list of LaTeX package options
84 #' with the names being package names (e.g. \code{list(hyperef =
85 #' c("unicode=true", "breaklinks=true"), lmodern = NULL)}). It can be used to
86 #' add custom LaTeX packages to the .tex header.
87 #' @return R Markdown output format to pass to \code{\link{render}}
88 #' @examples
89 #' \dontrun{
90 #' library(rmarkdown)
91 #'
92 #' # simple invocation
93 #' render("input.Rmd", pdf_document())
94 #'
95 #' # specify an option for latex engine
96 #' render("input.Rmd", pdf_document(latex_engine = "lualatex"))
97 #'
98 #' # add a table of contents and pass an option to pandoc
99 #' render("input.Rmd", pdf_document(toc = TRUE, "--listings"))
100 #' }
101 #' @export
102 pdf_document <- function(toc = FALSE,
103 toc_depth = 2,
104 number_sections = FALSE,
105 fig_width = 6.5,
106 fig_height = 4.5,
107 fig_crop = 'auto',
108 fig_caption = TRUE,
109 dev = 'pdf',
110 df_print = "default",
111 highlight = "default",
112 template = "default",
113 keep_tex = FALSE,
114 keep_md = FALSE,
115 latex_engine = "pdflatex",
116 citation_package = c("default", "natbib", "biblatex"),
117 includes = NULL,
118 md_extensions = NULL,
119 output_extensions = NULL,
120 pandoc_args = NULL,
121 extra_dependencies = NULL) {
122
123 # base pandoc options for all PDF output
124 args <- self_contained_args()
125
126 # table of contents
127 args <- c(args, pandoc_toc_args(toc, toc_depth))
128
129 # template path and assets
130 if (!is.null(template) && !identical(template, "default")) {
131 args <- c(args, "--template", pandoc_path_arg(template))
132 }
133
134 # numbered sections
135 if (number_sections)
136 args <- c(args, "--number-sections")
137
138 # highlighting
139 if (!is.null(highlight)) highlight <- resolve_highlight(highlight, highlighters())
140 args <- c(args, pandoc_highlight_args(highlight))
141
142 # latex engine
143 latex_engine <- match.arg(latex_engine, c("pdflatex", "lualatex", "xelatex", "tectonic"))
144 args <- c(args, pandoc_latex_engine_args(latex_engine))
145
146 # citation package
147 args <- c(args, citation_package_arg(citation_package))
148
149 # content includes
150 args <- c(args, includes_to_pandoc_args(includes))
151
152 # make sure the graphics package is always loaded
153 if (identical(template, "default")) args <- c(args, "--variable", "graphics")
154
155 # args args
156 args <- c(args, pandoc_args)
157
158 saved_files_dir <- NULL
159
160 # Use filter to set pdf geometry defaults (while making sure we don't override
161 # any geometry settings already specified by the user)
162 pdf_pre_processor <- function(metadata, input_file, runtime, knit_meta, files_dir,
163 output_dir) {
164
165 # make sure --include-in-header from command line will not completely
166 # override header-includes in metadata but give the latter lower precedence:
167 # https://github.com/rstudio/rmarkdown/issues/1359
168 args <- append_in_header(process_header_includes(metadata))
169
170 # use a geometry filter when we are using the "default" template
171 if (identical(template, "default")) {
172 # set the margin to 1 inch if no geometry options or document class specified
173 if (default_geometry(names(metadata), pandoc_args))
174 args <- c(args, "--variable", "geometry:margin=1in")
175 # support subtitle for Pandoc < 2.6
176 if (("subtitle" %in% names(metadata)) && !pandoc_available("2.6")) args <- c(
177 args, append_in_header(file = pkg_file("rmd/latex/subtitle.tex"))
178 )
179 }
180
181 if (length(extra_dependencies) || has_latex_dependencies(knit_meta)) {
182 extra_dependencies <- latex_dependencies(extra_dependencies)
183 all_dependencies <- append(extra_dependencies, flatten_latex_dependencies(knit_meta))
184 args <- c(args, append_in_header(latex_dependencies_as_string(all_dependencies)))
185 }
186 args
187 }
188
189
190 pre_processor <- function(metadata, input_file, runtime, knit_meta,
191 files_dir, output_dir) {
192 # save files dir (for generating intermediates)
193 saved_files_dir <<- files_dir
194
195 pdf_pre_processor(metadata, input_file, runtime, knit_meta, files_dir,
196 output_dir)
197 }
198
199 intermediates_generator <- function(...) {
200 general_intermediates_generator(saved_files_dir, ...)
201 }
202
203 # return format
204 output_format(
205 knitr = knitr_options_pdf(fig_width, fig_height, fig_crop, dev),
206 pandoc = pandoc_options(
207 to = paste(c("latex", output_extensions), collapse = ""),
208 from = from_rmarkdown(fig_caption, md_extensions),
209 args = args,
210 latex_engine = latex_engine,
211 keep_tex = keep_tex,
212 lua_filters = pkg_file_lua(c("pagebreak.lua", "latex-div.lua"))
213 ),
214 clean_supporting = !keep_tex,
215 keep_md = keep_md,
216 df_print = df_print,
217 pre_processor = pre_processor,
218 intermediates_generator = intermediates_generator
219 )
220 }
221
222 #' @param ... Arguments passed to \code{pdf_document()}.
223 #' @rdname pdf_document
224 #' @export
225 latex_document <- function(...) {
226 merge_lists(pdf_document(..., keep_tex = TRUE), list(pandoc = list(ext = ".tex")))
227 }
228
229 #' @rdname pdf_document
230 #' @export
231 latex_fragment <- function(...) {
232 latex_document(..., template = pkg_file("rmd/fragment/default.tex"))
233 }
234
235 general_intermediates_generator <- function(
236 saved_files_dir, original_input, intermediates_dir
237 ) {
238
239 # copy all intermediates (pandoc will need to bundle them in the PDF)
240 intermediates <- copy_render_intermediates(original_input, intermediates_dir, FALSE)
241
242 # we need figures from the supporting files dir to be available during
243 # render as well; if we have a files directory, copy its contents
244 if (!is.null(saved_files_dir) && dir_exists(saved_files_dir)) {
245 file.copy(saved_files_dir, intermediates_dir, recursive = TRUE)
246 intermediates <- c(intermediates, list.files(
247 path = file.path(intermediates_dir, basename(saved_files_dir)),
248 all.files = TRUE, recursive = TRUE, full.names = TRUE))
249 }
250
251 intermediates
252 }
253
254 patch_tex_output <- function(file) {
255 x <- read_utf8(file)
256 if (length(i <- which(x == '\\begin{document}')) == 0) return()
257 if (length(i <- grep('^\\\\date\\{', head(x, i[1]))) == 0) return()
258
259 i <- i[1]
260 # add \author{} if missing: https://github.com/jgm/pandoc/pull/5961
261 if (length(grep('^\\\\author\\{', head(x, i))) == 0) {
262 x <- append(x, '\\author{}', i - 1)
263 i <- i + 1
264 }
265 # reduce the vertical spacing in \date{} if no author is given
266 if (any(head(x, i) == '\\author{}')) {
267 x[i] <- paste0('\\date{\\vspace{-2.5em}', sub('^\\\\date\\{', '', x[i]))
268 }
269 write_utf8(x, file)
270 }
271
272 # patch output from Pandoc < 2.8: https://github.com/jgm/pandoc/issues/5801
273 fix_horiz_rule <- function(file) {
274 if (pandoc_available('2.8')) return()
275 x <- read_utf8(file)
276 i <- x == '\\begin{center}\\rule{0.5\\linewidth}{\\linethickness}\\end{center}'
277 if (any(i)) {
278 x[i] <- '\\begin{center}\\rule{0.5\\linewidth}{0.5pt}\\end{center}'
279 write_utf8(x, file)
280 }
281 }
282
283 citation_package_arg <- function(value) {
284 value <- value[1]
285 if (value == "none") {
286 warning("citation_package = 'none' was deprecated; please use 'default' instead.")
287 value <- "default"
288 }
289 value <- match.arg(value, c("default", "natbib", "biblatex"))
290 if (value != "default") paste0("--", value)
291 }
292
293 # utils
294 default_geometry <- function(meta_names, pandoc_args = NULL) {
295 !any(c('geometry', 'documentclass') %in% meta_names) &&
296 length(grep('^(--(variable|metadata)=)?documentclass:', pandoc_args)) == 0
297 }
298
299 process_header_includes <- function(x) {
300 x <- unlist(x[["header-includes"]])
301 gsub('(^|\n)\\s*```\\{=latex\\}\n(.+?\n)```\\s*(\n|$)', '\\1\\2\\3', x)
302 }
303
304 append_in_header <- function(text, file = as_tmpfile(text)) {
305 includes_to_pandoc_args(includes(in_header = file))
306 }
307