rstudio / rstudioapi

Safely access RStudio's API (when available)
http://rstudio.github.io/rstudioapi
Other
165 stars 35 forks source link

setSelectionRanges also removes part of the string it has selected. #276

Open karlvurdst opened 1 year ago

karlvurdst commented 1 year ago

I am creating a snippet that automatically takes the function name below the cursor, and creates a documentation title from the function name.

The snippet creates the title as expected, but it for some reason removes parts of the line the function definition is on. I have narrowed it down to the setSelectionRanges. It seems that for some reason it deletes the selection.

I have tried to move the selection to the beginning of the document, just to make sure its not because its selected at the end of the snippet, but no matter what I do, the setSelectionRanges removes a part of the selection.

snippet doc
    `r
    editor <- rstudioapi::getSourceEditorContext()
    editor_start <- editor$selection[[1]]$range$start[[1]]
    start <- rstudioapi::document_position(editor_start + 1, 1)
    end <- rstudioapi::document_position(editor_start + 1, 999)
    range_ <- rstudioapi::document_range(start, end)

    rstudioapi::setSelectionRanges(range_, editor$id)
    text <- rstudioapi::primary_selection(
      rstudioapi::getSourceEditorContext()
    )$text
    split_text <- stringr::str_split(stringr::word(text, 1), "_", simplify = T)
    title <- stringr::str_to_title(paste(split_text, collapse =" "))

    start <- rstudioapi::document_position(editor_start, 1)
    end <- rstudioapi::document_position(editor_start, 999)
    range_ <- rstudioapi::document_range(start, end)

    rstudioapi::insertText(
        range_,
        paste("#' @title", title),
        editor[["id"]]
    )

    rstudioapi::setCursorPosition(c(editor_start, nchar(title) + 1))
    NULL
    `

To test, run the snippet in the following code:

doc
test_fun <- function() {
  NULL
}

I expect:

#' @title Test Fun
test_fun <- function() {
  NULL
}

But I get:

#' @title Test Fun

tion() {
  NULL
}

RStudio 2023.03.0+386 "Cherry Blossom" Release (3c53477afb13ab959aeb5b34df1f10c237b256c3, 2023-03-09) for CentOS 7 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36

kevinushey commented 1 year ago

One possibility here is that these APIs are (unfortunately) not synchronous -- you might have better luck if you add a short Sys.sleep() call following the calls to setSelectionRanges and insertText.