R Extension for Visual Studio Code

repository·master·Indexed 22 days ago

https://github.com/reditorsupport/vscode-r

A full-featured IDE experience for the R programming language in VS Code. Features include language services via the languageserver package, R Markdown support, interactive data and plot viewing (with jgd and httpgd), and workspace management. Version 3.0.0-rc.0 introduces the sess package, implementing a modern JSON-RPC 2.0 IPC architecture using WebSockets, Unix domain sockets, and Windows named pipes for improved performance and RStudio API emulation.

Tokens
15.1K
Snippets
50
Records
91
Agent score
77%

What's inside vscode-r

  1. Overview of R extension features

    master

    The R extension provides a comprehensive environment for R development, including:

    • Language Support: R Language Service (completion, signatures, diagnostics, etc.) and R Markdown support (chunk navigation, execution, and preview).
    • Interactive Viewers:
      • Data Viewer: View data.frame or matrix in grid or treeview structures.
      • Plot Viewer: Interactive viewing with jgd or httpgd support.
      • Webpage/Browser Viewers: View htmlwidgets and interactive shiny apps.
    • Workspace Management: Sidebar tools for viewing global variables (Workspace viewer), searching help topics (Help pages viewer), and managing/installing packages.
    • Development Tools: Package development commands (build, test, install, load) via devtools integration and RStudio add-in support.
    • Remote Development: Full support for working via SSH, Containers, or WSL.
  2. What is the `sess` package and why was it introduced?

    master

    Introduced in version 3.0.0-rc, sess is a modern R package that implements a new IPC (Inter-Process Communication) architecture for the extension.

    Key improvements over the legacy file-based IPC:

    • Architecture: Uses an in-memory WebSocket architecture based on JSON-RPC 2.0.
    • Performance: Eliminates the need for OS-level file watchers, resulting in faster and more robust communication.
    • Installation: The extension will automatically prompt you to install the sess package if it is missing when you start an R session.
  3. R-to-Client communication: Notifications and Requests

    master

    The R session can communicate with the client in two ways:

    1. Notifications (notify_client())

    One-way events sent from R to the client that do not require a response. Common notifications include:

    • attach: Sent immediately after connection.
    • dataview, plot_updated, httpgd, help, browser, webview, restart_r, send_to_console.

    2. Requests (request_client())

    Two-way JSON-RPC requests where R waits for a response from the client. This is primarily used for RStudio API emulation, allowing R to control the client's editor and environment.

    Common emulated methods include:

    • rstudioapi/active_editor_context
    • rstudioapi/replace_text_in_current_selection
    • rstudioapi/insert_or_modify_text
    • rstudioapi/show_dialog
    • rstudioapi/navigate_to_file
    • rstudioapi/set_selection_ranges
    • rstudioapi/document_save
    • rstudioapi/get_project_path
    • rstudioapi/document_context
    • rstudioapi/document_save_all
    • rstudioapi/document_new
    • rstudioapi/document_close

    Note on Coordinates: When R sends row/column indices, they are 1-indexed (R-style). The client is responsible for converting these to its internal representation (e.g., 0-indexed) if necessary.

  4. Interact with R help code examples

    master

    In the R help viewer (v2.5.2+), you can interact with code sections:

    • Hover: Highlights code sections.
    • Click: Copies the code to the clipboard.
    • Ctrl+Click (Win/Linux) / Cmd+Click (macOS): Sends the code directly to the R terminal.

    You can customize this behavior using the r.helpPanel.clickCodeExamples setting.

  5. How the R session watcher works

    master

    The R session watcher (introduced in v1.2.0) allows the extension to interact deeply with your R session.

    Key capabilities:

    • Attach Active Terminal: You can attach the extension to an R session via a command or by clicking the status bar item.
    • Auto-attach: If you source init.R in your .Rprofile, starting an R session will automatically notify vscode-R to attach.
    • Global Symbol Hover: Provides hover information for global symbols in the attached session.
    • Plotting: Shows plot files on the fly.
    • WebViews: Uses WebViews to present htmlwidgets, Shiny apps, and data structures (like data.frame or list) when calling View().
  6. How the `sess` protocol works

    master

    The sess protocol is a modern IPC layer designed for R-to-client communication. It relies on two core principles:

    1. JSON-RPC 2.0: All communication uses JSON-RPC 2.0 message formats, supporting Notifications (one-way), Requests (expecting a response), and Responses.
    2. JSON Lines (JSONL) Framing: Messages are delimited by newlines (\n). This allows the receiver to buffer stream chunks and dispatch complete JSON objects safely, even when the stream is fragmented.

    Unlike previous WebSocket-based transports, sess uses UDS/Named Pipes and has removed the authentication token exchange requirement.

  7. Enhance your R experience with recommended software

    master

    To improve the R development experience in VS Code, the following tools are recommended:

    Plotting Backends

    Install one of these for an improved interactive plotting experience:

    • jgd: A lightweight JSON graphics device with native vscode-R integration.
    • httpgd: An SVG-based graphics device served via HTTP and WebSockets.

    Enhanced Consoles

    • arf: A modern R console featuring syntax highlighting, fuzzy history search, multiline editing, and vi/emacs keybindings. It is the successor to radian.

    Debugging

    • VSCode-R-Debugger: A separate VS Code extension required to enable R debugging capabilities.
  8. Migrate from vscode-r-lsp to vscode-R

    master

    As of version 2.1.0, the R language service is integrated directly into vscode-R.

    Migration Steps:

    1. Search for the r-lsp extension in VS Code.
    2. Uninstall the r-lsp extension.
    3. Ensure the R package languageserver is installed in your R environment.
    4. vscode-R will now automatically start the language service.
  9. Attach to an existing R session using init.R

    master

    To work with existing self-managed, persistent R sessions when the extension is upgraded, you must source the init.R file again before attaching. This ensures the session watcher and other extension features are correctly linked to your R process.

    Run the following command in your R terminal:

    source(file.path(Sys.getenv(if (.Platform$OS.type == "windows") "USERPROFILE" else "HOME"), ".vscode-R", "init.R"))
  10. Install and set up the R extension for VS Code

    master

    To use R in Visual Studio Code, follow these steps:

    1. Install R: Ensure R (version >= 3.4.0) is installed on your system. On Windows, it is recommended to write the R path to the registry during installation.
    2. Install the Language Server: In your R terminal, install the languageserver package to enable code completion, diagnostics, and other language service features:
      install.packages("languageserver")
    3. Install the Extension: Search for and install the R extension from the VS Code Extension Marketplace or the Open VSX Registry.
    4. Start Coding: Create an .R file to begin.

    For platform-specific details, refer to the installation wiki pages for Windows, macOS, or Linux.

    install.packages("languageserver")
  11. Connect an R session to a client using `sess::connect()`

    master

    To establish an IPC connection between an R session and a client (like the VS Code R extension), use the sess::connect() function.

    By default, if pipe_path is NULL, the function attempts to resolve the connection path using the following priority:

    1. The SESS_PIPE environment variable.
    2. A session file located at ~/.vscode-R/sessions/{PID}.json (specifically the pipe field).

    Transport mechanisms used:

    • Unix domain sockets (macOS/Linux)
    • Windows named pipes
    sess::connect(
      pipe_path = NULL,      # Character: pipe/socket path. NULL -> SESS_PIPE or session file fallback
      use_rstudioapi = TRUE, # Logical: enable rstudioapi emulation
      use_httpgd = TRUE      # Logical: use httpgd for plotting if available
    )
  12. Manage R Help via the Help Tree View

    master

    The R extension provides a dedicated Help Tree View (rHelpPages) in VS Code to browse, search, and manage R documentation. The tree view is organized into several functional areas:

    • Navigation & Search: Quick access to the R help Home, searching by alias (?), searching by text (??), and opening help for the currently selected text in the editor.
    • Package Management: A section titled "Help Topics by Package" allows you to browse installed packages, filter them, and manage favorites. You can also install new CRAN packages or update existing ones directly from the tree.
    • Local Previews: If you are developing an R package locally, a "Local Preview" node appears, allowing you to browse the documentation of your local package.
    • Maintenance: Options to clear the help cache and restart the help server to ensure documentation is up to date.