-
Notifications
You must be signed in to change notification settings - Fork 28k
/
completions.ts
627 lines (554 loc) · 20.3 KB
/
completions.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import * as Proto from '../protocol';
import * as PConst from '../protocol.const';
import { ITypeScriptServiceClient } from '../typescriptService';
import API from '../utils/api';
import { applyCodeAction } from '../utils/codeAction';
import { Command, CommandManager } from '../utils/commandManager';
import * as Previewer from '../utils/previewer';
import * as typeConverters from '../utils/typeConverters';
import TypingsStatus from '../utils/typingsStatus';
import FileConfigurationManager from './fileConfigurationManager';
import { memoize } from '../utils/memoize';
const localize = nls.loadMessageBundle();
interface CommitCharactersSettings {
readonly enabled: boolean;
readonly enableDotCompletions: boolean;
readonly enableCallCompletions: boolean;
}
class MyCompletionItem extends vscode.CompletionItem {
public readonly useCodeSnippet: boolean;
constructor(
public readonly position: vscode.Position,
public readonly document: vscode.TextDocument,
line: string,
public readonly tsEntry: Proto.CompletionEntry,
useCodeSnippetsOnMethodSuggest: boolean,
public readonly commitCharactersSettings: CommitCharactersSettings
) {
super(tsEntry.name, MyCompletionItem.convertKind(tsEntry.kind));
if (tsEntry.isRecommended) {
// Make sure isRecommended property always comes first
// https://github.com/Microsoft/vscode/issues/40325
this.sortText = tsEntry.sortText;
this.preselect = true;
} else if (tsEntry.source) {
// De-prioritze auto-imports
// https://github.com/Microsoft/vscode/issues/40311
this.sortText = '\uffff' + tsEntry.sortText;
} else {
this.sortText = tsEntry.sortText;
}
this.position = position;
this.useCodeSnippet = useCodeSnippetsOnMethodSuggest && (this.kind === vscode.CompletionItemKind.Function || this.kind === vscode.CompletionItemKind.Method);
if (tsEntry.replacementSpan) {
this.range = typeConverters.Range.fromTextSpan(tsEntry.replacementSpan);
}
if (tsEntry.insertText) {
this.insertText = tsEntry.insertText;
if (tsEntry.replacementSpan) {
this.range = typeConverters.Range.fromTextSpan(tsEntry.replacementSpan);
if (this.insertText[0] === '[') { // o.x -> o['x']
this.filterText = '.' + this.label;
}
// Make sure we only replace a single line at most
if (!this.range.isSingleLine) {
this.range = new vscode.Range(this.range.start.line, this.range.start.character, this.range.start.line, line.length);
}
}
}
if (tsEntry.kindModifiers && tsEntry.kindModifiers.match(/\boptional\b/)) {
if (!this.insertText) {
this.insertText = this.label;
}
if (!this.filterText) {
this.filterText = this.label;
}
this.label += '?';
}
}
public resolve(): void {
if (!this.range) {
// Try getting longer, prefix based range for completions that span words
const wordRange = this.document.getWordRangeAtPosition(this.position);
const text = this.document.getText(new vscode.Range(this.position.line, Math.max(0, this.position.character - this.label.length), this.position.line, this.position.character)).toLowerCase();
const entryName = this.label.toLowerCase();
for (let i = entryName.length; i >= 0; --i) {
if (text.endsWith(entryName.substr(0, i)) && (!wordRange || wordRange.start.character > this.position.character - i)) {
this.range = new vscode.Range(this.position.line, Math.max(0, this.position.character - i), this.position.line, this.position.character);
break;
}
}
}
}
private static convertKind(kind: string): vscode.CompletionItemKind {
switch (kind) {
case PConst.Kind.primitiveType:
case PConst.Kind.keyword:
return vscode.CompletionItemKind.Keyword;
case PConst.Kind.const:
return vscode.CompletionItemKind.Constant;
case PConst.Kind.let:
case PConst.Kind.variable:
case PConst.Kind.localVariable:
case PConst.Kind.alias:
return vscode.CompletionItemKind.Variable;
case PConst.Kind.memberVariable:
case PConst.Kind.memberGetAccessor:
case PConst.Kind.memberSetAccessor:
return vscode.CompletionItemKind.Field;
case PConst.Kind.function:
return vscode.CompletionItemKind.Function;
case PConst.Kind.memberFunction:
case PConst.Kind.constructSignature:
case PConst.Kind.callSignature:
case PConst.Kind.indexSignature:
return vscode.CompletionItemKind.Method;
case PConst.Kind.enum:
return vscode.CompletionItemKind.Enum;
case PConst.Kind.module:
case PConst.Kind.externalModuleName:
return vscode.CompletionItemKind.Module;
case PConst.Kind.class:
case PConst.Kind.type:
return vscode.CompletionItemKind.Class;
case PConst.Kind.interface:
return vscode.CompletionItemKind.Interface;
case PConst.Kind.warning:
case PConst.Kind.script:
return vscode.CompletionItemKind.File;
case PConst.Kind.directory:
return vscode.CompletionItemKind.Folder;
case PConst.Kind.string:
return vscode.CompletionItemKind.Constant;
}
return vscode.CompletionItemKind.Property;
}
@memoize
public get commitCharacters(): string[] | undefined {
if (!this.commitCharactersSettings.enabled) {
return undefined;
}
const commitCharacters: string[] = [];
switch (this.tsEntry.kind) {
case PConst.Kind.memberGetAccessor:
case PConst.Kind.memberSetAccessor:
case PConst.Kind.constructSignature:
case PConst.Kind.callSignature:
case PConst.Kind.indexSignature:
case PConst.Kind.enum:
case PConst.Kind.interface:
if (this.commitCharactersSettings.enableDotCompletions) {
commitCharacters.push('.');
}
break;
case PConst.Kind.module:
case PConst.Kind.alias:
case PConst.Kind.const:
case PConst.Kind.let:
case PConst.Kind.variable:
case PConst.Kind.localVariable:
case PConst.Kind.memberVariable:
case PConst.Kind.class:
case PConst.Kind.function:
case PConst.Kind.memberFunction:
if (this.commitCharactersSettings.enableDotCompletions) {
commitCharacters.push('.', ',');
}
if (this.commitCharactersSettings.enableCallCompletions) {
commitCharacters.push('(');
}
break;
}
return commitCharacters.length === 0 ? undefined : commitCharacters;
}
}
class ApplyCompletionCodeActionCommand implements Command {
public static readonly ID = '_typescript.applyCompletionCodeAction';
public readonly id = ApplyCompletionCodeActionCommand.ID;
public constructor(
private readonly client: ITypeScriptServiceClient
) { }
public async execute(_file: string, codeActions: Proto.CodeAction[]): Promise<boolean> {
if (codeActions.length === 0) {
return true;
}
if (codeActions.length === 1) {
return applyCodeAction(this.client, codeActions[0]);
}
interface MyQuickPickItem extends vscode.QuickPickItem {
index: number;
}
const selection = await vscode.window.showQuickPick<MyQuickPickItem>(
codeActions.map((action, i): MyQuickPickItem => ({
label: action.description,
description: '',
index: i
})), {
placeHolder: localize('selectCodeAction', 'Select code action to apply')
}
);
if (!selection) {
return false;
}
const action = codeActions[selection.index];
if (!action) {
return false;
}
return applyCodeAction(this.client, action);
}
}
interface CompletionConfiguration {
readonly useCodeSnippetsOnMethodSuggest: boolean;
readonly nameSuggestions: boolean;
readonly quickSuggestionsForPaths: boolean;
readonly autoImportSuggestions: boolean;
}
namespace CompletionConfiguration {
export const useCodeSnippetsOnMethodSuggest = 'useCodeSnippetsOnMethodSuggest';
export const nameSuggestions = 'nameSuggestions';
export const quickSuggestionsForPaths = 'quickSuggestionsForPaths';
export const autoImportSuggestions = 'autoImportSuggestions.enabled';
export function getConfigurationForResource(
resource: vscode.Uri
): CompletionConfiguration {
// TS settings are shared by both JS and TS.
const typeScriptConfig = vscode.workspace.getConfiguration('typescript', resource);
return {
useCodeSnippetsOnMethodSuggest: typeScriptConfig.get<boolean>(CompletionConfiguration.useCodeSnippetsOnMethodSuggest, false),
quickSuggestionsForPaths: typeScriptConfig.get<boolean>(CompletionConfiguration.quickSuggestionsForPaths, true),
autoImportSuggestions: typeScriptConfig.get<boolean>(CompletionConfiguration.autoImportSuggestions, true),
nameSuggestions: vscode.workspace.getConfiguration('javascript', resource).get(CompletionConfiguration.nameSuggestions, true)
};
}
}
class TypeScriptCompletionItemProvider implements vscode.CompletionItemProvider {
public static readonly triggerCharacters = ['.', '"', '\'', '/', '@', '<'];
constructor(
private readonly client: ITypeScriptServiceClient,
private readonly typingsStatus: TypingsStatus,
private readonly fileConfigurationManager: FileConfigurationManager,
commandManager: CommandManager
) {
commandManager.register(new ApplyCompletionCodeActionCommand(this.client));
}
public async provideCompletionItems(
document: vscode.TextDocument,
position: vscode.Position,
token: vscode.CancellationToken,
context: vscode.CompletionContext
): Promise<vscode.CompletionItem[] | null> {
if (this.typingsStatus.isAcquiringTypings) {
return Promise.reject<vscode.CompletionItem[]>({
label: localize(
{ key: 'acquiringTypingsLabel', comment: ['Typings refers to the *.d.ts typings files that power our IntelliSense. It should not be localized'] },
'Acquiring typings...'),
detail: localize(
{ key: 'acquiringTypingsDetail', comment: ['Typings refers to the *.d.ts typings files that power our IntelliSense. It should not be localized'] },
'Acquiring typings definitions for IntelliSense.')
});
}
const file = this.client.toPath(document.uri);
if (!file) {
return null;
}
const line = document.lineAt(position.line);
const completionConfiguration = CompletionConfiguration.getConfigurationForResource(document.uri);
if (!this.shouldTrigger(context, completionConfiguration, line, position)) {
return null;
}
await this.fileConfigurationManager.ensureConfigurationForDocument(document, token);
const args: Proto.CompletionsRequestArgs = {
...typeConverters.Position.toFileLocationRequestArgs(file, position),
includeExternalModuleExports: completionConfiguration.autoImportSuggestions,
includeInsertTextCompletions: true,
triggerCharacter: context.triggerCharacter as Proto.CompletionsTriggerCharacter
};
let enableCommitCharacters = true;
let msg: ReadonlyArray<Proto.CompletionEntry> | undefined = undefined;
try {
if (this.client.apiVersion.gte(API.v300)) {
const { body } = await this.client.execute('completionInfo', args, token);
if (!body) {
return null;
}
enableCommitCharacters = !body.isNewIdentifierLocation;
msg = body.entries;
} else {
const { body } = await this.client.execute('completions', args, token);
if (!body) {
return null;
}
msg = body;
}
} catch {
return null;
}
const enableDotCompletions = this.shouldEnableDotCompletions(document, position);
return msg
.filter(entry => !shouldExcludeCompletionEntry(entry, completionConfiguration))
.map(entry => new MyCompletionItem(position, document, line.text, entry, completionConfiguration.useCodeSnippetsOnMethodSuggest, {
enabled: enableCommitCharacters,
enableDotCompletions,
enableCallCompletions: !completionConfiguration.useCodeSnippetsOnMethodSuggest
}));
}
public async resolveCompletionItem(
item: vscode.CompletionItem,
token: vscode.CancellationToken
): Promise<vscode.CompletionItem | undefined> {
if (!(item instanceof MyCompletionItem)) {
return undefined;
}
const filepath = this.client.toPath(item.document.uri);
if (!filepath) {
return undefined;
}
item.resolve();
const args: Proto.CompletionDetailsRequestArgs = {
...typeConverters.Position.toFileLocationRequestArgs(filepath, item.position),
entryNames: [
item.tsEntry.source ? { name: item.tsEntry.name, source: item.tsEntry.source } : item.tsEntry.name
]
};
let response: Proto.CompletionDetailsResponse;
try {
response = await this.client.execute('completionEntryDetails', args, token);
} catch {
return item;
}
const details = response.body;
if (!details || !details.length || !details[0]) {
return item;
}
const detail = details[0];
item.detail = detail.displayParts.length ? Previewer.plain(detail.displayParts) : undefined;
item.documentation = this.getDocumentation(detail, item);
const { command, additionalTextEdits } = this.getCodeActions(detail, filepath);
item.command = command;
item.additionalTextEdits = additionalTextEdits;
if (detail && item.useCodeSnippet) {
const shouldCompleteFunction = await this.isValidFunctionCompletionContext(filepath, item.position);
if (shouldCompleteFunction) {
item.insertText = this.snippetForFunctionCall(item, detail);
}
}
return item;
}
private getCodeActions(
detail: Proto.CompletionEntryDetails,
filepath: string
): { command?: vscode.Command, additionalTextEdits?: vscode.TextEdit[] } {
if (!detail.codeActions || !detail.codeActions.length) {
return {};
}
// Try to extract out the additionalTextEdits for the current file.
// Also check if we still have to apply other workspace edits and commands
// using a vscode command
const additionalTextEdits: vscode.TextEdit[] = [];
let hasReaminingCommandsOrEdits = false;
for (const tsAction of detail.codeActions) {
if (tsAction.commands) {
hasReaminingCommandsOrEdits = true;
}
// Apply all edits in the current file using `additionalTextEdits`
if (tsAction.changes) {
for (const change of tsAction.changes) {
if (change.fileName === filepath) {
additionalTextEdits.push(...change.textChanges.map(typeConverters.TextEdit.fromCodeEdit));
} else {
hasReaminingCommandsOrEdits = true;
}
}
}
}
let command: vscode.Command | undefined = undefined;
if (hasReaminingCommandsOrEdits) {
// Create command that applies all edits not in the current file.
command = {
title: '',
command: ApplyCompletionCodeActionCommand.ID,
arguments: [filepath, detail.codeActions.map((x): Proto.CodeAction => ({
commands: x.commands,
description: x.description,
changes: x.changes.filter(x => x.fileName !== filepath)
}))]
};
}
return {
command,
additionalTextEdits: additionalTextEdits.length ? additionalTextEdits : undefined
};
}
private shouldEnableDotCompletions(
document: vscode.TextDocument,
position: vscode.Position
): boolean {
// TODO: Workaround for https://github.com/Microsoft/TypeScript/issues/13456
// Only enable dot completions when previous character is an identifier.
// Prevents incorrectly completing while typing spread operators.
if (position.character > 1) {
const preText = document.getText(new vscode.Range(
position.line, 0,
position.line, position.character - 1));
return preText.match(/[a-z_$\(\)\[\]\{\}]\s*$/ig) !== null;
}
return true;
}
private shouldTrigger(
context: vscode.CompletionContext,
config: CompletionConfiguration,
line: vscode.TextLine,
position: vscode.Position
): boolean {
if (context.triggerCharacter && !this.client.apiVersion.gte(API.v290)) {
if ((context.triggerCharacter === '"' || context.triggerCharacter === '\'')) {
if (!config.quickSuggestionsForPaths) {
return false;
}
// make sure we are in something that looks like the start of an import
const pre = line.text.slice(0, position.character);
if (!pre.match(/\b(from|import)\s*["']$/) && !pre.match(/\b(import|require)\(['"]$/)) {
return false;
}
}
if (context.triggerCharacter === '/') {
if (!config.quickSuggestionsForPaths) {
return false;
}
// make sure we are in something that looks like an import path
const pre = line.text.slice(0, position.character);
if (!pre.match(/\b(from|import)\s*["'][^'"]*$/) && !pre.match(/\b(import|require)\(['"][^'"]*$/)) {
return false;
}
}
if (context.triggerCharacter === '@') {
// make sure we are in something that looks like the start of a jsdoc comment
const pre = line.text.slice(0, position.character);
if (!pre.match(/^\s*\*[ ]?@/) && !pre.match(/\/\*\*+[ ]?@/)) {
return false;
}
}
if (context.triggerCharacter === '<') {
return false;
}
}
return true;
}
private getDocumentation(
detail: Proto.CompletionEntryDetails,
item: MyCompletionItem
): vscode.MarkdownString | undefined {
const documentation = new vscode.MarkdownString();
if (detail.source) {
const importPath = `'${Previewer.plain(detail.source)}'`;
const autoImportLabel = localize('autoImportLabel', 'Auto import from {0}', importPath);
item.detail = `${autoImportLabel}\n${item.detail}`;
}
Previewer.addMarkdownDocumentation(documentation, detail.documentation, detail.tags);
return documentation.value.length ? documentation : undefined;
}
private async isValidFunctionCompletionContext(
filepath: string,
position: vscode.Position
): Promise<boolean> {
// Workaround for https://github.com/Microsoft/TypeScript/issues/12677
// Don't complete function calls inside of destructive assigments or imports
try {
const infoResponse = await this.client.execute('quickinfo', typeConverters.Position.toFileLocationRequestArgs(filepath, position));
const info = infoResponse.body;
switch (info && info.kind) {
case 'var':
case 'let':
case 'const':
case 'alias':
return false;
default:
return true;
}
} catch (e) {
return true;
}
}
private snippetForFunctionCall(
item: vscode.CompletionItem,
detail: Proto.CompletionEntryDetails
): vscode.SnippetString {
let hasOptionalParameters = false;
let hasAddedParameters = false;
const snippet = new vscode.SnippetString();
const methodName = detail.displayParts.find(part => part.kind === 'methodName');
if (item.insertText) {
if (typeof item.insertText === 'string') {
snippet.appendText(item.insertText);
} else {
return item.insertText;
}
} else {
snippet.appendText((methodName && methodName.text) || item.label);
}
snippet.appendText('(');
let parenCount = 0;
let i = 0;
for (; i < detail.displayParts.length; ++i) {
const part = detail.displayParts[i];
// Only take top level paren names
if (part.kind === 'parameterName' && parenCount === 1) {
const next = detail.displayParts[i + 1];
// Skip optional parameters
const nameIsFollowedByOptionalIndicator = next && next.text === '?';
if (!nameIsFollowedByOptionalIndicator) {
if (hasAddedParameters) {
snippet.appendText(', ');
}
hasAddedParameters = true;
snippet.appendPlaceholder(part.text);
}
hasOptionalParameters = hasOptionalParameters || nameIsFollowedByOptionalIndicator;
} else if (part.kind === 'punctuation') {
if (part.text === '(') {
++parenCount;
} else if (part.text === ')') {
--parenCount;
} else if (part.text === '...' && parenCount === 1) {
// Found rest parmeter. Do not fill in any further arguments
hasOptionalParameters = true;
break;
}
}
}
if (hasOptionalParameters) {
snippet.appendTabstop();
}
snippet.appendText(')');
snippet.appendTabstop(0);
return snippet;
}
}
function shouldExcludeCompletionEntry(
element: Proto.CompletionEntry,
completionConfiguration: CompletionConfiguration
) {
return (
(!completionConfiguration.nameSuggestions && element.kind === PConst.Kind.warning)
|| (!completionConfiguration.quickSuggestionsForPaths &&
(element.kind === PConst.Kind.directory || element.kind === PConst.Kind.script))
|| (!completionConfiguration.autoImportSuggestions && element.hasAction)
);
}
export function register(
selector: vscode.DocumentSelector,
client: ITypeScriptServiceClient,
typingsStatus: TypingsStatus,
fileConfigurationManager: FileConfigurationManager,
commandManager: CommandManager,
) {
return vscode.languages.registerCompletionItemProvider(selector,
new TypeScriptCompletionItemProvider(client, typingsStatus, fileConfigurationManager, commandManager),
...TypeScriptCompletionItemProvider.triggerCharacters);
}