rjournal_article.R 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #' R Journal format.
  2. #'
  3. #' Format for creating R Journal articles. Adapted from
  4. #' \href{https://journal.r-project.org/submissions.html}{https://journal.r-project.org/submissions.html}.
  5. #'
  6. #'
  7. #' @inheritParams rmarkdown::pdf_document
  8. #' @param ... Arguments to \code{rmarkdown::pdf_document}
  9. #'
  10. #' @return R Markdown output format to pass to
  11. #' \code{\link[rmarkdown:render]{render}}
  12. #'
  13. #' @examples
  14. #'
  15. #' \dontrun{
  16. #' library(rmarkdown)
  17. #' draft("MyArticle.Rmd", template = "rjournal_article", package = "rticles")
  18. #' }
  19. #'
  20. #' @export
  21. rjournal_article <- function(...) {
  22. rmarkdown::pandoc_available('2.2', TRUE)
  23. template <- find_resource("rjournal_article", "template.tex")
  24. base <- inherit_pdf_document(..., template = template)
  25. # Render will generate tex file, post-process hook generates appropriate
  26. # RJwrapper.tex and use pandoc to build pdf from that
  27. base$pandoc$to <- "latex"
  28. base$pandoc$ext <- ".tex"
  29. base$post_processor <- function(metadata, utf8_input, output_file, clean, verbose) {
  30. filename <- basename(output_file)
  31. # underscores in the filename will be problematic in \input{filename};
  32. # pandoc will escape underscores but it should not, i.e., should be
  33. # \input{foo_bar} instead of \input{foo\_bar}
  34. if (filename != (filename2 <- gsub('_', '-', filename))) {
  35. file.rename(filename, filename2); filename <- filename2
  36. }
  37. wrapper_metadata <- list(preamble = metadata$preamble, filename = xfun::sans_ext(filename))
  38. wrapper_template <- find_resource("rjournal_article", "RJwrapper.tex")
  39. wrapper_output <- file.path(getwd(), "RJwrapper.tex")
  40. template_pandoc(wrapper_metadata, wrapper_template, wrapper_output, verbose)
  41. tinytex::latexmk("RJwrapper.tex", base$pandoc$latex_engine, clean = clean)
  42. }
  43. # Mostly copied from knitr::render_sweave
  44. base$knitr$opts_chunk$comment <- "#>"
  45. hilight_source <- knitr_fun('hilight_source')
  46. hook_chunk = function(x, options) {
  47. if (output_asis(x, options)) return(x)
  48. paste0('```{=latex}\n\\begin{Schunk}\n', x, '\\end{Schunk}\n```')
  49. }
  50. hook_input <- function(x, options)
  51. paste(c('\\begin{Sinput}', hilight_source(x, 'sweave', options), '\\end{Sinput}', ''),
  52. collapse = '\n')
  53. hook_output <- function(x, options) paste('\\begin{Soutput}\n', x, '\\end{Soutput}\n', sep = '')
  54. base$knitr$knit_hooks <- merge_list(base$knitr$knit_hooks, list(
  55. chunk = hook_chunk,
  56. source = hook_input,
  57. output = hook_output,
  58. message = hook_output,
  59. warning = hook_output,
  60. plot = knitr::hook_plot_tex
  61. ))
  62. base
  63. }