R/rs_replace_in_selection.R

Defines functions rs_replace_in_selection

Documented in rs_replace_in_selection

# Main "replace" function
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#' Replace text in selection.
#'
#' @param pattern (character) A fixed pattern of text to be replaced
#'                            (not a regular expression).
#' @param replacement (character) The replacement text.
#' @inheritParams rs_get_ind
#' @export
rs_replace_in_selection <- function(pattern, replacement,
                                    context = get_context()) {

    sel <-  context$selection[[1]]
    old_text  <- sel$text
    Encoding(old_text) <- "UTF-8"

    new_text <- gsub(pattern = pattern,
                     replacement = replacement,
                     x = old_text,
                     fixed = TRUE)

    rstudioapi::modifyRange(location = sel$range,
                            text = as.character(new_text),
                            id = context$id)

}
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GegznaV/spAddins documentation built on Nov. 20, 2020, 10:42 p.m.