/
format.ts
329 lines (256 loc) · 8.93 KB
/
format.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
import type { EmbeddedFile } from '@volar/language-core';
import * as vscode from 'vscode-languageserver-protocol';
import { TextDocument } from 'vscode-languageserver-textdocument';
import { EmbeddedDocumentSourceMap, SourceFileDocument } from '../documents';
import type { DocumentServiceRuntimeContext } from '../types';
export function register(context: DocumentServiceRuntimeContext) {
const ts = context.typescript;
return async (
document: TextDocument,
options: vscode.FormattingOptions,
range?: vscode.Range,
onTypeParams?: {
ch: string,
position: vscode.Position,
},
) => {
if (!range) {
range = vscode.Range.create(document.positionAt(0), document.positionAt(document.getText().length));
}
const vueDocument = context.getSourceFileDocument(document);
const originalDocument = document;
const rootEdits = onTypeParams
? await tryFormat(document, onTypeParams.position, undefined, onTypeParams.ch)
: await tryFormat(document, range, undefined);
if (!vueDocument)
return rootEdits;
if (rootEdits?.length) {
applyEdits(rootEdits);
}
let level = 0;
const initialIndentLanguageId = await context.pluginContext.env.configurationHost?.getConfiguration<Record<string, boolean>>('volar.format.initialIndent') ?? { html: true };
while (true) {
tryUpdateVueDocument();
const embeddeds = getEmbeddedsByLevel(vueDocument[0], level++);
if (embeddeds.length === 0)
break;
let edits: vscode.TextEdit[] = [];
let toPatchIndent: {
sourceMapEmbeddedDocumentUri: string,
} | undefined;
for (const embedded of embeddeds) {
if (!embedded.capabilities.documentFormatting)
continue;
const sourceMap = vueDocument[0].getSourceMap(embedded);
const initialIndentBracket = typeof embedded.capabilities.documentFormatting === 'object' && initialIndentLanguageId[sourceMap.mappedDocument.languageId]
? embedded.capabilities.documentFormatting.initialIndentBracket
: undefined;
let _edits: vscode.TextEdit[] | undefined;
if (onTypeParams) {
const embeddedPosition = sourceMap.toGeneratedPosition(onTypeParams.position);
if (embeddedPosition) {
_edits = await tryFormat(
sourceMap.mappedDocument,
embeddedPosition,
initialIndentBracket,
onTypeParams.ch,
);
}
}
else {
let genRange = sourceMap.toGeneratedRange(range);
if (!genRange) {
const firstMapping = sourceMap.mappings.sort((a, b) => a.sourceRange[0] - b.sourceRange[0])[0];
const lastMapping = sourceMap.mappings.sort((a, b) => b.sourceRange[0] - a.sourceRange[0])[0];
if (
firstMapping && document.offsetAt(range.start) < firstMapping.sourceRange[0]
&& lastMapping && document.offsetAt(range.end) > lastMapping.sourceRange[1]
) {
genRange = {
start: sourceMap.mappedDocument.positionAt(firstMapping.generatedRange[0]),
end: sourceMap.mappedDocument.positionAt(lastMapping.generatedRange[1]),
};
}
}
if (genRange) {
toPatchIndent = {
sourceMapEmbeddedDocumentUri: sourceMap.mappedDocument.uri,
};
_edits = await tryFormat(
sourceMap.mappedDocument,
genRange,
initialIndentBracket,
);
}
}
if (!_edits)
continue;
for (const textEdit of _edits) {
const range = sourceMap.toSourceRange(textEdit.range);
if (range) {
edits.push({
newText: textEdit.newText,
range,
});
}
}
}
if (edits.length > 0) {
applyEdits(edits);
}
if (toPatchIndent) {
tryUpdateVueDocument();
const sourceMap = vueDocument[0].getSourceMaps().find(sourceMap => sourceMap.mappedDocument.uri === toPatchIndent?.sourceMapEmbeddedDocumentUri);
if (sourceMap) {
const indentEdits = patchInterpolationIndent(vueDocument[0], sourceMap);
if (indentEdits.length > 0) {
applyEdits(indentEdits);
}
}
}
}
if (document.getText() === originalDocument.getText())
return;
const editRange = vscode.Range.create(
originalDocument.positionAt(0),
originalDocument.positionAt(originalDocument.getText().length),
);
const textEdit = vscode.TextEdit.replace(editRange, document.getText());
return [textEdit];
function tryUpdateVueDocument() {
if (vueDocument && vueDocument[0].file.text !== document.getText()) {
context.updateSourceFile(vueDocument[0].file, ts.ScriptSnapshot.fromString(document.getText()));
}
}
function getEmbeddedsByLevel(vueDocument: SourceFileDocument, level: number) {
const embeddeds = vueDocument.file.embeddeds;
const embeddedsLevels: EmbeddedFile[][] = [embeddeds];
while (true) {
if (embeddedsLevels.length > level)
return embeddedsLevels[level];
let nextEmbeddeds: EmbeddedFile[] = [];
for (const embeddeds of embeddedsLevels[embeddedsLevels.length - 1]) {
nextEmbeddeds = nextEmbeddeds.concat(embeddeds.embeddeds);
}
embeddedsLevels.push(nextEmbeddeds);
}
}
async function tryFormat(document: TextDocument, range: vscode.Range | vscode.Position, initialIndentBracket: [string, string] | undefined, ch?: string) {
let formatDocument = document;
let formatRange = range;
if (initialIndentBracket) {
formatDocument = TextDocument.create(
document.uri,
document.languageId,
document.version,
initialIndentBracket[0] + document.getText() + initialIndentBracket[1],
);
if (vscode.Position.is(range)) {
formatRange = formatDocument.positionAt(document.offsetAt(range) + initialIndentBracket[0].length);
}
else {
const startOffset = document.offsetAt(range.start);
const endOffset = document.offsetAt(range.end);
if (startOffset === 0 && endOffset === document.getText().length) {
// full format
formatRange = {
start: formatDocument.positionAt(0),
end: formatDocument.positionAt(formatDocument.getText().length),
};
}
else {
// range format
formatRange = {
start: formatDocument.positionAt(startOffset + initialIndentBracket[0].length),
end: formatDocument.positionAt(endOffset + initialIndentBracket[0].length),
};
}
}
}
context.prepareLanguageServices(formatDocument);
for (const plugin of context.plugins) {
let edits: vscode.TextEdit[] | null | undefined;
try {
if (ch !== undefined && vscode.Position.is(formatRange)) {
edits = await plugin.formatOnType?.(formatDocument, formatRange, ch, options);
}
else if (ch === undefined && vscode.Range.is(formatRange)) {
edits = await plugin.format?.(formatDocument, formatRange, options);
}
}
catch (err) {
console.error(err);
}
if (!edits)
continue;
if (!edits.length)
return edits;
if (initialIndentBracket) {
let newText = TextDocument.applyEdits(formatDocument, edits);
newText = newText.substring(
newText.indexOf(initialIndentBracket[0]) + initialIndentBracket[0].length,
newText.lastIndexOf(initialIndentBracket[1]),
);
if (newText === document.getText()) {
edits = [];
}
else {
edits = [{
newText,
range: {
start: document.positionAt(0),
end: document.positionAt(document.getText().length),
},
}];
}
}
return edits;
}
}
function applyEdits(textEdits: vscode.TextEdit[]) {
const newText = TextDocument.applyEdits(document, textEdits);
if (newText !== document.getText()) {
document = TextDocument.create(document.uri, document.languageId, document.version + 1, newText);
}
}
};
}
function patchInterpolationIndent(vueDocument: SourceFileDocument, sourceMap: EmbeddedDocumentSourceMap) {
const indentTextEdits: vscode.TextEdit[] = [];
const document = vueDocument.getDocument();
for (const mapped of sourceMap.mappings) {
const textRange = {
start: document.positionAt(mapped.sourceRange[0]),
end: document.positionAt(mapped.sourceRange[1]),
};
const text = document.getText(textRange);
if (text.indexOf('\n') === -1)
continue;
const lines = text.split('\n');
const removeIndent = getRemoveIndent(lines);
const baseIndent = getBaseIndent(mapped.sourceRange[0]);
for (let i = 1; i < lines.length; i++) {
const line = lines[i];
if (line.startsWith(removeIndent)) {
lines[i] = line.replace(removeIndent, baseIndent);
}
else {
lines[i] = baseIndent.replace(removeIndent, '') + line;
}
}
indentTextEdits.push({
newText: lines.join('\n'),
range: textRange,
});
}
return indentTextEdits;
function getRemoveIndent(lines: string[]) {
const lastLine = lines[lines.length - 1];
return lastLine.substring(0, lastLine.length - lastLine.trimStart().length);
}
function getBaseIndent(pos: number) {
const startPos = document.positionAt(pos);
const startLineText = document.getText({ start: startPos, end: { line: startPos.line, character: 0 } });
return startLineText.substring(0, startLineText.length - startLineText.trimStart().length);
}
}