## Heading
Some initial text
Introduction
This is a short post to demonstrate a function that can be used to insert code chunks, from a library of chunks, into an active RMarkdown or Quarto document. The concept is simple - read in a chunk of code from a location, in this case GitHub, and use functions from {rstudioapi} to insert it at the current cursor position.
Code and Example
<- function(snippet = NULL, fences = TRUE) {
add_code_chunk
if (!is.null(snippet)) {
<- "https://raw.githubusercontent.com/harveyl888/insert-chunks/refs/heads/main/"
location <- paste0(file.path(location, snippet), ".qmd")
snippet_location <- readLines(snippet_location) |>
s paste(collapse = "\n")
if (fences == TRUE) {
<- paste("```{r}", s, "```", sep = "\n")
s
}
## inject at current cursor position
<- rstudioapi::getSourceEditorContext()
l ::insertText(text = s, id = l$id)
rstudioapi
} }
The function can be run from the console add_code_chunk("testfile_01", chunk = TRUE)
to insert the contents of harveyl888/insert-chunks/testfile_01.qmd at the current cursor position. With fences = TRUE
the chunk fences will be included.
The two {rstudioapi} functions take care of placing the content at the cursor. rstudioapi::getSourceEditorContent()
grabs details of the current open editor window. It returns a list with the follow members:
- id. A unique ID
- path. The document path
- contents. The document contents
- selection. The currently selected region range
For the purpose of inserting code, we want to capture the id, so that we can refer to the open document.
The second function, rstudioapi::insertText()
inserts text into a chosen document. We use the document id returned by rstudioapi::getSourceEditorContent()
and place text at the current cursor position.
Here’s an initial document
and here it is after scrolling to the end and executing add_code_chunk("testfile_01", chunk = TRUE)
## Heading
Some initial text
```{r}
df <- mtcars |>
dplyr::filter(cyl == 6)
print(nrow(df))
```