/
basic.ts
383 lines (319 loc) · 11.8 KB
/
basic.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
import type * as ts from 'typescript/lib/tsserverlibrary';
import * as PConst from '../../protocol.const';
import * as vscode from 'vscode-languageserver-protocol';
import type { TextDocument } from 'vscode-languageserver-textdocument';
import * as shared from '@volar/shared';
import * as semver from 'semver';
import { parseKindModifier } from '../../utils/modifiers';
import type { GetConfiguration } from '../../createLanguageService';
import { getUserPreferences } from '../../configs/getUserPreferences';
import { URI } from 'vscode-uri';
export interface Data {
uri: string,
fileName: string,
offset: number,
originalItem: ts.CompletionEntry;
}
export function register(
rootUri: URI,
languageService: ts.LanguageService,
getTextDocument: (uri: string) => TextDocument | undefined,
getConfiguration: GetConfiguration,
ts: typeof import('typescript/lib/tsserverlibrary'),
) {
const lt_320 = semver.lt(ts.version, '3.2.0');
const gte_300 = semver.gte(ts.version, '3.0.0');
return async (uri: string, position: vscode.Position, options?: ts.GetCompletionsAtPositionOptions): Promise<vscode.CompletionList | undefined> => {
const document = getTextDocument(uri);
if (!document)
return;
const preferences = await getUserPreferences(getConfiguration, document.uri, rootUri);
const fileName = shared.getPathOfUri(document.uri);
const offset = document.offsetAt(position);
let completionContext: ReturnType<typeof languageService.getCompletionsAtPosition> | undefined;
try {
completionContext = languageService.getCompletionsAtPosition(fileName, offset, {
...preferences,
...options,
});
} catch { }
if (completionContext === undefined)
return;
const wordRange = completionContext.optionalReplacementSpan ? vscode.Range.create(
document.positionAt(completionContext.optionalReplacementSpan.start),
document.positionAt(completionContext.optionalReplacementSpan.start + completionContext.optionalReplacementSpan.length),
) : undefined;
let line = document.getText({
start: { line: position.line, character: 0 },
end: { line: position.line + 1, character: 0 },
});
if (line.endsWith('\n')) {
line = line.substring(0, line.length - 1);
}
const dotAccessorContext = getDotAccessorContext(document);
const entries = completionContext.entries
.map(tsEntry => toVScodeItem(tsEntry, document));
return {
isIncomplete: !!completionContext.isIncomplete,
items: entries,
};
function toVScodeItem(tsEntry: ts.CompletionEntry, document: TextDocument) {
const item = vscode.CompletionItem.create(tsEntry.name);
item.kind = convertKind(tsEntry.kind);
if (tsEntry.source && tsEntry.hasAction) {
// De-prioritize auto-imports
// https://github.com/microsoft/vscode/issues/40311
item.sortText = '\uffff' + tsEntry.sortText;
} else {
item.sortText = tsEntry.sortText;
}
const { sourceDisplay, isSnippet } = tsEntry;
if (sourceDisplay) {
item.labelDetails = { description: ts.displayPartsToString(tsEntry.sourceDisplay) };
}
item.preselect = tsEntry.isRecommended;
let range: vscode.Range | ReturnType<typeof getRangeFromReplacementSpan> = getRangeFromReplacementSpan(tsEntry, document);
item.commitCharacters = getCommitCharacters(tsEntry, {
isNewIdentifierLocation: completionContext!.isNewIdentifierLocation,
isInValidCommitCharacterContext: isInValidCommitCharacterContext(document, position),
enableCallCompletions: true, // TODO: suggest.completeFunctionCalls
});
item.insertText = tsEntry.insertText;
item.insertTextFormat = isSnippet ? vscode.InsertTextFormat.Snippet : vscode.InsertTextFormat.PlainText;
item.filterText = getFilterText(tsEntry, wordRange, line, tsEntry.insertText);
if (completionContext?.isMemberCompletion && dotAccessorContext && !isSnippet) {
item.filterText = dotAccessorContext.text + (item.insertText || item.label);
if (!range) {
const replacementRange = wordRange;
if (replacementRange) {
range = {
inserting: dotAccessorContext.range,
replacing: rangeUnion(dotAccessorContext.range, replacementRange),
};
} else {
range = dotAccessorContext.range;
}
item.insertText = item.filterText;
}
}
handleKindModifiers(item, tsEntry);
if (!range && wordRange) {
range = {
inserting: vscode.Range.create(wordRange.start, position),
replacing: wordRange,
};
}
if (range) {
if (vscode.Range.is(range)) {
item.textEdit = vscode.TextEdit.replace(range, item.insertText || item.label);
}
else {
item.textEdit = vscode.InsertReplaceEdit.create(item.insertText || item.label, range.inserting, range.replacing);
}
}
return {
...item,
data: {
uri,
fileName,
offset,
originalItem: tsEntry,
} satisfies Data,
};
}
function getDotAccessorContext(document: TextDocument) {
let dotAccessorContext: {
range: vscode.Range;
text: string;
} | undefined;
if (gte_300) {
if (!completionContext)
return;
const isMemberCompletion = completionContext.isMemberCompletion;
if (isMemberCompletion) {
const dotMatch = line.slice(0, position.character).match(/\??\.\s*$/) || undefined;
if (dotMatch) {
const range = vscode.Range.create({ line: position.line, character: position.character - dotMatch[0].length }, position);
const text = document.getText(range);
dotAccessorContext = { range, text };
}
}
}
return dotAccessorContext;
}
// from vscode typescript
function getRangeFromReplacementSpan(tsEntry: ts.CompletionEntry, document: TextDocument) {
if (!tsEntry.replacementSpan) {
return;
}
let replaceRange = vscode.Range.create(
document.positionAt(tsEntry.replacementSpan.start),
document.positionAt(tsEntry.replacementSpan.start + tsEntry.replacementSpan.length),
);
// Make sure we only replace a single line at most
if (replaceRange.start.line !== replaceRange.end.line) {
replaceRange = vscode.Range.create(
replaceRange.start.line,
replaceRange.start.character,
replaceRange.start.line,
document.positionAt(document.offsetAt({ line: replaceRange.start.line + 1, character: 0 }) - 1).character,
);
}
// If TS returns an explicit replacement range, we should use it for both types of completion
return {
inserting: replaceRange,
replacing: replaceRange,
};
}
function getFilterText(tsEntry: ts.CompletionEntry, wordRange: vscode.Range | undefined, line: string, insertText: string | undefined): string | undefined {
// Handle private field completions
if (tsEntry.name.startsWith('#')) {
const wordStart = wordRange ? line.charAt(wordRange.start.character) : undefined;
if (insertText) {
if (insertText.startsWith('this.#')) {
return wordStart === '#' ? insertText : insertText.replace(/^this\.#/, '');
} else {
return insertText;
}
} else {
return wordStart === '#' ? undefined : tsEntry.name.replace(/^#/, '');
}
}
// For `this.` completions, generally don't set the filter text since we don't want them to be overly prioritized. #74164
if (insertText?.startsWith('this.')) {
return undefined;
}
// Handle the case:
// ```
// const xyz = { 'ab c': 1 };
// xyz.ab|
// ```
// In which case we want to insert a bracket accessor but should use `.abc` as the filter text instead of
// the bracketed insert text.
else if (insertText?.startsWith('[')) {
return insertText.replace(/^\[['"](.+)[['"]\]$/, '.$1');
}
// In all other cases, fallback to using the insertText
return insertText;
}
function convertKind(kind: string): vscode.CompletionItemKind {
switch (kind) {
case PConst.Kind.primitiveType:
case PConst.Kind.keyword:
return vscode.CompletionItemKind.Keyword;
case PConst.Kind.const:
case PConst.Kind.let:
case PConst.Kind.variable:
case PConst.Kind.localVariable:
case PConst.Kind.alias:
case PConst.Kind.parameter:
return vscode.CompletionItemKind.Variable;
case PConst.Kind.memberVariable:
case PConst.Kind.memberGetAccessor:
case PConst.Kind.memberSetAccessor:
return vscode.CompletionItemKind.Field;
case PConst.Kind.function:
case PConst.Kind.localFunction:
return vscode.CompletionItemKind.Function;
case PConst.Kind.method:
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.enumMember:
return vscode.CompletionItemKind.EnumMember;
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:
return vscode.CompletionItemKind.Text;
case PConst.Kind.script:
return vscode.CompletionItemKind.File;
case PConst.Kind.directory:
return vscode.CompletionItemKind.Folder;
case PConst.Kind.string:
return vscode.CompletionItemKind.Constant;
default:
return vscode.CompletionItemKind.Property;
}
}
function getCommitCharacters(entry: ts.CompletionEntry, context: {
isNewIdentifierLocation: boolean,
isInValidCommitCharacterContext: boolean,
enableCallCompletions: boolean,
}): string[] | undefined {
if (entry.kind === PConst.Kind.warning) { // Ambient JS word based suggestion
return undefined;
}
if (context.isNewIdentifierLocation || !context.isInValidCommitCharacterContext) {
return undefined;
}
const commitCharacters: string[] = ['.', ',', ';'];
if (context.enableCallCompletions) {
commitCharacters.push('(');
}
return commitCharacters;
}
function isInValidCommitCharacterContext(
document: TextDocument,
position: vscode.Position,
): boolean {
if (lt_320) {
// Workaround for https://github.com/microsoft/TypeScript/issues/27742
// Only enable dot completions when the previous character is not a dot preceded by whitespace.
// Prevents incorrectly completing while typing spread operators.
if (position.character > 1) {
const preText = document.getText(vscode.Range.create(
position.line, 0,
position.line, position.character));
return preText.match(/(\s|^)\.$/ig) === null;
}
}
return true;
}
};
}
export function handleKindModifiers(item: vscode.CompletionItem, tsEntry: ts.CompletionEntry | ts.CompletionEntryDetails) {
if (tsEntry.kindModifiers) {
const kindModifiers = parseKindModifier(tsEntry.kindModifiers);
if (kindModifiers.has(PConst.KindModifiers.optional)) {
if (!item.insertText) {
item.insertText = item.label;
}
if (!item.filterText) {
item.filterText = item.label;
}
item.label += '?';
}
if (kindModifiers.has(PConst.KindModifiers.deprecated)) {
item.tags = [vscode.CompletionItemTag.Deprecated];
}
if (kindModifiers.has(PConst.KindModifiers.color)) {
item.kind = vscode.CompletionItemKind.Color;
}
if (tsEntry.kind === PConst.Kind.script) {
for (const extModifier of PConst.KindModifiers.fileExtensionKindModifiers) {
if (kindModifiers.has(extModifier)) {
if (tsEntry.name.toLowerCase().endsWith(extModifier)) {
item.detail = tsEntry.name;
} else {
item.detail = tsEntry.name + extModifier;
}
break;
}
}
}
}
}
function rangeUnion(a: vscode.Range, b: vscode.Range): vscode.Range {
const start = (a.start.line < b.start.line || (a.start.line === b.start.line && a.start.character < b.start.character)) ? a.start : b.start;
const end = (a.end.line > b.end.line || (a.end.line === b.end.line && a.end.character > b.end.character)) ? a.end : b.end;
return { start, end };
}