utils.R 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. find_file <- function(template, file) {
  2. template <- system.file("rmarkdown", "templates", template, file,
  3. package = "rticles")
  4. if (template == "") {
  5. stop("Couldn't find template file ", template, "/", file, call. = FALSE)
  6. }
  7. template
  8. }
  9. find_resource <- function(template, file) {
  10. find_file(template, file.path("resources", file))
  11. }
  12. knitr_fun <- function(name) utils::getFromNamespace(name, 'knitr')
  13. output_asis <- knitr_fun('output_asis')
  14. merge_list <- function(x, y) {
  15. fun <- knitr_fun('merge_list')
  16. fun(as.list(x), y)
  17. }
  18. #' Render a pandoc template.
  19. #'
  20. #' This is a hacky way to access the pandoc templating engine.
  21. #'
  22. #' @param metadata A named list containing metadata to pass to template.
  23. #' @param template Path to a pandoc template.
  24. #' @param output Path to save output.
  25. #' @return (Invisibly) The path of the generate file.
  26. #' @examples
  27. #' x <- rticles:::template_pandoc(
  28. #' list(preamble = "%abc", filename = "wickham"),
  29. #' rticles:::find_resource("rjournal_article", "RJwrapper.tex"),
  30. #' tempfile()
  31. #' )
  32. #' if (interactive()) file.show(x)
  33. #' @noRd
  34. template_pandoc <- function(metadata, template, output, verbose = FALSE) {
  35. tmp <- tempfile(fileext = ".md")
  36. on.exit(unlink(tmp))
  37. cat("---\n", file = tmp)
  38. cat(yaml::as.yaml(metadata), file = tmp, append = TRUE)
  39. cat("---\n", file = tmp, append = TRUE)
  40. cat("\n", file = tmp, append = TRUE)
  41. rmarkdown::pandoc_convert(tmp, "markdown", output = output,
  42. options = paste0("--template=", template), verbose = verbose)
  43. invisible(output)
  44. }
  45. # Call rmarkdown::pdf_document and mark the return value as inheriting pdf_document
  46. inherit_pdf_document <- function(...) {
  47. fmt <- rmarkdown::pdf_document(...)
  48. fmt$inherits <- "pdf_document"
  49. fmt
  50. }
  51. # Helper function to create a custom format derived from pdf_document
  52. # that includes a custom LaTeX template and custom CSL definition
  53. pdf_document_format <- function(..., format, template, csl) {
  54. # base format
  55. fmt <- inherit_pdf_document(..., template = find_resource(format, template))
  56. # add csl to pandoc_args
  57. fmt$pandoc$args <- c(fmt$pandoc$args,
  58. "--csl",
  59. rmarkdown::pandoc_path_arg(find_resource(format, csl)))
  60. # return format
  61. fmt
  62. }