This repository has been archived by the owner on Jul 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
extension.ts
274 lines (249 loc) · 10.8 KB
/
extension.ts
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
import os = require('os');
import path = require('path');
import net = require('net');
import url = require('url');
import { spawn, ChildProcess } from 'child_process';
import { LanguageClient, LanguageClientOptions, StreamInfo, DocumentFilter, ErrorAction, CloseAction, RevealOutputChannelOn } from 'vscode-languageclient/node';
import { ExtensionContext, workspace, Uri, TextDocument, WorkspaceConfiguration, OutputChannel, window, WorkspaceFolder } from 'vscode';
import { getRPath } from './util'
let clients: Map<string, LanguageClient> = new Map();
let initSet: Set<string> = new Set();
async function createClient(config: WorkspaceConfiguration, selector: DocumentFilter[],
cwd: string, workspaceFolder: WorkspaceFolder, outputChannel: OutputChannel): Promise<LanguageClient> {
let client: LanguageClient;
const debug = config.get<boolean>("lsp.debug");
const path = await getRPath(config);
if (debug) {
console.log(`R binary: ${path}`);
}
const use_stdio = config.get<boolean>("lsp.use_stdio");
const env = Object.create(process.env);
const lang = config.get<string>("lsp.lang");
if (lang !== '') {
env.LANG = lang;
} else if (env.LANG == undefined) {
env.LANG = "en_US.UTF-8";
}
if (debug) {
console.log(`LANG: ${env.LANG}`);
}
const options = { cwd: cwd, env: env };
const initArgs: string[] = config.get<string[]>("lsp.args").concat("--quiet", "--slave");
const tcpServerOptions = () => new Promise<ChildProcess | StreamInfo>((resolve, reject) => {
// Use a TCP socket because of problems with blocking STDIO
const server = net.createServer(socket => {
// 'connection' listener
console.log('R process connected');
socket.on('end', () => {
console.log('R process disconnected');
});
socket.on('error', (e) => {
console.log(`R process error: ${e}`);
reject(e);
});
server.close();
resolve({ reader: socket, writer: socket });
});
// Listen on random port
server.listen(0, '127.0.0.1', () => {
const port = (server.address() as net.AddressInfo).port;
let args: string[];
// The server is implemented in R
if (debug) {
args = initArgs.concat(["-e", `languageserver::run(port=${port},debug=TRUE)`]);
} else {
args = initArgs.concat(["-e", `languageserver::run(port=${port})`]);
}
const childProcess = spawn(path, args, options);
client.outputChannel.appendLine(`R Language Server (${childProcess.pid}) started`);
childProcess.stderr.on('data', (chunk: Buffer) => {
client.outputChannel.appendLine(chunk.toString());
});
childProcess.on('exit', (code, signal) => {
client.outputChannel.appendLine(`R Language Server (${childProcess.pid}) exited ` +
(signal ? `from signal ${signal}` : `with exit code ${code}`));
if (code !== 0) {
client.outputChannel.show();
}
client.stop();
});
return childProcess;
});
});
// Options to control the language client
const clientOptions: LanguageClientOptions = {
// Register the server for selected R documents
documentSelector: selector,
uriConverters: {
// VS Code by default %-encodes even the colon after the drive letter
// NodeJS handles it much better
code2Protocol: uri => new url.URL(uri.toString(true)).toString(),
protocol2Code: str => Uri.parse(str)
},
workspaceFolder: workspaceFolder,
outputChannel: outputChannel,
synchronize: {
// Synchronize the setting section 'r' to the server
configurationSection: 'r.lsp',
fileEvents: workspace.createFileSystemWatcher('**/*.{R,r}'),
},
revealOutputChannelOn: RevealOutputChannelOn.Never,
errorHandler: {
error: () => ErrorAction.Shutdown,
closed: () => CloseAction.DoNotRestart,
},
};
// Create the language client and start the client.
if (use_stdio && process.platform != "win32") {
let args: string[];
if (debug) {
args = initArgs.concat(["-e", `languageserver::run(debug=TRUE)`]);
} else {
args = initArgs.concat(["-e", `languageserver::run()`]);
}
client = new LanguageClient('r', 'R Language Server', { command: path, args: args, options: options }, clientOptions);
} else {
client = new LanguageClient('r', 'R Language Server', tcpServerOptions, clientOptions);
}
return client;
}
function checkClient(name: string): boolean {
if (initSet.has(name)) return true;
initSet.add(name);
let client = clients.get(name);
return client && client.needsStop();
}
function getKey(uri: Uri) {
switch (uri.scheme) {
case 'untitled':
return uri.scheme;
case 'vscode-notebook-cell':
return `vscode-notebook:${uri.fsPath}`;
default:
return uri.toString(true);
}
}
export function activate(context: ExtensionContext) {
const config = workspace.getConfiguration('r');
const outputChannel: OutputChannel = window.createOutputChannel('R Language Server');
async function didOpenTextDocument(document: TextDocument) {
if (document.uri.scheme !== 'file' && document.uri.scheme !== 'untitled' && document.uri.scheme !== 'vscode-notebook-cell') {
return;
}
if (document.languageId !== 'r' && document.languageId !== 'rmd') {
return;
}
const folder = workspace.getWorkspaceFolder(document.uri);
// Each notebook uses a server started from parent folder
if (document.uri.scheme === 'vscode-notebook-cell') {
const key = getKey(document.uri);
if (!checkClient(key)) {
console.log(`Start language server for ${document.uri.toString(true)}`);
const documentSelector: DocumentFilter[] = [
{ scheme: 'vscode-notebook-cell', language: 'r', pattern: `${document.uri.fsPath}` },
];
let client = await createClient(config, documentSelector,
path.dirname(document.uri.fsPath), folder, outputChannel);
client.start();
clients.set(key, client);
initSet.delete(key);
}
return;
}
if (folder) {
// Each workspace uses a server started from the workspace folder
const key = getKey(folder.uri);
if (!checkClient(key)) {
console.log(`Start language server for ${document.uri.toString(true)}`);
const pattern = `${folder.uri.fsPath}/**/*`;
const documentSelector: DocumentFilter[] = [
{ scheme: 'file', language: 'r', pattern: pattern },
{ scheme: 'file', language: 'rmd', pattern: pattern },
];
let client = await createClient(config, documentSelector, folder.uri.fsPath, folder, outputChannel);
client.start();
clients.set(key, client);
initSet.delete(key);
}
} else {
// All untitled documents share a server started from home folder
if (document.uri.scheme === 'untitled') {
const key = getKey(document.uri);
if (!checkClient(key)) {
console.log(`Start language server for ${document.uri.toString(true)}`);
const documentSelector: DocumentFilter[] = [
{ scheme: 'untitled', language: 'r' },
{ scheme: 'untitled', language: 'rmd' },
];
let client = await createClient(config, documentSelector, os.homedir(), undefined, outputChannel);
client.start();
clients.set(key, client);
initSet.delete(key);
}
return;
}
// Each file outside workspace uses a server started from parent folder
if (document.uri.scheme === 'file') {
const key = getKey(document.uri);
if (!checkClient(key)) {
console.log(`Start language server for ${document.uri.toString(true)}`);
const documentSelector: DocumentFilter[] = [
{ scheme: 'file', pattern: document.uri.fsPath },
];
let client = await createClient(config, documentSelector,
path.dirname(document.uri.fsPath), undefined, outputChannel);
client.start();
clients.set(key, client);
initSet.delete(key);
}
return;
}
}
}
async function didCloseTextDocument(document: TextDocument) {
if (document.uri.scheme === 'untitled') {
const result = workspace.textDocuments.find((doc) => doc.uri.scheme === 'untitled');
if (result) {
// Stop the language server when all untitled documents are closed.
return;
}
}
if (document.uri.scheme === 'vscode-notebook-cell') {
const result = workspace.textDocuments.find((doc) =>
doc.uri.scheme === document.uri.scheme && doc.uri.fsPath === document.uri.fsPath);
if (result) {
// Stop the language server when all cell documents are closed (notebook closed).
return;
}
}
// Stop the language server when single file outside workspace is closed, or the above cases.
const key = getKey(document.uri);
let client = clients.get(key);
if (client) {
clients.delete(key);
initSet.delete(key);
client.stop();
}
}
workspace.onDidOpenTextDocument(didOpenTextDocument);
workspace.onDidCloseTextDocument(didCloseTextDocument);
workspace.textDocuments.forEach(didOpenTextDocument);
workspace.onDidChangeWorkspaceFolders((event) => {
for (let folder of event.removed) {
const key = getKey(folder.uri);
let client = clients.get(key);
if (client) {
clients.delete(key);
initSet.delete(key);
client.stop()
}
}
});
}
export function deactivate(): Thenable<void> {
let promises: Thenable<void>[] = [];
for (let client of clients.values()) {
promises.push(client.stop());
}
return Promise.all(promises).then(() => undefined);
}