forked from REditorSupport/vscode-R
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrTerminal.ts
More file actions
399 lines (360 loc) · 13.9 KB
/
Copy pathrTerminal.ts
File metadata and controls
399 lines (360 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
'use strict';
import * as path from 'path';
import { isDeepStrictEqual } from 'util';
import * as vscode from 'vscode';
import { extensionContext } from './extension';
import * as util from './util';
import * as selection from './selection';
import { getSelection } from './selection';
import { cleanupSession, deferWorkspaceRefresh } from './session';
import { config, delay, getRterm, getCurrentWorkspaceFolder } from './util';
import * as fs from 'fs';
import * as yaml from 'js-yaml';
export let rTerm: vscode.Terminal | undefined = undefined;
let lastParamsRmdPath: string | undefined;
let lastParamsRmdVersion: number | undefined;
const rExprType = new yaml.Type('!r', {
kind: 'scalar',
construct: (data: string) => ({ __rExpr: data }),
});
const RMARKDOWN_SCHEMA = yaml.DEFAULT_SCHEMA.extend([rExprType]);
function valueToR(val: unknown): string {
if (val === null || val === undefined) {
return 'NULL';
}
if (typeof val === 'boolean') {
return val ? 'TRUE' : 'FALSE';
}
if (typeof val === 'number') {
return String(val);
}
if (typeof val === 'string') {
return `"${val.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
}
if (typeof val === 'object' && val !== null && '__rExpr' in (val as Record<string, unknown>)) {
return (val as { __rExpr: string }).__rExpr;
}
if (Array.isArray(val)) {
return `c(${val.map(valueToR).join(', ')})`;
}
const obj = val as Record<string, unknown>;
if ('value' in obj) {
return valueToR(obj['value']);
}
const entries = Object.entries(obj).map(([k, v]) => `${k} = ${valueToR(v)}`);
return `list(${entries.join(', ')})`;
}
export function getRmdParamsCommand(document: vscode.TextDocument): string | undefined {
if (document.languageId !== 'rmd') {
return undefined;
}
const text = document.getText();
const match = text.match(/^---\s*\n([\s\S]*?)\n---/);
if (!match || !/^\s*params\s*:/m.test(match[1])) {
return undefined;
}
const filePath = document.uri.fsPath;
if (filePath === lastParamsRmdPath && document.version === lastParamsRmdVersion) {
return undefined;
}
lastParamsRmdPath = filePath;
lastParamsRmdVersion = document.version;
try {
const frontmatter = yaml.load(match[1], { schema: RMARKDOWN_SCHEMA }) as Record<string, unknown>;
const params = frontmatter?.['params'] as Record<string, unknown> | undefined;
if (!params || typeof params !== 'object') {
return undefined;
}
const entries = Object.entries(params).map(([k, v]) => `${k} = ${valueToR(v)}`);
return `params <- list(${entries.join(', ')})`;
} catch {
return undefined;
}
}
export async function runSource(echo: boolean): Promise<void> {
const wad = vscode.window.activeTextEditor?.document;
if (!wad) {
return;
}
const isSaved = await util.saveDocument(wad);
if (!isSaved) {
return;
}
let rPath: string = util.ToRStringLiteral(wad.fileName, '"');
let encodingParam = util.config().get<string>('source.encoding');
if (encodingParam === undefined) {
return;
}
encodingParam = `encoding = "${encodingParam}"`;
const echoParam = util.config().get<boolean>('source.echo');
rPath = [rPath, encodingParam].join(', ');
if (echoParam) {
echo = true;
}
if (echo) {
rPath = [rPath, 'echo = TRUE'].join(', ');
}
void runTextInTerm(`source(${rPath})`);
}
export async function runSelection(): Promise<void> {
await runSelectionInTerm(true);
}
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) {
return;
}
const wad: vscode.TextDocument = textEditor.document;
const isSaved = await util.saveDocument(wad);
if (isSaved) {
const rPath = util.ToRStringLiteral(wad.fileName, '');
const call = rCommand.replace(/\$\$/g, rPath);
await runTextInTerm(call);
}
}
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);
}
import { getGlobalPipePath, writeSessionFile } from './session';
export async function makeTerminalOptions(): Promise<vscode.TerminalOptions> {
const workspaceFolderPath = getCurrentWorkspaceFolder()?.uri.fsPath;
const termPath = await getRterm();
const shellArgs: string[] = config().get<string[]>('rterm.option')?.map(util.substituteVariables) || [];
const termOptions: vscode.TerminalOptions = {
name: 'R Interactive',
shellPath: termPath,
shellArgs: shellArgs,
cwd: workspaceFolderPath,
};
const newRprofile = extensionContext.asAbsolutePath(path.join('R', 'profile.R'));
if (config().get<boolean>('sessionWatcher')) {
const pipePath = await getGlobalPipePath();
termOptions.env = {
R_PROFILE_USER_OLD: process.env.R_PROFILE_USER,
R_PROFILE_USER: newRprofile,
SESS_PIPE: pipePath,
SESS_RSTUDIOAPI: config().get<boolean>('session.emulateRStudioAPI') ? 'TRUE' : 'FALSE',
SESS_USE_HTTPGD: config().get<boolean>('plot.useHttpgd') ? 'TRUE' : 'FALSE'
};
}
return termOptions;
}
export async function createRTerm(preserveshow?: boolean): Promise<boolean> {
const termOptions = await makeTerminalOptions();
void util.promptToInstallSessPackage(termOptions.cwd);
const termPath = termOptions.shellPath;
if(!termPath){
void vscode.window.showErrorMessage('Could not find R path. Please check r.rterm and r.rpath setting.');
return false;
} else if(!fs.existsSync(termPath)){
void vscode.window.showErrorMessage(`Cannot find R client at ${termPath}. Please check r.rterm setting.`);
return false;
}
rTerm = vscode.window.createTerminal(termOptions);
rTerm.show(preserveshow);
void rTerm.processId.then(async (pid: number | undefined) => {
if (pid) {
const pipePath = await getGlobalPipePath();
await writeSessionFile(pid.toString(), pipePath);
}
});
return true;
}
export async function restartRTerminal(): Promise<void>{
if (typeof rTerm !== 'undefined'){
rTerm.dispose();
deleteTerminal(rTerm);
await createRTerm(true);
}
}
export function deleteTerminal(term: vscode.Terminal): void {
if (isDeepStrictEqual(term, rTerm)) {
rTerm = undefined;
if (config().get<boolean>('sessionWatcher')) {
void term.processId.then((v) => {
if (v) {
void cleanupSession(v.toString());
}
});
}
}
}
export async function chooseTerminal(): Promise<vscode.Terminal | undefined> {
// VSCode Python's extension creates hidden terminal with string 'Deactivate'
// For now ignore terminals with this string
const ignoreTermIdentifier = 'Deactivate';
// Filter out terminals to be ignored
const visibleTerminals = vscode.window.terminals.filter(terminal => {
return !terminal.name.toLowerCase().includes(ignoreTermIdentifier);
});
if (config().get('alwaysUseActiveTerminal')) {
if (visibleTerminals.length < 1) {
void vscode.window.showInformationMessage('There are no open terminals.');
return undefined;
}
return vscode.window.activeTerminal;
}
let msg = '[chooseTerminal] ';
msg += `A. There are ${vscode.window.terminals.length} terminals: `;
for (let i = 0; i < vscode.window.terminals.length; i++){
msg += `Terminal ${i}: ${vscode.window.terminals[i].name} `;
}
const rTermNameOptions = ['R', 'R Interactive'];
const validRTerminals = visibleTerminals.filter(terminal => {
return rTermNameOptions.includes(terminal.name);
});
if (validRTerminals.length > 0) {
// If there is an active terminal that is an R terminal, use it
if (vscode.window.activeTerminal && rTermNameOptions.includes(vscode.window.activeTerminal.name)) {
return vscode.window.activeTerminal;
}
// Otherwise, use last valid R terminal
const rTerminal = validRTerminals[validRTerminals.length - 1];
rTerminal.show(true);
return rTerminal;
} else {
// If no valid R terminals are found, create a new one
console.info(msg);
await createRTerm(true);
await delay(200); // Let RTerm warm up
return rTerm;
}
}
export async function runSelectionInTerm(moveCursor: boolean, useRepl = true): Promise<void> {
const selection = getSelection();
if (!selection) {
return;
}
const textEditor = vscode.window.activeTextEditor;
if (moveCursor && selection.linesDownToMoveCursor > 0) {
if (!textEditor) {
return;
}
const lineCount = textEditor.document.lineCount;
if (selection.linesDownToMoveCursor + textEditor.selection.end.line === lineCount) {
const endPos = new vscode.Position(lineCount, textEditor.document.lineAt(lineCount - 1).text.length);
await textEditor.edit(e => e.insert(endPos, '\n'));
}
await vscode.commands.executeCommand('cursorMove', { to: 'down', value: selection.linesDownToMoveCursor });
await vscode.commands.executeCommand('cursorMove', { to: 'wrappedLineFirstNonWhitespaceCharacter' });
}
if(useRepl && vscode.debug.activeDebugSession?.type === 'R-Debugger'){
await sendRangeToRepl(selection.range);
} else{
const paramsCmd = textEditor ? getRmdParamsCommand(textEditor.document) : undefined;
await runTextInTerm(paramsCmd ? `${paramsCmd}\n${selection.selectedText}` : selection.selectedText);
}
}
export async function runChunksInTerm(chunks: vscode.Range[]): Promise<void> {
const textEditor = vscode.window.activeTextEditor;
if (!textEditor) {
return;
}
const paramsCmd = getRmdParamsCommand(textEditor.document);
const text = chunks
.map((chunk) => textEditor.document.getText(chunk).trim())
.filter((chunk) => chunk.length > 0)
.join('\n');
if (text.length > 0) {
return runTextInTerm(paramsCmd ? `${paramsCmd}\n${text}` : text);
}
}
export async function runTextInTerm(text: string, execute: boolean = true): Promise<void> {
deferWorkspaceRefresh();
const term = await chooseTerminal();
if (term === undefined) {
return;
}
if (config().get<boolean>('bracketedPaste')) {
// Surround with ANSI control characters for bracketed paste mode
text = `\x1b[200~${text}\x1b[201~`;
term.sendText(text, execute);
} else {
const rtermSendDelay: number = config().get('rtermSendDelay') || 8;
const split = text.split('\n');
const last_split = split.length - 1;
for (const [count, line] of split.entries()) {
if (count > 0) {
await delay(rtermSendDelay); // Increase delay if RTerm can't handle speed.
}
// Avoid sending newline on last line
if (count === last_split && !execute) {
term.sendText(line, false);
} else {
term.sendText(line);
}
}
}
setFocus(term);
// Scroll console to see latest output
await vscode.commands.executeCommand('workbench.action.terminal.scrollToBottom');
}
function setFocus(term: vscode.Terminal) {
const focus: string = config().get('source.focus') || 'editor';
if (focus !== 'none') {
term.show(focus !== 'terminal');
}
}
export async function sendRangeToRepl(rng: vscode.Range): Promise<void> {
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const sel0 = editor.selections;
let sel1 = new vscode.Selection(rng.start, rng.end);
while(/^[\r\n]/.exec(editor.document.getText(sel1))){
sel1 = new vscode.Selection(sel1.start.translate(1), sel1.end);
}
while(/\r?\n\r?\n$/.exec(editor.document.getText(sel1))){
sel1 = new vscode.Selection(sel1.start, sel1.end.translate(-1));
}
editor.selections = [sel1];
await vscode.commands.executeCommand('editor.debug.action.selectionToRepl');
editor.selections = sel0;
}