usethis icon indicating copy to clipboard operation
usethis copied to clipboard

feature request: helper functions to edit rstudio document templates

Open whtns opened this issue 3 years ago • 0 comments

It is useful to create custom document templates for .R and .Rmd files in rstudio. This process is a little finicky currently. Users need to:

  1. create a 'templates' folder inside an os-specific directory. (AppData/Roaming/RStudio on Windows, and ~/.config/rstudio in unix)
  2. create templates for specific document types according to a standard scheme

It would be helpful to have a function like edit_document_template with an argument that would create or edit the appropriate file. example below

#' Edit an rstudio document template
#'
#' @param document 
#' The document template
#' document.Rmd 	The default R Markdown document file content (without YAML header)
#' notebook.Rmd 	The default R Notebook file content (without YAML header)
#' presentation.Rmd 	The default R Markdown presentation file content (without YAML header)
#' shiny.Rmd 	The default Shiny R Markdown file content (without YAML header)
#' @param scope user 
#'
#' @return
#' @export
#'
#' @examples
edit_document_template <- function(document = c("Rscript", "Rmd document", "Rmd notebook", "Rmd presentation", 
                                                "Rmd shiny"), scope = c("user")) 
{
    
    
    templates_dir <- ifelse(.Platform$OS.type == "unix", ".config/rstudio/templates", "AppData/Roaming/RStudio")
    
    template <- switch(document, "Rscript" = "default.R", 
                       "Rmd document" = "document.Rmd",
                       "Rmd notebook" = "notebook.Rmd",
                       "Rmd presentation" = "presentation.Rmd",
                       "Rmd shiny" = "shiny.Rmd")
    
    path <- usethis:::scoped_path_r("user", templates_dir, template, envvar = "R_PROFILE_USER")
    edit_file(path)
    ui_todo("Restart R for changes to take effect")
    invisible(path)
}

whtns avatar Dec 04 '20 19:12 whtns