Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 11 additions & 20 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand All @@ -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)",
Expand Down
51 changes: 51 additions & 0 deletions src/editorRunCommands.ts
Original file line number Diff line number Diff line change
@@ -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<unknown>) {
const selected = async (makeCode: (text: string) => string | Promise<string | undefined>) => {
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),
};
}
11 changes: 2 additions & 9 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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,
Expand Down
48 changes: 0 additions & 48 deletions src/rTerminal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -203,24 +202,6 @@ export async function runSelectionRetainCursor(): Promise<void> {
await runSelectionInTerm(false);
}

export async function runSelectionOrWord(rFunctionName: string[]): Promise<void> {
const text = selection.getWordOrSelection();
if (!text) {
return;
}
const wrappedText = selection.surroundSelection(text, rFunctionName);
await runTextInTerm(wrappedText);
}

export async function runCommandWithSelectionOrWord(rCommand: string): Promise<void> {
const text = selection.getWordOrSelection();
if (!text) {
return;
}
const call = rCommand.replace(/\$\$/g, text);
await runTextInTerm(call);
}

export async function runCommandWithEditorPath(rCommand: string): Promise<void> {
const textEditor = vscode.window.activeTextEditor;
if (!textEditor) {
Expand All @@ -239,35 +220,6 @@ export async function runCommand(rCommand: string): Promise<void> {
await runTextInTerm(rCommand);
}

export async function runFromBeginningToLine(): Promise<void> {
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<void> {
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<string[]>(configuration, 'consoleArgs', 'rterm.option')?.value ?? [
Expand Down
3 changes: 1 addition & 2 deletions src/selection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
26 changes: 26 additions & 0 deletions src/test/suite/selectionWord.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()');
Expand Down
47 changes: 47 additions & 0 deletions src/test/web/webR.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions src/web/extension.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as vscode from 'vscode';
import { createEditorRunCommands } from '../editorRunCommands';
import { getSelection, moveAfterSelection } from '../selection';
import {
createChunkCommands,
Expand Down Expand Up @@ -50,6 +51,7 @@ export async function activate(context: vscode.ExtensionContext): Promise<void>
}
}, runSource);
const commands = {
...createEditorRunCommands(interactive.submit.bind(interactive)),
'r.newFileDocument': async () =>
vscode.window.showTextDocument(
await vscode.workspace.openTextDocument({ language: 'r' }),
Expand Down
1 change: 1 addition & 0 deletions website/docs/.vitepress/config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
Expand Down
2 changes: 1 addition & 1 deletion website/docs/configuration/keyboard-shortcuts.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 2 additions & 0 deletions website/docs/features/language-service.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 2 additions & 0 deletions website/docs/features/r-interactive.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
Loading
Loading