Debian Codegraph @

R/html_document_base.R

raw
1 #' Base output format for HTML-based output formats
2 #'
3 #' Creates an HTML base output format suitable for passing as the
4 #' \code{base_format} argument of the \code{\link{output_format}} function.
5 #'
6 #' @inheritParams html_document
7 #'
8 #' @param dependency_resolver A dependency resolver
9 #' @param copy_resources Copy resources
10 #' @param bootstrap_compatible Bootstrap compatible
11 #' @param ... Ignored
12 #'
13 #' @return HTML base output format.
14 #'
15 #' @export
16 html_document_base <- function(theme = NULL,
17 self_contained = TRUE,
18 lib_dir = NULL,
19 math_method = "default",
20 mathjax = "default",
21 pandoc_args = NULL,
22 template = "default",
23 dependency_resolver = NULL,
24 copy_resources = FALSE,
25 extra_dependencies = NULL,
26 css = NULL,
27 bootstrap_compatible = FALSE,
28 ...) {
29
30 # default for dependency_resolver
31 if (is.null(dependency_resolver))
32 dependency_resolver <- html_dependency_resolver
33
34 args <- c()
35
36 # backward compatibility for math /mathjax argument
37 # math is used only when `mathjax = "default"`
38 math <- mathjax_to_math(mathjax, math_method)
39 # any math to list(engine = , url = )
40 math <- check_math_argument(math)
41
42 # self contained document
43 if (self_contained) {
44 if (copy_resources)
45 stop("Local resource copying is incompatible with self-contained documents.")
46 validate_self_contained(math)
47 args <- c(args, self_contained_args())
48 }
49
50 # custom args
51 args <- c(args, pandoc_args)
52
53 preserved_chunks <- character()
54
55 output_dir <- ""
56
57 theme <- resolve_theme(theme)
58
59 # In the bs_theme() case, we set the theme globally so that knitting code may
60 # alter it before we ultimately compile it into an HTML dependency.
61 old_theme <- NULL
62 pre_knit <- function(input, ...) {
63 if (is_bs_theme(theme)) {
64 # merge css file with bslib mechanism...
65 for (f in css) theme <<- bslib::bs_add_rules(theme, xfun::read_utf8(f))
66 # ...and don't process CSS files further in Pandoc
67 css <<- NULL
68
69 # save old theme
70 old_theme <<- bslib::bs_global_set(theme)
71 }
72 }
73 post_knit <- function(metadata, input_file, runtime, ...) {}
74 on_exit <- function() {
75 # In this case, we know we've altered global state, so restore the old theme
76 if (is_bs_theme(theme)) bslib::bs_global_set(old_theme)
77 }
78
79 # pre_processor
80 pre_processor <- function(metadata, input_file, runtime, knit_meta,
81 files_dir, output_dir) {
82
83 args <- c()
84
85 # use files_dir as lib_dir if not explicitly specified
86 if (is.null(lib_dir))
87 lib_dir <<- files_dir
88
89 # copy supplied output_dir (for use in post-processor)
90 output_dir <<- output_dir
91
92 if (!is.null(theme)) {
93 theme_arg <- if (is.list(theme)) "bootstrap" else theme
94 args <- c(args, pandoc_variable_arg("theme", theme_arg))
95 }
96
97 # Process css files as Pandoc argument if not already been processed by bslib
98 for (f in css) {
99 if (needs_sass(f)) {
100 if (!xfun::loadable("sass")) {
101 stop2("Using `.sass` or `.scss` file in `css` argument requires the sass package.")
102 }
103 f <- sass::sass(
104 sass::sass_file(f),
105 # write output file to `lib_dir/sass-{sass:::sass_hash()}{[basename(f)}`
106 output = sass::output_template(
107 basename = xfun::sans_ext(basename(f)),
108 dirname = "sass",
109 path = lib_dir
110 ),
111 options = sass::sass_options(output_style = "compressed")
112 )
113 f <- normalized_relative_to(output_dir, f)
114 }
115 args <- c(args, "--css", pandoc_path_arg(f, backslash = FALSE))
116 }
117
118 # math support
119 math_support <- add_math_support(math, template, lib_dir, output_dir)
120 args <- c(args, math_support$args)
121 extra_dependencies <- c(extra_dependencies, math_support$extra_dependencies)
122
123 # resolve and inject extras, including dependencies specified by the format
124 # and dependencies specified by the user (via extra_dependencies)
125 format_deps <- list()
126 format_deps <- append(format_deps, html_dependency_header_attrs())
127 if (!is.null(theme)) {
128 format_deps <- append(format_deps, list(html_dependency_jquery()))
129 # theme was set globally pre-knit, and it may be modified during knit
130 if (is_bs_theme(theme)) {
131 theme <- bslib::bs_global_get()
132 }
133 bootstrap_deps <- if (is_bs_theme(theme) && is_shiny(runtime, metadata[["server"]])) {
134 list(shiny_bootstrap_lib(theme))
135 } else {
136 bootstrap_dependencies(theme)
137 }
138 format_deps <- append(format_deps, htmltools::resolveDependencies(bootstrap_deps))
139 }
140 else if (isTRUE(bootstrap_compatible) && is_shiny(runtime, metadata[["server"]])) {
141 # If we can add bootstrap for Shiny, do it
142 format_deps <- append(format_deps, bootstrap_dependencies("bootstrap"))
143 }
144 format_deps <- append(format_deps, extra_dependencies)
145
146 extras <- html_extras_for_document(knit_meta, runtime, dependency_resolver,
147 format_deps)
148 args <- c(args, pandoc_html_extras_args(extras, self_contained, lib_dir,
149 output_dir))
150
151 preserved_chunks <<- extract_preserve_chunks(input_file)
152
153 args
154 }
155
156 intermediates_generator <- function(original_input, intermediates_dir) {
157 # copy intermediates; skip web resources if not self contained (pandoc can
158 # create references to web resources without the file present)
159 copy_render_intermediates(original_input, intermediates_dir, !self_contained)
160 }
161
162 post_processor <- function(metadata, input_file, output_file, clean, verbose) {
163
164 # Special KaTeX math support
165 if (identical(math_method, "r-katex") && xfun::pkg_available("katex", "1.4.0")) {
166 katex::render_math_in_html(output_file, output = output_file)
167 }
168
169 # if there are no preserved chunks to restore and no resource to copy then no
170 # post-processing is necessary
171 if (length(preserved_chunks) == 0 && !isTRUE(copy_resources) && self_contained)
172 return(output_file)
173
174 # read the output file
175 output_str <- read_utf8(output_file)
176
177 # if we preserved chunks, restore them
178 if (length(preserved_chunks) > 0) {
179 # Pandoc adds an empty <p></p> around the IDs of preserved chunks, and we
180 # need to remove these empty tags, otherwise we may have invalid HTML like
181 # <p><div>...</div></p>. For the reason of the second gsub(), see
182 # https://github.com/rstudio/rmarkdown/issues/133.
183 for (i in names(preserved_chunks)) {
184 output_str <- gsub(paste0("<p>", i, "</p>"), i, output_str,
185 fixed = TRUE, useBytes = TRUE)
186 output_str <- gsub(paste0(' id="[^"]*?', i, '[^"]*?" '), ' ', output_str,
187 useBytes = TRUE)
188 }
189 output_str <- restorePreserveChunks(output_str, preserved_chunks)
190 }
191
192 if (copy_resources) {
193 # The copy_resources flag copies all the resources referenced in the
194 # document to its supporting files directory, and rewrites the document to
195 # use the copies from that directory.
196 output_str <- copy_html_resources(one_string(output_str), lib_dir, output_dir)
197 } else if (!self_contained) {
198 # if we're not self-contained, find absolute references to the output
199 # directory and replace them with relative ones
200 image_relative <- function(img_src, src) {
201 in_file <- utils::URLdecode(src)
202 # do not process paths that are already relative
203 if (grepl('^[.][.]', in_file)) return(img_src)
204 if (length(in_file) && file.exists(in_file)) {
205 img_src <- sub(
206 src, utils::URLencode(normalized_relative_to(output_dir, in_file)),
207 img_src, fixed = TRUE)
208 }
209 img_src
210 }
211 output_str <- process_images(output_str, image_relative)
212 }
213
214 write_utf8(output_str, output_file)
215
216 output_file
217 }
218
219 if (!is.null(theme)) {
220 bs3 <- identical("3", theme_version(theme))
221 args <- c(args, pandoc_variable_arg("bs3", bs3))
222 }
223
224 output_format(
225 knitr = NULL,
226 pandoc = pandoc_options(
227 to = "html", from = NULL, args = args,
228 lua_filters = pkg_file_lua(c(
229 "pagebreak.lua", "latex-div.lua",
230 if (pandoc_available("3.2.1")) "table-classes.lua"
231 ))
232 ),
233 keep_md = FALSE,
234 clean_supporting = FALSE,
235 pre_knit = pre_knit,
236 post_knit = post_knit,
237 on_exit = on_exit,
238 pre_processor = pre_processor,
239 intermediates_generator = intermediates_generator,
240 post_processor = post_processor
241 )
242 }
243
244 extract_preserve_chunks <- function(input_file, extract = extractPreserveChunks) {
245 # Don't try to modify the input file if it's not .md, otherwise the original
246 # input could be corrupted (#2534). In theory, preserved chunks should only
247 # exist in the intermediate .md file from knit(). If the .md file is not
248 # intermediate but original, this processing should be harmless.
249 if (!xfun::file_ext(input_file) %in% c('md', 'markdown')) return()
250 input_str <- one_string(read_utf8(input_file))
251 preserve <- extract(input_str)
252 if (!identical(preserve$value, input_str)) write_utf8(preserve$value, input_file)
253 preserve$chunks
254 }
255
256
257 # Math support ------------------------------------------------------------
258
259 default_mathjax <- function() {
260 paste0("https://mathjax.rstudio.com/latest/", mathjax_config())
261 }
262
263 mathjax_config <- function() {
264 "MathJax.js?config=TeX-AMS-MML_HTMLorMML"
265 }
266
267 add_math_support <- function(math, template, files_dir, output_dir) {
268
269 # check math argument should be already or NULL
270 # (list(engine = "", url = "")
271
272 extras <- NULL
273
274 if (is.null(math)) return(NULL)
275
276 # handle different engines
277
278 # Special handling: KaTeX R package
279 if (identical(math$engine, "r-katex")) {
280 if (xfun::pkg_available("katex", "1.4.0")) {
281 # We need to tell pandoc to process the equation,
282 # setting no math argument will make Pandoc throw a warning
283 # If used with a template contained `$math$`, JS and CSS will be inserted
284 # TODO: patch template to remove the math variable when needed.
285 return(list(args = pandoc_math_args("katex")))
286 }
287 stop2("katex R package (>= 1.4.0) is required for server-side rendering.\n",
288 "Install the package or change `math_method`.")
289 }
290
291 # Default
292 if (identical(math$engine, "default")) math$engine <- "mathjax"
293
294 # Check supported
295 if (!math$engine %in% c(pandoc_math_engines())) {
296 stop2(sprintf("`math_method='%s'` is not supported.", math$engine))
297 }
298
299 # support only mathjax for Pandoc before 2.0+
300 if (!pandoc2.0() && !identical(math$engine, "mathjax")) {
301 stop2("only `math_method = 'mathjax'` is supported with earlier version than Pandoc 2.0 ")
302 }
303
304 # change default for url for webtex to use SVG
305 # Pandoc still uses PNG
306 if (identical(math$engine, "webtex")) {
307 math$url <- math$url %||% "https://latex.codecogs.com/svg.image?"
308 }
309
310 # No special handling needed for most engine
311 if (math$engine %in% setdiff(pandoc_math_engines(), c("mathjax", "katex"))) {
312 return(list(args = pandoc_math_args(math$engine, math$url)))
313 }
314
315 # MATHJAX OR KATEX needs special handling
316
317 if (identical(math$engine, "katex")) {
318 if (identical(template, "default")) {
319 args <- pandoc_math_args(math$engine)
320 extras <- list(html_dependency_katex(math$url))
321 } else {
322 args <- c(pandoc_math_args(math$engine, math$url))
323 }
324 } else if (identical(math$engine, "mathjax")) {
325 if (identical(math$url, "local")) {
326 # local supported for mathjax only
327 mathjax_path <- render_supporting_files(
328 pandoc_mathjax_local_path(),
329 files_dir,
330 "mathjax-local")
331 math$url <- paste(normalized_relative_to(output_dir, mathjax_path), "/",
332 mathjax_config(), sep = "")
333 }
334 if (identical(template, "default")) {
335 args <- c(
336 pandoc_math_args(math$engine),
337 pandoc_variable_arg("mathjax-url", math$url %||% default_mathjax())
338 )
339 } else {
340 args <- c(pandoc_math_args(math$engine, math$url))
341 }
342 }
343
344 list(args = args, extra_dependencies = extras)
345 }
346
347 check_math_argument <- function(math) {
348 url <- NULL
349 engine <- NULL
350 # math is deactivated
351 if (is.null(math)) return(NULL)
352 # otherwise
353 if (is.list(math) && !is.null(names(math))) {
354 # can be a named list
355 engine <- if (is.character(math$engine)) math$engine
356 url <- math$url
357 } else if (length(math) == 1L && is.character(math[[1L]])) {
358 # can be a string
359 engine <- math[[1L]]
360 }
361
362 # if no engine found, incorrect value must have been provided
363 if (is.null(engine)) {
364 stop2("'math' can be the engine name (a string) or a list with engine and optionally the url to use.")
365 }
366
367 list(engine = engine, url = url)
368 }
369
370 mathjax_to_math <- function(mathjax, math) {
371 if (is.null(mathjax)) {
372 # deactivate math
373 return(NULL)
374 } else if (identical(mathjax, "default")) {
375 # default to other argument now
376 return(math)
377 } else if (identical(mathjax, "local")) {
378 # use local mathajx
379 return(list(engine = "mathjax", url = "local"))
380 } else if (is.logical(mathjax)) {
381 # let mathjax = FALSE deactivate
382 return(if(isTRUE(mathjax)) math)
383 } else if (is.character(mathjax)) {
384 # any other string should be a mathjax url
385 return(list(engine = "mathjax", url = mathjax))
386 }
387 # just return math for any other value
388 math
389 }