gadenbuie / shrtcts

Make Anything an RStudio Shortcut
https://pkg.garrickadenbuie.com/shrtcts/
Other
119 stars 4 forks source link

using rstudioapi in the shortcuts #16

Closed SNAnalyst closed 3 years ago

SNAnalyst commented 3 years ago

Currently, if you use a shortcut that involves the rstudioapi, the following error results when starting rstudio:

Error: RStudio not running

For example, I include this in my .shrtcts.R file:

#' flip slash
#'
#' flip the slash of a windows path
#'
#' @interactive
#' @shortcut Ctrl+Alt+\
context <- rstudioapi::getActiveDocumentContext()
for (con in rev(context$selection)) {
  rstudioapi::modifyRange(con$range, 
                          snippetsaddin:::find.replacement(con$text), context$id)
}

or:

#' chunkify
#'
#' turn selected text into a chunk
#'
#' @shortcut Ctrl+Alt+c
adc <- rstudioapi::getActiveDocumentContext()
newend <- adc$selection[[1]]$range$start[[1]] + (adc$selection[[1]]$range$end[[1]] - 
                                                   adc$selection[[1]]$range$start[[1]]) + 3
adc$selection[[1]]$range$start[[1]] <- adc$selection[[1]]$range$start[[1]] - 1
adc$selection[[1]]$range$end[[1]] <- newend
adc$selection[[1]]$range$end[[2]] <- 1
start_text <- "\n```{r , echo = FALSE}"
rstudioapi::insertText(location = adc$selection[[1]]$range$start, start_text)
rstudioapi::insertText(location = adc$selection[[1]]$range$end, "\n```\n")

Anything that uses the rstudioapi triggers this error. Is there a way that it can be used inside shrtcts?

gadenbuie commented 3 years ago

Yes, all you need is a slight syntax change. Each of the R code snippets need to be inside a function definition. The function doesn't need a name, but you could provide one if you want.

#' flip slash
#'
#' flip the slash of a windows path
#'
#' @interactive
#' @shortcut Ctrl+Alt+\
function() {
  context <- rstudioapi::getActiveDocumentContext()
  for (con in rev(context$selection)) {
    rstudioapi::modifyRange(con$range, 
                            snippetsaddin:::find.replacement(con$text), context$id)
  }
}
#' chunkify
#'
#' turn selected text into a chunk
#'
#' @shortcut Ctrl+Alt+c
chunkify <- function() {
  adc <- rstudioapi::getActiveDocumentContext()
  newend <- adc$selection[[1]]$range$start[[1]] + (adc$selection[[1]]$range$end[[1]] - 
                                                     adc$selection[[1]]$range$start[[1]]) + 3
  adc$selection[[1]]$range$start[[1]] <- adc$selection[[1]]$range$start[[1]] - 1
  adc$selection[[1]]$range$end[[1]] <- newend
  adc$selection[[1]]$range$end[[2]] <- 1
  start_text <- "\n```{r , echo = FALSE}"
  rstudioapi::insertText(location = adc$selection[[1]]$range$start, start_text)
  rstudioapi::insertText(location = adc$selection[[1]]$range$end, "\n```\n")
}
SNAnalyst commented 3 years ago

That works great, thanks!