Skip to content

Instantly share code, notes, and snippets.

@edonnachie
Last active December 27, 2022 14:30
Show Gist options
  • Save edonnachie/5f5919c9eadc6a8156fce02566e656d9 to your computer and use it in GitHub Desktop.
Save edonnachie/5f5919c9eadc6a8156fce02566e656d9 to your computer and use it in GitHub Desktop.
Call rmarkdown::render interactively to create a preview version of a Rmd
#' Call rmarkdown::render to create a preview version of a Rmd
#'
#' This function is intended to be used interactively to create a preview
#' version of a Rmd (e.g. compile a chapter of a bookdown project to docx).
#' By default, it renders the file currently opened in the RStudio source
#' editor, and saves the output to a subfolder called "preview".
#'
#' The default format is html. The argument word = TRUE will change the output
#' format to docx, and using pdf = TRUE will create PDF output.
#'
#' If docx output is to be created, the yaml header of the source document
#' should contain "always_allow_html: true". Due to the limitations of the file
#' format, do not expect complete or perfect output.
#'
#' For use in scripts, it is better to call rmarkdown::render directly
#'
#' @param file File to compile (Default: Use the rstudioapi package to specify the file currently opened in the source editor)
#' @param output_dir Output directory (Default: "preview")
#' @param format Output format (Default: html_document)
#' @param word Whether to change the output format to word_document
#' @param pdf Whether to change the output format to pdf_document
#'
#' @return Result of rmarkdown::render
#' @export
#'
render_preview <- function(file = rstudioapi::getSourceEditorContext()$path,
output_dir = "preview",
format = "html_document",
word = FALSE,
pdf = FALSE) {
if (word) format <- "word_document"
if (pdf) format <- "pdf_document"
rmarkdown::render(
input = file,
output_dir = output_dir,
output_format = format
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment