Debian Codegraph @

R/beamer_presentation.R

raw
1 #' Convert to a Beamer presentation
2 #'
3 #' Format for converting from R Markdown to a Beamer presentation.
4 #'
5 #' See the [online documentation](https://yihui.org/rmarkdown/beamer-presentation.html)
6 #' for additional details on using the `beamer_presentation` format.
7 #'
8 #' Creating Beamer output from R Markdown requires that LaTeX be installed.
9 #'
10 #' R Markdown documents can have optional metadata that is used to generate a
11 #' document header that includes the title, author, and date. For more details
12 #' see the documentation on R Markdown [metadata][rmd_metadata].
13 #'
14 #' R Markdown documents also support citations. You can find more information on
15 #' the markdown syntax for citations in the
16 #' [Bibliographies and Citations](https://pandoc.org/MANUAL.html#citations)
17 #' article in the online documentation.
18 #' @inheritParams pdf_document
19 #' @inheritParams html_document
20 #' @param toc `TRUE` to include a table of contents in the output (only
21 #' level 1 headers will be included in the table of contents).
22 #' @param slide_level The heading level which defines individual slides. By
23 #' default this is the highest header level in the hierarchy that is followed
24 #' immediately by content, and not another header, somewhere in the document.
25 #' This default can be overridden by specifying an explicit
26 #' `slide_level`.
27 #' @param incremental `TRUE` to render slide bullets incrementally. Note
28 #' that if you want to reverse the default incremental behavior for an
29 #' individual bullet you can precede it with `>`. For example:
30 #' *`> - Bullet Text`*. See more in
31 #' [Pandoc's Manual](https://pandoc.org/MANUAL.html#incremental-lists)
32 #' @param theme Beamer theme (e.g. "AnnArbor").
33 #' @param colortheme Beamer color theme (e.g. "dolphin").
34 #' @param fonttheme Beamer font theme (e.g. "structurebold").
35 #' @param self_contained Whether to generate a full LaTeX document (`TRUE`)
36 #' or just the body of a LaTeX document (`FALSE`). Note the LaTeX
37 #' document is an intermediate file unless `keep_tex = TRUE`.
38 #' @return R Markdown output format to pass to [render()]
39 #' @examples
40 #' \dontrun{
41 #'
42 #' library(rmarkdown)
43 #'
44 #' # simple invocation
45 #' render("pres.Rmd", beamer_presentation())
46 #'
47 #' # specify an option for incremental rendering
48 #' render("pres.Rmd", beamer_presentation(incremental = TRUE))
49 #' }
50 #' @md
51 #' @export
52 beamer_presentation <- function(toc = FALSE,
53 slide_level = NULL,
54 number_sections = FALSE,
55 incremental = FALSE,
56 fig_width = 10,
57 fig_height = 7,
58 fig_crop = 'auto',
59 fig_caption = TRUE,
60 dev = 'pdf',
61 df_print = "default",
62 theme = "default",
63 colortheme = "default",
64 fonttheme = "default",
65 highlight = "default",
66 template = "default",
67 keep_tex = FALSE,
68 keep_md = FALSE,
69 latex_engine = "pdflatex",
70 citation_package = c("default", "natbib", "biblatex"),
71 self_contained = TRUE,
72 includes = NULL,
73 md_extensions = NULL,
74 pandoc_args = NULL,
75 extra_dependencies = NULL) {
76
77 # base pandoc options for all beamer output
78 args <- c()
79
80 # template path and assets
81 if (!is.null(template)) {
82 if (identical(template, "default")) template <- patch_beamer_template()
83 if (!is.null(template))
84 args <- c(args, "--template", pandoc_path_arg(template))
85 }
86
87 # table of contents
88 if (toc)
89 args <- c(args, "--table-of-contents")
90
91 # slide level
92 if (!is.null(slide_level))
93 args <- c(args, "--slide-level", as.character(slide_level))
94
95 if (number_sections)
96 args <- c(args, "--number-sections")
97
98 # incremental
99 if (incremental)
100 args <- c(args, "--incremental")
101
102 # themes
103 if (!identical(theme, "default"))
104 args <- c(args, pandoc_variable_arg("theme", theme))
105 if (!identical(colortheme, "default"))
106 args <- c(args, pandoc_variable_arg("colortheme", colortheme))
107 if (!identical(fonttheme, "default"))
108 args <- c(args, pandoc_variable_arg("fonttheme", fonttheme))
109
110 # highlighting
111 if (!is.null(highlight)) highlight <- resolve_highlight(highlight, highlighters())
112 args <- c(args, pandoc_highlight_args(highlight))
113
114 # latex engine
115 latex_engine <- match.arg(latex_engine, c("pdflatex", "lualatex", "xelatex", "tectonic"))
116 args <- c(args, pandoc_latex_engine_args(latex_engine))
117
118 # citation package
119 args <- c(args, citation_package_arg(citation_package))
120
121 # generate a self-contained LaTeX document (including preamble)
122 if (self_contained) args <- c(args, self_contained_args())
123
124 # content includes
125 args <- c(args, includes_to_pandoc_args(includes))
126
127 # make sure the graphics package is always loaded
128 if (identical(template, "default")) args <- c(args, "--variable", "graphics=yes")
129
130 # custom args
131 args <- c(args, pandoc_args)
132
133 # initialize saved files dir
134 saved_files_dir <- NULL
135
136 pre_processor <- function(metadata, input_file, runtime, knit_meta,
137 files_dir, output_dir) {
138 # save files dir (for generating intermediates)
139 saved_files_dir <<- files_dir
140
141 # make sure --include-in-header from command line will not completely
142 # override header-includes in metadata but give the latter lower precedence:
143 # https://github.com/rstudio/rmarkdown/issues/1359
144 # Same in PDF for beamer
145 # https://github.com/rstudio/rmarkdown/issues/2294
146 args <- append_in_header(process_header_includes(metadata))
147
148 if (length(extra_dependencies) || has_latex_dependencies(knit_meta)) {
149 extra_dependencies <- latex_dependencies(extra_dependencies)
150 all_dependencies <- append(extra_dependencies, flatten_latex_dependencies(knit_meta))
151 args <- c(args, append_in_header(latex_dependencies_as_string(all_dependencies)))
152 }
153
154 # no-op other than caching dir location
155 args
156 }
157
158 # generate intermediates (required to make resources available for publish)
159 intermediates_generator <- function(...) {
160 general_intermediates_generator(saved_files_dir, ...)
161 }
162
163 # return format
164 output_format(
165 knitr = knitr_options_pdf(fig_width, fig_height, fig_crop, dev),
166 pandoc = pandoc_options(
167 to = "beamer",
168 from = from_rmarkdown(fig_caption, md_extensions),
169 args = args,
170 latex_engine = latex_engine,
171 keep_tex = keep_tex,
172 lua_filters = pkg_file_lua(c("pagebreak.lua", "latex-div.lua"))
173 ),
174 pre_processor = pre_processor,
175 intermediates_generator = intermediates_generator,
176 clean_supporting = !keep_tex,
177 keep_md = keep_md,
178 df_print = df_print
179 )
180 }
181
182
183 patch_beamer_template_pagenumber <- function(template) {
184
185 patch <- paste(
186 "% Comment these out if you don't want a slide with just the",
187 "% part/section/subsection/subsubsection title:", "\\AtBeginPart{",
188 " \\let\\insertpartnumber\\relax", " \\let\\partname\\relax",
189 " \\frame{\\partpage}", "}", "\\AtBeginSection{",
190 " \\let\\insertsectionnumber\\relax", " \\let\\sectionname\\relax",
191 " \\frame{\\sectionpage}", "}", "\\AtBeginSubsection{",
192 " \\let\\insertsubsectionnumber\\relax", " \\let\\subsectionname\\relax",
193 " \\frame{\\subsectionpage}", "}",
194 sep = "\n"
195 )
196
197 pasted <- one_string(template)
198 patched <- sub(patch, "", pasted, fixed = TRUE)
199 strsplit(patched, "\n", fixed = TRUE)[[1]]
200 }
201
202 patch_beamer_template_paragraph_spacing <- function(template) {
203
204 patch <- c(
205 "\\setlength{\\parindent}{0pt}",
206 "\\setlength{\\parskip}{6pt plus 2pt minus 1pt}"
207 )
208
209 lines <- unlist(lapply(patch, function(line) {
210 index <- grep(line, template, fixed = TRUE)
211 if (length(index) == 1) index else -1
212 }))
213
214 # bail if we already have these lines in the document
215 if (all(lines >= 0) && lines[[1]] == lines[[2]] - 1)
216 return(template)
217
218 # find patch location -- we insert before this line
219 targetLine <- "\\setlength{\\emergencystretch}{3em} % prevent overfull lines"
220 targetIdx <- grep(targetLine, template, fixed = TRUE)
221 if (!length(targetIdx))
222 return(template)
223
224 # insert patch
225 c(
226 utils::head(template, n = targetIdx - 1),
227 patch,
228 utils::tail(template, n = -(targetIdx - 1))
229 )
230 }
231
232 patch_beamer_template <- function() {
233 pandoc_available(error = TRUE)
234
235 # invoke pandoc to read default template
236 command <- paste(quoted(pandoc()), "-D beamer")
237 template <- with_pandoc_safe_environment({
238 tryCatch(
239 system(command, intern = TRUE),
240 error = function(e) NULL
241 )
242 })
243
244 # make failure to read template non-fatal
245 if (is.null(template))
246 return(NULL)
247
248 # trim whitespace
249 template <- gsub("^\\s+|\\s+$", "", template, perl = TRUE)
250
251 # apply patches (store original version of template so we can
252 # compare after applying patches)
253 original <- template
254 version <- pandoc_version()
255
256 if (version < "1.15.2")
257 template <- patch_beamer_template_pagenumber(template)
258
259 if (version > "1.15.2" && version < "1.17.3")
260 template <- patch_beamer_template_paragraph_spacing(template)
261
262 # if the template hasn't changed, return NULL (we don't need
263 # to apply a custom template)
264 if (identical(template, original))
265 return(NULL)
266
267 # write and return path to template
268 as_tmpfile(enc2utf8(template))
269 }