Skip to content

Interacting with R terminals

Nathan Kim edited this page Dec 15, 2021 · 10 revisions

Creating R terminal

In VS Code window, press F1 (or Ctrl + Shift + P) and choose "R: Create R terminal" command, then the VS Code terminal will be revealed and an R terminal will be launched.

By default, the official R terminal is launched.

R

We recommend radian as a better alternative.

radian

If the R session watcher is enabled, then it will attach to the R session whenever a new R terminal is created. The status of the session watcher is shown in the status bar like below:

status

Sending code to R terminals

By default, if there is no active R terminal, then a new R terminal will be created before sending code to it. To always send code to the active terminal without creating a new one, turn on r.alwaysUseActiveTerminal in VS Code settings.

The behavior of sending code to the terminal is following:

  • If a range of code is selected, then the selected code will be sent to the terminal.
  • If no code is selected, then an executable range of code will be sent to the terminal and the cursor will move to the next line.

Using multiple R terminals

Each time "R: Create R terminal" is executed, a new R terminal is created. The user could switch between these R terminals, and customize the icon color and the label of each terminal.

R terminals

To make the session watcher attach the R session of the current R terminal, click the status bar item "R: (not attached)" or "R: #PID" if a session is previously attached.

Using self-managed R terminals

Self-managed R terminals could be useful if one needs one or more R sessions to be preserved so that closing the VS Code window does not terminate the R sessions. On Linux and macOS, both screen and tmux could be used to preserve any number of R sessions or any other terminal programs in a customizable layout.

radian in tmux

To make self-managed R sessions behave like those created by "R: Create R terminal", the following code should be added to ~/.Rprofile:

if (interactive() && Sys.getenv("RSTUDIO") == "") {
  Sys.setenv(TERM_PROGRAM = "vscode")
  source(file.path(Sys.getenv(
    if (.Platform$OS.type == "windows") "USERPROFILE" else "HOME"
  ), ".vscode-R", "init.R"))
}

Then starting an R terminal anywhere will request the session watcher to attach the R session.