-
-
Notifications
You must be signed in to change notification settings - Fork 370
/
languageService.ts
219 lines (204 loc) · 8.92 KB
/
languageService.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
import createCssPlugin from '@volar-plugins/css';
import createEmmetPlugin from '@volar-plugins/emmet';
import createHtmlPlugin from '@volar-plugins/html';
import createJsonPlugin from '@volar-plugins/json';
import createPugPlugin from '@volar-plugins/pug';
import createTsPlugin from '@volar-plugins/typescript';
import createTsTqPlugin from '@volar-plugins/typescript-twoslash-queries';
import * as embedded from '@volar/language-core';
import * as embeddedLS from '@volar/language-service';
import * as vue from '@volar/vue-language-core';
import { VueLanguageServiceHost } from '@volar/vue-language-core';
import type * as html from 'vscode-html-languageservice';
import * as vscode from 'vscode-languageserver-protocol';
import createVuePlugin from './plugins/vue';
import createAutoDotValuePlugin from './plugins/vue-autoinsert-dotvalue';
import createReferencesCodeLensPlugin from './plugins/vue-codelens-references';
import createHtmlPugConversionsPlugin from './plugins/vue-convert-htmlpug';
import createRefSugarConversionsPlugin from './plugins/vue-convert-refsugar';
import createScriptSetupConversionsPlugin from './plugins/vue-convert-scriptsetup';
import createTwoslashQueries from './plugins/vue-twoslash-queries';
import createVueTemplateLanguagePlugin from './plugins/vue-template';
import type { Data } from '@volar-plugins/typescript/src/services/completions/basic';
import type * as ts from 'typescript/lib/tsserverlibrary';
import { LanguageServicePlugin } from '@volar/language-service';
import createPugFormatPlugin from '@volar-plugins/pug-beautify';
import createAutoWrapParenthesesPlugin from './plugins/vue-autoinsert-parentheses';
import createAutoAddSpacePlugin from './plugins/vue-autoinsert-space';
export interface Settings {
json?: Parameters<typeof createJsonPlugin>[0];
}
export function getLanguageServicePlugins(settings?: Settings) {
const tsPlugin = createTsPlugin();
const tsPluginPatchAutoImport: embeddedLS.LanguageServicePlugin = (_context, service) => {
if (!_context.typescript)
return {};
const ts = _context.typescript.module;
const base = tsPlugin(_context, service);
const autoImportPositions = new WeakSet<vscode.Position>();
return {
...base,
resolveEmbeddedRange(range) {
if (autoImportPositions.has(range.start) && autoImportPositions.has(range.end))
return range;
},
complete: {
...base.complete,
async on(document, position, context) {
const result = await base.complete!.on!(document, position, context);
if (result) {
for (const [_, map] of _context.documents.getMapsByVirtualFileUri(document.uri)) {
const virtualFile = _context.documents.getRootFileBySourceFileUri(map.sourceFileDocument.uri);
if (virtualFile instanceof vue.VueFile) {
if (map.toSourcePosition(position, data => typeof data.completion === 'object' && !!data.completion.autoImportOnly)) {
result.items.forEach(item => {
item.data.__isComponentAutoImport = true;
});
}
}
}
}
return result;
},
async resolve(item) {
item = await base.complete!.resolve!(item);
if (
item.textEdit?.newText && /\w*Vue$/.test(item.textEdit.newText)
&& item.additionalTextEdits?.length === 1 && item.additionalTextEdits[0].newText.indexOf('import ' + item.textEdit.newText + ' from ') >= 0
&& (await _context.env.configurationHost?.getConfiguration<boolean>('volar.completion.normalizeComponentAutoImportName') ?? true)
) {
let newName = item.textEdit.newText.slice(0, -'Vue'.length);
newName = newName[0].toUpperCase() + newName.substring(1);
item.additionalTextEdits[0].newText = item.additionalTextEdits[0].newText.replace(
'import ' + item.textEdit.newText + ' from ',
'import ' + newName + ' from ',
);
item.textEdit.newText = newName;
}
const data: Data = item.data;
if (item.data?.__isComponentAutoImport && data && item.additionalTextEdits?.length && item.textEdit) {
for (const [_, map] of _context.documents.getMapsByVirtualFileUri(data.uri)) {
const virtualFile = _context.documents.getRootFileBySourceFileUri(map.sourceFileDocument.uri);
if (virtualFile instanceof vue.VueFile) {
const sfc = virtualFile.sfc;
const componentName = item.textEdit.newText;
const textDoc = _context.documents.getDocumentByFileName(virtualFile.snapshot, virtualFile.fileName);
if (sfc.scriptAst && sfc.script) {
const _scriptRanges = vue.scriptRanges.parseScriptRanges(ts, sfc.scriptAst, !!sfc.scriptSetup, true);
const exportDefault = _scriptRanges.exportDefault;
if (exportDefault) {
// https://github.com/microsoft/TypeScript/issues/36174
const printer = ts.createPrinter();
if (exportDefault.componentsOption && exportDefault.componentsOptionNode) {
const newNode: typeof exportDefault.componentsOptionNode = {
...exportDefault.componentsOptionNode,
properties: [
...exportDefault.componentsOptionNode.properties,
ts.factory.createShorthandPropertyAssignment(componentName),
] as any as ts.NodeArray<ts.ObjectLiteralElementLike>,
};
const printText = printer.printNode(ts.EmitHint.Expression, newNode, sfc.scriptAst);
const editRange = vscode.Range.create(
textDoc.positionAt(sfc.script.startTagEnd + exportDefault.componentsOption.start),
textDoc.positionAt(sfc.script.startTagEnd + exportDefault.componentsOption.end),
);
autoImportPositions.add(editRange.start);
autoImportPositions.add(editRange.end);
item.additionalTextEdits.push(vscode.TextEdit.replace(
editRange,
unescape(printText.replace(/\\u/g, '%u')),
));
}
else if (exportDefault.args && exportDefault.argsNode) {
const newNode: typeof exportDefault.argsNode = {
...exportDefault.argsNode,
properties: [
...exportDefault.argsNode.properties,
ts.factory.createShorthandPropertyAssignment(`components: { ${componentName} }`),
] as any as ts.NodeArray<ts.ObjectLiteralElementLike>,
};
const printText = printer.printNode(ts.EmitHint.Expression, newNode, sfc.scriptAst);
const editRange = vscode.Range.create(
textDoc.positionAt(sfc.script.startTagEnd + exportDefault.args.start),
textDoc.positionAt(sfc.script.startTagEnd + exportDefault.args.end),
);
autoImportPositions.add(editRange.start);
autoImportPositions.add(editRange.end);
item.additionalTextEdits.push(vscode.TextEdit.replace(
editRange,
unescape(printText.replace(/\\u/g, '%u')),
));
}
}
}
}
}
}
return item;
},
},
};
};
// template plugins
const htmlPlugin = createVueTemplateLanguagePlugin({
templateLanguagePlugin: createHtmlPlugin(),
getScanner: (document, htmlPlugin): html.Scanner | undefined => {
return htmlPlugin.getHtmlLs().createScanner(document.getText());
},
isSupportedDocument: (document) => document.languageId === 'html',
});
const pugPlugin = createVueTemplateLanguagePlugin({
templateLanguagePlugin: createPugPlugin(),
getScanner: (document, pugPlugin): html.Scanner | undefined => {
const pugDocument = pugPlugin.getPugDocument(document);
if (pugDocument) {
return pugPlugin.getPugLs().createScanner(pugDocument);
}
},
isSupportedDocument: (document) => document.languageId === 'jade',
});
return [
createVuePlugin(),
createCssPlugin(),
htmlPlugin,
pugPlugin,
createJsonPlugin(settings?.json),
createReferencesCodeLensPlugin(),
createHtmlPugConversionsPlugin(),
createScriptSetupConversionsPlugin(),
createRefSugarConversionsPlugin(),
tsPluginPatchAutoImport,
createAutoDotValuePlugin(),
createTsTqPlugin(),
createTwoslashQueries(),
createPugFormatPlugin(),
createAutoWrapParenthesesPlugin(),
createAutoAddSpacePlugin(),
// put emmet plugin at last to fix https://github.com/johnsoncodehk/volar/issues/1088
createEmmetPlugin(),
] as LanguageServicePlugin[];
}
export function createLanguageService(
host: VueLanguageServiceHost,
env: embeddedLS.LanguageServiceRuntimeContext['env'],
documentRegistry?: ts.DocumentRegistry,
settings?: Settings,
) {
const ts = host.getTypeScriptModule();
const vueLanguageModules = ts ? vue.createLanguageModules(
ts,
host.getCompilationSettings(),
host.getVueCompilationSettings(),
) : [];
const core = embedded.createLanguageContext(host, vueLanguageModules);
const languageServiceContext = embeddedLS.createLanguageServiceContext({
env,
host,
context: core,
documentRegistry,
getPlugins: () => getLanguageServicePlugins(settings),
getLanguageService: () => languageService,
});
const languageService = embeddedLS.createLanguageService(languageServiceContext);
return languageService;
}