rstudio / rstudioapi

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

reformatCode adds unnecessary new-lines and always applies in all (popped out) source windows with a cursor #218

Open AltfunsMA opened 3 years ago

AltfunsMA commented 3 years ago

The combination of these two effects makes it impossible to use.

Note the function below, which serves as foundation for wrappers that add a sign at the end and insert a new line; e.g.: endwrite(' %>% \n') or endwrite(' + \n'), each with their own keybindings.

endwrite <- function(sign) {

  ctx <- rstudioapi::getSourceEditorContext()

  current_line <-
    as.numeric(ctx[["selection"]][[1]][["range"]][["start"]][["row"]])

  source_id <- ctx$id

  end_of_line <- rstudioapi::as.document_position(c(current_line, Inf))

  nextline <- rstudioapi::as.document_position(c(current_line + 1, Inf))

  rstudioapi::insertText(location = end_of_line, text = sign, id = source_id)

  rstudioapi::setCursorPosition(position = nextline, id = source_id)

  rstudioapi::executeCommand("reformatCode")

  # Currently ineffective workaround:
   rstudioapi::insertText("")

}

In the specific example below, endwrite(' %>% \n') is called after writing var2 inside of the automatically generated parentheses (the typical use-case). reformatCode unnecessarily adds two blank lines afterwards. Because it selects them as well, it is most often fine to just keep typing, as they get deleted at the stylistically correct position... except that these new lines get added across all source documents with a cursor (e.g. popped out) that were recently active, so they start accumulating empty new lines wherever the cursor was. Adding a call to rstudioapi::insertText("") does not change things, to my surprise.

df %>% 
  distinct(var1, var2)  %>% 

Is there a workaround I'm not aware of?

I'm using rstudioapi version 0.13 with R 4.0.3 on Windows 10.