Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
karlvurdst opened this issue May 16, 2023 · 1 comment
Open

Comments

@karlvurdst
Copy link

karlvurdst commented May 16, 2023

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
Copy link
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants