I am creating a snippet that automatically takes the name of the function defined in the line below, and creates a roxygen2 documentation where the title is printed "nicely".
I have defined the following snippet:
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, one can run the following code, and press shift + tab
with cursor behind doc
:
doc
test_snippet <- function(
x, y
) {
NULL
}
It then changes the code to the following:
#' @title Test Snippet
unction(
x, y
) {
NULL
}
It succesfuly writes the title in the format I expected, but it removes part of the function definition line. Any suggestions as to why this is happening, and how to solve it+