Hi,
I am playing around with the rstudioapi package to try and write a toy function that would take a file name as an argument, create a file with this name, open the file, and insert some code. Here is what I have so far:
open_and_write <- function(path = NULL){
fs::file_create(path)
rstudioapi::navigateToFile(path)
id <- rstudioapi::getSourceEditorContext()$id
rstudioapi::insertText(c(1,1), '# Here is a sweet comment', id)
}
open_and_write('~/foo.R')
I anticipated that when RStudio navigated to the newly created file (foo.R) in the editor pane, the getActiveDocumentContext() would return the ID for foo.R. But instead, it seems to returns the ID for the script containing open_and_write() function, and it places the comment at the start of that script, and not the new file...What am I doing wrong?
EDIT: So it seems that when I add a Sys.sleep(1) to the code, it works as expected. Is rstudioapi::insertText() just inserting the text too quickly? The working code is:
open_and_write <- function(path = NULL){
fs::file_create(path)
rstudioapi::navigateToFile(path)
Sys.sleep(1)
id <- rstudioapi::getSourceEditorContext()$id
rstudioapi::insertText(c(1,1), '# Here is a sweet comment', id)
}