-
Notifications
You must be signed in to change notification settings - Fork 31.5k
/
Copy pathcssServerMain.ts
393 lines (345 loc) · 14.2 KB
/
cssServerMain.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
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import {
createConnection, IConnection, TextDocuments, InitializeParams, InitializeResult, ServerCapabilities, ConfigurationRequest, WorkspaceFolder
} from 'vscode-languageserver';
import { URI } from 'vscode-uri';
import { TextDocument, CompletionList, Position } from 'vscode-languageserver-types';
import { stat as fsStat } from 'fs';
import { getCSSLanguageService, getSCSSLanguageService, getLESSLanguageService, LanguageSettings, LanguageService, Stylesheet, FileSystemProvider, FileType } from 'vscode-css-languageservice';
import { getLanguageModelCache } from './languageModelCache';
import { getPathCompletionParticipant } from './pathCompletion';
import { formatError, runSafe, runSafeAsync } from './utils/runner';
import { getDocumentContext } from './utils/documentContext';
import { getDataProviders } from './customData';
export interface Settings {
css: LanguageSettings;
less: LanguageSettings;
scss: LanguageSettings;
}
// Create a connection for the server.
const connection: IConnection = createConnection();
console.log = connection.console.log.bind(connection.console);
console.error = connection.console.error.bind(connection.console);
process.on('unhandledRejection', (e: any) => {
connection.console.error(formatError(`Unhandled exception`, e));
});
// Create a text document manager.
const documents: TextDocuments = new TextDocuments();
// Make the text document manager listen on the connection
// for open, change and close text document events
documents.listen(connection);
const stylesheets = getLanguageModelCache<Stylesheet>(10, 60, document => getLanguageService(document).parseStylesheet(document));
documents.onDidClose(e => {
stylesheets.onDocumentRemoved(e.document);
});
connection.onShutdown(() => {
stylesheets.dispose();
});
let scopedSettingsSupport = false;
let foldingRangeLimit = Number.MAX_VALUE;
let workspaceFolders: WorkspaceFolder[];
const languageServices: { [id: string]: LanguageService } = {};
const fileSystemProvider: FileSystemProvider = {
stat(documentUri: string) {
const filePath = URI.parse(documentUri).fsPath;
return new Promise((c, e) => {
fsStat(filePath, (err, stats) => {
if (err) {
if (err.code === 'ENOENT') {
return c({
type: FileType.Unknown,
ctime: -1,
mtime: -1,
size: -1
});
} else {
return e(err);
}
}
let type = FileType.Unknown;
if (stats.isFile()) {
type = FileType.File;
} else if (stats.isDirectory) {
type = FileType.Directory;
} else if (stats.isSymbolicLink) {
type = FileType.SymbolicLink;
}
c({
type,
ctime: stats.ctime.getTime(),
mtime: stats.mtime.getTime(),
size: stats.size
});
});
});
}
};
// After the server has started the client sends an initialize request. The server receives
// in the passed params the rootPath of the workspace plus the client capabilities.
connection.onInitialize((params: InitializeParams): InitializeResult => {
workspaceFolders = (<any>params).workspaceFolders;
if (!Array.isArray(workspaceFolders)) {
workspaceFolders = [];
if (params.rootPath) {
workspaceFolders.push({ name: '', uri: URI.file(params.rootPath).toString() });
}
}
const dataPaths: string[] = params.initializationOptions.dataPaths || [];
const customDataProviders = getDataProviders(dataPaths);
function getClientCapability<T>(name: string, def: T) {
const keys = name.split('.');
let c: any = params.capabilities;
for (let i = 0; c && i < keys.length; i++) {
if (!c.hasOwnProperty(keys[i])) {
return def;
}
c = c[keys[i]];
}
return c;
}
const snippetSupport = !!getClientCapability('textDocument.completion.completionItem.snippetSupport', false);
scopedSettingsSupport = !!getClientCapability('workspace.configuration', false);
foldingRangeLimit = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE);
languageServices.css = getCSSLanguageService({ customDataProviders, fileSystemProvider, clientCapabilities: params.capabilities });
languageServices.scss = getSCSSLanguageService({ customDataProviders, fileSystemProvider, clientCapabilities: params.capabilities });
languageServices.less = getLESSLanguageService({ customDataProviders, fileSystemProvider, clientCapabilities: params.capabilities });
const capabilities: ServerCapabilities = {
// Tell the client that the server works in FULL text document sync mode
textDocumentSync: documents.syncKind,
completionProvider: snippetSupport ? { resolveProvider: false, triggerCharacters: ['/', '-'] } : undefined,
hoverProvider: true,
documentSymbolProvider: true,
referencesProvider: true,
definitionProvider: true,
documentHighlightProvider: true,
documentLinkProvider: {
resolveProvider: false
},
codeActionProvider: true,
renameProvider: true,
colorProvider: {},
foldingRangeProvider: true,
selectionRangeProvider: true
};
return { capabilities };
});
function getLanguageService(document: TextDocument) {
let service = languageServices[document.languageId];
if (!service) {
connection.console.log('Document type is ' + document.languageId + ', using css instead.');
service = languageServices['css'];
}
return service;
}
let documentSettings: { [key: string]: Thenable<LanguageSettings | undefined> } = {};
// remove document settings on close
documents.onDidClose(e => {
delete documentSettings[e.document.uri];
});
function getDocumentSettings(textDocument: TextDocument): Thenable<LanguageSettings | undefined> {
if (scopedSettingsSupport) {
let promise = documentSettings[textDocument.uri];
if (!promise) {
const configRequestParam = { items: [{ scopeUri: textDocument.uri, section: textDocument.languageId }] };
promise = connection.sendRequest(ConfigurationRequest.type, configRequestParam).then(s => s[0]);
documentSettings[textDocument.uri] = promise;
}
return promise;
}
return Promise.resolve(undefined);
}
// The settings have changed. Is send on server activation as well.
connection.onDidChangeConfiguration(change => {
updateConfiguration(<Settings>change.settings);
});
function updateConfiguration(settings: Settings) {
for (const languageId in languageServices) {
languageServices[languageId].configure((settings as any)[languageId]);
}
// reset all document settings
documentSettings = {};
// Revalidate any open text documents
documents.all().forEach(triggerValidation);
}
const pendingValidationRequests: { [uri: string]: NodeJS.Timer } = {};
const validationDelayMs = 500;
// The content of a text document has changed. This event is emitted
// when the text document first opened or when its content has changed.
documents.onDidChangeContent(change => {
triggerValidation(change.document);
});
// a document has closed: clear all diagnostics
documents.onDidClose(event => {
cleanPendingValidation(event.document);
connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] });
});
function cleanPendingValidation(textDocument: TextDocument): void {
const request = pendingValidationRequests[textDocument.uri];
if (request) {
clearTimeout(request);
delete pendingValidationRequests[textDocument.uri];
}
}
function triggerValidation(textDocument: TextDocument): void {
cleanPendingValidation(textDocument);
pendingValidationRequests[textDocument.uri] = setTimeout(() => {
delete pendingValidationRequests[textDocument.uri];
validateTextDocument(textDocument);
}, validationDelayMs);
}
function validateTextDocument(textDocument: TextDocument): void {
const settingsPromise = getDocumentSettings(textDocument);
settingsPromise.then(settings => {
const stylesheet = stylesheets.get(textDocument);
const diagnostics = getLanguageService(textDocument).doValidation(textDocument, stylesheet, settings);
// Send the computed diagnostics to VSCode.
connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
}, e => {
connection.console.error(formatError(`Error while validating ${textDocument.uri}`, e));
});
}
connection.onCompletion((textDocumentPosition, token) => {
return runSafe(() => {
const document = documents.get(textDocumentPosition.textDocument.uri);
if (!document) {
return null;
}
const cssLS = getLanguageService(document);
const pathCompletionList: CompletionList = {
isIncomplete: false,
items: []
};
cssLS.setCompletionParticipants([getPathCompletionParticipant(document, workspaceFolders, pathCompletionList)]);
const result = cssLS.doComplete(document, textDocumentPosition.position, stylesheets.get(document));
return {
isIncomplete: pathCompletionList.isIncomplete,
items: [...pathCompletionList.items, ...result.items]
};
}, null, `Error while computing completions for ${textDocumentPosition.textDocument.uri}`, token);
});
connection.onHover((textDocumentPosition, token) => {
return runSafe(() => {
const document = documents.get(textDocumentPosition.textDocument.uri);
if (document) {
const styleSheet = stylesheets.get(document);
return getLanguageService(document).doHover(document, textDocumentPosition.position, styleSheet);
}
return null;
}, null, `Error while computing hover for ${textDocumentPosition.textDocument.uri}`, token);
});
connection.onDocumentSymbol((documentSymbolParams, token) => {
return runSafe(() => {
const document = documents.get(documentSymbolParams.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentSymbols(document, stylesheet);
}
return [];
}, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`, token);
});
connection.onDefinition((documentDefinitionParams, token) => {
return runSafe(() => {
const document = documents.get(documentDefinitionParams.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDefinition(document, documentDefinitionParams.position, stylesheet);
}
return null;
}, null, `Error while computing definitions for ${documentDefinitionParams.textDocument.uri}`, token);
});
connection.onDocumentHighlight((documentHighlightParams, token) => {
return runSafe(() => {
const document = documents.get(documentHighlightParams.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentHighlights(document, documentHighlightParams.position, stylesheet);
}
return [];
}, [], `Error while computing document highlights for ${documentHighlightParams.textDocument.uri}`, token);
});
connection.onDocumentLinks(async (documentLinkParams, token) => {
return runSafeAsync(async () => {
const document = documents.get(documentLinkParams.textDocument.uri);
if (document) {
const documentContext = getDocumentContext(document.uri, workspaceFolders);
const stylesheet = stylesheets.get(document);
return await getLanguageService(document).findDocumentLinks2(document, stylesheet, documentContext);
}
return [];
}, [], `Error while computing document links for ${documentLinkParams.textDocument.uri}`, token);
});
connection.onReferences((referenceParams, token) => {
return runSafe(() => {
const document = documents.get(referenceParams.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findReferences(document, referenceParams.position, stylesheet);
}
return [];
}, [], `Error while computing references for ${referenceParams.textDocument.uri}`, token);
});
connection.onCodeAction((codeActionParams, token) => {
return runSafe(() => {
const document = documents.get(codeActionParams.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).doCodeActions(document, codeActionParams.range, codeActionParams.context, stylesheet);
}
return [];
}, [], `Error while computing code actions for ${codeActionParams.textDocument.uri}`, token);
});
connection.onDocumentColor((params, token) => {
return runSafe(() => {
const document = documents.get(params.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentColors(document, stylesheet);
}
return [];
}, [], `Error while computing document colors for ${params.textDocument.uri}`, token);
});
connection.onColorPresentation((params, token) => {
return runSafe(() => {
const document = documents.get(params.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).getColorPresentations(document, stylesheet, params.color, params.range);
}
return [];
}, [], `Error while computing color presentations for ${params.textDocument.uri}`, token);
});
connection.onRenameRequest((renameParameters, token) => {
return runSafe(() => {
const document = documents.get(renameParameters.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).doRename(document, renameParameters.position, renameParameters.newName, stylesheet);
}
return null;
}, null, `Error while computing renames for ${renameParameters.textDocument.uri}`, token);
});
connection.onFoldingRanges((params, token) => {
return runSafe(() => {
const document = documents.get(params.textDocument.uri);
if (document) {
return getLanguageService(document).getFoldingRanges(document, { rangeLimit: foldingRangeLimit });
}
return null;
}, null, `Error while computing folding ranges for ${params.textDocument.uri}`, token);
});
connection.onSelectionRanges((params, token) => {
return runSafe(() => {
const document = documents.get(params.textDocument.uri);
const positions: Position[] = params.positions;
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).getSelectionRanges(document, positions, stylesheet);
}
return [];
}, [], `Error while computing selection ranges for ${params.textDocument.uri}`, token);
});
// Listen on the connection
connection.listen();