rstudio / rstudioapi

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

Document locations don't work when in "Visual" mode in Rmd/Qmd documents #265

Open daattali opened 1 year ago

daattali commented 1 year ago

If I want to insert text at the end of the currently open document, I can use

id <- rstudioapi::getSourceEditorContext()$id
rstudioapi::insertText(location = Inf, text = "test", id = id)

However, when I'm in a Rmd or Qmd file and the "Visual" mode is selected, nothing happens. No text gets added. This is especially problematic with Qmd files because Visual mode is the default.

Another way to see this issue: rstudioapi::getSourceEditorContext()$selection always returns [1, 1] -- [1, 1]: '' when in Visual mode.

daattali commented 1 year ago

setCursorPosition() also doesn't work in Visual mode

kevinushey commented 1 year ago

Part of the challenge here is that Visual Mode documents don't really have a well-defined cursor "position" in terms of row / column numbers; instead, it's just what that might map to in the associated Source document.

We could in theory sort of guess by rendering from visual to source mode, and using some heuristics to figure out the source document location, make edits in the source document, and then re-synchronize back to the visual editor ... but hopefully you can see how this might be a challenge.

What do you actually want to do in this case? Can you think of a general way of expressing what you want to do without the notion of a cursor position?

daattali commented 1 year ago

I understand how this is a challenging thing to know.

My actual usecase is that I'd like to insert text at the end of a file. But I want to ensure that the new text goes on a new line. I don't want to blindly always prepend a newline, because if the file already ended in a newline character, then I would be adding an extra line, which isn't ideal. So my solution was to set the cursor at the end of the document, and check where the cursor is: if it's at column 1, that means I can insert right away; if it's not at column 1 then I need to insert a newline.

Here is a simplified version of my function:

insert_text <- function(text) {
  id <- rstudioapi::getSourceEditorContext()$id
  if (is.null(id)) {
    id <- rstudioapi::documentNew("")
  }

  rstudioapi::setCursorPosition(Inf, id = id)
  loc <- rstudioapi::getSourceEditorContext()$selection
  # if the end of the document is not a new line, add a new line
  if (loc[[1]]$range$end[[2]] != 1) {
    text <- paste0("\n", text)
  }
  rstudioapi::insertText(id = id, text = text)
}

This breaks when I'm in visual mode.


Another thing that would help in my case (although it's not really a solution to this issue) is (1) knowing whether Visual mode is currently selected, and (2) being able to programatically change to Source mode