R/addin_bindings.R

Defines functions prompt_lib insertAssign new_parallel.r addlib

Documented in addlib insertAssign new_parallel.r

<<<<<<< HEAD:R/libcalls.R
#' Library Calls
#'
#' Add library statement to the top of your script
#'
#' @import rstudioapi
#' @importFrom stringr str_split
#' @importFrom utils installed.packages
#'
#' @export
prompt_lib <- function(){
  txt <- rstudioapi::showPrompt("Library", "Enter package(s) (seperated by a single space) to load and insert")

  if(length(txt) != 0){
    pkgs <- stringr::str_split(txt, " ")[[1]]
    all <- rownames(utils::installed.packages())
    loaded <- loadedNamespaces()

    not_inst <- which(!sapply(pkgs, `%in%`, all))

    if(length(not_inst) > 0){
      ni_pkgs <- pkgs[not_inst]

      for(i in ni_pkgs){
        if(rstudioapi::showQuestion("Library Found", paste0("Install '", i, "' from cran?"), ok = "YES", cancel = "NO"))
          rstudioapi::sendToConsole(paste0("install.packages('", i, "')"), execute = TRUE)
      }

      all <- rownames(utils::installed.packages())
      pkgs <- pkgs[which(sapply(pkgs, `%in%`, all))]
    }

    if(length(pkgs) == 0){
      rstudioapi::showDialog("Error", "Unable to load libraries")
    }else{
      for(i in pkgs){
        # id  <- paste0("package:", i)
        txt <- paste0("library('", i, "')\n")
        # if it's loaded already, then unload and detach, then reload
        # Useful if you refresh package function in one R session and need it updated in another

        if(!(i %in% loaded)){
          attachNamespace(loadNamespace(i))
        }
        rstudioapi::insertText(rstudioapi::document_position(0,0), txt)
      }
    }
  }

}



# # construct the text to be inserted
# fmt <- "# This document was last modified on %s.\n"
# text <- sprintf(fmt, Sys.Date())
#
# # specify a range where this text should be inserted; here,
# # we use the first line; that is, the 'range' between the start
# # of the first row, and the start of the second row
#
# range <- rstudioapi::document_range(c(1, 0), c(2, 0))
# rstudioapi::insertText(range, text)
#
# # put the cursor at the end of the document -- note that here,
# # `Inf` is automatically truncated to the actual length of the
# # document
#
# rstudioapi::setCursorPosition()
#
#
# # select the first 10 even lines in the document
# ranges <- lapply(seq(2, by = 2, length.out = 10), function(start) {
#   rstudioapi::document_range(
#     c(start, 0),
#     c(start, Inf)
#   )
# })
# rstudioapi::setSelectionRanges(ranges)

=======
#' Functions that are Binded for addIns
#'
#' TBD
#'
#' @param noask boolean default TRUE will execute without requiring user input.
#'
#' @import rstudioapi
#' @importFrom stringr str_split
#' @importFrom utils installed.packages
#'
#' @name addin_bindings
NULL

#' @describeIn addin_bindings TBD
#' @export
insertAssign <- function(){
  context <- rstudioapi::getActiveDocumentContext()
  rstudioapi::insertText(context$selection[[1]]$range$end, text = " <- ")
}



#' @describeIn addin_bindings open new boilerplate script to exec parallelized func call.
#' @export
new_parallel.r <- function(noask = TRUE){
  ##
  ## path to boilerplate code txt
  ##

  # bpath <- "inst/etc/bp-parallel_func_call.txt"
  bpath <- system.file("etc/bp-parallel_func_call.txt", package = "ninjar")

  rlines <- readLines(bpath)
  nloc <- length(rlines)
  cursor_pos <- rstudioapi::as.document_position(c(nloc+5, 1))

  if(!noask){
    new_fnam <- rstudioapi::showPrompt("Save As:", message = "New script name:", default = "parallel.R")
  }else{
    new_fnam <- paste0("parallel_", sodium::bin2hex(sodium::random(2)), ".R")
  }

  rstudioapi::documentNew(
    text = paste0(paste0(rlines, collapse = "\n"), "\n\n"),
    type = "r",
    position = cursor_pos,
    execute = FALSE
  )

  invisible(NULL)
}

#' @describeIn addin_bindings TBD
#' @export
addlib <- function(){
  txt <- rstudioapi::showPrompt("Library", "Enter package(s) (seperated by a single space) to load and insert")

  if(length(txt) != 0){
    pkgs <- stringr::str_split(txt, " ")[[1]]
    all <- rownames(utils::installed.packages())
    loaded <- loadedNamespaces()

    not_inst <- which(!sapply(pkgs, `%in%`, all))

    if(length(not_inst) > 0){
      ni_pkgs <- pkgs[not_inst]

      for(i in ni_pkgs){
        if(rstudioapi::showQuestion("Library Found", paste0("Install '", i, "' from cran?"), ok = "YES", cancel = "NO"))
          rstudioapi::sendToConsole(paste0("install.packages('", i, "')"), execute = TRUE)
      }

      all <- rownames(utils::installed.packages())
      pkgs <- pkgs[which(sapply(pkgs, `%in%`, all))]
    }

    if(length(pkgs) == 0){
      rstudioapi::showDialog("Error", "Unable to load libraries")
    }else{
      for(i in pkgs){
        # id  <- paste0("package:", i)
        txt <- paste0("library('", i, "')\n")
        # if it's loaded already, then unload and detach, then reload
        # Useful if you refresh package function in one R session and need it updated in another

        if(!(i %in% loaded)){
          attachNamespace(loadNamespace(i))
        }
        rstudioapi::insertText(rstudioapi::document_position(0,0), txt)
      }
    }
  }

}
>>>>>>> 681c87557e94fcfc1a30a0185aca4c8d5737a0a8:R/addin_bindings.R
bfatemi/ninjar documentation built on Sept. 8, 2019, 7:37 p.m.