-
-
Notifications
You must be signed in to change notification settings - Fork 511
Expand file tree
/
Copy pathPrettierEditService.ts
More file actions
793 lines (706 loc) · 25.2 KB
/
PrettierEditService.ts
File metadata and controls
793 lines (706 loc) · 25.2 KB
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
import * as path from "path";
import { pathToFileURL } from "url";
import {
Disposable,
DocumentFilter,
languages,
Range,
TextDocument,
TextEdit,
TextEditor,
Uri,
window,
workspace,
} from "vscode";
import { getParserFromLanguageId } from "./utils/get-parser-from-language.js";
import { LoggingService } from "./LoggingService.js";
import { RESTART_TO_ENABLE } from "./message.js";
import { PrettierEditProvider } from "./PrettierEditProvider.js";
import { PrettierCodeActionProvider } from "./PrettierCodeActionProvider.js";
import { FormatterStatus, StatusBar } from "./StatusBar.js";
import {
ExtensionFormattingOptions,
ModuleResolverInterface,
PrettierBuiltInParserName,
PrettierFileInfoResult,
PrettierInstance,
PrettierModule,
PrettierOptions,
PrettierPlugin,
RangeFormattingOptions,
} from "./types.js";
import { getWorkspaceConfig } from "./utils/workspace.js";
import { isAboveV3 } from "./utils/versions.js";
import { resolveModuleEntry } from "./utils/resolve-module-entry.js";
/**
* Resolve plugin paths for Prettier.
* Matches Prettier CLI behavior:
* - URLs pass through
* - Absolute paths → kept as-is or converted to file:// URL (for v3)
* - Relative paths (./plugin.js) → resolved relative to file
* - Package names → resolved from file's directory via createRequire
*
* @param useFileUrls - If true, converts paths to file:// URLs (needed for Prettier v3+ ESM import)
* If false, returns absolute paths (for Prettier v2 require())
*/
async function resolvePluginPaths(
plugins: (string | PrettierPlugin)[] | undefined,
fileName: string,
useFileUrls: boolean,
): Promise<(string | PrettierPlugin)[]> {
if (!plugins) {
return [];
}
const dir = path.dirname(fileName);
const resolvedPlugins: (string | PrettierPlugin)[] = [];
for (const plugin of plugins) {
// Plugin objects pass through
if (typeof plugin !== "string") {
resolvedPlugins.push(plugin);
continue;
}
// URLs pass through
if (plugin.startsWith("file://") || plugin.startsWith("data:")) {
resolvedPlugins.push(plugin);
continue;
}
// Absolute paths
if (path.isAbsolute(plugin)) {
resolvedPlugins.push(useFileUrls ? pathToFileURL(plugin).href : plugin);
continue;
}
// Relative paths (./foo or ../foo) → resolve relative to file
if (plugin.startsWith(".")) {
const resolved = path.resolve(dir, plugin);
resolvedPlugins.push(
useFileUrls ? pathToFileURL(resolved).href : resolved,
);
continue;
}
// Package names → resolve from file's directory using createRequire
try {
const resolved = resolveModuleEntry(dir, plugin);
resolvedPlugins.push(
useFileUrls ? pathToFileURL(resolved).href : resolved,
);
} catch {
// If resolution fails, pass through and let Prettier handle/report the error
resolvedPlugins.push(plugin);
}
}
return resolvedPlugins;
}
interface ISelectors {
rangeLanguageSelector: ReadonlyArray<DocumentFilter>;
languageSelector: ReadonlyArray<DocumentFilter>;
}
export default class PrettierEditService implements Disposable {
private formatterHandler: undefined | Disposable;
private rangeFormatterHandler: undefined | Disposable;
private codeActionHandler: undefined | Disposable;
private registeredWorkspaces = new Set<string>();
private allLanguages: string[] = [];
private allExtensions: string[] = [];
private allRangeLanguages: string[] = [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
"json",
"jsonc",
"graphql",
];
constructor(
private moduleResolver: ModuleResolverInterface,
private loggingService: LoggingService,
private statusBar: StatusBar,
) {}
public registerDisposables(): Disposable[] {
const packageWatcher = workspace.createFileSystemWatcher("**/package.json");
packageWatcher.onDidChange(this.resetFormatters);
packageWatcher.onDidCreate(this.resetFormatters);
packageWatcher.onDidDelete(this.resetFormatters);
const configurationWatcher = workspace.onDidChangeConfiguration((event) => {
if (event.affectsConfiguration("prettier.enable")) {
this.loggingService.logWarning(RESTART_TO_ENABLE);
} else if (event.affectsConfiguration("prettier")) {
this.resetFormatters();
}
});
// Create individual watchers for different config file patterns
// Using multiple watchers instead of brace expansion because VS Code's
// createFileSystemWatcher doesn't reliably support complex {a,b,c} patterns
// across all platforms (especially Windows). See: https://github.com/microsoft/vscode/issues/177617
const prettierConfigWatchers = [
workspace.createFileSystemWatcher("**/.prettierrc"),
workspace.createFileSystemWatcher("**/.prettierrc.*"),
workspace.createFileSystemWatcher("**/prettier.config.*"),
workspace.createFileSystemWatcher("**/.editorconfig"),
];
for (const watcher of prettierConfigWatchers) {
watcher.onDidChange(this.prettierConfigChanged);
watcher.onDidCreate(this.prettierConfigChanged);
watcher.onDidDelete(this.prettierConfigChanged);
}
// Watch .prettierignore for changes to invalidate ignore cache
const prettierIgnoreWatcher =
workspace.createFileSystemWatcher("**/.prettierignore");
prettierIgnoreWatcher.onDidChange(this.prettierConfigChanged);
prettierIgnoreWatcher.onDidCreate(this.prettierConfigChanged);
prettierIgnoreWatcher.onDidDelete(this.prettierConfigChanged);
const textEditorChange = window.onDidChangeActiveTextEditor(
this.handleActiveTextEditorChangedSync,
);
this.handleActiveTextEditorChangedSync(window.activeTextEditor);
return [
packageWatcher,
configurationWatcher,
...prettierConfigWatchers,
prettierIgnoreWatcher,
textEditorChange,
];
}
public forceFormatDocument = async () => {
try {
const editor = window.activeTextEditor;
if (!editor) {
this.loggingService.logInfo(
"No active document. Nothing was formatted.",
);
return;
}
this.loggingService.logInfo(
"Forced formatting will not use ignore files.",
);
const edits = await this.provideEdits(editor.document, { force: true });
if (edits.length === 0) {
this.loggingService.logInfo("Document is already formatted.");
return;
}
if (edits.length > 1) {
this.loggingService.logWarning(
`Unexpected multiple edits (${edits.length}), expected 0 or 1`,
);
return;
}
await editor.edit((editBuilder) => {
editBuilder.replace(edits[0].range, edits[0].newText);
});
} catch (e) {
this.loggingService.logError("Error formatting document", e);
}
};
private prettierConfigChanged = async (uri: Uri) => {
// Clear Prettier's internal config cache so it re-reads the config file
await this.moduleResolver.clearModuleCache(uri.fsPath);
this.resetFormatters(uri);
};
private resetFormatters = (uri?: Uri) => {
if (uri) {
const workspaceFolder = workspace.getWorkspaceFolder(uri);
this.registeredWorkspaces.delete(workspaceFolder?.uri.fsPath ?? "global");
} else {
// VS Code config change, reset everything
this.registeredWorkspaces.clear();
}
this.statusBar.update(FormatterStatus.Ready);
};
private handleActiveTextEditorChangedSync = (
textEditor: TextEditor | undefined,
) => {
this.handleActiveTextEditorChanged(textEditor).catch((err) => {
this.loggingService.logError("Error handling text editor change", err);
});
};
private handleActiveTextEditorChanged = async (
textEditor: TextEditor | undefined,
) => {
if (!textEditor) {
this.statusBar.hide();
return;
}
const { document } = textEditor;
if (document.uri.scheme !== "file") {
// We set as ready for untitled documents,
// but return because these will always
// use the global registered formatter.
this.statusBar.update(FormatterStatus.Ready);
return;
}
const workspaceFolder = workspace.getWorkspaceFolder(document.uri);
if (!workspaceFolder) {
// Do nothing, this is only for registering formatters in workspace folder.
return;
}
const prettierInstance = await this.moduleResolver.getPrettierInstance(
workspaceFolder.uri.fsPath,
);
const isRegistered = this.registeredWorkspaces.has(
workspaceFolder.uri.fsPath,
);
// If there isn't an instance here, it is because the module
// could not be loaded either locally or globally when specified
if (!prettierInstance) {
this.statusBar.update(FormatterStatus.Error);
return;
}
const selectors = await this.getSelectors(
prettierInstance,
document.uri,
workspaceFolder.uri,
);
this.statusBar.updateConfig({
selector: selectors.languageSelector,
});
if (!isRegistered) {
this.registerDocumentFormatEditorProviders(selectors);
this.registeredWorkspaces.add(workspaceFolder.uri.fsPath);
this.loggingService.logDebug(
`Enabling Prettier for Workspace ${workspaceFolder.uri.fsPath}`,
selectors,
);
}
const score = languages.match(selectors.languageSelector, document);
if (score > 0) {
this.statusBar.update(FormatterStatus.Ready);
} else {
this.statusBar.update(FormatterStatus.Disabled);
}
};
public async registerGlobal() {
const instance = await this.moduleResolver.getGlobalPrettierInstance();
const selectors = await this.getSelectors(instance);
this.registerDocumentFormatEditorProviders(selectors);
this.loggingService.logDebug("Enabling Prettier globally", selectors);
}
public dispose = () => {
this.moduleResolver.dispose();
this.formatterHandler?.dispose();
this.rangeFormatterHandler?.dispose();
this.codeActionHandler?.dispose();
this.formatterHandler = undefined;
this.rangeFormatterHandler = undefined;
this.codeActionHandler = undefined;
};
private registerDocumentFormatEditorProviders({
languageSelector,
rangeLanguageSelector,
}: ISelectors) {
this.dispose();
const editProvider = new PrettierEditProvider(this.provideEdits);
const codeActionProvider = new PrettierCodeActionProvider(
this.provideEdits,
);
this.rangeFormatterHandler =
languages.registerDocumentRangeFormattingEditProvider(
rangeLanguageSelector,
editProvider,
);
this.formatterHandler = languages.registerDocumentFormattingEditProvider(
languageSelector,
editProvider,
);
this.codeActionHandler = languages.registerCodeActionsProvider(
languageSelector,
codeActionProvider,
{
providedCodeActionKinds:
PrettierCodeActionProvider.providedCodeActionKinds,
},
);
}
/**
* Build formatter selectors
*/
private getSelectors = async (
prettierInstance: PrettierModule | PrettierInstance,
documentUri?: Uri,
workspaceFolderUri?: Uri,
): Promise<ISelectors> => {
let plugins: (string | PrettierPlugin)[] = [];
// Prettier v3 does not load plugins automatically
// So need to resolve config to get plugin paths for Prettier to import.
if (
documentUri &&
"resolveConfig" in prettierInstance &&
isAboveV3(prettierInstance.version)
) {
const resolvedConfig = await this.moduleResolver.resolveConfig(
prettierInstance,
documentUri.fsPath,
getWorkspaceConfig(documentUri),
);
if (resolvedConfig === "error") {
this.statusBar.update(FormatterStatus.Error);
} else if (resolvedConfig === "disabled") {
this.statusBar.update(FormatterStatus.Disabled);
} else if (resolvedConfig?.plugins) {
// Resolve plugin paths so getSupportInfo can discover their languages
// We're inside isAboveV3 check, so use file:// URLs for ESM import
plugins = await resolvePluginPaths(
resolvedConfig.plugins,
documentUri.fsPath,
true, // Use file:// URLs for Prettier v3+
);
}
}
const { languages } = await prettierInstance.getSupportInfo({
plugins,
});
languages.forEach((lang) => {
if (lang && lang.vscodeLanguageIds) {
this.allLanguages.push(...lang.vscodeLanguageIds);
}
});
this.allLanguages = this.allLanguages.filter((value, index, self) => {
return self.indexOf(value) === index;
});
languages.forEach((lang) => {
if (lang && lang.extensions) {
this.allExtensions.push(...lang.extensions);
}
});
this.allExtensions = this.allExtensions.filter((value, index, self) => {
return self.indexOf(value) === index;
});
const { documentSelectors } = getWorkspaceConfig();
// Language selector for file extensions
const extensionLanguageSelector: DocumentFilter[] = workspaceFolderUri
? this.allExtensions.length === 0
? []
: [
{
pattern: `${workspaceFolderUri.fsPath}/**/*.{${this.allExtensions
.map((e) => e.substring(1))
.join(",")}}`,
scheme: "file",
},
]
: [];
const customLanguageSelectors: DocumentFilter[] = workspaceFolderUri
? documentSelectors.map((pattern) => ({
pattern: `${workspaceFolderUri.fsPath}/${pattern}`,
scheme: "file",
}))
: [];
const defaultLanguageSelectors: DocumentFilter[] = [
...this.allLanguages.map((language) => ({ language })),
{ language: "jsonc", scheme: "vscode-userdata" }, // Selector for VSCode settings.json
];
const languageSelector = [
...customLanguageSelectors,
...extensionLanguageSelector,
...defaultLanguageSelectors,
];
const rangeLanguageSelector: DocumentFilter[] = [
...this.allRangeLanguages.map((language) => ({
language,
})),
];
return { languageSelector, rangeLanguageSelector };
};
private provideEdits = async (
document: TextDocument,
options: ExtensionFormattingOptions,
): Promise<TextEdit[]> => {
const startTime = new Date().getTime();
const result = await this.format(document.getText(), document, options);
if (!result) {
// No edits happened, return never so VS Code can try other formatters
return [];
}
const duration = new Date().getTime() - startTime;
this.loggingService.logInfo(`Formatting completed in ${duration}ms.`);
const edit = this.minimalEdit(document, result);
if (!edit) {
// Document is already formatted, no changes needed
this.loggingService.logDebug(
"Document is already formatted, no changes needed.",
);
return [];
}
return [edit];
};
private minimalEdit(
document: TextDocument,
string1: string,
): TextEdit | null {
const string0 = document.getText();
// Quick check: if strings are identical, no edit needed
if (string0 === string1) {
return null;
}
// length of common prefix
let i = 0;
while (
i < string0.length &&
i < string1.length &&
string0[i] === string1[i]
) {
++i;
}
// length of common suffix
let j = 0;
while (
i + j < string0.length &&
i + j < string1.length &&
string0[string0.length - j - 1] === string1[string1.length - j - 1]
) {
++j;
}
const newText = string1.substring(i, string1.length - j);
const pos0 = document.positionAt(i);
const pos1 = document.positionAt(string0.length - j);
return TextEdit.replace(new Range(pos0, pos1), newText);
}
/**
* Format the given text with user's configuration.
* @param text Text to format
* @param path formatting file's path
* @returns {string} formatted text
*/
private async format(
text: string,
doc: TextDocument,
options: ExtensionFormattingOptions,
): Promise<string | undefined> {
const { fileName, uri, languageId } = doc;
this.loggingService.logInfo(`Formatting ${uri}`);
const vscodeConfig = getWorkspaceConfig(doc);
const resolvedConfig = await this.moduleResolver.getResolvedConfig(
doc,
vscodeConfig,
);
if (resolvedConfig === "error") {
this.statusBar.update(FormatterStatus.Error);
return;
}
if (resolvedConfig === "disabled") {
this.statusBar.update(FormatterStatus.Disabled);
return;
}
const prettierInstance =
await this.moduleResolver.getPrettierInstance(fileName);
this.loggingService.logInfo("PrettierInstance:", prettierInstance);
if (!prettierInstance) {
this.loggingService.logError(
"Prettier could not be loaded. See previous logs for more information.",
);
this.statusBar.update(FormatterStatus.Error);
return;
}
let resolvedIgnorePath: string | undefined;
if (vscodeConfig.ignorePath) {
resolvedIgnorePath = await this.moduleResolver.getResolvedIgnorePath(
fileName,
vscodeConfig.ignorePath,
);
if (resolvedIgnorePath) {
this.loggingService.logInfo(
`Using ignore file (if present) at ${resolvedIgnorePath}`,
);
}
}
// Resolve plugin paths for Prettier
// For v3+, use file:// URLs (ESM import); for v2, use absolute paths (require)
const useFileUrls = isAboveV3(prettierInstance.version);
const resolvedPlugins = await resolvePluginPaths(
resolvedConfig?.plugins,
fileName,
useFileUrls,
);
this.loggingService.logInfo("Resolved plugins:", resolvedPlugins);
let fileInfo: PrettierFileInfoResult | undefined;
// Only call getFileInfo for actual files (not untitled documents)
// Untitled documents have uri.scheme === 'untitled' and their fileName
// is just a display name like 'Untitled-1', not a real path
if (uri.scheme === "file") {
// We set resolveConfig: false because we've already resolved the config
// ourselves with pre-loaded plugins. If we set it to true, Prettier v3
// would try to resolve the config again and import plugins from its own
// context, which fails when running from the extension directory.
fileInfo = await prettierInstance.getFileInfo(fileName, {
ignorePath: resolvedIgnorePath,
plugins: resolvedPlugins,
resolveConfig: false,
withNodeModules: vscodeConfig.withNodeModules,
});
this.loggingService.logInfo("File Info:", fileInfo);
}
if (!options.force && fileInfo && fileInfo.ignored) {
this.loggingService.logInfo("File is ignored, skipping.");
this.statusBar.update(FormatterStatus.Ignore);
return;
}
const parserSetting =
typeof vscodeConfig.parser === "string"
? vscodeConfig.parser.trim()
: undefined;
const parserSettingIsVSCode =
parserSetting?.toLowerCase() === "vscode";
let parserSettingWasExplicit = false;
let parser: PrettierBuiltInParserName | string | undefined;
let supportInfoLanguages:
| Awaited<ReturnType<typeof prettierInstance.getSupportInfo>>["languages"]
| undefined;
const getSupportInfoLanguages = async () => {
if (!supportInfoLanguages) {
const { languages } = await prettierInstance.getSupportInfo({
plugins: resolvedPlugins,
});
supportInfoLanguages = languages;
}
return supportInfoLanguages;
};
if (parserSetting) {
parserSettingWasExplicit = true;
if (parserSettingIsVSCode) {
if (languageId !== "plaintext") {
const languages = await getSupportInfoLanguages();
parser = getParserFromLanguageId(languages, uri, languageId);
} else {
this.loggingService.logWarning(
"Parser set to 'vscode' but language is plaintext; no parser available.",
);
}
} else {
parser = parserSetting;
}
this.loggingService.logInfo(
"Using parser from VS Code settings:",
parser ?? parserSetting,
);
}
if (!parser && !parserSettingWasExplicit) {
if (fileInfo && fileInfo.inferredParser) {
parser = fileInfo.inferredParser;
} else if (resolvedConfig && resolvedConfig.parser) {
// Parser specified in config (e.g., via overrides for custom extensions)
parser = resolvedConfig.parser as string;
} else if (languageId !== "plaintext") {
// Don't attempt VS Code language for plaintext because we never have
// a formatter for plaintext and most likely the reason for this is
// somebody has registered a custom file extension without properly
// configuring the parser in their prettier config.
this.loggingService.logWarning(
`Parser not inferred, trying VS Code language.`,
);
const languages = await getSupportInfoLanguages();
parser = getParserFromLanguageId(languages, uri, languageId);
}
}
if (!parser) {
this.loggingService.logError(
`Failed to resolve a parser, skipping file. If you registered a custom file extension, be sure to configure the parser.`,
);
this.statusBar.update(FormatterStatus.Error);
return;
}
const resolvedConfigForFormatting =
parserSettingWasExplicit && resolvedConfig
? (() => {
const { parser: _parser, ...rest } = resolvedConfig;
return rest;
})()
: resolvedConfig;
const prettierOptions = this.getPrettierOptions(
fileName,
parser as PrettierBuiltInParserName,
vscodeConfig,
resolvedConfigForFormatting,
options,
resolvedPlugins,
parserSettingWasExplicit,
);
this.loggingService.logInfo("Prettier Options:", prettierOptions);
try {
const formattedText = await prettierInstance.format(
text,
prettierOptions,
);
this.statusBar.update(FormatterStatus.Success);
return formattedText;
} catch (error) {
this.loggingService.logError("Error formatting document.", error);
this.statusBar.update(FormatterStatus.Error);
return text;
}
}
private getPrettierOptions(
fileName: string,
parser: PrettierBuiltInParserName,
vsCodeConfig: PrettierOptions,
configOptions: PrettierOptions | null,
extensionFormattingOptions: ExtensionFormattingOptions,
resolvedPlugins: (string | PrettierPlugin)[],
parserSettingWasExplicit: boolean,
): Partial<PrettierOptions> {
const fallbackToVSCodeConfig = configOptions === null;
const vsOpts: PrettierOptions = {};
if (fallbackToVSCodeConfig) {
vsOpts.arrowParens = vsCodeConfig.arrowParens;
vsOpts.bracketSpacing = vsCodeConfig.bracketSpacing;
vsOpts.endOfLine = vsCodeConfig.endOfLine;
vsOpts.htmlWhitespaceSensitivity = vsCodeConfig.htmlWhitespaceSensitivity;
vsOpts.insertPragma = vsCodeConfig.insertPragma;
vsOpts.singleAttributePerLine = vsCodeConfig.singleAttributePerLine;
vsOpts.bracketSameLine = vsCodeConfig.bracketSameLine;
vsOpts.jsxBracketSameLine = vsCodeConfig.jsxBracketSameLine;
vsOpts.jsxSingleQuote = vsCodeConfig.jsxSingleQuote;
vsOpts.printWidth = vsCodeConfig.printWidth;
vsOpts.proseWrap = vsCodeConfig.proseWrap;
vsOpts.quoteProps = vsCodeConfig.quoteProps;
vsOpts.requirePragma = vsCodeConfig.requirePragma;
vsOpts.semi = vsCodeConfig.semi;
vsOpts.singleQuote = vsCodeConfig.singleQuote;
vsOpts.tabWidth = vsCodeConfig.tabWidth;
vsOpts.trailingComma = vsCodeConfig.trailingComma;
vsOpts.useTabs = vsCodeConfig.useTabs;
vsOpts.embeddedLanguageFormatting =
vsCodeConfig.embeddedLanguageFormatting;
vsOpts.vueIndentScriptAndStyle = vsCodeConfig.vueIndentScriptAndStyle;
vsOpts.experimentalTernaries = vsCodeConfig.experimentalTernaries;
vsOpts.objectWrap = vsCodeConfig.objectWrap;
vsOpts.experimentalOperatorPosition =
vsCodeConfig.experimentalOperatorPosition;
}
this.loggingService.logInfo(
fallbackToVSCodeConfig
? "Using VS Code configuration"
: "Using local configuration (VS Code configuration will not be used)",
);
let rangeFormattingOptions: RangeFormattingOptions | undefined;
if (
extensionFormattingOptions.rangeEnd &&
extensionFormattingOptions.rangeStart
) {
rangeFormattingOptions = {
rangeEnd: extensionFormattingOptions.rangeEnd,
rangeStart: extensionFormattingOptions.rangeStart,
};
}
const configOptionsToApply =
parserSettingWasExplicit && configOptions
? (() => {
const { parser: _parser, ...rest } = configOptions;
return rest;
})()
: configOptions;
const options: PrettierOptions = {
...(fallbackToVSCodeConfig ? vsOpts : {}),
...{
/* cspell: disable-next-line */
filepath: fileName,
parser: parser as PrettierBuiltInParserName,
},
...(rangeFormattingOptions || {}),
...(configOptionsToApply || {}),
// Pass resolved plugin paths for Prettier to import
...(resolvedPlugins.length > 0 ? { plugins: resolvedPlugins } : {}),
};
if (extensionFormattingOptions.force && options.requirePragma === true) {
options.requirePragma = false;
}
return options;
}
}