R/save_object.R

save.object <- function() {
  isValidName <- function(string) {
    grepl("^([[:alpha:]]|[.][._[:alpha:]])[._[:alnum:]]*$",
          string)
  }

  isValidAndUnreservedName <- function(string) {
    make.names(string) == string
  }

  testValidity <- function(string) {
    valid <- isValidName(string)
    unreserved <- isValidAndUnreservedName(string)
    reserved <- (valid & !unreserved)
    list("Valid" = valid,
         "Unreserved" = unreserved,
         "Reserved" = reserved)
  }

  if (!dir.exists("aux_files")) {
    dir.create("aux_files/")
  }
  ctx = rstudioapi::getSourceEditorContext()
  rng = ctx$selection[[1]]$range
  line.number <- rng$start[1]

  rng <- rstudioapi::document_range(c(line.number, 1),
                                    c(line.number, Inf))
  rstudioapi::setSelectionRanges(rng)
  slct = rstudioapi::getSourceEditorContext()$selection[[1]]
  my.variable.name <- blogdown:::trim_ws(slct$text)
  if (isValidName(my.variable.name)) {
    if (ctx$path == '')
      stop('Please select the blog post source file before using this addin',
           call. = FALSE)
    ctx_ext = tolower(xfun::file_ext(ctx$path))

    path = normalizePath(ctx$path)

    path <- paste0("aux_files/", xfun::sans_ext(basename(path)))
    if (!dir.exists(path)) {
      dir.create(path)
    }

    output <- paste0("save.path <- \"../../",
                     path,
                     "/\"\n")
    output <- paste0(
      output,
      paste0(
        "saveRDS(",
        my.variable.name,
        ", file = paste0(save.path,\n\t\"",
        my.variable.name,
        ".Rds\"))"
      )
    )
    rstudioapi::modifyRange(rng, "")

    rstudioapi::insertText(rng, output)
    rng <- rstudioapi::document_range(c(line.number, 1),
                                      c(line.number + 2, Inf))

    rstudioapi::setSelectionRanges(rng)
  } else{
    stop("Not a variable R variable. Is your variable name on a line by itself?")
  }

}
beeflavor/useful-blogdown-addins documentation built on May 31, 2019, 5:11 p.m.