Debian Codegraph @

R/ioslides_presentation.R

raw
1 #' Convert to an ioslides Presentation
2 #'
3 #' Format for converting from R Markdown to an
4 #' [ioslides](https://code.google.com/archive/p/io-2012-slides/) presentation.
5 #'
6 #' @md
7 #' @inheritParams html_document
8 #' @param logo Path to file that includes a logo for use in the presentation
9 #' (should be square and at least 128x128).
10 #' @param slide_level Header level to consider as slide separator (Defaults to
11 #' header 2).
12 #' @param incremental `TRUE` to render slide bullets incrementally.
13 #' Note that if you want to reverse the default incremental behavior for an
14 #' individual bullet you can preceded it with `>`.
15 #' For example: *`> - Bullet Text`*.
16 #' @param widescreen Display presentation with wider dimensions.
17 #' @param smaller Use smaller text on all slides. You can also enable this for
18 #' individual slides by adding the `.smaller` attribute to the slide
19 #' header (see *Presentation Size* below for details).
20 #' @param transition Speed of slide transitions. This can be "default",
21 #' "slower", "faster", or a numeric value with a number of seconds (e.g. 0.5).
22 #' @param analytics A Google analytics property ID.
23 #' @param smart Produce typographically correct output, converting straight
24 #' quotes to curly quotes, `---` to em-dashes, `--` to en-dashes, and
25 #' `...` to ellipses.
26 #' @param css One or more css files to include.
27 #' @return R Markdown output format to pass to [render()].
28 #' @details
29 #' See the [
30 #' online documentation](https://yihui.org/rmarkdown/ioslides-presentation.html) for additional details on using the
31 #' `ioslides_presentation` format.
32 #'
33 #' Note that, if a `before_body` include is specified in `includes`,
34 #' then it will replace the standard title slide entirely.
35 #'
36 #' Regarding previewing slide in RStudio IDE, `ioslides_presentation()` will
37 #' always open preview in a new Window and the RStudio IDE configuration "Open in Viewer
38 #' Pane" will have no effect for this format.
39 #'
40 #' @section Slide Basics:
41 #' You can create a slide show broken up into sections by using the # and ##
42 #' heading tags (you can also create a new slide without a header using a
43 #' horizontal rule (`----------`). For example here's a simple slide show:
44 #' ````markdown
45 #' ---
46 #' title: "Habits"
47 #' author: John Doe
48 #' date: March 22, 2005
49 #' output: ioslides_presentation
50 #' ---
51 #'
52 #' # In the morning
53 #'
54 #' ## Getting up
55 #'
56 #' - Turn off alarm
57 #' - Get out of bed
58 #'
59 #' ## Breakfast
60 #'
61 #' - Eat eggs
62 #' - Drink coffee
63 #'
64 #' # In the evening
65 #'
66 #' ## Dinner
67 #'
68 #' - Eat spaghetti
69 #' - Drink wine
70 #'
71 #' ----------
72 #'
73 #' ![picture of spaghetti](images/spaghetti.jpg)
74 #'
75 #' ## Going to sleep
76 #'
77 #' - Get in bed
78 #' - Count sheep
79 #' ````
80 #'
81 #' You can add a subtitle to a slide or section by including text after the
82 #' pipe (|) character. For example:
83 #' ```markdown
84 #' ## Getting up | What I like to do first thing
85 #' ```
86 #'
87 #' @section Display Modes:
88 #' The following single character keyboard shortcuts enable alternate display
89 #' modes:
90 #' \describe{
91 #' \item{`'f'` }{enable fullscreen mode}
92 #' \item{`'w'` }{toggle widescreen mode}
93 #' \item{`'o'` }{enable overview mode}
94 #' \item{`'h'` }{enable code highlight mode}
95 #' \item{`'p'` }{show presenter notes}
96 #' }
97 #' Pressing `Esc` exits all of these modes. See the sections below on
98 #' *Code Highlighting* and *Presenter Mode* for additional
99 #' detail on those modes.
100 #'
101 #' @section Incremental Bullets:
102 #' You can render bullets incrementally by adding the `incremental`
103 #' option:
104 #' ```markdown
105 #' ---
106 #' output:
107 #' ioslides_presentation:
108 #' incremental: true
109 #' ---
110 #' ```
111 #' If you want to render bullets incrementally for some slides but not
112 #' others you can use this syntax:
113 #' ```
114 #' > - Eat eggs
115 #' > - Drink coffee
116 #' ```
117 #'
118 #' @section Presentation Size:
119 #' You can display the presentation using a wider form factor using the
120 #' `widescreen` option. You can specify that smaller text be used with
121 #' the `smaller` option. For example:
122 #' ````yaml
123 #' ---
124 #' output:
125 #' ioslides_presentation:
126 #' widescreen: true
127 #' smaller: true
128 #' ---
129 #' ````
130 #' You can also enable the `smaller` option on a slide-by-slide basis
131 #' by adding the `.smaller` attribute to the slide header:
132 #' ```markdown
133 #' ## Getting up {.smaller}
134 #' ```
135 #' @section Adding a Logo:
136 #' You can add a logo to the presentation using the `logo` option (the
137 #' logo should be square and at least 128x128). For example:
138 #' ```markdown
139 #' ---
140 #' output:
141 #' ioslides_presentation:
142 #' logo: logo.png
143 #' ---
144 #' ```
145 #' A 128x128 version of the logo graphic will be added to the title slide and
146 #' an icon version of the logo will be included in the bottom-left footer of
147 #' each slide.
148 #' @section Build Slides:
149 #' Slides can also have a `.build` attribute that indicate that their
150 #' content should be displayed incrementally. For example:
151 #' ```markdown
152 #' ## Getting up {.build}
153 #' ```
154 #' Slide attributes can be combined if you need to specify more than one,
155 #' for example:
156 #' ```markdown
157 #' ## Getting up {.smaller .build}
158 #' ```
159 #' @section Code Highlighting:
160 #' It's possible to select subsets of code for additional emphasis by adding a
161 #' special "highlight" comment around the code. For example:
162 #' ```markdown
163 #' ### <b>
164 #' x <- 10
165 #' y <- x * 2
166 #' ### </b>
167 #' ```
168 #' The highlighted region will be displayed with a bold font. When you want to
169 #' help the audience focus exclusively on the highlighted region press the
170 #' `'h'` key and the rest of the code will fade away.
171 #' @section Tables:
172 #' The ioslides template has an attractive default style for tables so you
173 #' shouldn't hesitate to add tables for presenting more complex sets of
174 #' information. Pandoc markdown supports several syntaxes for defining
175 #' tables which are described in the
176 #' [pandoc online documentation](https://pandoc.org/MANUAL.html).
177 #' @section Advanced Layout:
178 #' You can center content on a slide by adding the `.flexbox`
179 #' and `.vcenter` attributes to the slide title. For example:
180 #' ```markdown
181 #' ## Dinner {.flexbox .vcenter}
182 #' ```
183 #' You can horizontally center content by enclosing it in a `div` tag
184 #' with class `centered`. For example:
185 #' ```html
186 #' <div class="centered">
187 #' This text is centered.
188 #' </div>
189 #' ```
190 #' You can do a two-column layout using the `columns-2` class.
191 #' For example:
192 #' ```
193 #' <div class="columns-2">
194 #' ![Image](image.png)
195 #'
196 #' - Bullet 1
197 #' - Bullet 2
198 #' - Bullet 3
199 #' </div>
200 #' ```
201 #' Note that content will flow across the columns so if you want to
202 #' have an image on one side and text on the other you should make
203 #' sure that the image has sufficient height to force the text to
204 #' the other side of the slide.
205 #' @section Text Color:
206 #' You can color content using base color classes red, blue, green, yellow,
207 #' and gray (or variations of them e.g. red2, red3, blue2, blue3, etc.).
208 #' For example:
209 #' ```html
210 #' <div class="red2">
211 #' This text is red
212 #' </div>
213 #' ```
214 #' @section Presenter Mode:
215 #' A separate presenter window can also be opened (ideal for when you are
216 #' presenting on one screen but have another screen that's private to you).
217 #' The window stays in sync with the main presentation window and also
218 #' shows presenter notes and a thumbnail of the next slide. To enable
219 #' presenter mode add `?presentme=true` to the URL of the presentation,
220 #' for example:
221 #' ```
222 #' mypresentation.html?presentme=true
223 #' ```
224 #' The presenter mode window will open and will always re-open with the
225 #' presentation until it's disabled with:
226 #' ```
227 #' mypresentation.html?presentme=false
228 #' ```
229 #' To add presenter notes to a slide you include it within a "notes"
230 #' `div`. For example:
231 #' ```
232 #' <div class="notes">
233 #' This is my *note*.
234 #'
235 #' - It can contain markdown
236 #' - like this list
237 #'
238 #' </div>
239 #' ```
240 #' @section Printing and PDF Output:
241 #' You can print an ioslides presentation from within browsers that have
242 #' good support for print CSS (i.e. as of this writing Google Chrome
243 #' has the best support). Printing maintains most of the visual styles
244 #' of the HTML version of the presentation.
245 #'
246 #' To create a PDF version of a presentation you can use Print to PDF
247 #' from Google Chrome.
248 #' @export
249 ioslides_presentation <- function(number_sections = FALSE,
250 logo = NULL,
251 slide_level = 2,
252 incremental = FALSE,
253 fig_width = 7.5,
254 fig_height = 4.5,
255 fig_retina = 2,
256 fig_caption = TRUE,
257 dev = 'png',
258 df_print = "default",
259 smart = TRUE,
260 self_contained = TRUE,
261 widescreen = FALSE,
262 smaller = FALSE,
263 transition = "default",
264 math_method = "mathjax",
265 mathjax = "default",
266 analytics = NULL,
267 template = NULL,
268 css = NULL,
269 includes = NULL,
270 keep_md = FALSE,
271 lib_dir = NULL,
272 md_extensions = NULL,
273 pandoc_args = NULL,
274 extra_dependencies = NULL,
275 ...) {
276
277 # base pandoc options for all output
278 args <- c()
279
280 # math
281 math <- mathjax_to_math(mathjax, math_method)
282 math <- check_math_argument(math)
283 if (!identical(math$engine, "mathjax")) {
284 stop2("Only mathjax is supported for `ioslide_presentation()` for 'math'.")
285 }
286
287 # widescreen
288 if (widescreen)
289 args <- c(args, "--variable", "widescreen");
290
291 # pagedtables
292 if (identical(df_print, "paged")) {
293 extra_dependencies <- append(extra_dependencies,
294 list(html_dependency_pagedtable()))
295
296 }
297
298 # transition
299 if (is.numeric(transition))
300 transition <- as.character(transition)
301 else if (transition %in% c("default", "faster", "slower"))
302 transition <- switch(transition,
303 "default" = "0.4",
304 "faster" = "0.2",
305 "slower" = "0.6")
306 else
307 stop2('transition must be "default", "faster", "slower" or a ',
308 'numeric value (representing seconds)')
309 args <- c(args, pandoc_variable_arg("transition", transition))
310
311 # additional css
312 for (css_file in css)
313 args <- c(args, "--css", pandoc_path_arg(css_file, backslash = FALSE))
314
315 # content includes
316 args <- c(args, includes_to_pandoc_args(includes))
317
318 # template path and assets
319 if (is.null(template) || !file.exists(template))
320 template <- pkg_file("rmd/ioslides/default.html")
321 args <- c(args, "--template", pandoc_path_arg(template))
322
323 # html dependency for ioslides
324 extra_dependencies <- append(extra_dependencies,
325 list(html_dependency_ioslides()))
326
327 # analytics
328 if (!is.null(analytics))
329 args <- c(args, pandoc_variable_arg("analytics", analytics))
330
331 # do not wrap lines: https://github.com/rstudio/rmarkdown/issues/2327
332 if (!length(grep('--wrap', pandoc_args)))
333 pandoc_args <- c('--wrap', 'none', pandoc_args)
334
335 logo_placeholder <- "data:,LOGO"
336
337 # pre-processor for arguments that may depend on the name of the
338 # the input file (e.g. ones that need to copy supporting files)
339 pre_processor <- function(metadata, input_file, runtime, knit_meta, files_dir,
340 output_dir) {
341
342 # use files_dir as lib_dir if not explicitly specified
343 if (is.null(lib_dir))
344 lib_dir <- files_dir
345
346 # extra args
347 args <- c()
348
349 # create the files dir if it doesn't exist
350 if (!dir_exists(files_dir))
351 dir.create(files_dir)
352
353 # logo
354 if (!is.null(logo)) {
355 logo_path <- logo
356 if (!self_contained) {
357 # use same extension as specified logo (default is png if unspecified)
358 logo_ext <- xfun::file_ext(logo)
359 if (nchar(logo_ext) < 1)
360 logo_ext <- "png"
361 logo_path <- file.path(files_dir, paste("logo", logo_ext, sep = "."))
362 file.copy(from = logo, to = logo_path)
363 logo_path <- normalized_relative_to(output_dir, logo_path)
364 } else {
365 # placeholder, will be replaced by base64-encoded logo in post_processor
366 logo_path <- logo_placeholder
367 }
368 args <- c(args, "--variable", paste("logo=", logo_path, sep = ""))
369 }
370
371 # return additional args
372 args
373 }
374
375 # post processor that renders our markdown using our custom lua
376 # renderer and then inserts it into the main file
377 post_processor <- function(metadata, input_file, output_file, clean, verbose) {
378
379 # setup args
380 args <- c()
381
382 # add any custom pandoc args
383 args <- c(args, pandoc_args)
384
385 # number sections
386 if (number_sections)
387 args <- c(args, pandoc_lua_filter_args(pkg_file_lua("number-sections.lua")))
388
389 lua_writer <- file.path(dirname(input_file), "ioslides_presentation.lua")
390 # The input directory may not be writable (on e.g. Shiny Server), so write
391 # to the output directory in this case. We don't always do this since
392 # supplying a fully qualified path to the writer can trigger a bug on some
393 # Linux configurations.
394 if (!file.create(lua_writer, showWarnings = FALSE))
395 lua_writer <- file.path(dirname(output_file), basename(lua_writer))
396 on.exit(unlink(lua_writer), add = TRUE)
397
398 # determine whether we need to run citeproc
399 run_citeproc <- citeproc_required(metadata, read_utf8(input_file))
400
401 # write settings to file
402 settings <- c()
403 add_setting <- function(name, value) {
404 settings <<- c(settings, paste("local", name, "=",
405 ifelse(value, "true", "false")))
406 }
407 add_setting("fig_caption", fig_caption)
408 add_setting("incremental", incremental)
409 add_setting("smaller", smaller)
410 add_setting("smart", smart)
411 add_setting("mathjax", !is.null(mathjax))
412
413 # Set level of slide header (used by ioslides_presentation.lua)
414 settings <- c(settings, sprintf("local slide_level = %s", slide_level))
415 write_utf8(settings, lua_writer)
416
417 # For consistency add as pandoc argument
418 args <- c(args, "--slide-level", as.character(slide_level))
419
420 # append main body of script
421 file.append(lua_writer,
422 pkg_file("rmd/ioslides/ioslides_presentation.lua"))
423
424 output_tmpfile <- tempfile("ioslides-output", fileext = ".html")
425 on.exit(unlink(output_tmpfile), add = TRUE)
426
427 # on Windows, cache the current codepage and set it to 65001 (UTF-8) for the
428 # duration of the Pandoc command. Without this, Pandoc fails when attempting
429 # to hand UTF-8 encoded non-ASCII characters over to the custom Lua writer.
430 # See https://github.com/rstudio/rmarkdown/issues/134
431 if (is_windows() && !pandoc2.0()) {
432 # 'chcp' returns e.g., "Active code page: 437"; strip characters and parse
433 # the number
434 codepage <- as.numeric(gsub("\\D", "", system2("chcp", stdout = TRUE)))
435
436 if (!is.na(codepage)) {
437 # if we got a valid codepage, restore it on exit
438 on.exit(system2("chcp", args = codepage, stdout = TRUE), add = TRUE)
439
440 # change to the UTF-8 codepage
441 system2("chcp", args = 65001, stdout = TRUE)
442 }
443 }
444
445 pandoc_convert(input = input_file,
446 to = relative_to(dirname(input_file), lua_writer),
447 from = from_rmarkdown(fig_caption),
448 output = output_tmpfile,
449 options = args,
450 citeproc = run_citeproc,
451 verbose = verbose)
452
453 # read the slides
454 slides_lines <- read_utf8(output_tmpfile)
455
456 # read the output file
457 output_lines <- read_utf8(output_file)
458
459 # base64 encode if needed
460 if (self_contained) {
461 slides_lines <- base64_encode_images(slides_lines)
462 if (!is.null(logo)) {
463 logo_base64 <- if (grepl("^data:", logo)) logo else xfun::base64_uri(logo)
464 output_lines <- gsub(logo_placeholder, logo_base64, output_lines, fixed = TRUE)
465 }
466 }
467
468 # substitute slides for the sentinel line
469 sentinel_line <- grep("^RENDERED_SLIDES$", output_lines)
470 if (length(sentinel_line) == 1) {
471 preface_lines <- c(output_lines[1:sentinel_line[1] - 1])
472 suffix_lines <- c(output_lines[-(1:sentinel_line[1])])
473 output_lines <- c(preface_lines, slides_lines, suffix_lines)
474 write_utf8(output_lines, output_file)
475 } else {
476 stop2("Slides placeholder not found in slides HTML")
477 }
478
479 output_file
480 }
481
482 # return format
483 output_format(
484 knitr = knitr_options_html(fig_width, fig_height, fig_retina, keep_md, dev),
485 pandoc = pandoc_options(to = "html",
486 from = from_rmarkdown(fig_caption, md_extensions),
487 args = args),
488 keep_md = keep_md,
489 clean_supporting = self_contained,
490 df_print = df_print,
491 pre_processor = pre_processor,
492 post_processor = post_processor,
493 base_format = html_document_base(lib_dir = lib_dir,
494 self_contained = self_contained,
495 mathjax = mathjax,
496 pandoc_args = pandoc_args,
497 extra_dependencies = extra_dependencies,
498 bootstrap_compatible = TRUE, ...))
499 }
500
501
502 html_dependency_ioslides <- function() {
503 htmlDependency(
504 name = "ioslides",
505 version = "13.5.1",
506 src = pkg_file("rmd/ioslides/ioslides-13.5.1"),
507 script = c(
508 "js/modernizr.custom.45394.js",
509 "js/prettify/prettify.js",
510 "js/prettify/lang-r.js",
511 "js/prettify/lang-yaml.js",
512 "js/hammer.js",
513 "js/slide-controller.js",
514 "js/slide-deck.js"
515 ),
516 stylesheet = c(
517 "fonts/fonts.css",
518 "theme/css/default.css",
519 "theme/css/phone.css")
520 )
521 }