3.6 Emulating rstudioapi functions

The VSCode-R extension is compatible with a subset of RStudio Addins via an {rstudioapi} emulation layer. Nearly all of the document inspection and manipulation API is supported, allowing RStudio add-ins and packages that rely on rstudioapi to function within VS Code.

  • This emulation is achieved by “duck punching” or “monkey patching” the rstudioapi functions within the R session running in VS Code. This means the original rstudioapi functions are replaced with custom implementations that communicate with VS Code instead of RStudio.

  • To enable RStudio Addins, you may need to add options(vsc.rstudioapi = TRUE) to your ~/.Rprofile file. This ensures the rstudioapi emulation is loaded when your R session starts.

    getOption("vsc.rstudioapi") will return TRUE if the emulation is enabled.


Use RStudio Addins from VS Code

How to use your RStudio Addins in VS Code after enabling the emulation:

  • Use the command palette (Ctrl+Shift+P) and type “R: Launch RStudio Addin”.
  • You will see a list of available RStudio add-ins that you can run directly from VS Code.
  • Choose the add-in you want to run, and it will execute in the current R session.

You can also bind a keyboard shortcut to launch the RStudio Addin picker (command id: r.launchAddinPicker):

{
    "key": "ctrl+shift+A",  // launch RStudio Addin
    "command": "r.launchAddinPicker",
    "when": "editorTextFocus && (editorLangId == 'markdown' || editorLangId == 'r' || editorLangId == 'rmd' || editorLangId == 'quarto')"
},

This will allow you to quickly access and run RStudio add-ins without needing to open the command palette each time.


To launch a specific RStudio addin, you can map a direct keybinding to the addin R functions.

  • The function can be found in inst/rstudion/addins.dcf file of the addin-providing-package’s source.
    • Look for the keyword Binding in the file to find the function name.
    • The package name is the repository name of the addin-providing package.

Use example: Here I want to invoke two RStudio addins: shoRtcut::set_new_chapter() and shoRtcut2::set_new_chapter2().

Add the following keybindings to your keybindings.json file:

{
  "description": "Pad line with dashes",
  "key": "ctrl+shift+S",
  "command": "r.runCommand",
  "when": "editorTextFocus && (editorLangId == 'markdown' || editorLangId == 'r' || editorLangId == 'rmd' || editorLangId == 'quarto')",
  "args": "shoRtcut:::set_new_chapter()"
},
{
  "description": "Pad line with equals",
  "key": "ctrl+shift+=",
  "command": "r.runCommand",
  "when": "editorTextFocus && (editorLangId == 'markdown' || editorLangId == 'r' || editorLangId == 'rmd' || editorLangId == 'quarto')",
  "args": "shoRtcut2:::set_new_chapter2()"
},

Now you can use

  • Ctrl+Shift+S to pad a line with dashes, and
  • Ctrl+Shift+= to pad a line with equals.

ref: RStudio addin support in VSCode-R