-
Notifications
You must be signed in to change notification settings - Fork 23
/
resolve.ts
173 lines (151 loc) · 5.84 KB
/
resolve.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
import { SharedContext } from '../../types';
import type * as ts from 'typescript/lib/tsserverlibrary';
import type * as vscode from '@volar/language-service';
import type { TextDocument } from 'vscode-languageserver-textdocument';
import { getFormatCodeSettings } from '../../configs/getFormatCodeSettings';
import { getUserPreferences } from '../../configs/getUserPreferences';
import { getConfigTitle } from '../../shared';
import * as previewer from '../../utils/previewer';
import { snippetForFunctionCall } from '../../utils/snippetForFunctionCall';
import { entriesToLocations } from '../../utils/transforms';
import type { Data } from './basic';
import { handleKindModifiers } from './basic';
export function register(ctx: SharedContext) {
const { ts } = ctx;
return async (item: vscode.CompletionItem, newPosition?: vscode.Position): Promise<vscode.CompletionItem> => {
const data: Data | undefined = item.data;
if (!data)
return item;
const fileName = data.fileName;
let offset = data.offset;
const document = ctx.getTextDocument(data.uri);
if (newPosition && document) {
offset = document.offsetAt(newPosition);
}
const [formatOptions, preferences] = document ? await Promise.all([
getFormatCodeSettings(ctx, document),
getUserPreferences(ctx, document),
]) : [{}, {}];
let details: ts.CompletionEntryDetails | undefined;
try {
details = ctx.typescript.languageService.getCompletionEntryDetails(fileName, offset, data.originalItem.name, formatOptions, data.originalItem.source, preferences, data.originalItem.data);
}
catch (err) {
item.detail = `[TS Error]\n${err}\n${JSON.stringify(err, undefined, 2)}`;
}
if (!details)
return item;
if (data.originalItem.labelDetails) {
item.labelDetails ??= {};
Object.assign(item.labelDetails, data.originalItem.labelDetails);
}
const { sourceDisplay } = details;
if (sourceDisplay) {
item.labelDetails ??= {};
item.labelDetails.description = ts.displayPartsToString(sourceDisplay);
}
const detailTexts: string[] = [];
if (details.codeActions) {
if (!item.additionalTextEdits) item.additionalTextEdits = [];
for (const action of details.codeActions) {
detailTexts.push(action.description);
for (const changes of action.changes) {
const entries = changes.textChanges.map(textChange => {
return { fileName, textSpan: textChange.span };
});
const locs = entriesToLocations(entries, ctx);
locs.forEach((loc, index) => {
item.additionalTextEdits?.push({ range: loc.range, newText: changes.textChanges[index].newText });
});
}
}
}
if (details.displayParts) {
detailTexts.push(previewer.plainWithLinks(details.displayParts, { toResource }, ctx));
}
if (detailTexts.length) {
item.detail = detailTexts.join('\n');
}
item.documentation = {
kind: 'markdown',
value: previewer.markdownDocumentation(details.documentation, details.tags, { toResource }, ctx),
};
if (details) {
handleKindModifiers(item, details);
}
if (document) {
const useCodeSnippetsOnMethodSuggest = await ctx.env.getConfiguration?.<boolean>(getConfigTitle(document) + '.suggest.completeFunctionCalls') ?? false;
const useCodeSnippet = useCodeSnippetsOnMethodSuggest && (item.kind === 3 satisfies typeof vscode.CompletionItemKind.Function || item.kind === 2 satisfies typeof vscode.CompletionItemKind.Method);
if (useCodeSnippet) {
const shouldCompleteFunction = isValidFunctionCompletionContext(ctx.typescript.languageService, fileName, offset, document);
if (shouldCompleteFunction) {
const { snippet, parameterCount } = snippetForFunctionCall(
{
insertText: item.insertText ?? item.textEdit?.newText, // insertText is dropped by LSP in some case: https://github.com/microsoft/vscode-languageserver-node/blob/9b742021fb04ad081aa3676a9eecf4fa612084b4/client/src/common/codeConverter.ts#L659-L664
label: item.label,
},
details.displayParts,
);
if (item.textEdit) {
item.textEdit.newText = snippet;
}
if (item.insertText) {
item.insertText = snippet;
}
item.insertTextFormat = 2 satisfies typeof vscode.InsertTextFormat.Snippet;
if (parameterCount > 0) {
//Fix for https://github.com/microsoft/vscode/issues/104059
//Don't show parameter hints if "editor.parameterHints.enabled": false
// if (await getConfiguration('editor.parameterHints.enabled', document.uri)) {
// item.command = {
// title: 'triggerParameterHints',
// command: 'editor.action.triggerParameterHints',
// };
// }
}
}
}
}
return item;
function toResource(path: string) {
return ctx.env.fileNameToUri(path);
}
};
}
function isValidFunctionCompletionContext(
client: ts.LanguageService,
filepath: string,
offset: number,
document: TextDocument,
): boolean {
// Workaround for https://github.com/microsoft/TypeScript/issues/12677
// Don't complete function calls inside of destructive assignments or imports
try {
const response = client.getQuickInfoAtPosition(filepath, offset);
if (response) {
switch (response.kind) {
case 'var':
case 'let':
case 'const':
case 'alias':
return false;
}
}
} catch {
// Noop
}
// Don't complete function call if there is already something that looks like a function call
// https://github.com/microsoft/vscode/issues/18131
const position = document.positionAt(offset);
const after = getLineText(document, position.line).slice(position.character);
return after.match(/^[a-z_$0-9]*\s*\(/gi) === null;
}
export function getLineText(document: TextDocument, line: number) {
const endOffset = document.offsetAt({ line: line + 1, character: 0 });
const end = document.positionAt(endOffset);
const text = document.getText({
start: { line: line, character: 0 },
end: end.line === line ? end : document.positionAt(endOffset - 1),
});
return text;
}