::opts_chunk$set(eval = FALSE) knitr
The rstudioapi
package provides a small family of functions that can be used to interact with documents open in an RStudio session. For example, the following code could be used to insert a ‘last modified’ comment at the start of a document:
# construct the text to be inserted
<- "# This document was last modified on %s.\n"
fmt <- sprintf(fmt, Sys.Date())
text
# specify a range where this text should be inserted; here,
# we use the first line; that is, the 'range' between the start
# of the first row, and the start of the second row
<- rstudioapi::document_range(c(1, 0), c(2, 0))
range ::insertText(range, text) rstudioapi
By default, these APIs target the editor instance either currently focused by the user, or when no such editor is currently focused, the last focused editor. If you need to target a specific editor instance (for example, you want to write code that inserts text into the console), you can use getConsoleEditorContext()
to get the id
for the console editor:
# get console editor id
<- rstudioapi::getConsoleEditorContext()
context <- context$id
id
# send some R code to the console
::insertText(text = "print(1 + 1)", id = id)
rstudioapi
# see also: `getActiveEditorContext()`, `getSourceEditorContext()`
You can also modify the cursor position through the use of the setCursorPosition()
and setSelectionRanges()
APIs.
# put the cursor at the end of the document -- note that here,
# `Inf` is automatically truncated to the actual length of the
# document
::setCursorPosition(Inf)
rstudioapi
# select the first 10 even lines in the document
<- lapply(seq(2, by = 2, length.out = 10), function(start) {
ranges ::document_range(
rstudioapic(start, 0),
c(start, Inf)
)
})::setSelectionRanges(ranges) rstudioapi
See the ?"rstudio-documents"
help page for more details.