Debian Codegraph @

R/html_document.R

raw
1 #' Convert to an HTML document
2 #'
3 #' Format for converting from R Markdown to an HTML document.
4 #'
5 #' See the [online documentation](https://yihui.org/rmarkdown/html-document.html) for additional details on using the `html_document`
6 #' format.
7 #'
8 #' R Markdown documents can have optional metadata that is used to generate a
9 #' document header that includes the title, author, and date. For more details
10 #' see the documentation on R Markdown \link[=rmd_metadata]{metadata}.
11 #'
12 #' R Markdown documents also support citations. You can find more information on
13 #' the markdown syntax for citations in the
14 #' [Bibliographies and Citations](https://pandoc.org/MANUAL.html#citations) article in the online documentation.
15 #'
16 #' @inheritParams output_format
17 #' @param toc `TRUE` to include a table of contents in the output
18 #' @param toc_depth Depth of headers to include in table of contents
19 #' @param toc_float `TRUE` to float the table of contents to the left of the
20 #' main document content. Rather than `TRUE` you may also pass a list of
21 #' options that control the behavior of the floating table of contents. See the
22 #' *Floating Table of Contents* section below for details.
23 #' @param number_sections `TRUE` to number section headings
24 #' @param anchor_sections `TRUE` to show section anchors when mouse hovers
25 #' for all headers. A list can also be passed with `style` and/or
26 #' `depth` to customize the behavior. See
27 #' \link[rmarkdown:html_document]{Anchor Sections Customization section}.
28 #' @param fig_width Default width (in inches) for figures
29 #' @param fig_height Default height (in inches) for figures
30 #' @param fig_retina Scaling to perform for retina displays (defaults to 2, which
31 #' currently works for all widely used retina displays). Set to `NULL` to
32 #' prevent retina scaling. Note that this will always be `NULL` when
33 #' `keep_md` is specified (this is because `fig_retina` relies on
34 #' outputting HTML directly into the markdown document).
35 #' @param fig_caption `TRUE` to render figures with captions
36 #' @param dev Graphics device to use for figure output (defaults to png)
37 #' @param code_folding Enable document readers to toggle the display of R code
38 #' chunks. Specify `"none"` to display all code chunks. Specify
39 #' `"hide"` or `"show"` to hide or show all R code chunks by
40 #' default, and let readers toggle the states on browsers. See the
41 #' *Code folding*
42 #' @param code_download Embed the Rmd source code within the document and provide
43 #' a link that can be used by readers to download the code.
44 #' @param self_contained Produce a standalone HTML file with no external
45 #' dependencies, using data: URIs to incorporate the contents of linked
46 #' scripts, stylesheets, images, and videos. Note that even for self contained
47 #' documents MathJax is still loaded externally (this is necessary because of
48 #' its size).
49 #' @param theme One of the following:
50 #' * A [bslib::bs_theme()] object (or a list of [bslib::bs_theme()] argument values)
51 #' * Use this option for custom themes using Bootstrap 4 or 3.
52 #' * In this case, any `.scss`/`.sass` files provided to the `css`
53 #' parameter may utilize the `theme`'s underlying Sass utilities
54 #' (e.g., variables, mixins, etc).
55 #' * `NULL` for no theme (i.e., no [html_dependency_bootstrap()]).
56 #' * A character string specifying a [Bootswatch 3](https://bootswatch.com/3/)
57 #' theme name (for backwards-compatibility).
58 #' @param highlight Syntax highlight engine and style. See the
59 #' *Highlighting* section below for details.
60 #'
61 #' "default" (and "textmate") will use highlightjs as syntax highlighting
62 #' engine instead of Pandoc.
63 #'
64 #' Any other value will be passed as Pandoc's highlighting style. Pandoc's
65 #' built-in styles include "tango", "pygments", "kate", "monochrome",
66 #' "espresso", "zenburn", "haddock" and "breezedark".
67 #'
68 #' Two custom styles are also included, "arrow", an accessible color scheme,
69 #' and "rstudio", which mimics the default IDE theme. Alternatively, supply a
70 #' path to a \samp{.theme} to use
71 #' [a custom Pandoc
72 #' style](https://pandoc.org/MANUAL.html#syntax-highlighting). Note that custom theme requires Pandoc 2.0+.
73 #'
74 #' Pass `NULL` to prevent syntax highlighting.
75 #'
76 #' @param highlight_downlit `TRUE` to use the \pkg{downlit} package as
77 #' syntax highlight engine to highlight inline code and R code chunks
78 #' (including providing hyperlinks to function documentation). The package
79 #' needs to be installed to use this feature.
80 #'
81 #' Only Pandoc color schemes are supported with this engine. With
82 #' `highlight = "default"`, it will use the accessible theme called
83 #' "arrow". To learn more about \pkg{downlit} highlighting engine, see
84 #' <https://downlit.r-lib.org/>.
85 #' @param mathjax Include mathjax. The "default" option uses an https URL from a
86 #' MathJax CDN. The "local" option uses a local version of MathJax (which is
87 #' copied into the output directory). You can pass an alternate URL or pass
88 #' `NULL` to exclude MathJax entirely.
89 #' @param math_method Math rendering engine to use. This will define the math method to use with Pandoc.
90 #'
91 #' - It can be a string for the engine, one of `r knitr::combine_words(c(pandoc_math_engines(), "r-katex"), and = "or ", before = '"')`
92 #' or "default" for `mathjax`.
93 #' - It can be a list of
94 #' - `engine`: one of
95 #' `r knitr::combine_words(pandoc_math_engines(), and = "or ", before = '"')`.
96 #' - `url`: A specific url to use with `mathjax`, `katex` or `webtex`.
97 #' Note that for `engine = "mathjax"`, `url = "local"` will use a local version of MathJax (which is
98 #' copied into the output directory).
99 #'
100 #' For example,
101 #' ```yaml
102 #' output:
103 #' html_document:
104 #' math_method:
105 #' engine: katex
106 #' url: https://cdn.jsdelivr.net/npm/[email protected]/dist/
107 #' ```
108 #'
109 #' See [Pandoc's Manual about Math in
110 #' HTML](https://pandoc.org/MANUAL.html#math-rendering-in-html) for the details
111 #' about Pandoc supported methods.
112 #'
113 #' Using `math_method = "r-katex"` will opt-in server side rendering using
114 #' KaTeX thanks to [katex](https://docs.ropensci.org/katex/) R package. This is
115 #' useful compared to `math_method = "katex"` to have no JS dependency, only a
116 #' CSS dependency for styling equation.
117 #' @param section_divs Wrap sections in `<div>` tags, and attach identifiers to the
118 #' enclosing `<div>` rather than the header itself.
119 #' @param template Pandoc template to use for rendering. Pass "default" to use
120 #' the rmarkdown package default template; pass `NULL` to use pandoc's
121 #' built-in template; pass a path to use a custom template that you've created.
122 #' Note that if you don't use the "default" template then some features of
123 #' `html_document` won't be available (see the Templates section below for
124 #' more details).
125 #' @param extra_dependencies Extra dependencies as a list of the
126 #' `html_dependency` class objects typically generated by
127 #' [htmltools::htmlDependency()].
128 #' @param css CSS and/or Sass files to include. Files with an extension of .sass
129 #' or .scss are compiled to CSS via `sass::sass()`. Also, if `theme` is a
130 #' [bslib::bs_theme()] object, Sass code may reference the relevant Bootstrap
131 #' Sass variables, functions, mixins, etc.
132 #' @param includes Named list of additional content to include within the
133 #' document (typically created using the [`includes`] function).
134 #' @param keep_md Keep the markdown file generated by knitting.
135 #' @param lib_dir Directory to copy dependent HTML libraries (e.g. jquery,
136 #' bootstrap, etc.) into. By default this will be the name of the document with
137 #' `_files` appended to it.
138 #' @param md_extensions Markdown extensions to be added or removed from the
139 #' default definition of R Markdown. See the [`rmarkdown_format`] for
140 #' additional details.
141 #' @param pandoc_args Additional command line options to pass to pandoc
142 #' @param ... Additional function arguments to pass to the base R Markdown HTML
143 #' output formatter [`html_document_base`]
144 #' @return R Markdown output format to pass to [`render`]
145 #'
146 #' @section Highlighting:
147 #'
148 #' There are three highlighting engines available to HTML documents:
149 #'
150 #' \describe{
151 #' \item{highlightjs}{It does highlighting in the browser, using javascript It
152 #' can only be used with the default template (i.e `template = "default"`)
153 #' and it has two styles ("default" and "textmate"). When activated, it adds
154 #' two additional dependencies to the output file: a JS script and a CSS file.
155 #' For now, this is the default engine for the default template - this could
156 #' change in the future.}
157 #'
158 #' \item{Pandoc}{Pandoc's built-in highlighting.engine works with any template,
159 #' default or custom, and style can be chosen among the built-in ones ("tango",
160 #' "pygments", "kate", "monochrome", "espresso", "zenburn", "haddock" and
161 #' "breezedark") or a path to a custom theme ".theme" file (see Details in the
162 #' [Pandoc Manual](https://pandoc.org/MANUAL.html#syntax-highlighting)).
163 #' \pkg{rmarkdown} includes two custom themes to select with `highlight`
164 #' parameter:
165 #' - "arrow", an accessible style using colors [optimized for accessibility and color contrast](https://www.a11yproject.com/)
166 #' - "rstudio", a color scheme close to RStudio's default highlighting and
167 #' highglightjs's textmate.
168 #'
169 #' Custom themes are only available for Pandoc 2.0 and above.}
170 #'
171 #' \item{downlit}{[\pkg{downlit}](https://downlit.r-lib.org/) is an R package that
172 #' provides a syntax highlighting engine in R. It will also do automatic
173 #' linking of R code (requires internet connectivity). It is activated only if
174 #' `highlight_downlit = TRUE` and only affects R code, leaving
175 #' highlighting for other languages unchanged. The default color scheme is
176 #' the accessible theme "arrow".
177 #'
178 #' It requires some CSS in the template to correctly style links. This is included
179 #' in the default template, but if you want to use with a custom template, you will
180 #' need to add this to your template:
181 #'
182 #' ```
183 #' $if(highlight-downlit)$
184 #' <style type="text/css">
185 #' code a:any-link {
186 #' color: inherit; /* use colour from syntax highlighting */
187 #' text-decoration: underline;
188 #' text-decoration-color: #ccc;
189 #' }
190 #' </style>
191 #' $endif$
192 #' ```
193 #' }}
194 #'
195 #' @section Anchor Sections Customization:
196 #'
197 #' This will be the default to activate anchor sections link on header
198 #' ```yaml
199 #' output:
200 #' html_document:
201 #' anchor_sections: TRUE
202 #' ````
203 #' There are currently two options to modify the default behavior
204 #'
205 #' \describe{
206 #' \item{`style`}{Select a predefined visual style:
207 #' * `style = "dash"`, the default, uses \samp{#}, a minimalist choice that evokes the id selector from HTML and CSS.
208 #' * `style = "symbol"` will use a [link symbol](https://codepoints.net/U+1F517) \if{html}{\out{(&#x1F517;&#xFE0E;)}}
209 #' * `style = "icon"` will use an svg icon. \if{html}{(\figure{link-black-18dp.svg}{options: alt="icon link"})}
210 #'
211 #' You can also customize using a css rule in your
212 #' document. For example, to get a pictogram \if{html}{\out{(&#x1F517;)}}:
213 #' ```css
214 #' a.anchor-section::before {
215 #' content: '\\01F517';
216 #' }
217 #' ```
218 #' About how to apply custom CSS in R Markdown document, see
219 #' <https://yihui.org/rmarkdown-cookbook/html-css.html>
220 #' }
221 #' \item{`depth`}{Select the maximum header level to add the
222 #' anchor link to. For example, this yaml will use the symbol style and
223 #' only with level 1 and 2 headings:
224 #' ```yaml
225 #' output:
226 #' html_document:
227 #' anchor_sections:
228 #' style: icon
229 #' depth: 2
230 #' ```
231 #' If omitted, anchor will be added to all headers (equivalent of
232 #' `depth=6`). You can also set anchors manually with `depth = 0` using this syntax
233 #' ```markdown
234 #' # my header {.hasAnchor}
235 #' ```
236 #' }
237 #'
238 #' Using anchor sections will add some CSS to your document output for the
239 #' styling, and a JS script if `section_divs = TRUE`. The anchor link itself
240 #' is added using a Lua filter, and hence requires Pandoc 2.0+
241 #' }
242 #'
243 #' @section Navigation Bars:
244 #'
245 #' If you have a set of html documents which you'd like to provide a common
246 #' global navigation bar for, you can include a "_navbar.yml" or "_navbar.html"
247 #' file within the same directory as your html document and it will automatically
248 #' be included at the top of the document.
249 #'
250 #' The "_navbar.yml" file includes `title`, `type`, `left`, and
251 #' `right` fields (to define menu items for the left and right of the navbar
252 #' respectively). Menu items include `text` and `href` fields. For example:
253 #'
254 #' ```yaml
255 #' title: "My Website"
256 #' type: default
257 #' left:
258 #' - text: "Home"
259 #' href: index.html
260 #' - text: "Other"
261 #' href: other.html
262 #' right:
263 #' - text: GitHub
264 #' href: https://github.com
265 #' ```
266 #' The `type` field is optional and can take the value "default" or "inverse" (which
267 #' provides a different color scheme for the navigation bar).
268 #'
269 #' Alternatively, you can include a "_navbar.html" file which is a full HTML definition
270 #' of a bootstrap navigation bar. For a simple example of including a navigation bar see
271 #' <https://github.com/rstudio/rmarkdown-website/blob/master/_navbar.html>.
272 #' For additional documentation on creating Bootstrap navigation bars see
273 #' <https://getbootstrap.com/docs/4.5/components/navbar/>.
274 #'
275 #'
276 #' @section Floating Table of Contents:
277 #'
278 #' You may specify a list of options for the `toc_float` parameter which
279 #' control the behavior of the floating table of contents. Options include:
280 #'
281 #' - `collapsed` (defaults to `TRUE`) controls whether the table of contents appears with only the top-level (H2) headers. When collapsed the table of contents is automatically expanded inline when necessary.
282 #' - `smooth_scroll` (defaults to `TRUE`) controls whether page scrolls are animated when table of contents items are navigated to via mouse clicks.
283 #' - `print` (defaults to `TRUE`) controls whether the table of contents appears when user prints out the HTML page.
284 #'
285 #' @section Code folding:
286 #'
287 #' Code blocks become foldable by specifying "show" or "hide" to the
288 #' `code_folding` parameter. The state can be toggled individually on
289 #' browsers. The document-wide toggle button is also provided for
290 #' `html_document` and some of its extensions such as
291 #' `html_notebook`. Note that this feature applies not only to source
292 #' codes of chunks, but also markdown code blocks.
293 #'
294 #' Supported languages are R, Python, Bash, SQL, C++, Stan, and Julia. To
295 #' support code blocks with other languages, add `foldable` class to them
296 #' (i.e., `class.source = "foldable"` as a chunk option).
297 #'
298 #' The default initial state of code folding respects the value given to the
299 #' `code_folding` parameter. To override the behavior individually, add
300 #' `fold-none` to disable, `fold-hide` to initially hide,
301 #' `fold-show` to initially show.
302 #'
303 #' @section Tabbed Sections:
304 #'
305 #' You can organize content using tabs by applying the `.tabset` class
306 #' attribute to headers within a document. This will cause all sub-headers of
307 #' the header with the `.tabset` attribute to appear within tabs rather
308 #' than as standalone sections. For example:
309 #'
310 #' ```markdown
311 #' ## Quarterly Results {.tabset}
312 #'
313 #' ### By Product
314 #'
315 #' ### By Region
316 #' ```
317 #'
318 #' With [html_document()], you can also specify two additional attributes to
319 #' control the appearance and behavior of the tabs. The `.tabset-fade`
320 #' attributes causes the tabs to fade in and out when switching. The
321 #' `.tabset-pills` attribute causes the visual appearance of the tabs to
322 #' be "pill" rather than traditional tabs. For example:
323 #'
324 #' ```markdown
325 #' ## Quarterly Results {.tabset .tabset-fade .tabset-pills}
326 #' ```
327 #'
328 #' If tabbed sections relies on [html_dependency_tabset()], for example by
329 #' [html_vignette()], these two attributes are not supported.
330 #'
331 #' @section Templates:
332 #'
333 #' You can provide a custom HTML template to be used for rendering. The syntax
334 #' for templates is described in the
335 #' [pandoc documentation](https://pandoc.org/MANUAL.html). You can also use
336 #' the basic pandoc template by passing `template = NULL`.
337 #'
338 #' Note however that if you choose not to use the "default" HTML template then
339 #' several aspects of HTML document rendering will behave differently:
340 #'
341 #' - The `theme` parameter does not work (you can still provide styles using the `css` parameter).
342 #' - For the `highlight` parameter, the default highlighting engine will resolve to Pandoc instead of highlightjs and highlighting style will default to "pygments". "textmate" style is not available as related to highlightjs
343 #' - The `toc_float` parameter will not work.
344 #' - The `code_folding` parameter will not work.
345 #' - Tabbed sections (as described above) will not work.
346 #' - Navigation bars (as described above) will not work.
347 #' - MathJax will not work if `self_contained` is `TRUE` (these two options can't be used together in normal pandoc templates).
348 #'
349 #' Due to the above restrictions, you might consider using the `includes`
350 #' parameter as an alternative to providing a fully custom template.
351 #'
352 #' @examples
353 #' \dontrun{
354 #' library(rmarkdown)
355 #'
356 #' render("input.Rmd", html_document())
357 #'
358 #' render("input.Rmd", html_document(toc = TRUE))
359 #' }
360 #' @md
361 #' @export
362 html_document <- function(
363 toc = FALSE,
364 toc_depth = 3,
365 toc_float = FALSE,
366 number_sections = FALSE,
367 anchor_sections = FALSE,
368 section_divs = TRUE,
369 fig_width = 7,
370 fig_height = 5,
371 fig_retina = 2,
372 fig_caption = TRUE,
373 dev = 'png',
374 df_print = "default",
375 code_folding = c("none", "show", "hide"),
376 code_download = FALSE,
377 self_contained = TRUE,
378 theme = "default",
379 highlight = "default",
380 highlight_downlit = FALSE,
381 math_method = "default",
382 mathjax = "default",
383 template = "default",
384 extra_dependencies = NULL,
385 css = NULL,
386 includes = NULL,
387 keep_md = FALSE,
388 lib_dir = NULL,
389 md_extensions = NULL,
390 pandoc_args = NULL,
391 ...
392 ) {
393 # self_contained = TRUE already uses --standalone
394 args <- if (!self_contained) c("--standalone")
395
396 # to add lua_filters
397 lua_filters <- c()
398
399 # use section divs
400 if (section_divs) {
401 args <- c(args, "--section-divs")
402 }
403
404 # table of contents
405 args <- c(args, pandoc_toc_args(toc, toc_depth))
406
407 # makes downstream logic easier to reason about
408 theme <- resolve_theme(theme)
409
410 # toc_float
411 if (toc && !identical(toc_float, FALSE)) {
412 # must have a theme
413 if (is.null(theme)) {
414 stop("You must use a theme when specifying the 'toc_float' option")
415 }
416
417 # resolve options
418 toc_float_options <- list(
419 collapsed = TRUE,
420 smooth_scroll = TRUE,
421 print = TRUE
422 )
423 if (is.list(toc_float)) {
424 toc_float_options <- merge_lists(toc_float_options, toc_float)
425 toc_float <- TRUE
426 } else if (!isTRUE(toc_float)) {
427 stop("toc_float must be a logical or a list with options")
428 }
429
430 # dependencies
431 extra_dependencies <- append(
432 extra_dependencies,
433 list(
434 html_dependency_jquery(),
435 html_dependency_jqueryui(),
436 html_dependency_tocify()
437 )
438 )
439
440 # flag for template
441 args <- c(args, pandoc_variable_arg("toc_float", "1"))
442
443 # selectors
444 selectors <- paste0("h", seq(1, toc_depth), collapse = ",")
445 args <- c(args, pandoc_variable_arg("toc_selectors", selectors))
446
447 # options
448 if (toc_float_options$collapsed) {
449 args <- c(args, pandoc_variable_arg("toc_collapsed", "1"))
450 }
451 if (toc_float_options$smooth_scroll) {
452 args <- c(args, pandoc_variable_arg("toc_smooth_scroll", "1"))
453 }
454 if (toc_float_options$print) {
455 args <- c(args, pandoc_variable_arg("toc_print", "1"))
456 }
457 }
458
459 # template path and assets
460 template_file <- if (identical(template, "default")) {
461 pkg_file("rmd/h/default.html")
462 } else {
463 template
464 }
465 if (!is.null(template_file)) {
466 args <- c(args, "--template", pandoc_path_arg(template_file))
467 }
468
469 # validate code_folding
470 code_folding <- match.arg(code_folding)
471
472 # navigation dependencies
473 if (!is.null(theme)) {
474 code_menu <- !identical(code_folding, "none") || code_download
475 source_embed <- code_download
476 extra_dependencies <- append(
477 extra_dependencies,
478 list(
479 html_dependency_jquery(),
480 html_dependency_navigation(
481 code_menu = code_menu,
482 source_embed = source_embed
483 )
484 )
485 )
486 }
487
488 # highlighting ---------
489 if (highlight_downlit && !xfun::loadable("downlit")) {
490 stop(
491 "highlight_downlit=TRUE requires the downlit package to be installed.",
492 call. = FALSE
493 )
494 }
495 args <- c(
496 args,
497 pandoc_html_highlight_args(template, highlight, highlight_downlit)
498 )
499
500 # add highlight.js html_dependency if required
501 extra_dependencies <- append(
502 extra_dependencies,
503 if (identical(template, "default") && is_highlightjs(highlight)) {
504 list(html_dependency_highlightjs(highlight))
505 } else if (!is.null(highlight)) {
506 # for screen-reader accessibility improvement
507 list(html_dependency_accessible_code_block())
508 }
509 )
510
511 # numbered sections
512 if (number_sections) {
513 args <- c(args, "--number-sections")
514 }
515
516 # manage list of exit_actions (backing out changes to knitr options)
517 exit_actions <- list()
518 on_exit <- function() {
519 for (action in exit_actions) {
520 try(action())
521 }
522 }
523
524 # capture the source code if requested
525 source_code <- NULL
526 source_file <- NULL
527 pre_knit <- function(input, ...) {
528 if (code_download) {
529 source_file <<- basename(input)
530 source_code <<- paste0(
531 '<div id="rmd-source-code">',
532 xfun::base64_encode(input),
533 '</div>'
534 )
535 }
536 }
537
538 # pagedtable
539 if (identical(df_print, "paged")) {
540 extra_dependencies <- append(
541 extra_dependencies,
542 list(html_dependency_pagedtable())
543 )
544 }
545
546 # anchor-sections
547 components <- add_anchor_sections(anchor_sections, section_divs)
548 args <- c(args, components$args)
549 lua_filters <- c(lua_filters, components$lua_filters)
550 extra_dependencies <- append(
551 extra_dependencies,
552 components$extra_dependencies
553 )
554
555 # pre-processor for arguments that may depend on the name of the
556 # the input file AND which need to inject html dependencies
557 # (otherwise we could just call the pre_processor)
558 post_knit <- function(metadata, input_file, runtime, ...) {
559 # extra args
560 args <- c()
561
562 # navbar (requires theme)
563 if (!is.null(theme)) {
564 # add navbar to includes if necessary
565 navbar <- file.path(normalize_path(dirname(input_file)), "_navbar.html")
566
567 # if there is no _navbar.html look for a _navbar.yml
568 if (!file.exists(navbar)) {
569 navbar_yaml <- file.path(dirname(navbar), "_navbar.yml")
570 if (file.exists(navbar_yaml)) {
571 navbar <- navbar_html_from_yaml(navbar_yaml)
572 }
573 # if there is no _navbar.yml then look in site config (if we have it)
574 config <- site_config(input_file)
575 if (!is.null(config) && !is.null(config$navbar)) {
576 navbar <- navbar_html(config$navbar)
577 }
578 }
579
580 if (file.exists(navbar)) {
581 # include the navbar html
582 includes <- list(before_body = navbar)
583 args <- c(
584 args,
585 includes_to_pandoc_args(
586 includes,
587 filter = if (is_shiny_classic(runtime)) {
588 function(x) normalize_path(x, must_work = FALSE)
589 } else {
590 identity
591 }
592 )
593 )
594
595 # flag indicating we need extra navbar css and js
596 args <- c(args, pandoc_variable_arg("navbar", "1"))
597
598 # navbar icon dependencies
599 iconDeps <- navbar_icon_dependencies(navbar)
600 if (length(iconDeps) > 0) {
601 knitr::knit_meta_add(list(iconDeps))
602 }
603 }
604 }
605
606 args
607 }
608
609 # pre-processor for arguments that may depend on the name of the
610 # the input file (e.g. ones that need to copy supporting files)
611 pre_processor <- function(
612 metadata,
613 input_file,
614 runtime,
615 knit_meta,
616 files_dir,
617 output_dir
618 ) {
619 # use files_dir as lib_dir if not explicitly specified
620 if (is.null(lib_dir)) {
621 lib_dir <- files_dir
622 }
623
624 # extra args
625 args <- c()
626
627 # track whether we have a code menu
628 code_menu <- FALSE
629
630 # code_folding
631 if (code_folding %in% c("show", "hide")) {
632 # must have a theme
633 if (is.null(theme)) {
634 stop("You must use a theme when specifying the 'code_folding' option")
635 }
636 args <- c(args, pandoc_variable_arg("code_folding", code_folding))
637 code_menu <- TRUE
638 }
639
640 # source_embed
641 if (code_download) {
642 if (is.null(theme)) {
643 stop("You must use a theme when specifying the 'code_download' option")
644 }
645 args <- c(args, pandoc_variable_arg("source_embed", source_file))
646 sourceCodeFile <- tempfile(fileext = ".html")
647 write_utf8(source_code, sourceCodeFile)
648 args <- c(args, pandoc_include_args(after_body = sourceCodeFile))
649 code_menu <- TRUE
650 }
651
652 # code menu
653 if (code_menu) {
654 args <- c(args, pandoc_variable_arg("code_menu", "1"))
655 }
656
657 # content includes (we do this here so that user include-in-header content
658 # goes after dependency generated content). make the paths absolute if
659 # making a Shiny document so we can resolve them even if rendering
660 # elsewhere.
661 args <- c(
662 args,
663 includes_to_pandoc_args(
664 includes,
665 filter = if (is_shiny_classic(runtime)) {
666 function(x) normalize_path(x, must_work = FALSE)
667 } else {
668 identity
669 }
670 )
671 )
672
673 # return additional args
674 args
675 }
676
677 # post-processor that uses the output file from pandoc
678 post_processor <- function(
679 metadata,
680 input_file,
681 output_file,
682 clean,
683 verbose
684 ) {
685 # add a post processor for syntax highlighting with downlit if requested
686 if (highlight_downlit) {
687 output_file <- downlit::downlit_html_path(
688 output_file,
689 output_file,
690 classes = downlit::classes_pandoc()
691 )
692 }
693
694 output_file
695 }
696
697 # return format
698 output_format(
699 knitr = knitr_options_html(fig_width, fig_height, fig_retina, keep_md, dev),
700 pandoc = pandoc_options(
701 to = "html",
702 from = from_rmarkdown(fig_caption, md_extensions),
703 args = args,
704 lua_filters = lua_filters
705 ),
706 keep_md = keep_md,
707 clean_supporting = self_contained,
708 df_print = df_print,
709 pre_knit = pre_knit,
710 post_knit = post_knit,
711 pre_processor = pre_processor,
712 post_processor = post_processor,
713 on_exit = on_exit,
714 base_format = html_document_base(
715 theme = theme,
716 self_contained = self_contained,
717 lib_dir = lib_dir,
718 math_method = math_method,
719 mathjax = mathjax,
720 template = template,
721 pandoc_args = pandoc_args,
722 extra_dependencies = extra_dependencies,
723 css = css,
724 ...
725 )
726 )
727 }
728
729
730 #' Knitr options for an HTML output format
731 #'
732 #' Define knitr options for an R Markdown output format that creates
733 #' HTML output.
734 #'
735 #' @inheritParams html_document
736 #' @return An list that can be passed as the \code{knitr} argument of the
737 #' \code{\link{output_format}} function.
738 #' @seealso \link{knitr_options}, \link{output_format}
739 #' @export
740 knitr_options_html <- function(
741 fig_width,
742 fig_height,
743 fig_retina,
744 keep_md,
745 dev = 'png'
746 ) {
747 opts_chunk <- list(
748 dev = dev,
749 dpi = 96,
750 fig.width = fig_width,
751 fig.height = fig_height,
752 fig.retina = fig_retina
753 )
754
755 if (keep_md) {
756 opts_chunk$fig.retina <- NULL
757 }
758
759 knitr_options(opts_chunk = opts_chunk)
760 }
761
762 # CSS files in inst/rmd/h/bootstrap/css
763 themes <- function() {
764 c(
765 "default", # keep for backward compatibility reason, changed to 'bootstrap' internally
766 "bootstrap",
767 "cerulean",
768 "cosmo",
769 "darkly",
770 "flatly",
771 "journal",
772 "lumen",
773 "paper",
774 "readable",
775 "sandstone",
776 "simplex",
777 "spacelab",
778 "united",
779 "yeti"
780 )
781 }
782
783 html_highlighters <- function() {
784 c(highlighters(), "textmate")
785 }
786
787 navbar_html_from_yaml <- function(navbar_yaml) {
788 # parse the yaml
789 navbar <- yaml_load_file(navbar_yaml)
790
791 # generate the html
792 navbar_html(navbar)
793 }
794
795
796 #' Create a navbar HTML file from a navbar definition
797 #'
798 #' @param navbar Navbar definition
799 #' @param links List of navbar links
800 #' @return Path to temporary file with navbar definition
801 #' @keywords internal
802 #' @export
803 navbar_html <- function(navbar) {
804 # title and type
805 if (is.null(navbar$title)) {
806 navbar$title <- ""
807 }
808 if (is.null(navbar$type)) {
809 navbar$type <- "default"
810 }
811
812 # menu entries
813 left <- navbar_links_html(navbar$left)
814 right <- navbar_links_html(navbar$right)
815
816 # build the navigation bar and return it as a temp file
817 template <- file_string(pkg_file("rmd/h/_navbar.html"))
818 navbar_html <- sprintf(template, navbar$type, navbar$title, left, right)
819 as_tmpfile(navbar_html)
820 }
821
822 #' @keywords internal
823 #' @name navbar_html
824 #' @export
825 navbar_links_html <- function(links) {
826 as.character(navbar_links_tags(links))
827 }
828
829 navbar_links_tags <- function(links, depth = 0L) {
830 if (!is.null(links)) {
831 tags <- lapply(links, function(x) {
832 if (!is.null(x$menu)) {
833 # sub-menu
834 is_submenu <- depth > 0L
835
836 if (is_submenu) {
837 menu_class <- "dropdown-submenu"
838 link_text <- navbar_link_text(x)
839 } else {
840 menu_class <- "dropdown"
841 link_text <- navbar_link_text(x, " ", tags$span(class = "caret"))
842 }
843
844 submenuLinks <- navbar_links_tags(x$menu, depth = depth + 1L)
845
846 tags$li(
847 class = menu_class,
848 tags$a(
849 href = "#",
850 class = "dropdown-toggle",
851 `data-toggle` = "dropdown",
852 role = "button",
853 `data-bs-toggle` = "dropdown", # BS5
854 `aria-expanded` = "false",
855 link_text
856 ),
857 tags$ul(class = "dropdown-menu", role = "menu", submenuLinks)
858 )
859 } else if (!is.null(x$text) && grepl("^\\s*-{3,}\\s*$", x$text)) {
860 # divider
861 tags$li(class = "divider")
862 } else if (!is.null(x$text) && is.null(x$href)) {
863 # header
864 tags$li(class = "dropdown-header", x$text)
865 } else {
866 # standard menu item
867 textTags <- navbar_link_text(x)
868 tags$li(tags$a(href = x$href, textTags))
869 }
870 })
871 tagList(tags)
872 } else {
873 tagList()
874 }
875 }
876
877 navbar_link_text <- function(x, ...) {
878 if (!is.null(x$icon)) {
879 # find the iconset
880 split <- strsplit(x$icon, "-")
881 if (length(split[[1]]) > 1) {
882 iconset <- split[[1]][[1]]
883 } else {
884 iconset <- ""
885 }
886 # check if a full class is passed for fontawesome = V5
887 # Add fa deprecated fa prefix otherwise = V4 compatibility
888 # https://github.com/rstudio/rmarkdown/issues/1554
889 class = if (grepl("^fa\\w? fa", iconset)) {
890 # Fontawesome 5 - full new prefix + name must be passed
891 # if old fa prefix is passed - keep it for compatibility
892 x$icon
893 } else if (iconset == "fa") {
894 # Fontawesome 4 compatibility - Add deprecated fa prefix
895 paste("fa", x$icon)
896 } else {
897 # Other Icon sets
898 paste(iconset, x$icon)
899 }
900 tagList(tags$span(class = class), " ", x$text, ...)
901 } else {
902 tagList(x$text, ...)
903 }
904 }
905
906 add_anchor_sections <- function(anchor_sections, section_divs = FALSE) {
907 # expected output object
908 res <- list(args = NULL, lua_filters = NULL, extra_dependencies = NULL)
909 # Do nothing
910 if (identical(anchor_sections, FALSE)) {
911 return(res)
912 }
913 # Requires Pandoc 2.0 because using a Lua filter
914 if (!pandoc2.0()) {
915 stop("Using anchor_sections requires Pandoc 2.0+", call. = FALSE)
916 }
917
918 allowed_args <- c("style", "depth")
919 default_style <- "hash"
920
921 if (isTRUE(anchor_sections)) {
922 style <- default_style
923 depth <- NULL
924 } else if (is.list(anchor_sections)) {
925 # check list elements
926 all_allowed <- all(names(anchor_sections) %in% allowed_args)
927 if (!all_allowed) {
928 stop(
929 "`anchor_sections` could be a list with only names in [",
930 paste(allowed_args, collapse = ", "),
931 "]",
932 call. = FALSE
933 )
934 }
935 style <- anchor_sections[["style"]] %||% default_style
936 depth <- anchor_sections[["depth"]]
937 } else {
938 stop(
939 "`anchor_sections` should be FALSE, TRUE or a list with names [",
940 paste(allowed_args, collapse = ", "),
941 "]",
942 call. = FALSE
943 )
944 }
945
946 res$args <- if (!is.null(depth)) {
947 pandoc_metadata_arg("rmd_anchor_depth", depth)
948 }
949 res$lua_filters <- pkg_file_lua("anchor-sections.lua")
950 res$extra_dependencies <- list(html_dependency_anchor_sections(
951 style,
952 section_divs
953 ))
954
955 res
956 }