Skip to contents

An editor with its own R runtime can use languageserver::run_embedded() to analyze open files and notebook cells. In webR, the host keeps a dedicated analysis worker so editor requests can be served separately from the user’s code. For an editor that launches a local R process, use the workspace server described in the editor setup guide.

Follow a definition from an unsaved buffer

Try this exchange in an R session with languageserver installed. It demonstrates what an editor host sends its analysis worker. The document has an untitled: URI and the only copy of its source is the text in the message.

dispatch <- languageserver::run_embedded()

send <- function(method, params = NULL, id = NULL) {
  packet <- list(jsonrpc = "2.0", method = method)
  if (!is.null(params)) packet$params <- params
  if (!is.null(id)) packet$id <- id
  wire <- jsonlite::toJSON(packet, auto_unbox = TRUE)
  lapply(dispatch(as.character(wire)), jsonlite::fromJSON, simplifyVector = FALSE)
}

init <- send("initialize", list(capabilities = list(
  workspace = list(workspaceFolders = TRUE)
)), id = 1L)
init[[1]]$result$capabilities$definitionProvider  # TRUE
dispatch('{"jsonrpc":"2.0","method":"initialized","params":{}}')

uri <- "untitled:scores.R"
send("textDocument/didOpen", list(textDocument = list(
  uri = uri, languageId = "r", version = 1L,
  text = "double_score <- function(x) x * 2\ndouble_score(8)"
)))
reply <- send("textDocument/definition", list(
  textDocument = list(uri = uri),
  position = list(line = 1L, character = 2L)
), id = 2L)
reply[[1]]$result$uri               # "untitled:scores.R"
reply[[1]]$result$range$start$line  # 0 (the declaration)

send("shutdown", id = 3L)
send("exit")

Keep one dispatcher per language client. Pass each complete JSON-RPC string without transport headers, in arrival order, and forward every returned string to the client. Most notifications return character(0). A returned string can also be a server request, such as a diagnostics refresh. If the client replies, pass its response back to the same dispatcher. During editing, send increasing document versions and UTF-16 ranges with incremental changes. Send didClose when the buffer closes. Dispatcher API

Choose the server for an editor feature

What the reader wants Embedded worker Workspace server (run())
Complete a call and inspect its arguments Completion, completion details, hover, and Signature Help from open text and available package metadata Also discovers local definitions through indexed package files and source dependencies
Follow a name or find its uses Go to Definition and Find References across open documents in the owning workspace folder Can find definitions and references in eligible closed workspace files
Explore the structure of a file Outline, occurrence highlights, folding, and full-document semantic highlighting Also offers selection ranges, token range and delta requests, workspace symbols, and call and type hierarchies
Diagnose code Pull syntax diagnostics for the requested buffer and optional lintr infix-spacing findings Publishes findings using the selected diagnostics backend and project rules
Format or refactor Full-document formatting when styler is installed, and Rename within the scope described below Supports code actions and additional formatting modes according to the selected backend

Use the capabilities returned during initialization when enabling editor commands. Generated package definitions require a client that supports workspace text document content. The client retrieves the generated text using the URI in the definition result and opens it in a separate, read-only scope. Full provider index

Understand notebook scope and rename

The host supplies workspace folders at initialization and updates them when folders change. VS Code notebook cell URIs are associated with their notebook’s owning workspace folder, so a definition in an open sibling R script can be found from the cell. Moving a buffer between folder scopes preserves unsaved text. Relative path completion inside source() and sys.source() uses open document URIs. Go to Definition on a quoted file path never searches the worker’s filesystem.

A function-body local variable can be renamed within its lexical scope. A project-level binding or function parameter may have callers in closed files. In that case the client must support annotated, versioned workspace edits and ask the user to confirm Rename in open documents only. A client that cannot confirm that edit receives a request error. A session with no workspace folders and only untitled buffers can rename across those scratch buffers.

Request diagnostics in a notebook

Request textDocument/diagnostic for the open document. For an R Markdown or Quarto buffer, the server checks each executable R chunk separately and returns positions in the original document. A broken chunk can report a syntax error while a valid sibling still reports a spacing issue. Pass the last report’s resultId as previousResultId on the next request to allow an unchanged report.

The embedded server honors diagnostics and diagnostics_backend. The lintr backend checks infix spacing when installed, using built-in rules independent of project lint files. Other backend selections give syntax diagnostics. A client advertising diagnostics refresh support can receive workspace/diagnostic/refresh when the effective configuration changes. Embedded formatting uses styler for the whole document and can format valid R chunks when a sibling chunk cannot be formatted.

Match a separate execution session’s packages

When the analysis worker and the execution session have different libraries, pass a zero-argument package_context function when creating the dispatcher. Have the host make compatible package files available on the analysis runtime’s .libPaths(). The callback returns the latest package snapshot when the server handles a provider request.

snapshot <- list(
  installed = c("dplyr", "stats", "base"),
  attached = c("dplyr", "stats", "base"),
  unavailable = "dplyr",
  revision = 1L
)
dispatch <- languageserver::run_embedded(package_context = function() snapshot)

Here the execution session searches dplyr before stats, but the analysis worker cannot inspect dplyr. Its package name can still complete in library(). For the unqualified call filter(), the server can fall through to stats::filter. Completion for members of dplyr:: needs inspectable dplyr metadata. Include every attached package in search order, including unavailable ones. Returning NULL uses the analysis runtime’s own package library.

Change revision when the worker should discard package caches even though the names and attachment order are the same. If the host replaces or removes a package whose namespace or DLL was already loaded in the analysis runtime, start a fresh worker and dispatcher, then replay initialization and the current open documents.