| 1 |
#' R Markdown Metadata |
| 2 |
#' |
| 3 |
#' Rmd files include a metadata section (typically located at the top of the |
| 4 |
#' file) that can specify (among other things) the title, author, and date of |
| 5 |
#' the document. Metadata adheres to the \href{https://yaml.org}{YAML} format |
| 6 |
#' and is delimited by lines containing three dashes (\code{---}). Here is an |
| 7 |
#' example metadata section: |
| 8 |
#' \preformatted{--- |
| 9 |
#' title: "Crop Analysis Q3 2013" |
| 10 |
#' author: Martha Smith |
| 11 |
#' date: October 23rd, 2013 |
| 12 |
#' --- |
| 13 |
#' } |
| 14 |
#' Note that the \code{title} field is quoted. This is because titles often |
| 15 |
#' contained embedded colons (\code{:}) and colons followed by a space need to |
| 16 |
#' be quoted in YAML. |
| 17 |
#' @details When title, author, and date metadata is provided it's used to |
| 18 |
#' automatically create a title section within output documents. If you don't |
| 19 |
#' want this section included in your document then you should remove the |
| 20 |
#' corresponding metadata fields. |
| 21 |
#' |
| 22 |
#' When generating PDF and Beamer output there are also a number of other |
| 23 |
#' metadata fields that can be included to customize the appearance and theme |
| 24 |
#' of PDF output. For more details see the documentation for |
| 25 |
#' \code{\link{pdf_document}} and \code{\link{beamer_presentation}}. |
| 26 |
#' @name rmd_metadata |
| 27 |
NULL |
| 28 |
|
| 29 |
|
| 30 |
#' The YAML metadata of the current R Markdown document |
| 31 |
#' |
| 32 |
#' The object \code{metadata} stores the YAML metadata of the current R Markdown |
| 33 |
#' document as a list, which you may use in the R code chunks, e.g. |
| 34 |
#' \code{rmarkdown::metadata$title} (the title of the document), |
| 35 |
#' \code{rmarkdown::metadata$author}, and \code{rmarkdown::metadata$foo} (if you |
| 36 |
#' have a YAML field named \code{foo}), etc. |
| 37 |
#' @usage NULL |
| 38 |
#' @examples rmarkdown::metadata |
| 39 |
#' @export |
| 40 |
metadata <- list() |
| 41 |
|
| 42 |
|
| 43 |
#' Compiling R scripts to a notebook |
| 44 |
#' |
| 45 |
#' R Markdown can also compile R scripts to a notebook which includes |
| 46 |
#' commentary, source code, and script output. Notebooks can be compiled to any |
| 47 |
#' output format including HTML, PDF, and MS Word. |
| 48 |
#' |
| 49 |
#' @section Overview: |
| 50 |
#' To compile a notebook from an R script you simply pass the script to |
| 51 |
#' \code{\link{render}}. For example: |
| 52 |
#' \preformatted{ |
| 53 |
#' rmarkdown::render("analysis.R") |
| 54 |
#' rmarkdown::render("analysis.R", "pdf_document") |
| 55 |
#' } |
| 56 |
#' The first call to \code{\link{render}} creates an HTML document, whereas |
| 57 |
#' the second creates a PDF document. |
| 58 |
#' |
| 59 |
#' By default the name of the script, username, and current date and time are |
| 60 |
#' included in the header of the generated notebook. You can override this |
| 61 |
#' default behavior by including explicit metadata in a specially formatted R |
| 62 |
#' comment: |
| 63 |
#' \preformatted{ |
| 64 |
#' #' --- |
| 65 |
#' #' title: "Crop Analysis Q3 2013" |
| 66 |
#' #' author: "John Smith" |
| 67 |
#' #' date: "May 3rd, 2014" |
| 68 |
#' #' --- |
| 69 |
#' } |
| 70 |
#' @section Including Markdown: |
| 71 |
#' Note that the R comment used above to add a title, author, and date |
| 72 |
#' includes a single-quote as a special prefix character. This is a |
| 73 |
#' \pkg{roxygen2} style comment, and it's actually possible to include many |
| 74 |
#' such comments in an R script, all of which will be converted to markdown |
| 75 |
#' content within the generated notebook. For example: |
| 76 |
#' \preformatted{#' A script comment that includes **markdown** formatting.} |
| 77 |
#' Rather than displaying as an R comment in the compiled notebook any |
| 78 |
#' \pkg{roxygen2} style comment will be treated as markdown and rendered |
| 79 |
#' accordingly. |
| 80 |
#' @section knitr Spin: |
| 81 |
#' Including markdown within R comments is possible because \code{\link{render}} |
| 82 |
#' calls the \code{\link[knitr:spin]{knitr spin}} function to convert the R |
| 83 |
#' script to an Rmd file. The \code{spin} function also enables you to add |
| 84 |
#' knitr |
| 85 |
#' chunk options with another special comment prefix (\code{#+}). |
| 86 |
#' |
| 87 |
#' Here's an example of a script that uses the various features of \code{spin}: |
| 88 |
#' |
| 89 |
#' \url{https://github.com/yihui/knitr/blob/master/inst/examples/knitr-spin.R} |
| 90 |
#' |
| 91 |
#' For more details on \code{knitr::spin} see the following documentation: |
| 92 |
#' |
| 93 |
#' \url{https://yihui.org/knitr/demo/stitch/} |
| 94 |
#' @name compile_notebook |
| 95 |
NULL |
| 96 |
|
| 97 |
|
| 98 |
#' Render R Markdown |
| 99 |
#' |
| 100 |
#' Render the input file to the specified output format using pandoc. If the |
| 101 |
#' input requires knitting then \code{\link[knitr:knit]{knit}} is called prior |
| 102 |
#' to pandoc. |
| 103 |
#' |
| 104 |
#' Note that the \pkg{knitr} \code{error} option is set to \code{FALSE} during |
| 105 |
#' rendering (which is different from the \pkg{knitr} default value of |
| 106 |
#' \code{TRUE}). |
| 107 |
#' |
| 108 |
#' For additional details on rendering R scripts see |
| 109 |
#' \link[=compile_notebook]{Compiling R scripts to a notebook}. |
| 110 |
#' |
| 111 |
#' If no \code{output_format} parameter is specified then the output format is |
| 112 |
#' read from the YAML front-matter of the input file. For example, the |
| 113 |
#' following YAML would yield a PDF document: |
| 114 |
#' |
| 115 |
#' \preformatted{ |
| 116 |
#' output: pdf_document |
| 117 |
#' } |
| 118 |
#' |
| 119 |
#' Additional format options can also be specified in metadata. For example: |
| 120 |
#' |
| 121 |
#' \preformatted{ |
| 122 |
#' output: |
| 123 |
#' pdf_document: |
| 124 |
#' toc: true |
| 125 |
#' highlight: zenburn |
| 126 |
#' } |
| 127 |
#' |
| 128 |
#' Multiple formats can be specified in metadata. If no \code{output_format} |
| 129 |
#' is passed to \code{render} then the first one defined will be used: |
| 130 |
#' |
| 131 |
#' \preformatted{ |
| 132 |
#' output: |
| 133 |
#' pdf_document: |
| 134 |
#' toc: true |
| 135 |
#' highlight: zenburn |
| 136 |
#' html_document: |
| 137 |
#' toc: true |
| 138 |
#' theme: united |
| 139 |
#' } |
| 140 |
#' |
| 141 |
#' Formats specified in metadata can be any one of the built in formats (e.g. |
| 142 |
#' \code{\link{html_document}}, \code{\link{pdf_document}}) or a format defined |
| 143 |
#' in another package (e.g. \code{pkg::custom_format}). |
| 144 |
#' |
| 145 |
#' If there is no format defined in the YAML then |
| 146 |
#' \code{\link{html_document}} will be used. |
| 147 |
#' @section R Markdown: |
| 148 |
#' R Markdown supports all of the base pandoc markdown features as well as some |
| 149 |
#' optional features for compatibility with GitHub Flavored Markdown (which |
| 150 |
#' previous versions of R Markdown were based on). See |
| 151 |
#' \code{\link{rmarkdown_format}} for details. |
| 152 |
#' @seealso |
| 153 |
#' \link[knitr:knit]{knit}, \link{output_format}, |
| 154 |
#' \url{https://pandoc.org} |
| 155 |
#' @inheritParams default_output_format |
| 156 |
#' @param input The input file to be rendered. This can be an R script (.R), |
| 157 |
#' an R Markdown document (.Rmd), or a plain markdown document. |
| 158 |
#' @param output_format The R Markdown output format to convert to. The option |
| 159 |
#' \code{"all"} will render all formats defined within the file. The option can |
| 160 |
#' be the name of a format (e.g. \code{"html_document"}) and that will render |
| 161 |
#' the document to that single format. One can also use a vector of format |
| 162 |
#' names to render to multiple formats. Alternatively, you can pass an output |
| 163 |
#' format object (e.g. \code{html_document()}). If using \code{NULL} then the |
| 164 |
#' output format is the first one defined in the YAML frontmatter in the input |
| 165 |
#' file (this defaults to HTML if no format is specified there). |
| 166 |
#' If you pass an output format object to \code{output_format}, the options |
| 167 |
#' specified in the YAML header or \code{_output.yml} will be ignored and you |
| 168 |
#' must explicitly set all the options you want when you construct the object. |
| 169 |
#' If you pass a string, the output format will use the output parameters in |
| 170 |
#' the YAML header or \code{_output.yml}. |
| 171 |
#' @param output_file The name of the output file. If using \code{NULL} then the |
| 172 |
#' output filename will be based on filename for the input file. If a filename |
| 173 |
#' is provided, a path to the output file can also be provided. Note that the |
| 174 |
#' \code{output_dir} option allows for specifying the output file path as well, |
| 175 |
#' however, if also specifying the path, the directory must exist. If |
| 176 |
#' \code{output_file} is specified but does not have a file extension, an |
| 177 |
#' extension will be automatically added according to the output format. To |
| 178 |
#' avoid the automatic file extension, put the \code{output_file} value in |
| 179 |
#' \code{\link{I}()}, e.g., \code{I('my-output')}. |
| 180 |
#' @param output_dir The output directory for the rendered \code{output_file}. |
| 181 |
#' This allows for a choice of an alternate directory to which the output file |
| 182 |
#' should be written (the default output directory of that of the input file). |
| 183 |
#' If a path is provided with a filename in \code{output_file} the directory |
| 184 |
#' specified here will take precedence. Please note that any directory path |
| 185 |
#' provided will create any necessary directories if they do not exist. |
| 186 |
#' @param output_options List of output options that can override the options |
| 187 |
#' specified in metadata (e.g. could be used to force \code{self_contained} or |
| 188 |
#' \code{mathjax = "local"}). Note that this is only valid when the output |
| 189 |
#' format is read from metadata (i.e. not a custom format object passed to |
| 190 |
#' \code{output_format}). |
| 191 |
#' @param intermediates_dir Intermediate files directory. If a path is specified |
| 192 |
#' then intermediate files will be written to that path. If \code{NULL}, |
| 193 |
#' intermediate files are written to the same directory as the input file. |
| 194 |
#' @param knit_root_dir The working directory in which to knit the document; |
| 195 |
#' uses knitr's \code{root.dir} knit option. If \code{NULL} then the behavior |
| 196 |
#' will follow the knitr default, which is to use the parent directory of the |
| 197 |
#' document. |
| 198 |
#' @param runtime The runtime target for rendering. The \code{static} option |
| 199 |
#' produces output intended for static files; \code{shiny} produces output |
| 200 |
#' suitable for use in a Shiny document (see \code{\link{run}}). The default, |
| 201 |
#' \code{auto}, allows the \code{runtime} target specified in the YAML metadata |
| 202 |
#' to take precedence, and renders for a \code{static} runtime target otherwise. |
| 203 |
#' @param clean Using \code{TRUE} will clean intermediate files that are created |
| 204 |
#' during rendering. |
| 205 |
#' @param params A list of named parameters that override custom params |
| 206 |
#' specified within the YAML front-matter (e.g. specifying a dataset to read or |
| 207 |
#' a date range to confine output to). Pass \code{"ask"} to start an |
| 208 |
#' application that helps guide parameter configuration. |
| 209 |
#' @param knit_meta (This option is reserved for expert use.) Metadata |
| 210 |
#' generated by \pkg{knitr}. |
| 211 |
#' @param envir The environment in which the code chunks are to be evaluated |
| 212 |
#' during knitting (can use \code{\link{new.env}()} to guarantee an empty new |
| 213 |
#' environment). |
| 214 |
#' @param run_pandoc An option for whether to run pandoc to convert Markdown |
| 215 |
#' output. |
| 216 |
#' @param quiet An option to suppress printing during rendering from knitr, |
| 217 |
#' pandoc command line and others. To only suppress printing of the last |
| 218 |
#' "Output created: " message, you can set \code{rmarkdown.render.message} to |
| 219 |
#' \code{FALSE} |
| 220 |
#' @param encoding Ignored. The encoding is always assumed to be UTF-8. |
| 221 |
#' @return |
| 222 |
#' When \code{run_pandoc = TRUE}, the compiled document is written into |
| 223 |
#' the output file, and the path of the output file is returned. When |
| 224 |
#' \code{run_pandoc = FALSE}, the path of the Markdown output file, with |
| 225 |
#' attributes \code{knit_meta} (the \pkg{knitr} meta data collected from code |
| 226 |
#' chunks) and \code{intermediates} (the intermediate files/directories |
| 227 |
#' generated by \code{render()}). |
| 228 |
#' @examples |
| 229 |
#' \dontrun{ |
| 230 |
#' library(rmarkdown) |
| 231 |
#' |
| 232 |
#' # Render the default (first) format defined in the file |
| 233 |
#' render("input.Rmd") |
| 234 |
#' |
| 235 |
#' # Render all formats defined in the file |
| 236 |
#' render("input.Rmd", "all") |
| 237 |
#' |
| 238 |
#' # Render a single format, using parameters for \code{html_document} from |
| 239 |
#' # the YAML header parameters. |
| 240 |
#' render("input.Rmd", "html_document") |
| 241 |
#' |
| 242 |
#' # Render a single format, ignoring parameters for \code{html_document} in |
| 243 |
#' # the YAML header. Any parameters not passed as arguments to |
| 244 |
#' # \code{html_document()} will be assigned to their default values, regardless |
| 245 |
#' # of anything in the YAML header |
| 246 |
#' render("input.Rmd", html_document(toc = TRUE, toc_depth = 2)) |
| 247 |
#' |
| 248 |
#' # Render multiple formats |
| 249 |
#' render("input.Rmd", c("html_document", "pdf_document")) |
| 250 |
#' } |
| 251 |
#' @export |
| 252 |
render <- function(input, |
| 253 |
output_format = NULL, |
| 254 |
output_file = NULL, |
| 255 |
output_dir = NULL, |
| 256 |
output_options = NULL, |
| 257 |
output_yaml = NULL, |
| 258 |
intermediates_dir = NULL, |
| 259 |
knit_root_dir = NULL, |
| 260 |
runtime = c("auto", "static", "shiny", "shinyrmd", "shiny_prerendered"), |
| 261 |
clean = TRUE, |
| 262 |
params = NULL, |
| 263 |
knit_meta = NULL, |
| 264 |
envir = parent.frame(), |
| 265 |
run_pandoc = TRUE, |
| 266 |
quiet = FALSE, |
| 267 |
encoding = "UTF-8") { |
| 268 |
|
| 269 |
perf_timer_start("render") |
| 270 |
|
| 271 |
init_render_context() |
| 272 |
on.exit(clear_render_context(), add = TRUE) |
| 273 |
|
| 274 |
# render() may call itself, e.g., in discover_rmd_resources(); in this case, |
| 275 |
# we should not clean up temp files in the nested render() call, but wait |
| 276 |
# until the top-level render() exits to clean up temp files |
| 277 |
.globals$level <- .globals$level + 1L # increment level in a nested render() |
| 278 |
on.exit({ |
| 279 |
.globals$level <- .globals$level - 1L |
| 280 |
if (.globals$level == 0) clean_tmpfiles() |
| 281 |
}, add = TRUE) |
| 282 |
|
| 283 |
# check for "all" output formats |
| 284 |
if (identical(output_format, "all")) { |
| 285 |
output_format <- enumerate_output_formats(input) |
| 286 |
if (is.null(output_format)) |
| 287 |
output_format <- "html_document" |
| 288 |
} |
| 289 |
|
| 290 |
# check for a list of output formats -- if there is more than one |
| 291 |
# then recursively call this function with each format by name |
| 292 |
if (is.character(output_format) && length(output_format) > 1) { |
| 293 |
outputs <- character() |
| 294 |
if (length(output_file) == 1) output_file <- rep(output_file, length(output_format)) |
| 295 |
for (i in seq_along(output_format)) { |
| 296 |
# the output_file argument is intentionally ignored (we can't give |
| 297 |
# the same name to each rendered output); copy the rest by name |
| 298 |
output <- render(input = input, |
| 299 |
output_format = output_format[i], |
| 300 |
output_file = output_file[i], |
| 301 |
output_dir = output_dir, |
| 302 |
output_options = output_options, |
| 303 |
intermediates_dir = intermediates_dir, |
| 304 |
knit_root_dir = knit_root_dir, |
| 305 |
runtime = runtime, |
| 306 |
clean = clean, |
| 307 |
params = params, |
| 308 |
knit_meta = knit_meta, |
| 309 |
envir = envir, |
| 310 |
run_pandoc = run_pandoc, |
| 311 |
quiet = quiet) |
| 312 |
outputs <- c(outputs, output) |
| 313 |
} |
| 314 |
return(invisible(outputs)) |
| 315 |
} |
| 316 |
|
| 317 |
# check for required version of pandoc if we are running pandoc |
| 318 |
if (run_pandoc) { |
| 319 |
required_pandoc <- "1.12.3" |
| 320 |
pandoc_available(required_pandoc, error = TRUE) |
| 321 |
} |
| 322 |
|
| 323 |
# setup a cleanup function for intermediate files |
| 324 |
intermediates <- c() |
| 325 |
on.exit(if (clean) unlink(intermediates, recursive = TRUE), add = TRUE) |
| 326 |
|
| 327 |
# ensure we have a directory to store intermediates |
| 328 |
if (!is.null(intermediates_dir)) { |
| 329 |
if (!dir_exists(intermediates_dir)) |
| 330 |
dir.create(intermediates_dir, recursive = TRUE) |
| 331 |
intermediates_dir <- normalize_path(intermediates_dir) |
| 332 |
} |
| 333 |
intermediates_loc <- function(file) { |
| 334 |
if (is.null(intermediates_dir)) |
| 335 |
file |
| 336 |
else |
| 337 |
file.path(intermediates_dir, file) |
| 338 |
} |
| 339 |
|
| 340 |
# resolve output directory before we change the working directory in |
| 341 |
# preparation for rendering the document |
| 342 |
if (!is.null(output_dir)) { |
| 343 |
if (!dir_exists(output_dir)) |
| 344 |
dir.create(output_dir, recursive = TRUE) |
| 345 |
output_dir <- normalize_path(output_dir) |
| 346 |
} |
| 347 |
|
| 348 |
# check whether this document requires a knit |
| 349 |
requires_knit <- tolower(xfun::file_ext(input)) %in% c("r", "rmd", "rmarkdown", "qmd") |
| 350 |
|
| 351 |
# remember the name of the original input document (we overwrite 'input' once |
| 352 |
# we've knitted) |
| 353 |
original_input <- normalize_path(input) |
| 354 |
|
| 355 |
# if the input file has shell characters in its name then make a copy that |
| 356 |
# doesn't have shell characters |
| 357 |
if (grepl(.shell_chars_regex, basename(input))) { |
| 358 |
# form the name of the file w/o shell characters |
| 359 |
input_no_shell_chars <- intermediates_loc( |
| 360 |
file_name_without_shell_chars(basename(input))) |
| 361 |
|
| 362 |
if (file.exists(input_no_shell_chars)) { |
| 363 |
stop2("The name of the input file cannot contain the special shell ", |
| 364 |
"characters: ", .shell_chars_regex, " (attempted to copy to a ", |
| 365 |
"version without those characters '", input_no_shell_chars, "' ", |
| 366 |
"however that file already exists)") |
| 367 |
} |
| 368 |
file.copy(input, input_no_shell_chars, overwrite = TRUE) |
| 369 |
intermediates <- c(intermediates, input_no_shell_chars) |
| 370 |
input <- input_no_shell_chars |
| 371 |
|
| 372 |
# if an intermediates directory wasn't explicit before, make it explicit now |
| 373 |
if (is.null(intermediates_dir)) { |
| 374 |
intermediates_dir <- |
| 375 |
dirname(normalize_path(input_no_shell_chars)) |
| 376 |
} |
| 377 |
} |
| 378 |
|
| 379 |
# never use the original input directory as the intermediate directory, |
| 380 |
# otherwise external resources discovered will be deleted as intermediate |
| 381 |
# files later (because they are copied to the "intermediate" dir) |
| 382 |
if (!is.null(intermediates_dir) && |
| 383 |
same_path(intermediates_dir, dirname(original_input))) |
| 384 |
intermediates_dir <- NULL |
| 385 |
|
| 386 |
# force evaluation of knitr root dir before we change directory context |
| 387 |
force(knit_root_dir) |
| 388 |
|
| 389 |
# execute within the input file's directory |
| 390 |
oldwd <- setwd(dirname(abs_path(input))) |
| 391 |
on.exit(setwd(oldwd), add = TRUE) |
| 392 |
|
| 393 |
# reset the name of the input file to be relative and generate the name of |
| 394 |
# the intermediate knitted file. The extension can be set as an option mainly for blogdown |
| 395 |
# as `.md~` will be ignored. |
| 396 |
input <- basename(input) |
| 397 |
knit_input <- input |
| 398 |
knit_output <- intermediates_loc( |
| 399 |
file_with_meta_ext(input, "knit", getOption("rmarkdown.knit.ext", "md")) |
| 400 |
) |
| 401 |
intermediates <- c(intermediates, knit_output) |
| 402 |
|
| 403 |
# track whether this was straight markdown input (to prevent keep_md later) |
| 404 |
md_input <- identical(tolower(xfun::file_ext(input)), "md") |
| 405 |
|
| 406 |
# if this is an R script then spin it first |
| 407 |
if (identical(tolower(xfun::file_ext(input)), "r")) { |
| 408 |
# make a copy of the file to spin |
| 409 |
spin_input <- intermediates_loc(file_with_meta_ext(input, "spin", "R")) |
| 410 |
file.copy(input, spin_input, overwrite = TRUE) |
| 411 |
intermediates <- c(intermediates, spin_input) |
| 412 |
# spin it |
| 413 |
spin_rmd <- knitr::spin(spin_input, |
| 414 |
knit = FALSE, |
| 415 |
envir = envir, |
| 416 |
format = "Rmd") |
| 417 |
intermediates <- c(intermediates, spin_rmd) |
| 418 |
knit_input <- spin_rmd |
| 419 |
# append default metadata unless the field exists in YAML |
| 420 |
meta1 <- yaml_front_matter(knit_input) |
| 421 |
meta2 <- list( |
| 422 |
title = input, author = Sys.info()[["user"]], |
| 423 |
date = as.character(Sys.Date()) |
| 424 |
) |
| 425 |
for (i in names(meta2)) if (!is.null(meta1[[i]])) meta2[[i]] <- NULL |
| 426 |
if (length(meta2)) { |
| 427 |
input_lines <- read_utf8(knit_input) |
| 428 |
write_utf8(c(input_lines, '\n\n---', yaml::as.yaml(meta2), '---'), knit_input) |
| 429 |
} |
| 430 |
} |
| 431 |
|
| 432 |
# read the input file |
| 433 |
input_lines <- read_utf8(knit_input) |
| 434 |
|
| 435 |
# read the yaml front matter |
| 436 |
front_matter <- parse_yaml_front_matter(input_lines) |
| 437 |
|
| 438 |
# metadata to be attached to the returned value of render() as an attribute |
| 439 |
old_output_metadata <- output_metadata$get() |
| 440 |
on.exit(output_metadata$restore(old_output_metadata), add = TRUE) |
| 441 |
output_metadata$restore(as.list(front_matter[['rmd_output_metadata']])) |
| 442 |
|
| 443 |
# if this is shiny_prerendered then modify the output format to |
| 444 |
# be single-page and to output dependencies to the shiny.dep file |
| 445 |
shiny_prerendered_dependencies <- list() |
| 446 |
if (requires_knit && is_shiny_prerendered(front_matter$runtime, |
| 447 |
front_matter$server)) { |
| 448 |
|
| 449 |
# require shiny for the knit |
| 450 |
if (requireNamespace("shiny")) { |
| 451 |
if (!"package:shiny" %in% search()) |
| 452 |
attachNamespace("shiny") |
| 453 |
} |
| 454 |
else |
| 455 |
stop("The shiny package is required for shiny documents") |
| 456 |
|
| 457 |
# source global.R if it exists |
| 458 |
global_r <- file.path.ci(".", "global.R") |
| 459 |
if (file.exists(global_r)) { |
| 460 |
source(global_r, local = envir) |
| 461 |
} |
| 462 |
|
| 463 |
# force various output options |
| 464 |
output_options$self_contained <- FALSE |
| 465 |
output_options$dependency_resolver <- function(deps) { |
| 466 |
shiny_prerendered_dependencies <<- list( |
| 467 |
deps = deps, |
| 468 |
packages = get_loaded_packages() |
| 469 |
) |
| 470 |
list() |
| 471 |
} |
| 472 |
} |
| 473 |
|
| 474 |
# if we haven't been passed a fully formed output format then |
| 475 |
# resolve it by looking at the yaml |
| 476 |
if (!is_output_format(output_format)) { |
| 477 |
output_format <- output_format_from_yaml_front_matter(input_lines, |
| 478 |
output_options, |
| 479 |
output_format, |
| 480 |
output_yaml, |
| 481 |
output_file) |
| 482 |
output_format <- create_output_format(output_format$name, |
| 483 |
output_format$options) |
| 484 |
} |
| 485 |
pandoc_to <- output_format$pandoc$to |
| 486 |
|
| 487 |
# generate outpout file based on input filename |
| 488 |
output_auto <- pandoc_output_file(input, output_format$pandoc) |
| 489 |
if (is.null(output_file) || is.na(output_file)) output_file <- output_auto else { |
| 490 |
if (!inherits(output_file, "AsIs") && xfun::file_ext(output_file) == "") |
| 491 |
output_file <- paste(output_file, xfun::file_ext(output_auto), sep = ".") |
| 492 |
} |
| 493 |
|
| 494 |
# if an output_dir was specified then concatenate it with the output file |
| 495 |
if (!is.null(output_dir)) { |
| 496 |
output_file <- file.path(output_dir, basename(output_file)) |
| 497 |
} |
| 498 |
output_dir <- dirname(output_file) |
| 499 |
|
| 500 |
# Stop the render process early if the output directory does not exist |
| 501 |
if (!dir_exists(output_dir)) { |
| 502 |
stop2("The directory '", output_dir, "' does not exist.") |
| 503 |
} |
| 504 |
|
| 505 |
# use output filename based files dir |
| 506 |
files_dir_slash <- file.path(output_dir, knitr_files_dir(basename(output_file))) |
| 507 |
files_dir <- pandoc_path_arg(files_dir_slash) |
| 508 |
|
| 509 |
# default to no cache_dir (may be generated by the knit) |
| 510 |
cache_dir <- NULL |
| 511 |
|
| 512 |
# call any intermediate files generator, if we have an intermediates directory |
| 513 |
# (do this before knitting in case the knit requires intermediates) |
| 514 |
if (!is.null(intermediates_dir) && |
| 515 |
!is.null(output_format$intermediates_generator)) { |
| 516 |
intermediates <- c(intermediates, |
| 517 |
output_format$intermediates_generator(original_input, |
| 518 |
intermediates_dir)) |
| 519 |
} |
| 520 |
|
| 521 |
# reset knit_meta (and ensure it's always reset before exiting render) |
| 522 |
old_knit_meta <- knit_meta_reset() |
| 523 |
on.exit({ |
| 524 |
knit_meta_reset() |
| 525 |
if (length(old_knit_meta)) { |
| 526 |
knitr::knit_meta_add(old_knit_meta, attr(old_knit_meta, 'knit_meta_id')) |
| 527 |
} |
| 528 |
}, add = TRUE) |
| 529 |
|
| 530 |
# presume that we're rendering as a static document unless specified |
| 531 |
# otherwise in the parameters |
| 532 |
runtime <- match.arg(runtime) |
| 533 |
if (identical(runtime, "auto")) { |
| 534 |
if (is_shiny_prerendered(front_matter$runtime, front_matter$server)) { |
| 535 |
runtime <- "shiny_prerendered" |
| 536 |
} else { |
| 537 |
runtime <- front_matter$runtime %||% "static" |
| 538 |
} |
| 539 |
} |
| 540 |
|
| 541 |
|
| 542 |
# set df_print |
| 543 |
context <- render_context() |
| 544 |
context$df_print <- resolve_df_print(output_format$df_print) |
| 545 |
|
| 546 |
# make the front_matter available as 'metadata' within the knit environment |
| 547 |
# (unless it is already defined there, in which case we emit a warning) |
| 548 |
env <- environment(render) |
| 549 |
metadata_this <- env$metadata |
| 550 |
do.call("unlockBinding", list("metadata", env)) |
| 551 |
on.exit({ |
| 552 |
if (bindingIsLocked("metadata", env)) { |
| 553 |
do.call("unlockBinding", list("metadata", env)) |
| 554 |
} |
| 555 |
env$metadata <- metadata_this |
| 556 |
lockBinding("metadata", env) |
| 557 |
}, add = TRUE) |
| 558 |
env$metadata <- front_matter |
| 559 |
|
| 560 |
# call any pre_knit handler |
| 561 |
if (!is.null(output_format$pre_knit)) { |
| 562 |
if ('...' %in% names(formals(output_format$pre_knit))) { |
| 563 |
output_format$pre_knit(input = original_input, metadata = front_matter) |
| 564 |
} else { |
| 565 |
warning("The 'pre_knit' function of the output format should have a '...' argument.") |
| 566 |
output_format$pre_knit(input = original_input) |
| 567 |
} |
| 568 |
} |
| 569 |
|
| 570 |
# function used to call post_knit handler |
| 571 |
call_post_knit_handler <- function() { |
| 572 |
if (!is.null(output_format$post_knit)) { |
| 573 |
post_knit_extra_args <- output_format$post_knit(front_matter, |
| 574 |
knit_input, |
| 575 |
runtime, |
| 576 |
encoding = 'UTF-8') |
| 577 |
} else { |
| 578 |
post_knit_extra_args <- NULL |
| 579 |
} |
| 580 |
c(output_format$pandoc$args, post_knit_extra_args) |
| 581 |
} |
| 582 |
|
| 583 |
# determine our id-prefix (add one if necessary for runtime: shiny) |
| 584 |
id_prefix <- id_prefix_from_args(output_format$pandoc$args) |
| 585 |
if (!nzchar(id_prefix) && is_shiny(runtime, front_matter[["server"]])) { |
| 586 |
id_prefix <- "section-" |
| 587 |
output_format$pandoc$args <- c(output_format$pandoc$args, rbind("--id-prefix", id_prefix)) |
| 588 |
} |
| 589 |
|
| 590 |
# knit if necessary |
| 591 |
if (requires_knit) { |
| 592 |
|
| 593 |
# restore options and hooks after knit |
| 594 |
optk <- knitr::opts_knit$get() |
| 595 |
on.exit(knitr::opts_knit$restore(optk), add = TRUE) |
| 596 |
optc <- knitr::opts_chunk$get() |
| 597 |
on.exit(knitr::opts_chunk$restore(optc), add = TRUE) |
| 598 |
hooks <- knitr::knit_hooks$get() |
| 599 |
on.exit(knitr::knit_hooks$restore(hooks), add = TRUE) |
| 600 |
ohooks <- knitr::opts_hooks$get() |
| 601 |
on.exit(knitr::opts_hooks$restore(ohooks), add = TRUE) |
| 602 |
templates <- knitr::opts_template$get() |
| 603 |
on.exit(knitr::opts_template$restore(templates), add = TRUE) |
| 604 |
|
| 605 |
# specify that htmltools::htmlPreserve() should use the Pandoc raw attribute |
| 606 |
# by default (e.g. ```{=html}) rather than preservation tokens when pandoc |
| 607 |
# >= v2.0. |
| 608 |
if (pandoc2.0() && is.null(prev <- getOption("htmltools.preserve.raw"))) { |
| 609 |
options(htmltools.preserve.raw = TRUE) |
| 610 |
on.exit(options(htmltools.preserve.raw = prev), add = TRUE) |
| 611 |
} |
| 612 |
|
| 613 |
# run render on_exit (run after the knit hooks are saved so that |
| 614 |
# any hook restoration can take precedence) |
| 615 |
if (is.function(output_format$on_exit)) |
| 616 |
on.exit(output_format$on_exit(), add = TRUE) |
| 617 |
|
| 618 |
# default rendering and chunk options |
| 619 |
knitr::render_markdown() |
| 620 |
knitr::opts_chunk$set(tidy = FALSE, error = FALSE) |
| 621 |
# the retina option does not make sense to non-HTML output formats |
| 622 |
if (!grepl('[.]html$', output_file)) knitr::opts_chunk$set(fig.retina = NULL) |
| 623 |
|
| 624 |
# store info about the final output format in opts_knit |
| 625 |
knitr::opts_knit$set( |
| 626 |
rmarkdown.pandoc.from = output_format$pandoc$from, |
| 627 |
rmarkdown.pandoc.to = pandoc_to, |
| 628 |
rmarkdown.pandoc.args = output_format$pandoc$args, |
| 629 |
rmarkdown.pandoc.id_prefix = id_prefix, |
| 630 |
rmarkdown.keep_md = output_format$keep_md, |
| 631 |
rmarkdown.df_print = output_format$df_print, |
| 632 |
rmarkdown.version = 2, |
| 633 |
rmarkdown.runtime = runtime |
| 634 |
) |
| 635 |
|
| 636 |
# read root directory from argument (has precedence) or front matter |
| 637 |
root_dir <- knit_root_dir |
| 638 |
if (is.null(root_dir)) |
| 639 |
root_dir <- front_matter$knit_root_dir |
| 640 |
if (!is.null(root_dir)) |
| 641 |
knitr::opts_knit$set(root.dir = root_dir) |
| 642 |
|
| 643 |
# use filename based figure and cache directories |
| 644 |
base_pandoc_to <- gsub('[-+].*', '', pandoc_to) |
| 645 |
if (base_pandoc_to == 'html4') base_pandoc_to <- 'html' |
| 646 |
fig_path <- paste0( |
| 647 |
pandoc_path_arg(files_dir_slash, backslash = FALSE), |
| 648 |
"/figure-", base_pandoc_to, "/" |
| 649 |
) |
| 650 |
knitr::opts_chunk$set(fig.path = fig_path) |
| 651 |
# Use --extract-media for non-HTML formats to handle base64-encoded images |
| 652 |
# For HTML formats, don't use it as it can interfere with file management (e.g., pkgdown) |
| 653 |
if (!knitr::is_html_output() && !("--extract-media" %in% output_format$pandoc$args)) { |
| 654 |
output_format$pandoc$args <- c(output_format$pandoc$args, "--extract-media", files_dir) |
| 655 |
} |
| 656 |
cache_dir <- knitr_cache_dir(input, base_pandoc_to) |
| 657 |
knitr::opts_chunk$set(cache.path = cache_dir) |
| 658 |
|
| 659 |
# strip the trailing slash from cache_dir so that file.exists() and unlink() |
| 660 |
# check on it later works on windows |
| 661 |
cache_dir <- gsub("/$", "", cache_dir) |
| 662 |
|
| 663 |
# merge user options and hooks |
| 664 |
if (!is.null(output_format$knitr)) { |
| 665 |
knitr::opts_knit$set(as.list(output_format$knitr$opts_knit)) |
| 666 |
knitr::opts_chunk$set(adjust_dev(as.list(output_format$knitr$opts_chunk))) |
| 667 |
knitr::opts_template$set(as.list(output_format$knitr$opts_template)) |
| 668 |
knitr::knit_hooks$set(as.list(output_format$knitr$knit_hooks)) |
| 669 |
knitr::opts_hooks$set(as.list(output_format$knitr$opts_hooks)) |
| 670 |
} |
| 671 |
|
| 672 |
# setting the runtime (static/shiny) type |
| 673 |
knitr::opts_knit$set(rmarkdown.runtime = runtime) |
| 674 |
|
| 675 |
# install evaluate hook for shiny_prerendred |
| 676 |
if (is_shiny_prerendered(runtime)) { |
| 677 |
|
| 678 |
# remove uncached .RData (will be recreated from context="data" chunks) |
| 679 |
shiny_prerendered_remove_uncached_data(original_input) |
| 680 |
|
| 681 |
# set the cache option hook and evaluate hook |
| 682 |
knitr::opts_hooks$set(label = shiny_prerendered_option_hook(original_input)) |
| 683 |
knitr::knit_hooks$set(evaluate = shiny_prerendered_evaluate_hook(original_input)) |
| 684 |
} |
| 685 |
|
| 686 |
# install global chunk handling for runtime: shiny (evaluate the 'global' |
| 687 |
# chunk only once, and in the global environment) |
| 688 |
if (is_shiny_classic(runtime) && !is.null(shiny::getDefaultReactiveDomain())) { |
| 689 |
|
| 690 |
# install evaluate hook to ensure that the 'global' chunk for this source |
| 691 |
# file is evaluated only once and is run outside of a user reactive domain |
| 692 |
knitr::knit_hooks$set(evaluate = function(code, envir, ...) { |
| 693 |
|
| 694 |
# check for 'global' chunk label |
| 695 |
if (identical(knitr::opts_current$get("label"), "global")) { |
| 696 |
|
| 697 |
# check list of previously evaluated global chunks |
| 698 |
code_string <- one_string(code) |
| 699 |
if (!code_string %in% .globals$evaluated_global_chunks) { |
| 700 |
|
| 701 |
# save it in our list of evaluated global chunks |
| 702 |
.globals$evaluated_global_chunks <- |
| 703 |
c(.globals$evaluated_global_chunks, code_string) |
| 704 |
|
| 705 |
# evaluate with no reactive domain to prevent any shiny code (e.g. |
| 706 |
# a reactive timer) from attaching to the current user session |
| 707 |
# (resulting in it's destruction when that session ends) |
| 708 |
shiny::withReactiveDomain(NULL, { |
| 709 |
evaluate::evaluate(code, envir = globalenv(), ...) |
| 710 |
}) |
| 711 |
|
| 712 |
} else { |
| 713 |
list() |
| 714 |
} |
| 715 |
# delegate to standard evaluate for everything else |
| 716 |
} else { |
| 717 |
evaluate::evaluate(code, envir, ...) |
| 718 |
} |
| 719 |
}) |
| 720 |
} |
| 721 |
|
| 722 |
# make the params available within the knit environment |
| 723 |
# (only do this if there are parameters in the front matter |
| 724 |
# so we don't require recent knitr for all users) |
| 725 |
if (!is.null(front_matter$params)) { |
| 726 |
|
| 727 |
params <- knit_params_get(input_lines, params) |
| 728 |
|
| 729 |
# bail if an object called 'params' exists in this environment, |
| 730 |
# and it seems to be an unrelated user-created object. store |
| 731 |
# references so we can restore them post-render |
| 732 |
hasParams <- exists("params", envir = envir, inherits = FALSE) |
| 733 |
envirParams <- NULL |
| 734 |
|
| 735 |
if (hasParams) { |
| 736 |
envirParams <- get("params", envir = envir, inherits = FALSE) |
| 737 |
isKnownParamsObject <- |
| 738 |
inherits(envirParams, "knit_param_list") || |
| 739 |
inherits(envirParams, "knit_param") |
| 740 |
|
| 741 |
if (!isKnownParamsObject) { |
| 742 |
stop2("params object already exists in knit environment ", |
| 743 |
"so can't be overwritten by render params") |
| 744 |
} |
| 745 |
} |
| 746 |
|
| 747 |
# make the params available in the knit environment |
| 748 |
assign("params", params, envir = envir) |
| 749 |
lockBinding("params", envir) |
| 750 |
on.exit({ |
| 751 |
if (exists("params", envir = envir, inherits = FALSE)) { |
| 752 |
do.call("unlockBinding", list("params", envir)) |
| 753 |
if (hasParams) |
| 754 |
assign("params", envirParams, envir = envir) |
| 755 |
else |
| 756 |
remove("params", envir = envir) |
| 757 |
} |
| 758 |
}, add = TRUE) |
| 759 |
} |
| 760 |
|
| 761 |
# call onKnit hooks (normalize to list) |
| 762 |
sapply(as.list(getHook("rmarkdown.onKnit")), function(hook) { |
| 763 |
tryCatch(hook(input = original_input), error = function(e) NULL) |
| 764 |
}) |
| 765 |
on.exit({ |
| 766 |
sapply(as.list(getHook("rmarkdown.onKnitCompleted")), function(hook) { |
| 767 |
tryCatch(hook(input = original_input), error = function(e) NULL) |
| 768 |
}) |
| 769 |
}, add = TRUE) |
| 770 |
|
| 771 |
perf_timer_start("knitr") |
| 772 |
|
| 773 |
# perform the knit |
| 774 |
input <- knitr::knit(knit_input, |
| 775 |
knit_output, |
| 776 |
envir = envir, |
| 777 |
quiet = quiet) |
| 778 |
|
| 779 |
perf_timer_stop("knitr") |
| 780 |
|
| 781 |
front_matter <- yaml_front_matter(input) |
| 782 |
|
| 783 |
# call post_knit handler |
| 784 |
output_format$pandoc$args <- call_post_knit_handler() |
| 785 |
|
| 786 |
# pull any R Markdown warnings from knit_meta and emit |
| 787 |
rmd_warnings <- knit_meta_reset(class = "rmd_warning") |
| 788 |
for (rmd_warning in rmd_warnings) { |
| 789 |
message("Warning: ", rmd_warning) |
| 790 |
} |
| 791 |
|
| 792 |
# pull out shiny_prerendered_contexts and append them as script tags |
| 793 |
shiny_prerendered_append_contexts(runtime, input) |
| 794 |
|
| 795 |
# collect remaining knit_meta |
| 796 |
knit_meta <- knit_meta_reset() |
| 797 |
|
| 798 |
} else { |
| 799 |
output_format$pandoc$args <- call_post_knit_handler() |
| 800 |
} |
| 801 |
|
| 802 |
# if this isn't html and there are html dependencies then flag an error |
| 803 |
if (!(is_pandoc_to_html(output_format$pandoc) || |
| 804 |
identical(tolower(xfun::file_ext(output_file)), "html"))) { |
| 805 |
if (has_html_dependencies(knit_meta)) { |
| 806 |
if (!isTRUE(front_matter$always_allow_html)) { |
| 807 |
stop2("Functions that produce HTML output found in document targeting ", |
| 808 |
pandoc_to, " output.\nPlease change the output type ", |
| 809 |
"of this document to HTML.\n", |
| 810 |
"If you're aiming to have some HTML widgets shown in non-HTML format as a screenshot,\n", |
| 811 |
"please install webshot or webshot2 R package for knitr to do the screenshot, and configure it by looking at its documentation.\n", |
| 812 |
"Alternatively, you can allow HTML output in non-HTML formats\n", |
| 813 |
"by adding this option to the YAML front-matter of\nyour rmarkdown file:\n\n", |
| 814 |
" always_allow_html: true\n\n", |
| 815 |
"Note however that the HTML output will not be visible in non-HTML formats.\n\n" |
| 816 |
) |
| 817 |
} |
| 818 |
} |
| 819 |
if (!identical(runtime, "static")) { |
| 820 |
stop2("Runtime '", runtime, "' is not supported for ", |
| 821 |
pandoc_to, " output.\nPlease change the output type ", |
| 822 |
"of this document to HTML.") |
| 823 |
} |
| 824 |
} |
| 825 |
|
| 826 |
# clean the files_dir if we've either been asking to clean supporting files or |
| 827 |
# the knitr cache is active; clean the figure-* dir instead of the whole |
| 828 |
# files_dir if other subdirs are generated by another format and still needed: |
| 829 |
# https://github.com/rstudio/rmarkdown/issues/1472 and also #1503 |
| 830 |
intermediates_fig <- if (output_format$clean_supporting && !dir_exists(cache_dir)) { |
| 831 |
# unlink does not support / at the end of file path |
| 832 |
fig_path <- gsub("/$", "", knitr::opts_chunk$get('fig.path')) |
| 833 |
|
| 834 |
# existing figure folder(s), can be character(0) |
| 835 |
# if no figure is generated, clean the whole files_dir (#1664) |
| 836 |
files_dir_fig <- list.files(files_dir, '^figure-.+') |
| 837 |
|
| 838 |
if (length(files_dir_fig) < 1 || identical(files_dir_fig, basename(fig_path))) { |
| 839 |
files_dir |
| 840 |
} else { |
| 841 |
fig_path |
| 842 |
} |
| 843 |
} |
| 844 |
intermediates <- c(intermediates, intermediates_fig) |
| 845 |
|
| 846 |
if (run_pandoc) { |
| 847 |
|
| 848 |
# set env vars required during Pandoc processing |
| 849 |
lua_env_vars <- xfun::set_envvar(c(RMARKDOWN_LUA_SHARED = pkg_file_lua("shared.lua"))) |
| 850 |
on.exit(xfun::set_envvar(lua_env_vars), add = TRUE) |
| 851 |
|
| 852 |
perf_timer_start("pre-processor") |
| 853 |
|
| 854 |
if (has_dependencies(knit_meta, "output_format_dependency")) { |
| 855 |
output_format <- merge_output_format_dependencies(output_format, knit_meta) |
| 856 |
} |
| 857 |
# call any pre_processor |
| 858 |
if (!is.null(output_format$pre_processor)) { |
| 859 |
extra_args <- output_format$pre_processor(front_matter, |
| 860 |
input, |
| 861 |
runtime, |
| 862 |
knit_meta, |
| 863 |
files_dir, |
| 864 |
output_dir) |
| 865 |
output_format$pandoc$args <- c(output_format$pandoc$args, extra_args) |
| 866 |
} |
| 867 |
|
| 868 |
# write shiny_prerendered_dependencies if we have them |
| 869 |
if (is_shiny_prerendered(runtime)) { |
| 870 |
shiny_prerendered_append_dependencies(input, |
| 871 |
shiny_prerendered_dependencies, |
| 872 |
files_dir, |
| 873 |
output_dir) |
| 874 |
# Include special comment in header for correc insertion of HTML dependencies |
| 875 |
# during shiny_prerendered process (See `shiny_prerendered_html()`). |
| 876 |
# This should be the last header-includes to be set. |
| 877 |
# Context in https://github.com/rstudio/rmarkdown/pull/2249 |
| 878 |
output_format$pandoc$args <- c(output_format$pandoc$args, |
| 879 |
pandoc_include_args(in_header = pkg_file("rmd/h/shiny-header.html"))) |
| 880 |
} |
| 881 |
|
| 882 |
perf_timer_stop("pre-processor") |
| 883 |
|
| 884 |
need_bibtex <- grepl('[.](pdf|tex)$', output_file) && |
| 885 |
any(c('--natbib', '--biblatex') %in% output_format$pandoc$args) |
| 886 |
|
| 887 |
perf_timer_start("pandoc") |
| 888 |
|
| 889 |
convert <- function(output, citeproc = FALSE) { |
| 890 |
|
| 891 |
# temporarily move figures and bib files to the intermediate dir if |
| 892 |
# specified: https://github.com/rstudio/rmarkdown/issues/500 |
| 893 |
if (!is.null(intermediates_dir)) { |
| 894 |
figures_dir <- gsub('/$', '', knitr::opts_chunk$get("fig.path")) |
| 895 |
files <- list.files(figures_dir, full.names = TRUE, recursive = TRUE) |
| 896 |
# https://github.com/rstudio/rmarkdown/issues/1358 |
| 897 |
if (citeproc) files <- c(files, front_matter[['bibliography']]) |
| 898 |
for (f in files) { |
| 899 |
intermediates <<- c(intermediates, copy_file_with_dir(f, intermediates_dir)) |
| 900 |
} |
| 901 |
} |
| 902 |
|
| 903 |
# ensure we expand paths (for Windows where leading `~/` does |
| 904 |
# not get expanded by pandoc) |
| 905 |
input <- path.expand(input) |
| 906 |
output <- path.expand(output) |
| 907 |
|
| 908 |
# Tweak Pandoc argument for all formats |
| 909 |
pandoc_args <- output_format$pandoc$args |
| 910 |
|
| 911 |
# if Lua filters are provided, add the command line switch |
| 912 |
if (!is.null(lua_filters <- output_format$pandoc$lua_filters)) { |
| 913 |
lua_filters <- pandoc_lua_filter_args(lua_filters) |
| 914 |
} |
| 915 |
pandoc_args <- c(lua_filters, pandoc_args) |
| 916 |
|
| 917 |
# in case the output format turns on the --file-scope flag, run its |
| 918 |
# file_scope function to split the input into multiple files |
| 919 |
input_files <- input |
| 920 |
if (is.function(output_format$file_scope)) { |
| 921 |
input_files <- file_scope_split(input, output_format$file_scope) |
| 922 |
# ignore if input_files has not really been splitted |
| 923 |
if (length(input_files) > 1) { |
| 924 |
# add the --file-scope option |
| 925 |
pandoc_args <- c(pandoc_args, "--file-scope") |
| 926 |
# cleanup the split files after render |
| 927 |
on.exit(unlink(input_files), add = TRUE) |
| 928 |
} |
| 929 |
} |
| 930 |
|
| 931 |
# use the convert function from the output format if provided |
| 932 |
if (!is.function(convert_fun <- output_format$pandoc$convert_fun)) |
| 933 |
convert_fun <- pandoc_convert |
| 934 |
convert_it <- function(output) convert_fun( |
| 935 |
output = output, input_files, pandoc_to, output_format$pandoc$from, |
| 936 |
citeproc, pandoc_args, !quiet |
| 937 |
) |
| 938 |
|
| 939 |
# if we don't detect any invalid shell characters in the |
| 940 |
# target path, then just call pandoc directly |
| 941 |
if (!grepl(.shell_chars_regex, output) && !grepl(.shell_chars_regex, input)) { |
| 942 |
return(convert_it(output)) |
| 943 |
} |
| 944 |
|
| 945 |
# render to temporary file (preserve extension) |
| 946 |
# this also ensures we don't pass a file path with invalid |
| 947 |
# characters to our pandoc invocation |
| 948 |
ext <- xfun::file_ext(output) |
| 949 |
if (ext != '') ext <- paste0('.', ext) |
| 950 |
|
| 951 |
# render to a path in the current working directory |
| 952 |
# (avoid passing invalid characters to shell) |
| 953 |
pandoc_output_tmp <- basename(tempfile("pandoc", getwd(), ext)) |
| 954 |
|
| 955 |
# clean up temporary file on exit |
| 956 |
on.exit(unlink(pandoc_output_tmp), add = TRUE) |
| 957 |
|
| 958 |
# call pandoc to render file |
| 959 |
status <- convert_it(pandoc_output_tmp) |
| 960 |
|
| 961 |
# construct output path (when passed only a file name to '--output', |
| 962 |
# pandoc seems to render in the same directory as the input file) |
| 963 |
pandoc_output_tmp_path <- file.path(dirname(input), pandoc_output_tmp) |
| 964 |
|
| 965 |
# rename output file to desired location |
| 966 |
renamed <- suppressWarnings(file.rename(pandoc_output_tmp_path, output)) |
| 967 |
|
| 968 |
# rename can fail if the temporary directory and output path |
| 969 |
# lie on different volumes; in such a case attempt a file copy |
| 970 |
# see: https://github.com/rstudio/rmarkdown/issues/705 |
| 971 |
if (!renamed) { |
| 972 |
copied <- file.copy(pandoc_output_tmp_path, output, overwrite = TRUE) |
| 973 |
if (!copied) { |
| 974 |
stop("failed to copy rendered pandoc artefact to '", output, "'") |
| 975 |
} |
| 976 |
} |
| 977 |
|
| 978 |
# return status |
| 979 |
status |
| 980 |
} |
| 981 |
texfile <- file_with_ext(output_file, "tex") |
| 982 |
# determine whether we need to run citeproc (based on whether we have |
| 983 |
# references in the input) |
| 984 |
run_citeproc <- citeproc_required(front_matter, input_lines) |
| 985 |
# if the output format is LaTeX, first convert .md to .tex, and then convert |
| 986 |
# .tex to .pdf via latexmk() if PDF output is requested (in rmarkdown <= |
| 987 |
# v1.8, we used to call Pandoc to convert .md to .tex and .pdf separately) |
| 988 |
if (output_format$pandoc$keep_tex || grepl("^(latex|beamer)($|[-+].*)", pandoc_to)) { |
| 989 |
# do not use pandoc-citeproc if needs to build bibliography |
| 990 |
convert(texfile, run_citeproc && !need_bibtex) |
| 991 |
# patch the .tex output generated from the default Pandoc LaTeX template |
| 992 |
if (!("--template" %in% output_format$pandoc$args)) patch_tex_output(texfile) |
| 993 |
fix_horiz_rule(texfile) |
| 994 |
# unless the output file has the extension .tex, we assume it is PDF |
| 995 |
if (!grepl('[.]tex$', output_file)) { |
| 996 |
latexmk(texfile, output_format$pandoc$latex_engine, '--biblatex' %in% output_format$pandoc$args) |
| 997 |
file.rename(file_with_ext(texfile, "pdf"), output_file) |
| 998 |
# clean up the tex file if necessary |
| 999 |
if (!output_format$pandoc$keep_tex) { |
| 1000 |
texfile <- normalize_path(texfile) |
| 1001 |
on.exit(unlink(texfile), add = TRUE) |
| 1002 |
} |
| 1003 |
} |
| 1004 |
} else { |
| 1005 |
convert(output_file, run_citeproc) |
| 1006 |
} |
| 1007 |
|
| 1008 |
# pandoc writes the output alongside the input, so if we rendered from an |
| 1009 |
# intermediate directory, move the output file |
| 1010 |
if (!is.null(intermediates_dir)) { |
| 1011 |
intermediate_output <- file.path(intermediates_dir, basename(output_file)) |
| 1012 |
if (file.exists(intermediate_output)) { |
| 1013 |
move_dir(intermediate_output, output_file) |
| 1014 |
} |
| 1015 |
} |
| 1016 |
|
| 1017 |
perf_timer_stop("pandoc") |
| 1018 |
|
| 1019 |
perf_timer_start("post-processor") |
| 1020 |
|
| 1021 |
# if there is a post-processor then call it |
| 1022 |
if (!is.null(output_format$post_processor)) |
| 1023 |
output_file <- output_format$post_processor(front_matter, |
| 1024 |
input, |
| 1025 |
output_file, |
| 1026 |
clean, |
| 1027 |
!quiet) |
| 1028 |
|
| 1029 |
if (!quiet && getOption('rmarkdown.render.message', TRUE)) { |
| 1030 |
message("\nOutput created: ", relative_to(oldwd, output_file)) |
| 1031 |
} |
| 1032 |
|
| 1033 |
perf_timer_stop("post-processor") |
| 1034 |
|
| 1035 |
} |
| 1036 |
|
| 1037 |
perf_timer_stop("render") |
| 1038 |
|
| 1039 |
# write markdown output if requested |
| 1040 |
if (output_format$keep_md && !md_input) { |
| 1041 |
file.copy(input, file_with_ext(output_file, "md"), overwrite = TRUE) |
| 1042 |
} |
| 1043 |
|
| 1044 |
if (run_pandoc) { |
| 1045 |
# return the full path to the output file |
| 1046 |
output_file <- abs_path(output_file) |
| 1047 |
# attach the metadata specified as rmd_output_metadata in YAML |
| 1048 |
if (length(output_meta <- output_metadata$get())) |
| 1049 |
attr(output_file, 'rmd_output_metadata') <- output_meta |
| 1050 |
invisible(output_file) |
| 1051 |
} else { |
| 1052 |
# make sure the markdown output and fig dir are not cleaned up |
| 1053 |
intermediates <- setdiff(intermediates, c(input, intermediates_fig)) |
| 1054 |
# did not run pandoc; returns the markdown output with attributes of the |
| 1055 |
# knitr meta data and intermediate files |
| 1056 |
invisible(structure(input, |
| 1057 |
knit_meta = knit_meta, |
| 1058 |
files_dir = files_dir, |
| 1059 |
intermediates_dir = intermediates_fig, |
| 1060 |
intermediates = intermediates)) |
| 1061 |
} |
| 1062 |
} |
| 1063 |
|
| 1064 |
|
| 1065 |
#' Render supporting files for an input document |
| 1066 |
#' |
| 1067 |
#' Render (copy) required supporting files for an input document to the |
| 1068 |
#' \code{_files} directory that is associated with the document. |
| 1069 |
#' |
| 1070 |
#' @param from The directory from which the files should be copied. |
| 1071 |
#' @param files_dir The directory that will receive the copied files. |
| 1072 |
#' @param rename_to An option to rename the source directory after the copy |
| 1073 |
#' operation is complete. |
| 1074 |
#' @return The relative path to the supporting files. This path is suitable |
| 1075 |
#' for inclusion in HTML\code{href} and \code{src} attributes. |
| 1076 |
#' @export |
| 1077 |
render_supporting_files <- function(from, files_dir, rename_to = NULL) { |
| 1078 |
|
| 1079 |
# auto-create directory for supporting files |
| 1080 |
if (!dir_exists(files_dir)) |
| 1081 |
dir.create(files_dir) |
| 1082 |
|
| 1083 |
# target directory is based on the dirname of the path or the rename_to |
| 1084 |
# value if it was provided |
| 1085 |
target_stage_dir <- file.path(files_dir, basename(from)) |
| 1086 |
target_dir <- file.path(files_dir, ifelse(is.null(rename_to), |
| 1087 |
basename(from), |
| 1088 |
rename_to)) |
| 1089 |
|
| 1090 |
# copy the directory if it hasn't already been copied |
| 1091 |
if (!dir_exists(target_dir) && !dir_exists(target_stage_dir)) { |
| 1092 |
file.copy(from = from, |
| 1093 |
to = files_dir, |
| 1094 |
recursive = TRUE, |
| 1095 |
copy.mode = FALSE) |
| 1096 |
if (!is.null(rename_to)) { |
| 1097 |
file.rename(from = target_stage_dir, |
| 1098 |
to = target_dir) |
| 1099 |
} |
| 1100 |
} |
| 1101 |
|
| 1102 |
# return the target dir (used to form links in the HTML) |
| 1103 |
target_dir |
| 1104 |
} |
| 1105 |
|
| 1106 |
# reset knitr meta output (returns any meta output generated since the last |
| 1107 |
# call to knit_meta_reset), optionally scoped to a specific output class |
| 1108 |
knit_meta_reset <- function(class = NULL) { |
| 1109 |
knitr::knit_meta(class, clean = TRUE) |
| 1110 |
} |
| 1111 |
|
| 1112 |
# render context (render-related state can be stuffed here) |
| 1113 |
.render_context <- NULL # initialized in .onLoad |
| 1114 |
render_context <- function() { |
| 1115 |
.render_context$peek() |
| 1116 |
} |
| 1117 |
|
| 1118 |
init_render_context <- function() { |
| 1119 |
.render_context$push(new_render_context()) |
| 1120 |
} |
| 1121 |
|
| 1122 |
clear_render_context <- function() { |
| 1123 |
.render_context$pop() |
| 1124 |
} |
| 1125 |
|
| 1126 |
new_render_context <- function() { |
| 1127 |
env <- new.env(parent = emptyenv()) |
| 1128 |
env$chunk.index <- 1 |
| 1129 |
env |
| 1130 |
} |
| 1131 |
|
| 1132 |
merge_render_context <- function(context) { |
| 1133 |
elements <- ls(envir = render_context(), all.names = TRUE) |
| 1134 |
for (el in elements) |
| 1135 |
context[[el]] <- get(el, envir = render_context()) |
| 1136 |
context |
| 1137 |
} |
| 1138 |
|
| 1139 |
|
| 1140 |
id_prefix_from_args <- function(args) { |
| 1141 |
|
| 1142 |
# scan for id-prefix argument |
| 1143 |
for (i in 1:length(args)) { |
| 1144 |
arg <- args[[i]] |
| 1145 |
if (identical(arg, "--id-prefix") && (i < length(args))) |
| 1146 |
return(args[[i + 1]]) |
| 1147 |
} |
| 1148 |
|
| 1149 |
# default to empty string |
| 1150 |
"" |
| 1151 |
} |
| 1152 |
|
| 1153 |
|
| 1154 |
resolve_df_print <- function(df_print) { |
| 1155 |
|
| 1156 |
# available methods |
| 1157 |
valid_methods <- c("default", "kable", "tibble", "paged") |
| 1158 |
|
| 1159 |
# if we are passed NULL then select the first method |
| 1160 |
if (is.null(df_print)) |
| 1161 |
df_print <- valid_methods[[1]] |
| 1162 |
|
| 1163 |
# if we are passed all of valid_methods then select the first one |
| 1164 |
if (identical(valid_methods, df_print)) |
| 1165 |
df_print <- valid_methods[[1]] |
| 1166 |
|
| 1167 |
if (!is.function(df_print)) { |
| 1168 |
if (df_print == "kable") |
| 1169 |
df_print <- knitr::kable |
| 1170 |
else if (df_print == "tibble") { |
| 1171 |
if (!requireNamespace("tibble", quietly = TRUE)) |
| 1172 |
stop("Printing 'tibble' without 'tibble' package available") |
| 1173 |
|
| 1174 |
df_print <- function(x) print(tibble::as_tibble(x)) |
| 1175 |
} |
| 1176 |
else if (df_print == "paged") |
| 1177 |
df_print <- function(x) { |
| 1178 |
if (!identical(knitr::opts_current$get("paged.print"), FALSE)) { |
| 1179 |
knitr::asis_output(paged_table_html(x)) |
| 1180 |
} |
| 1181 |
else { |
| 1182 |
print(x) |
| 1183 |
} |
| 1184 |
} |
| 1185 |
else if (df_print == "default") |
| 1186 |
df_print <- print |
| 1187 |
else |
| 1188 |
stop2('Invalid value for df_print (valid values are ', |
| 1189 |
paste(valid_methods, collapse = ", ")) |
| 1190 |
} |
| 1191 |
|
| 1192 |
df_print |
| 1193 |
} |
| 1194 |
|
| 1195 |
|
| 1196 |
# package level globals |
| 1197 |
.globals <- new.env(parent = emptyenv()) |
| 1198 |
.globals$evaluated_global_chunks <- character() |
| 1199 |
.globals$level <- 0L |
| 1200 |
|
| 1201 |
|
| 1202 |
#' The output metadata object |
| 1203 |
#' |
| 1204 |
#' This object provides a mechanism for users to attach metadata as an attribute |
| 1205 |
#' (named \code{rmd_output_metadata}) of the returned value of |
| 1206 |
#' \code{\link{render}()}. The initial value of the metadata comes from in the |
| 1207 |
#' \code{rmd_output_metadata} field of the YAML frontmatter of an R Markdown |
| 1208 |
#' document. The metadata can be queried via the |
| 1209 |
#' \code{output_metadata$get()} method, and modified via the |
| 1210 |
#' \code{output_metadata$set()} method. |
| 1211 |
#' @format NULL |
| 1212 |
#' @usage NULL |
| 1213 |
#' @keywords NULL |
| 1214 |
#' @export |
| 1215 |
output_metadata = knitr:::new_defaults() |
| 1216 |
|
| 1217 |
file_scope_split <- function(input, fun) { |
| 1218 |
inputs <- if (length(formals(fun)) == 1L) { |
| 1219 |
fun(input) # for the backward compatibility |
| 1220 |
} else { |
| 1221 |
fun(input, NULL) # the second argument implies current file scope |
| 1222 |
} |
| 1223 |
|
| 1224 |
# file_scope_fun should split the input file in several |
| 1225 |
# do nothing if not and return input file unsplited |
| 1226 |
if (length(inputs) <= 1) return(input) |
| 1227 |
|
| 1228 |
# write the split content into *.split.md files |
| 1229 |
input_files <- lapply(inputs, function(f) { |
| 1230 |
file <- file_with_meta_ext(f$name, "split", "md") |
| 1231 |
file <- file.path(dirname(input), file) |
| 1232 |
write_utf8(f$content, file) |
| 1233 |
file |
| 1234 |
}) |
| 1235 |
|
| 1236 |
unlist(input_files) |
| 1237 |
} |