rstudio / rstudioapi

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

FR: Add an `id` parameter to `documentOpen()` #283

Open olivroy opened 1 year ago

olivroy commented 1 year ago

I am trying to write a wrapper that navigate to a file location of a potentially unsaved document. Therefore with

rstudioapi::getSourceEditorContext()$path
#> ""

However the file has a Rstudio id.

Therefore, I was wondering if documentOpen() could have an id parameter, so it would be possible to open an unsaved document to a specified location.

navigate_to_unsaved_file <- function(regex) {
 file_content <- rstudioapi::getSourceEditorContext()$content
 line_regex <- stringr::str_which(file_content, regex)
  rstudioapi::documentOpen(
    id = rstudioapi::getSourceEditorContext()$id,
    line = line_regex[1] # just using the first match for simplicity and example
  )
}

For reference, I am trying to achieve quarto-dev/quarto-cli#5335 with rstudioapi

Thanks

Edit: with an unsaved file,

rstudioapi::getSourceEditorContext()$id |> rstudioapi::documentPath()
Error in `Encoding<-`(`*tmp*`, value = "UTF-8") : 
  a character vector argument expected

Edit: using rstudioapi::setCursorPosition() works. However, it doesn't move focus to the required place (if my focus was on console, it remains this way) Maybe adding a moveCursor argument to setCursorPosition() would work?