Debian Codegraph @

R/pandoc.R

raw
1 #' Convert a document with pandoc
2 #'
3 #' Convert documents to and from various formats using the pandoc utility.
4 #'
5 #' Supported input and output formats are described in the
6 #' \href{https://pandoc.org/MANUAL.html}{pandoc user guide}.
7 #'
8 #' The system path as well as the version of pandoc shipped with RStudio (if
9 #' running under RStudio) are scanned for pandoc and the highest version
10 #' available is used.
11 #' @param input Character vector containing paths to input files
12 #' (files must be UTF-8 encoded)
13 #' @param to Format to convert to (if not specified, you must specify
14 #' \code{output})
15 #' @param from Format to convert from (if not specified then the format is
16 #' determined based on the file extension of \code{input}).
17 #' @param output Output file (if not specified then determined based on format
18 #' being converted to).
19 #' @param citeproc \code{TRUE} to run the pandoc-citeproc filter (for processing
20 #' citations) as part of the conversion.
21 #' @param options Character vector of command line options to pass to pandoc.
22 #' @param verbose \code{TRUE} to show the pandoc command line which was executed
23 #' @param wd Working directory in which code will be executed. If not
24 #' supplied, defaults to the common base directory of \code{input}.
25 #' @examples
26 #' \dontrun{
27 #' library(rmarkdown)
28 #'
29 #' # convert markdown to various formats
30 #' pandoc_convert("input.md", to = "html")
31 #' pandoc_convert("input.md", to = "latex")
32 #'
33 #' # process citations
34 #' pandoc_convert("input.md", to = "html", citeproc = TRUE)
35 #'
36 #' # add some pandoc options
37 #' pandoc_convert("input.md", to = "latex", options = c("--listings"))
38 #' }
39 #' @export
40 pandoc_convert <- function(input,
41 to = NULL,
42 from = NULL,
43 output = NULL,
44 citeproc = FALSE,
45 options = NULL,
46 verbose = FALSE,
47 wd = NULL) {
48
49 # ensure pandoc is available
50 pandoc_available(error = TRUE)
51
52 # evaluate path arguments before changing working directory
53 force(output)
54
55 # execute in specified working directory
56 if (is.null(wd)) {
57 wd <- base_dir(input)
58 }
59
60 oldwd <- setwd(wd)
61 on.exit(setwd(oldwd), add = TRUE)
62
63 # input file and formats
64 args <- pandoc_path_arg(input)
65 if (!is.null(to)) {
66 if (to == 'html') to <- 'html4'
67 if (to == 'pdf') to <- 'latex'
68 args <- c(args, "--to", to)
69 }
70 if (!is.null(from))
71 args <- c(args, "--from", from)
72
73 # output file
74 if (!is.null(output))
75 args <- c(args, "--output", pandoc_path_arg(output))
76
77 # set pandoc stack size
78 args <- prepend_pandoc_stack_size(args)
79
80 # additional command line options
81 args <- c(args, options)
82
83 # citeproc filter if requested
84 if (citeproc) {
85 # --natbib/--biblatex conflicts with pandoc own citation processing,
86 # '--filter pandoc-citeproc' or '--citeproc'
87 args <- c(args[!args %in% c("--natbib", "--biblatex")],
88 pandoc_citeproc_args())
89 }
90
91 # change the --self-contained argument for Pandoc 2.19+
92 i <- match('--self-contained', args)
93 if (!is.na(i) && pandoc_available('2.19')) args <- c(args[-i], self_contained_args())
94
95 # build the conversion command
96 command <- paste(quoted(pandoc()), paste(quoted(args), collapse = " "))
97
98 # show it in verbose mode
99 if (verbose)
100 cat(command, "\n")
101
102 # run the conversion
103 with_pandoc_safe_environment({
104 result <- system(command)
105 })
106 if (result != 0)
107 stop2("pandoc document conversion failed with error ", result)
108
109 invisible(NULL)
110 }
111
112
113 #' Convert a bibliograpy file
114 #'
115 #' Convert a bibliography file (e.g. a BibTeX file) to an R list, JSON text,
116 #' or YAML text
117 #'
118 #' @param file Bibliography file
119 #' @param type Conversion type
120 #'
121 #' @return For `type = "list"`, and R list. For `type = "json"` or `type = "yaml"`,
122 #' a character vector with the specified format.
123 #'
124 #' @export
125 pandoc_citeproc_convert <- function(file, type = c("list", "json", "yaml")) {
126
127 # ensure we've scanned for pandoc
128 find_pandoc()
129
130 # resolve type
131 type <- match.arg(type)
132
133 if (pandoc_available("2.11")) {
134 bin <- pandoc()
135 to <- switch(type,
136 list = "csljson",
137 json = "csljson",
138 yaml = "markdown"
139 )
140 args <- c(file, "-s", "-t", to)
141 } else {
142 bin <- pandoc_citeproc()
143 conversion <- switch(type,
144 list = "--bib2json",
145 json = "--bib2json",
146 yaml = "--bib2yaml"
147 )
148 args <- c(conversion, file)
149 }
150
151 # build the conversion command
152 command <- paste(quoted(bin), paste(quoted(args), collapse = " "))
153
154 # run the conversion
155 with_pandoc_safe_environment({
156 result <- system(command, intern = TRUE)
157 })
158 status <- attr(result, "status")
159 if (!is.null(status)) {
160 cat(result, sep = "\n")
161 stop("Error ", status, " occurred building shared library.")
162 }
163
164 Encoding(result) <- "UTF-8"
165
166 # convert the output if requested
167 if (type == "list") {
168 jsonlite::fromJSON(result, simplifyVector = FALSE)
169 } else {
170 result
171 }
172 }
173
174 #' Check pandoc availability and version
175 #'
176 #' Determine whether pandoc is currently available on the system (optionally
177 #' checking for a specific version or greater). Determine the specific version
178 #' of pandoc available.
179 #'
180 #' The system environment variable \samp{PATH} as well as the version of pandoc
181 #' shipped with RStudio (its location is set via the environment variable
182 #' \samp{RSTUDIO_PANDOC} by RStudio products like the RStudio IDE, RStudio
183 #' Server, Shiny Server, and RStudio Connect, etc) are scanned for pandoc and
184 #' the highest version available is used. Please do not modify the environment
185 #' variable \samp{RSTUDIO_PANDOC} unless you know what it means.
186 #' @param version Required version of pandoc
187 #' @param error Whether to signal an error if pandoc with the required version
188 #' is not found
189 #' @return \code{pandoc_available} returns a logical indicating whether the
190 #' required version of pandoc is available. \code{pandoc_version} returns a
191 #' \code{\link[base]{numeric_version}} with the version of pandoc found.
192 #' @examples
193 #' \dontrun{
194 #' library(rmarkdown)
195 #'
196 #' if (pandoc_available())
197 #' cat("pandoc", as.character(pandoc_version()), "is available!\n")
198 #'
199 #' if (pandoc_available("1.12.3"))
200 #' cat("required version of pandoc is available!\n")
201 #' }
202 #' @export
203 pandoc_available <- function(version = NULL,
204 error = FALSE) {
205
206 # ensure we've scanned for pandoc
207 find_pandoc()
208
209 # check availability
210 found <- !is.null(.pandoc$dir) && (is.null(version) || .pandoc$version >= version)
211
212 msg <- c(
213 "pandoc", if (!is.null(version)) c("version", version, "or higher"),
214 "is required and was not found (see the help page ?rmarkdown::pandoc_available)."
215 )
216 if (error && !found) stop2(paste(msg, collapse = " "))
217
218 found
219 }
220
221
222 #' @rdname pandoc_available
223 #' @export
224 pandoc_version <- function() {
225 find_pandoc()
226 .pandoc$version
227 }
228
229 #' Functions for generating pandoc command line arguments
230 #'
231 #' Functions that assist in creating various types of pandoc command line
232 #' arguments (e.g. for templates, table of contents, highlighting, and content
233 #' includes).
234 #'
235 #' Non-absolute paths for resources referenced from the
236 #' \code{in_header}, \code{before_body}, and \code{after_body}
237 #' parameters are resolved relative to the directory of the input document.
238 #' @inheritParams includes
239 #' @param name Name of template variable to set.
240 #' @param value Value of template variable (defaults to \code{true} if missing).
241 #' @param toc \code{TRUE} to include a table of contents in the output.
242 #' @param toc_depth Depth of headers to include in table of contents.
243 #' @param highlight The name of a pandoc syntax highlighting theme.
244 #' @param latex_engine LaTeX engine for producing PDF output. Options are
245 #' "pdflatex", "lualatex", "xelatex", and "tectonic".
246 #' @param default The highlighting theme to use if "default"
247 #' is specified.
248 #' @return A character vector with pandoc command line arguments.
249 #' @examples
250 #' \dontrun{
251 #' library(rmarkdown)
252 #'
253 #' pandoc_include_args(before_body = "header.htm")
254 #' pandoc_include_args(before_body = "header.tex")
255 #'
256 #' pandoc_highlight_args("kate")
257 #'
258 #' pandoc_latex_engine_args("pdflatex")
259 #'
260 #' pandoc_toc_args(toc = TRUE, toc_depth = 2)
261 #' }
262 #' @name pandoc_args
263 NULL
264
265 #' @rdname pandoc_args
266 #' @export
267 pandoc_variable_arg <- function(name,
268 value) {
269
270 c("--variable", if (missing(value)) name else paste(name, "=", value, sep = ""))
271 }
272
273 #' @rdname pandoc_args
274 #' @export
275 pandoc_metadata_arg <- function(name,
276 value) {
277
278 c("--metadata", if (missing(value)) name else paste(name, "=", value, sep = ""))
279 }
280
281 #' @rdname pandoc_args
282 #' @param file string. Path to a file
283 #' @export
284 pandoc_metadata_file_arg <- function(file) {
285
286 c("--metadata-file", pandoc_path_arg(file))
287 }
288
289
290 #' @rdname pandoc_args
291 #' @export
292 pandoc_include_args <- function(in_header = NULL,
293 before_body = NULL,
294 after_body = NULL) {
295 args <- c()
296
297 for (file in in_header)
298 args <- c(args, "--include-in-header", pandoc_path_arg(file))
299
300 for (file in before_body)
301 args <- c(args, "--include-before-body", pandoc_path_arg(file))
302
303 for (file in after_body)
304 args <- c(args, "--include-after-body", pandoc_path_arg(file))
305
306 args
307 }
308
309 #' @rdname pandoc_args
310 #' @export
311 pandoc_highlight_args <- function(highlight, default = "tango") {
312 p38 <- pandoc_available("3.8")
313 if (is.null(highlight)) {
314 if (!p38) return("--no-highlight")
315 highlight <- "none"
316 }
317 if (identical(highlight, "default")) highlight <- default
318 c(if (p38) "--syntax-highlighting" else "--highlight-style", highlight)
319 }
320
321 #' @rdname pandoc_args
322 #' @export
323 pandoc_latex_engine_args <- function(latex_engine) {
324
325 c(if (pandoc2.0()) "--pdf-engine" else "--latex-engine",
326 find_latex_engine(latex_engine))
327 }
328
329 # For macOS, use a full path to the latex engine since the stripping
330 # of the PATH environment variable by OSX 10.10 Yosemite prevents
331 # pandoc from finding the engine in e.g. /usr/texbin
332 find_latex_engine <- function(latex_engine) {
333
334 # do not need full path if latex_engine is available from PATH
335 if (!is_osx() || nzchar(Sys.which(latex_engine))) return(latex_engine)
336 # resolve path if it's not already an absolute path
337 if (!grepl("/", latex_engine) && nzchar(path <- find_program(latex_engine)))
338 latex_engine <- path
339 latex_engine
340 }
341
342 #' @rdname pandoc_args
343 #' @export
344 pandoc_toc_args <- function(toc,
345 toc_depth = 3) {
346
347 args <- c()
348
349 if (toc) {
350 args <- c(args, "--table-of-contents")
351 args <- c(args, "--toc-depth", toc_depth)
352 }
353
354 args
355 }
356
357 #' @section About Pandoc citeproc:
358 #' For Pandoc version before 2.11, a pandoc filter \samp{pandoc-citeproc} is
359 #' used. Since Pandoc 2.11, the feature is built-in and activated using
360 #' \samp{--citeproc} flag. \samp{pandoc_citeproc_arg} will return the correct
361 #' switches depending on the Pandoc version in use.
362 #' @rdname pandoc_args
363 #' @export
364 pandoc_citeproc_args <- function() {
365 if (pandoc_available("2.11"))
366 "--citeproc"
367 else
368 c("--filter", pandoc_citeproc())
369 }
370
371
372 #' Transform path for passing to pandoc
373 #'
374 #' Transform a path for passing to pandoc on the command line. Calls
375 #' \code{\link[base:path.expand]{path.expand}} on all platforms. On Windows,
376 #' transform it to a short path name if it contains spaces, and then convert
377 #' forward slashes to back slashes (as required by pandoc for some path
378 #' references).
379 #' @param path Path to transform
380 #' @param backslash Whether to replace forward slashes in \code{path} with
381 #' backslashes on Windows.
382 #' @return Transformed path that can be passed to pandoc on the command line.
383 #' @export
384 pandoc_path_arg <- function(path, backslash = TRUE) {
385
386 path <- path.expand(path)
387
388 # remove redundant ./ prefix if present
389 path <- sub('^[.]/', '', path)
390 # paths starting with - shouldn't be treated as command-line options (#2503)
391 i <- grepl('^-', path) & xfun::is_rel_path(path)
392 path[i] <- paste0('./', path[i])
393
394 if (is_windows()) {
395 i <- grep(' ', path)
396 if (length(i))
397 path[i] <- utils::shortPathName(path[i])
398 if (backslash) path <- gsub('/', '\\\\', path)
399 }
400
401 path
402 }
403
404
405 #' Render a pandoc template.
406 #'
407 #' Use the pandoc templating engine to render a text file. Substitutions are
408 #' done using the \code{metadata} list passed to the function.
409 #' @param metadata A named list containing metadata to pass to template.
410 #' @param template Path to a pandoc template.
411 #' @param output Path to save output.
412 #' @param verbose \code{TRUE} to show the pandoc command line which was
413 #' executed.
414 #' @return (Invisibly) The path of the generated file.
415 #' @export
416 pandoc_template <- function(metadata, template, output, verbose = FALSE) {
417
418 tmp <- tempfile(fileext = ".md")
419 on.exit(unlink(tmp))
420
421 cat("---\n", file = tmp)
422 cat(yaml::as.yaml(metadata), file = tmp, append = TRUE)
423 cat("---\n", file = tmp, append = TRUE)
424 cat("\n", file = tmp, append = TRUE)
425
426 pandoc_convert(tmp, "markdown", output = output,
427 options = paste0("--template=", template),
428 verbose = verbose)
429
430 invisible(output)
431 }
432
433 #' Create a self-contained HTML document using pandoc.
434 #'
435 #' Create a self-contained HTML document by base64 encoding images,
436 #' scripts, and stylesheets referred by the input document.
437 #' @param input Input html file to create self-contained version of.
438 #' @param output Path to save output.
439 #' @return (Invisibly) The path of the generated file.
440 #' @export
441 pandoc_self_contained_html <- function(input, output) {
442
443 # make input file path absolute
444 input <- normalize_path(input)
445
446 # ensure output file exists and make it's path absolute
447 if (!file.exists(output))
448 file.create(output)
449 output <- normalize_path(output)
450
451 # create a simple body-only template
452 template <- tempfile(fileext = ".html")
453 on.exit(unlink(template), add = TRUE)
454 write_utf8("$body$", template)
455
456 # convert from markdown to html to get base64 encoding
457 # (note there is no markdown in the source document but
458 # we still need to do this "conversion" to get the
459 # base64 encoding)
460
461 # determine from (there are bugs in pandoc < 1.17 that
462 # cause markdown_strict to hang on very large script
463 # elements)
464 from <- if (pandoc_available("1.17"))
465 "markdown_strict"
466 else
467 "markdown"
468
469 # do the conversion
470 pandoc_convert(
471 input = input,
472 from = from,
473 output = output,
474 options = c(
475 self_contained_args(),
476 "--template", template
477 )
478 )
479
480 invisible(output)
481 }
482
483
484 validate_self_contained <- function(math) {
485 if (identical(math$engine, "mathjax") && identical(math$url, "local"))
486 stop2("Local MathJax isn't compatible with self_contained\n",
487 "(you should set self_contained to FALSE)")
488 }
489
490 pandoc_math_engines <- function() {
491 c("mathjax", "mathml", "webtex", "katex", "gladtex")
492 }
493
494 pandoc_math_args <- function(engine, url = NULL) {
495
496 engine <- match.arg(engine, choices = pandoc_math_engines())
497
498 if (!is.null(url) && engine %in% c("mathml", "gladtex")) {
499 stop2(sprintf("%s does not support setting a URL.", engine))
500 }
501
502 paste0(c("--", engine, if (!is.null(url)) c("=", url)), collapse = "")
503 }
504
505
506 pandoc_mathjax_local_path <- function() {
507
508 local_path <- Sys.getenv("RMARKDOWN_MATHJAX_PATH", unset = NA)
509 if (is.na(local_path)) {
510 local_path <- unix_mathjax_path()
511 if (is.na(local_path)) {
512 stop("For mathjax = \"local\", please set the RMARKDOWN_MATHJAX_PATH ",
513 "environment variable to the location of MathJax. ",
514 "On Linux systems you can also install MathJax using your ",
515 "system package manager.")
516 } else {
517 local_path
518 }
519 } else {
520 local_path
521 }
522 }
523
524
525 unix_mathjax_path <- function() {
526
527 if (identical(.Platform$OS.type, "unix")) {
528 mathjax_path <- "/usr/share/javascript/mathjax"
529 if (file.exists(file.path(mathjax_path, "MathJax.js")))
530 mathjax_path
531 else
532 NA
533 } else {
534 NA
535 }
536 }
537
538
539 pandoc_html_highlight_args <- function(template,
540 highlight,
541 highlight_downlit = FALSE) {
542
543 # Reminder: we do not use pandoc_path_arg() for argument to --highlight-style
544 # https://github.com/rstudio/rmarkdown/issues/1976
545
546 args <- c()
547
548 # no highlighting engine
549 if (is.null(highlight)) return(pandoc_highlight_args(NULL))
550
551 highlight <- resolve_highlight(highlight, html_highlighters())
552
553 check_highlightjs <- function(highlight, engine) {
554 if (highlight != "default" && is_highlightjs(highlight)) {
555 stop(
556 sprintf(c(
557 "'%s' theme is for highlightjs highlighting engine ",
558 "and can't be used with %s engine."), c(highlight, engine)),
559 call. = FALSE
560 )
561 }
562 }
563
564 # downlit engine
565 if (highlight_downlit) {
566 check_highlightjs(highlight, "downlit")
567 default <- if (pandoc2.0()) resolve_highlight("arrow") else "pygments"
568 args <- c(
569 pandoc_highlight_args(highlight, default = default),
570 # variable used to insert some css in a Pandoc template
571 pandoc_variable_arg("highlight-downlit")
572 )
573 } else if (identical(template, "default") && is_highlightjs(highlight)) {
574 # highlightjs engine for default template only
575 args <- c(pandoc_highlight_args(NULL),
576 # variable used to insert some css and js
577 # in the Pandoc default template
578 pandoc_variable_arg("highlightjs", "1"))
579 } else {
580 # Pandoc engine
581 check_highlightjs(highlight, "Pandoc")
582 args <- pandoc_highlight_args(highlight, default = "pygments")
583 }
584
585 args
586 }
587
588 is_highlightjs <- function(highlight) {
589 !is.null(highlight) && (highlight %in% c("default", "textmate"))
590 }
591
592 resolve_highlight <- function(highlight, supported = highlighters()) {
593 # for backward compatibility, partial match still need to work
594 i <- pmatch(highlight, supported, nomatch = 0L)
595 if (i > 0L) return(supported[i])
596
597 # Otherwise it could be a custom (built-in) .theme file
598 if (!pandoc2.0()) {
599 stop("Using a custom highlighting style requires Pandoc 2.0 and above",
600 call. = FALSE)
601 }
602 custom <- list(
603 # from distill
604 # https://raw.githubusercontent.com/apreshill/distill/arrow/inst/rmarkdown/templates/distill_article/resources/arrow.theme
605 arrow = pkg_file_highlight("arrow.theme"),
606 # from distill
607 # https://github.com/rstudio/distill/blob/c98d332192ff75f268ddf69bddace34e4db6d89b/inst/rmarkdown/templates/distill_article/resources/rstudio.theme
608 rstudio = pkg_file_highlight("rstudio.theme")
609 )
610 # if not an alias use the provided custom path
611 highlight <- custom[[highlight]] %||% highlight
612 # Check for extension or give informative error otherwise
613 if (!identical(xfun::file_ext(highlight), "theme")) {
614 msg <- c(
615 sprintf("`highlight` argument must be one of %s",
616 knitr::combine_words(c(supported, names(custom)), and = " or ", before = "`")),
617 " or a file with extension `.theme`."
618 )
619 stop(msg, call. = FALSE)
620 }
621 highlight
622 }
623
624 #' Find the \command{pandoc} executable
625 #'
626 #' Searches for the \command{pandoc} executable in a few places and use the
627 #' highest version found, unless a specific version is requested.
628 #' @param cache Whether to search for \command{pandoc} again if a Pandoc
629 #' directory containing the \command{pandoc} executable of the expected
630 #' version (if provided) has been found previously. Search again if
631 #' \code{cache = FALSE}.
632 #' @param dir A character vector of potential directory paths under which
633 #' \command{pandoc} may be found. If not provided, this function searches for
634 #' \command{pandoc} from the environment variable \var{RSTUDIO_PANDOC} (the
635 #' RStudio IDE will set this variable to the directory of Pandoc bundled with
636 #' the IDE), the environment variable \var{PATH}, and the directory
637 #' \file{~/opt/pandoc/}.
638 #' @param version The version of Pandoc to look for (e.g., \code{"2.9.2.1"}). If
639 #' not provided, this function searches for the highest version under the
640 #' potential directories.
641 #' @note Usually you do not need to install Pandoc if you use the RStudio IDE,
642 #' because the IDE has bundled a version of Pandoc. If you have installed a
643 #' version of Pandoc by yourself and want to use this version instead, you may
644 #' use the \code{dir} argument of this function.
645 #' @return A list containing the directory and version of Pandoc (if found).
646 #' @export
647 #' @examples rmarkdown::find_pandoc()
648 #' rmarkdown::find_pandoc(dir = '~/Downloads/Pandoc')
649 #' rmarkdown::find_pandoc(version = '2.7.3')
650 find_pandoc <- function(cache = TRUE, dir = NULL, version = NULL) {
651
652 if (!cache) set_pandoc_info(NULL) # clear previously found pandoc path
653 if (!is.null(.pandoc$dir) && (is.null(version) || version == .pandoc$version))
654 return(as.list(.pandoc))
655
656 # look up pandoc in potential sources unless user has supplied `dir`
657 sources <- if (length(dir) == 0) c(
658 Sys.getenv("RSTUDIO_PANDOC"),
659 dirname(find_program("pandoc")),
660 "~/opt/pandoc"
661 ) else dir
662 sources <- path.expand(sources)
663
664 # determine the versions of the sources
665 versions <- lapply(sources, function(src) {
666 if (dir_exists(src)) get_pandoc_version(src) else numeric_version("0")
667 })
668
669 # find the maximum version
670 found_src <- NULL
671 found_ver <- numeric_version("0")
672 for (i in seq_along(sources)) {
673 ver <- versions[[i]]
674 if ((!is.null(version) && ver == version) || (is.null(version) && ver > found_ver)) {
675 found_ver <- ver
676 found_src <- sources[[i]]
677 }
678 }
679
680 set_pandoc_info(found_src, found_ver)
681 as.list(.pandoc)
682 }
683
684 # Get an S3 numeric_version for the pandoc utility at the specified path
685 get_pandoc_version <- function(pandoc_dir) {
686 path <- file.path(pandoc_dir, "pandoc")
687 if (is_windows()) path <- paste0(path, ".exe")
688 if (!utils::file_test("-x", path)) return(numeric_version("0"))
689 info <- with_pandoc_safe_environment(
690 system(paste(shQuote(path), "--version"), intern = TRUE)
691 )
692 version <- strsplit(info, "\n", useBytes = TRUE)[[1]][1]
693 version <- strsplit(version, " ")[[1]][2]
694 components <- strsplit(version, "-")[[1]]
695 version <- components[1]
696 # pandoc nightly adds -nightly-YYYY-MM-DD to last release version
697 # https://github.com/jgm/pandoc/issues/8016
698 # mark it as devel appending YYYY.MM.DD
699 nightly <- match("nightly", components)
700 if (!is.na(nightly)) version <- paste(c(
701 version, grep("^[0-9]+$", components[-(1:nightly)], value = TRUE)
702 ), collapse = ".")
703 numeric_version(version)
704 }
705
706 set_pandoc_info <- function(dir, version = if (!is.null(dir)) get_pandoc_version(dir)) {
707 .pandoc$dir <- dir
708 .pandoc$version <- version
709 }
710
711 # prepend pandoc stack size arguments
712 prepend_pandoc_stack_size <- function(args) {
713 stack_size <- getOption("pandoc.stack.size", default = "512m")
714 c(c("+RTS", paste0("-K", stack_size), "-RTS"), args)
715 }
716
717 # wrap a system call to pandoc so that LC_ALL is not set
718 # see: https://github.com/rstudio/rmarkdown/issues/31
719 # see: https://ghc.haskell.org/trac/ghc/ticket/7344
720 with_pandoc_safe_environment <- function(code) {
721
722 lc_all <- Sys.getenv("LC_ALL", unset = NA)
723
724 if (!is.na(lc_all)) {
725 Sys.unsetenv("LC_ALL")
726 on.exit(Sys.setenv(LC_ALL = lc_all), add = TRUE)
727 }
728
729 lc_ctype <- Sys.getenv("LC_CTYPE", unset = NA)
730
731 if (!is.na(lc_ctype)) {
732 Sys.unsetenv("LC_CTYPE")
733 on.exit(Sys.setenv(LC_CTYPE = lc_ctype), add = TRUE)
734 }
735
736 if (Sys.info()['sysname'] == "Linux" &&
737 is.na(Sys.getenv("HOME", unset = NA))) {
738 stop("The 'HOME' environment variable must be set before running Pandoc.")
739 }
740
741 if (Sys.info()['sysname'] == "Linux" &&
742 is.na(Sys.getenv("LANG", unset = NA))) {
743 # fill in a the LANG environment variable if it doesn't exist
744 Sys.setenv(LANG = detect_generic_lang())
745 on.exit(Sys.unsetenv("LANG"), add = TRUE)
746 }
747
748 if (Sys.info()['sysname'] == "Linux" &&
749 identical(Sys.getenv("LANG"), "en_US")) {
750 Sys.setenv(LANG = "en_US.UTF-8")
751 on.exit(Sys.setenv(LANG = "en_US"), add = TRUE)
752 }
753
754 force(code)
755 }
756
757 # if there is no LANG environment variable set pandoc is going to hang so
758 # we need to specify a "generic" lang setting. With glibc >= 2.13 you can
759 # specify C.UTF-8 so we prefer that. If we can't find that then we fall back
760 # to en_US.UTF-8.
761 detect_generic_lang <- function() {
762
763 locale_util <- Sys.which("locale")
764
765 if (nzchar(locale_util)) {
766 locales <- system(paste(locale_util, "-a"), intern = TRUE)
767 locales <- suppressWarnings(
768 strsplit(locales, split = "\n", fixed = TRUE)
769 )
770 if ("C.UTF-8" %in% locales)
771 return("C.UTF-8")
772 }
773
774 # default to en_US.UTF-8
775 "en_US.UTF-8"
776 }
777
778
779 # get the path to the pandoc binary
780 pandoc <- function() {
781 find_pandoc()
782 file.path(.pandoc$dir, "pandoc")
783 }
784
785
786 # get the path to the pandoc-citeproc binary
787 pandoc_citeproc <- function() {
788 find_pandoc()
789 bin <- "pandoc-citeproc"
790 p <- file.path(.pandoc$dir, bin)
791 if (xfun::is_windows()) p <- xfun::with_ext(p, "exe")
792 if (file.exists(p)) p else bin
793 }
794
795 #' @rdname pandoc_args
796 #' @param lua_files Character vector of file paths to Lua filter files. Paths
797 #' will be transformed by \code{\link{pandoc_path_arg}}.
798 #' @export
799 pandoc_lua_filter_args <- function(lua_files) {
800 # Lua filters was introduced in pandoc 2.0
801 if (pandoc2.0()) c(rbind("--lua-filter", pandoc_path_arg(lua_files)))
802 }
803
804 # quote args if they need it
805 quoted <- function(args) {
806
807 # some characters are legal in filenames but without quoting are likely to be
808 # interpreted by the shell (e.g. redirection, wildcard expansion, etc.) --
809 # wrap arguments containing these characters in quotes.
810 shell_chars <- grepl(.shell_chars_regex, args)
811 args[shell_chars] <- shQuote(args[shell_chars])
812 args
813 }
814
815 find_pandoc_theme_variable <- function(args) {
816
817 range <- length(args) - 1
818
819 for (i in 1:range) {
820 if (args[[i]] == "--variable" && grepl("^theme:", args[[i + 1]])) {
821 return(substring(args[[i + 1]], nchar("theme:") + 1))
822 }
823 }
824
825 # none found, return NULL
826 NULL
827 }
828
829
830 # Environment used to cache the current pandoc directory and version
831 .pandoc <- new.env()
832 .pandoc$dir <- NULL
833 .pandoc$version <- NULL
834
835 pandoc2.0 <- function() {
836 pandoc_available("2.0")
837 }
838
839 # Pandoc 2.19 deprecated --self-contained
840 self_contained_args <- function() {
841 if (pandoc_available('2.19')) c('--embed-resources', '--standalone') else '--self-contained'
842 }
843
844 #' Get the path of the pandoc executable
845 #'
846 #' Returns the path of the pandoc executable used by functions in the the
847 #' \pkg{rmarkdown} package. This is the most recent version of pandoc found in
848 #' either the system path or shipped with RStudio.
849 #'
850 #' See the
851 #' \href{https://pandoc.org/MANUAL.html}{pandoc manual}
852 #' for pandoc commands.
853 #'
854 #' @export
855 pandoc_exec <- pandoc