5  Visual Studio Code

5.1 Using VScode for R development

On Linux Mint, the default R installation directory is not the same as on Ubuntu. I have configured VScode to use the R bin installation directory of Ubuntu. Hence, on Mint, code completion, help viewer are not working. The simple work around is to create a symbolic link?

sudo ln -s /usr/bin/R /usr/local/bin/R

5.2 Show plot externally on a web browser

Use this in .Rprofile inside a project directory or globally.

if (interactive() && Sys.getenv("RSTUDIO") == "") {
  Sys.setenv(TERM_PROGRAM = "vscode")
  if ("httpgd" %in% .packages(all.available = TRUE)) {
    options(vsc.plot = FALSE)
    options(device = function(...) {
      httpgd::hgd(silent = TRUE)
      .vsc.browser(httpgd::hgd_url(history = FALSE), viewer = FALSE)
    })
  }
}


# Use an external browser for displaying html files, such as {gt} and {xaringan}
options(vsc.viewer = FALSE)
# External browser for web apps, such as {shiny}
options(vsc.browser = FALSE)
# View help page in an external browser
options(vsc.helpPanel = FALSE)
# Use original data viewer
options(vsc.view = FALSE)

If you close the web page by accident, it can be reopened using ctrl+alt+p (depending on the chosen keybinding).

{
  "key": "ctrl+alt+p",
  "command": "r.runCommand",
  "when": "editorTextFocus && editorLangId == 'r'",
  "args": ".vsc.browser(httpgd::hgd_url(), viewer = FALSE)"
},
Important

Do not forget to install the httpdg package. Otherwise, plot will be displayed as png in an external window.

5.3 Debugging

Debugging can be done using the VSCode-R-Debugger package.

remotes::install_github("ManuelHentschel/vscDebugger")

This .vscode/launch.json configuration file is placed in the project root directory:

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "R-Debugger",
      "request": "attach",
      "name": "Attach to R process"
    }
  ]
}

Open the R terminal and type:

vscDebugger::.vsc.listenForDAP()

Then, press F5to start the debugger.