Skip to content

Commit

Permalink
refactor pal retrieval code into helper
Browse files Browse the repository at this point in the history
  • Loading branch information
simonpcouch committed Oct 30, 2024
1 parent c96aa9a commit 4fe2054
Showing 1 changed file with 19 additions and 36 deletions.
55 changes: 19 additions & 36 deletions R/rstudioapi.R
Original file line number Diff line number Diff line change
@@ -1,17 +1,6 @@
# replace selection with refactored code
rs_replace_selection <- function(context, role) {
# check if pal exists
if (exists(paste0(".pal_last_", role))) {
pal <- get(paste0(".pal_last_", role))
} else {
tryCatch(
pal <- .init_pal(role),
error = function(e) {
rstudioapi::showDialog("Error", "Unable to create a pal. See `?.init_pal()`.")
return(NULL)
}
)
}
pal <- retrieve_pal(role)

selection <- rstudioapi::primary_selection(context)

Expand All @@ -38,6 +27,22 @@ rs_replace_selection <- function(context, role) {
)
}

retrieve_pal <- function(role) {
if (exists(paste0(".pal_last_", role))) {
pal <- get(paste0(".pal_last_", role))
} else {
tryCatch(
pal <- .init_pal(role),
error = function(e) {
rstudioapi::showDialog("Error", "Unable to create a pal. See `?.init_pal()`.")
return(NULL)
}
)
}

pal
}

standardize_selection <- function(selection, context) {
# if the first entry on a newline, make it the last entry on the line previous
if (selection$range$end[["column"]] == 1L) {
Expand Down Expand Up @@ -123,18 +128,7 @@ stream_selection <- function(selection, context, pal, n_lines_orig, remainder =

# prefix selection with new code -----------------------------------------------
rs_prefix_selection <- function(context, role) {
# check if pal exists
if (exists(paste0(".pal_last_", role))) {
pal <- get(paste0(".pal_last_", role))
} else {
tryCatch(
pal <- .init_pal(role),
error = function(e) {
rstudioapi::showDialog("Error", "Unable to create a pal. See `?.init_pal()`.")
return(NULL)
}
)
}
pal <- retrieve_pal(role)

selection <- rstudioapi::primary_selection(context)

Expand Down Expand Up @@ -165,18 +159,7 @@ rs_prefix_selection <- function(context, role) {

# suffix selection with new code -----------------------------------------------
rs_suffix_selection <- function(context, role) {
# check if pal exists
if (exists(paste0(".pal_last_", role))) {
pal <- get(paste0(".pal_last_", role))
} else {
tryCatch(
pal <- .init_pal(role),
error = function(e) {
rstudioapi::showDialog("Error", "Unable to create a pal. See `?.init_pal()`.")
return(NULL)
}
)
}
pal <- retrieve_pal(role)

selection <- rstudioapi::primary_selection(context)

Expand Down

0 comments on commit 4fe2054

Please sign in to comment.