diff --git a/package.json b/package.json index c41e05b39..2c0476c4c 100644 --- a/package.json +++ b/package.json @@ -348,38 +348,32 @@ { "title": "Show number of rows for selected object", "category": "R", - "command": "r.nrow", - "enablement": "!r.webExtension" + "command": "r.nrow" }, { "title": "Show length for a selected object", "category": "R", - "command": "r.length", - "enablement": "!r.webExtension" + "command": "r.length" }, { "title": "Show first part of a selected object", "category": "R", - "command": "r.head", - "enablement": "!r.webExtension" + "command": "r.head" }, { "title": "Show first part of a selected object (transposed)", "category": "R", - "command": "r.thead", - "enablement": "!r.webExtension" + "command": "r.thead" }, { "title": "Show names for a selected object", "category": "R", - "command": "r.names", - "enablement": "!r.webExtension" + "command": "r.names" }, { "title": "View selected object", "category": "R", - "command": "r.view", - "enablement": "!r.webExtension" + "command": "r.view" }, { "title": "Create gitignore", @@ -466,10 +460,9 @@ "enablement": "!r.webExtension" }, { - "title": "Run Command With Selection or Word in Terminal", + "title": "Run Command With Selection or Word", "category": "R", - "command": "r.runCommandWithSelectionOrWord", - "enablement": "!r.webExtension" + "command": "r.runCommandWithSelectionOrWord" }, { "title": "Run Command With Editor Path in Terminal", @@ -478,21 +471,19 @@ "enablement": "!r.webExtension" }, { - "title": "Run Command in Terminal", + "title": "Run Command", "category": "R", "command": "r.runCommand" }, { "title": "Run from Beginning to Line", "category": "R", - "command": "r.runFromBeginningToLine", - "enablement": "!r.webExtension" + "command": "r.runFromBeginningToLine" }, { "title": "Run from Line to End", "category": "R", - "command": "r.runFromLineToEnd", - "enablement": "!r.webExtension" + "command": "r.runFromLineToEnd" }, { "title": "Run Selection/Line (Retain Cursor)", diff --git a/src/editorRunCommands.ts b/src/editorRunCommands.ts new file mode 100644 index 000000000..12106d7b0 --- /dev/null +++ b/src/editorRunCommands.ts @@ -0,0 +1,51 @@ +import { Range, window, type Uri } from 'vscode'; +import { getWordOrSelection, surroundSelection } from './selection'; + +/** Source commands shared by terminal, desktop Interactive and browser execution. */ +export function createEditorRunCommands(submit: (code: string, source: Uri) => Promise) { + const selected = async (makeCode: (text: string) => string | Promise) => { + const editor = window.activeTextEditor; + const text = getWordOrSelection(editor); + if (editor && text) { + const code = await makeCode(text); + if (code !== undefined) { + await submit(code, editor.document.uri); + } + } + }; + const call = (...functions: string[]) => selected((text) => surroundSelection(text, functions)); + const runExtent = async (fromBeginning: boolean) => { + const editor = window.activeTextEditor; + if (!editor) { + return; + } + const { document, selection } = editor; + const first = fromBeginning ? 0 : selection.start.line; + const last = fromBeginning ? selection.end.line : document.lineCount - 1; + const range = new Range( + document.lineAt(first).range.start, + document.lineAt(last).range.end, + ); + await submit(document.getText(range), document.uri); + }; + return { + 'r.nrow': () => call('nrow'), + 'r.length': () => call('length'), + 'r.head': () => call('head'), + 'r.thead': () => call('t', 'head'), + 'r.names': () => call('names'), + 'r.view': () => call('View'), + 'r.runCommandWithSelectionOrWord': (template?: string) => + selected(async (text) => { + const expression = + template ?? + (await window.showInputBox({ + title: 'Run R Command With Selection or Word', + prompt: 'Use $$ for the selected R expression.', + })); + return expression?.replace(/\$\$/g, () => text); + }), + 'r.runFromBeginningToLine': () => runExtent(true), + 'r.runFromLineToEnd': () => runExtent(false), + }; +} diff --git a/src/extension.ts b/src/extension.ts index adad7aab1..196a9b17a 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -2,6 +2,7 @@ // interfaces, functions, etc. provided by vscode import { WebRSessionFiles } from './webr/sessionFiles'; +import { createEditorRunCommands } from './editorRunCommands'; import * as vscode from 'vscode'; import * as os from 'os'; import path = require('path'); @@ -98,19 +99,11 @@ export async function activate( 'r.createRTerm': rTerminal.createRTerm, // run code from editor in terminal - 'r.nrow': () => rTerminal.runSelectionOrWord(['nrow']), - 'r.length': () => rTerminal.runSelectionOrWord(['length']), - 'r.head': () => rTerminal.runSelectionOrWord(['head']), - 'r.thead': () => rTerminal.runSelectionOrWord(['t', 'head']), - 'r.names': () => rTerminal.runSelectionOrWord(['names']), - 'r.view': () => rTerminal.runSelectionOrWord(['View']), + ...createEditorRunCommands((code) => rTerminal.runTextInTerm(code)), 'r.runSource': () => rTerminal.runSource(false), 'r.runSelection': (code?: string) => code ? rTerminal.runTextInTerm(code) : rTerminal.runSelection(), - 'r.runFromLineToEnd': rTerminal.runFromLineToEnd, - 'r.runFromBeginningToLine': rTerminal.runFromBeginningToLine, 'r.runSelectionRetainCursor': rTerminal.runSelectionRetainCursor, - 'r.runCommandWithSelectionOrWord': rTerminal.runCommandWithSelectionOrWord, 'r.runCommandWithEditorPath': rTerminal.runCommandWithEditorPath, 'r.runCommand': rTerminal.runCommand, 'r.runSourcewithEcho': rmarkdown.runSourceWithEcho, diff --git a/src/rTerminal.ts b/src/rTerminal.ts index 6b0adfc96..ea4b0fb19 100644 --- a/src/rTerminal.ts +++ b/src/rTerminal.ts @@ -10,7 +10,6 @@ import * as vscode from 'vscode'; import { extensionContext, globalPlotManager } from './extension'; import * as util from './util'; -import * as selection from './selection'; import { getSelection, moveAfterSelection } from './selection'; import { cleanupTerminalBinding, @@ -203,24 +202,6 @@ export async function runSelectionRetainCursor(): Promise { await runSelectionInTerm(false); } -export async function runSelectionOrWord(rFunctionName: string[]): Promise { - const text = selection.getWordOrSelection(); - if (!text) { - return; - } - const wrappedText = selection.surroundSelection(text, rFunctionName); - await runTextInTerm(wrappedText); -} - -export async function runCommandWithSelectionOrWord(rCommand: string): Promise { - const text = selection.getWordOrSelection(); - if (!text) { - return; - } - const call = rCommand.replace(/\$\$/g, text); - await runTextInTerm(call); -} - export async function runCommandWithEditorPath(rCommand: string): Promise { const textEditor = vscode.window.activeTextEditor; if (!textEditor) { @@ -239,35 +220,6 @@ export async function runCommand(rCommand: string): Promise { await runTextInTerm(rCommand); } -export async function runFromBeginningToLine(): Promise { - const textEditor = vscode.window.activeTextEditor; - if (!textEditor) { - return; - } - const endLine = textEditor.selection.end.line; - const charactersOnLine = textEditor.document.lineAt(endLine).text.length; - const endPos = new vscode.Position(endLine, charactersOnLine); - const range = new vscode.Range(new vscode.Position(0, 0), endPos); - const text = textEditor.document.getText(range); - if (text === undefined) { - return; - } - await runTextInTerm(text); -} - -export async function runFromLineToEnd(): Promise { - const textEditor = vscode.window.activeTextEditor; - if (!textEditor) { - return; - } - const startLine = textEditor.selection.start.line; - const startPos = new vscode.Position(startLine, 0); - const endLine = textEditor.document.lineCount; - const range = new vscode.Range(startPos, new vscode.Position(endLine, 0)); - const text = textEditor.document.getText(range); - await runTextInTerm(text); -} - function getConsoleArgs(configuration: vscode.WorkspaceConfiguration): string[] { return ( getMigratedSetting(configuration, 'consoleArgs', 'rterm.option')?.value ?? [ diff --git a/src/selection.ts b/src/selection.ts index 15ec51ef7..3bff2aede 100644 --- a/src/selection.ts +++ b/src/selection.ts @@ -4,8 +4,7 @@ import { commands, Position, Range, TextEditor, window, workspace } from 'vscode import { LineCache } from './lineCache'; -export function getWordOrSelection(): string | undefined { - const textEditor = window.activeTextEditor; +export function getWordOrSelection(textEditor = window.activeTextEditor): string | undefined { if (!textEditor) { return; } diff --git a/src/test/suite/selectionWord.test.ts b/src/test/suite/selectionWord.test.ts index 56113f3a7..0af35c4bc 100644 --- a/src/test/suite/selectionWord.test.ts +++ b/src/test/suite/selectionWord.test.ts @@ -2,8 +2,34 @@ import * as assert from 'assert'; import * as sinon from 'sinon'; import * as vscode from 'vscode'; import { getWordOrSelection } from '../../selection'; +import { createEditorRunCommands } from '../../editorRunCommands'; suite('Word execution selection', () => { + test('a command template uses the captured source URI and literal selection', async () => { + const sandbox = sinon.createSandbox(); + const uri = vscode.Uri.parse('vscode-r-webr:/project.R'); + sandbox.stub(vscode.window, 'activeTextEditor').value({ + selection: new vscode.Selection(0, 0, 0, 4), + document: { uri, getText: () => '"$&"' }, + }); + const prompt = sandbox.stub(vscode.window, 'showInputBox'); + const submit = sandbox.stub().resolves(); + try { + const run = createEditorRunCommands(submit)['r.runCommandWithSelectionOrWord']; + prompt.onFirstCall().resolves('c($$, $$)'); + prompt.onSecondCall().resolves(undefined); + await run(); + sinon.assert.calledOnceWithExactly(submit, 'c("$&", "$&")', uri); + await run(); + sinon.assert.calledOnce(submit); + await run('print($$)'); + sinon.assert.calledWithExactly(submit, 'print("$&")', uri); + sinon.assert.calledTwice(prompt); + } finally { + sandbox.restore(); + } + }); + test('a cursor outside a word never selects the entire document', () => { const sandbox = sinon.createSandbox(); const getText = sandbox.stub().returns('dangerous_full_document()'); diff --git a/src/test/web/webR.cjs b/src/test/web/webR.cjs index 6e642f279..0e25d824b 100644 --- a/src/test/web/webR.cjs +++ b/src/test/web/webR.cjs @@ -57,6 +57,51 @@ const command = (id, ...args) => vscode.commands.executeCommand(id, ...args); const items = cell => cell.outputs.flatMap(out => out.items); const stdout = cell => items(cell).filter(i => i.mime.endsWith('.stdout')).map(i => new TextDecoder().decode(i.data)).join(''); +async function editorRunCommands(notebook) { + const source = await editor('left <- 10L\nmiddle <- left + 1L\nright <- middle + 1L\nrows_for_test\n'); + const declared = vscode.extensions.getExtension('REditorSupport.r').packageJSON.contributes.commands; + const run = async (id, ...args) => { + const descriptor = declared.find(c => c.command === id); + assert(descriptor && !descriptor.enablement?.includes('!r.webExtension'), id + ' is disabled in web VS Code.'); + const index = notebook.cellCount; + await vscode.window.showTextDocument(source.document, source.viewColumn, false); + await command(id, ...args); + await until(() => typeof notebook.cellAt(index)?.executionSummary?.success === 'boolean', + id + ' did not finish.'); + const cell = notebook.cellAt(index); + assert(cell.executionSummary.success, id + ' failed: ' + + items(cell).map(i => new TextDecoder().decode(i.data)).join(' ')); + return cell; + }; + source.selection = new vscode.Selection(1, 8, 1, 11); + let cell = await run('r.runFromBeginningToLine'); + assert(cell.document.getText() === 'left <- 10L\nmiddle <- left + 1L', 'Run from beginning should include the entire end line.'); + await command('r.runCommand', 'rows_for_test <- data.frame(a = 1:7, b = 11:17)'); + cell = await run('r.runFromLineToEnd'); + assert(cell.document.getText() === 'middle <- left + 1L\nright <- middle + 1L\nrows_for_test\n', 'Run to end should start at column zero of the selected line.'); + source.selection = new vscode.Selection(3, 4, 3, 4); + for (const [id, expression] of [ + ['r.nrow','nrow(rows_for_test)'], ['r.length','length(rows_for_test)'], + ['r.names','names(rows_for_test)'], ['r.head','head(rows_for_test)'], + ['r.thead','t(head(rows_for_test))'], ['r.view','View(rows_for_test)'], + ]) { + cell = await run(id); + assert(cell.document.getText() === expression, id + ' used the wrong word.'); + if (id === 'r.nrow') {assert(stdout(cell).includes('7'), 'Expected seven rows.');} + if (id === 'r.length') {assert(stdout(cell).includes('2'), 'Expected two columns.');} + if (id === 'r.names') {assert(stdout(cell).includes('"b"'), 'Expected the column names.');} + if (id === 'r.view') { + const preview = items(cell).find(x => x.mime === 'application/vnd.vscode-r.display+json'); + assert(preview && JSON.parse(new TextDecoder().decode(preview.data)).kind === 'table', + 'View should publish a rich table from the selected object.'); + } + } + source.selection = new vscode.Selection(3, 0, 3, 13); + cell = await run('r.runCommandWithSelectionOrWord', 'c(nrow($$), length($$))'); + assert(cell.document.getText() === 'c(nrow(rows_for_test), length(rows_for_test))' && + stdout(cell).includes('7 2'), 'The template should substitute every placeholder.'); +} + async function notebookLanguagePolicy(source, files) { const settings = vscode.workspace.getConfiguration('r'); const previousRuntime = settings.inspect('lsp.runtime')?.globalValue; @@ -373,6 +418,8 @@ exports.run = async () => { const widget = rich(notebook.cellAt(notebook.cellCount - 1)).find(p => p.kind === 'htmlText'); assert(widget?.text.includes('html-widget') && widget.text.includes('plotly'), 'A live Plotly widget should retain its JavaScript and data.'); + await editorRunCommands(notebook); + const savedUri = files.uri('transcript.rnb'); const snapshot = new TextEncoder().encode(JSON.stringify({version:1,metadata:{},cells:[]})); await vscode.workspace.fs.writeFile(savedUri,snapshot); diff --git a/src/web/extension.ts b/src/web/extension.ts index fe1c42c5f..7801d16e5 100644 --- a/src/web/extension.ts +++ b/src/web/extension.ts @@ -1,4 +1,5 @@ import * as vscode from 'vscode'; +import { createEditorRunCommands } from '../editorRunCommands'; import { getSelection, moveAfterSelection } from '../selection'; import { createChunkCommands, @@ -50,6 +51,7 @@ export async function activate(context: vscode.ExtensionContext): Promise } }, runSource); const commands = { + ...createEditorRunCommands(interactive.submit.bind(interactive)), 'r.newFileDocument': async () => vscode.window.showTextDocument( await vscode.workspace.openTextDocument({ language: 'r' }), diff --git a/website/docs/.vitepress/config.mjs b/website/docs/.vitepress/config.mjs index 7f4dfff2a..eb4097f02 100644 --- a/website/docs/.vitepress/config.mjs +++ b/website/docs/.vitepress/config.mjs @@ -74,6 +74,7 @@ export default defineConfig({ { text: 'R Language Service', link: '/features/language-service' }, { text: 'Interacting with R terminals', link: '/features/r-terminals' }, { text: 'R Interactive (experimental)', link: '/features/r-interactive' }, + { text: 'webR (experimental)', link: '/features/webr' }, { text: 'Interactive viewers', link: '/features/interactive-viewers' }, { text: 'Sidebar user interface', link: '/features/sidebar' }, { text: 'Plot viewer', link: '/features/plot-viewer' }, diff --git a/website/docs/configuration/keyboard-shortcuts.md b/website/docs/configuration/keyboard-shortcuts.md index 7147d90c0..8a6b6dfce 100644 --- a/website/docs/configuration/keyboard-shortcuts.md +++ b/website/docs/configuration/keyboard-shortcuts.md @@ -150,7 +150,7 @@ R commands in the terminal: 1. `r.runCommand` to make a keybinding to run any R expression. 2. `r.runCommandWithEditorPath` to create a keybinding for an R expression where the placeholder value `$$` is interpolated with the current file path. -3. `runCommandWithSelectionOrWord` to create a keybinding for an R expression +3. `r.runCommandWithSelectionOrWord` to create a keybinding for an R expression where `$$` is interpolated with the current selection or the current word the cursor is on. diff --git a/website/docs/features/language-service.md b/website/docs/features/language-service.md index 93387ac22..d6fc6fbc2 100644 --- a/website/docs/features/language-service.md +++ b/website/docs/features/language-service.md @@ -1,5 +1,7 @@ # R Language Service +See [webR capabilities](./webr.md) for desktop and browser features. + ## Language server runtime vscode-R’s webR integration is **experimental**. Its implementation and behavior diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index e4e3c66ab..44ed7671b 100644 --- a/website/docs/features/r-interactive.md +++ b/website/docs/features/r-interactive.md @@ -1,5 +1,7 @@ # R Interactive +See [webR capabilities](./webr.md) for desktop and browser features. + R Interactive runs R independently of the VS Code extension host. Each session has its own Interactive window, execution queue, environment, retained transcript, plot service, and private agent. Reloading VS Code, closing a tab, or losing an SSH connection does not terminate R. ::: warning Experimental diff --git a/website/docs/features/webr.md b/website/docs/features/webr.md new file mode 100644 index 000000000..0d0b95779 --- /dev/null +++ b/website/docs/features/webr.md @@ -0,0 +1,48 @@ +# webR capabilities + +::: warning Experimental +vscode-R’s webR integration is experimental on desktop and in VS Code for the Web. +Its implementation and behavior may change substantially between releases. +::: + +webR runs R in a WebAssembly worker and uses packages built for that runtime. +In a trusted desktop or Remote workspace, choose **webR** when creating an +[R Interactive](./r-interactive.md) session. In browser-only VS Code, the R +Interactive notebook runs in the page. webR itself needs no native R or arf executable. A browser connected to a Codespace or +remote VS Code Server can also use the workspace extension and native tools +installed on that server. + +## Editor and execution + +| Feature | Desktop or Remote with webR | Browser-only VS Code | +| --- | --- | --- | +| Source editing | R syntax, snippets, New R Document, Run Source, Run Selection/Line and Retain Cursor. | The same commands work with open buffers, including virtual repository files. | +| Selection commands | View, Head, Transposed Head, Names, Length and Number of Rows use the selection or the word at the cursor. Run from Beginning to Line and Run from Line to End include the current line. | The same commands target the Interactive notebook. Custom keybindings can run R code or substitute the selected text for `$$` with `r.runCommandWithSelectionOrWord`. | +| R Markdown | Navigate, select and run R chunks, including the previous, next, above, below and all-chunks commands. | Chunk navigation, execution and CodeLens are available. The notebook records the submitted code. | +| Language features | `r.lsp.runtime` selects the workspace language server. Interactive inputs and cells use their session's runtime. | Open R and R Markdown buffers support completion, hover, signatures, Outline, folding, highlights, semantic tokens, definitions, references and rename. Cross-file searches cover open buffers in the same workspace. | +| Packages, formatting and diagnostics | Use `install.packages()` with a Wasm binary repository. Interactive inputs, cells and worker-local session files use package information from their owning session; ordinary source files follow workspace language-server policy. | The same package build requirement applies. When files are available to the language worker, it can complete installed namespaces and resolve attached package symbols. It supports syntax diagnostics, an in-process lintr spacing rule and full-document styler formatting. | +| Printed and graphical output | stdout, stderr, errors, warnings, static PNG plots and interactive HTML widgets appear in the transcript. | The same outputs appear in notebook cells. HTML widgets run in an isolated frame. For example, a Plotly chart supports hover and zoom. | +| Object viewers | Evaluate a data frame or plain list for an inline preview. `View()` and the table/list controls open a larger viewer with paging or nested navigation. | The same viewers are available. Live paging and navigation use the R objects in the running session. | +| Interruption and input | Interrupt a running calculation and keep its objects. `readline()` can request an answer in the editor. | The shared-memory channel supports interruption and nested input. On the PostMessage fallback, Interrupt offers to restart the worker, clearing live state. | + +## Files and session lifetime + +- **Desktop and Remote.** The session's initial `/project` directory mounts the selected host project. R can source a helper or write a CSV there directly. **Open webR Session File…** opens project files in the host workspace. Worker-local files such as those in `/tmp` use the owning session and generation. Closing and reconnecting to a supervised session retains its objects and files. Stop or restart ends that runtime. +- **Browser.** The session starts in `/workspace`. **Import Files into webR…** copies selected workspace files into that directory. **Export File from webR…** copies a result to a writable workspace destination. Use **Open webR Session File…** in Session Actions or the session tree to edit a live worker file. Its source commands target the owning notebook. Closing the notebook, reloading the page, or restarting ends access to that generation. +- **History.** Desktop sessions have a durable journal and asset store, session naming and binding, queued-cell cancellation, history search, plot browsing, export and cleanup commands. Browser notebooks support New, Open, Manage, Interrupt, Restart, Stop and Stop All. Save an `.rnb` notebook to retain cells and outputs across reloads. Reopening creates a fresh R environment. + +## Settings and native tools + +| Command or setting family | Scope | +| --- | --- | +| Language service and editor preferences | `r.lsp.enabled`, `r.lsp.runtime`, `r.lsp.diagnostics`, `r.removeLeadingComments` and R Markdown CodeLens settings apply to their corresponding browser features. A browser workspace set to `native` leaves its ordinary source editors without an R server. Bound webR notebook cells and session files still use webR while language features are enabled. Native launch arguments, locale, stdio, package-install prompts, renv library paths and desktop multi-server settings apply to their respective desktop workflows. | +| Interactive management and output | Desktop uses `r.interactive.executionTarget`, supervision, Node path, storage, restore, table presentation, history, journal and asset settings. `r.interactive.arfPath` and native graphics-backend selection apply to arf. Browser limits console output with `r.interactive.maxOutputSizeMiB`. The browser observes `r.session.viewers.viewColumn.view = "Disable"` when R requests a viewer. Native plot-device and terminal timing settings do not control the Wasm plot or console. | +| Terminal, Workspace Viewer and RStudio integration | **Create R Terminal**, external session attachment, arf adoption, the workspace object tree and legacy environment/data-frame previews, object removal, save/load workspace, RStudio addins and VS Code debugger integration require the corresponding native runtime or tools. Executable and console paths, console arguments and send delay, bracketed paste, source encoding/echo/focus, workspace watching, workspace sidebar options, native viewer settings and RStudio API emulation configure those workflows. | +| Help, plots and web apps | Session help such as `?mean` and `file.show()` can open a read-only text snapshot. The native Help Pages tree (search, navigation, favorites, example execution, and package management), its styling and cache settings, jgd/httpgd Plot Viewer (device history, resize, export and style), HTML Viewer history, webview find, and local Shiny/browser commands use the desktop integration. | +| Rendering, package development and project setup | R Markdown templates, knitting/render previews, Pandoc/Quarto, VS Code R tasks, devtools build/check/test/install/document, C/C++ configuration, gitignore and lintr setup commands are desktop workflows. Host-file-path keybindings such as `r.runCommandWithEditorPath` require a path the chosen R runtime can read. | + +The browser integration tests exercise source and selection commands, chunk +execution, file import/export, table and list output, Plotly widgets, open-file +navigation and notebook reopening. See the [language service](./language-service.md), +[Interactive viewers](./interactive-viewers.md), and [keyboard shortcuts](../configuration/keyboard-shortcuts.md) +for usage examples.