Skip to content
This repository was archived by the owner on May 7, 2020. It is now read-only.

Commit 8a5d23c

Browse files
authored
switch to using prettier-plugin-svelte for formatting (#10)
* switch to using prettier-plugin-svelte for formatting * fallback to prettier html formatting on svelte v2 * update to prettier-plugin-svelte v0.4.1 * update to prettier-plugin-svelte v0.4.2
1 parent 644261b commit 8a5d23c

File tree

9 files changed

+75
-139
lines changed

9 files changed

+75
-139
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
"indent-string": "^3.2.0",
5050
"lodash": "^4.17.10",
5151
"prettier": "1.17.0",
52+
"prettier-plugin-svelte": "0.4.2",
5253
"sinon": "^4.5.0",
5354
"source-map": "^0.7.3",
5455
"svelte": "3.2.0",

src/plugins/CSSPlugin.ts

Lines changed: 0 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,6 @@ import {
55
getLESSLanguageService,
66
LanguageService,
77
} from 'vscode-css-languageservice';
8-
import * as prettier from 'prettier';
9-
import detectIndent from 'detect-indent';
10-
import indentString from 'indent-string';
118
import {
129
Host,
1310
Document,
@@ -19,9 +16,7 @@ import {
1916
Fragment,
2017
DiagnosticsProvider,
2118
Diagnostic,
22-
TextEdit,
2319
Range,
24-
FormattingProvider,
2520
CompletionList,
2621
DocumentColorsProvider,
2722
ColorInformation,
@@ -38,7 +33,6 @@ export class CSSPlugin
3833
HoverProvider,
3934
CompletionsProvider,
4035
DiagnosticsProvider,
41-
FormattingProvider,
4236
DocumentColorsProvider,
4337
ColorPresentationsProvider,
4438
DocumentSymbolsProvider {
@@ -52,7 +46,6 @@ export class CSSPlugin
5246
diagnostics: { enable: true },
5347
hover: { enable: true },
5448
completions: { enable: true },
55-
format: { enable: true },
5649
documentColors: { enable: true },
5750
colorPresentations: { enable: true },
5851
documentSymbols: { enable: true },
@@ -127,31 +120,6 @@ export class CSSPlugin
127120
return [...(results ? results.items : []), ...emmetResults.items];
128121
}
129122

130-
async formatDocument(document: Document): Promise<TextEdit[]> {
131-
if (!this.host.getConfig<boolean>('css.format.enable')) {
132-
return [];
133-
}
134-
135-
if (document.getTextLength() === 0) {
136-
return [];
137-
}
138-
139-
const config = await prettier.resolveConfig(document.getFilePath()!);
140-
const formattedCode = prettier.format(document.getText(), {
141-
...config,
142-
parser: getLanguage(extractLanguage(document)),
143-
});
144-
145-
let indent = detectIndent(document.getText());
146-
return [
147-
TextEdit.replace(
148-
Range.create(document.positionAt(0), document.positionAt(document.getTextLength())),
149-
'\n' +
150-
indentString(formattedCode, indent.amount, indent.type == 'tab' ? '\t' : ' '),
151-
),
152-
];
153-
}
154-
155123
getDocumentColors(document: Document): ColorInformation[] {
156124
if (!this.host.getConfig<boolean>('css.documentColors.enable')) {
157125
return [];

src/plugins/HTMLPlugin.ts

Lines changed: 2 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
1-
import {
2-
getLanguageService,
3-
HTMLDocument,
4-
HTMLFormatConfiguration,
5-
} from 'vscode-html-languageservice';
1+
import { getLanguageService, HTMLDocument } from 'vscode-html-languageservice';
62
import { getEmmetCompletionParticipants } from 'vscode-emmet-helper';
73
import {
84
Host,
@@ -13,20 +9,16 @@ import {
139
CompletionsProvider,
1410
CompletionItem,
1511
CompletionList,
16-
FormattingProvider,
17-
TextEdit,
18-
Range,
1912
SymbolInformation,
2013
} from '../api';
2114

22-
export class HTMLPlugin implements HoverProvider, CompletionsProvider, FormattingProvider {
15+
export class HTMLPlugin implements HoverProvider, CompletionsProvider {
2316
public pluginId = 'html';
2417
public defaultConfig = {
2518
enable: true,
2619
hover: { enable: true },
2720
completions: { enable: true },
2821
tagComplete: { enable: true },
29-
format: { enable: true },
3022
documentSymbols: { enable: true },
3123
};
3224

@@ -89,33 +81,6 @@ export class HTMLPlugin implements HoverProvider, CompletionsProvider, Formattin
8981
return this.lang.doTagComplete(document, position, html);
9082
}
9183

92-
formatDocument(document: Document): TextEdit[] {
93-
if (!this.host.getConfig<boolean>('html.format.enable')) {
94-
return [];
95-
}
96-
97-
const html = this.documents.get(document);
98-
if (!html) {
99-
return [];
100-
}
101-
102-
const style = html.roots.find(node => node.tag === 'style');
103-
const script = html.roots.find(node => node.tag === 'script');
104-
105-
let rangeEnd = document.getTextLength();
106-
if (style && style.start < rangeEnd) {
107-
rangeEnd = style.start + 1;
108-
}
109-
if (script && script.start < rangeEnd) {
110-
rangeEnd = script.start + 1;
111-
}
112-
113-
const range = Range.create(document.positionAt(0), document.positionAt(rangeEnd));
114-
115-
const settings = this.host.getConfig<HTMLFormatConfiguration>('html.format.settings') || {};
116-
return this.lang.format(document, range, settings);
117-
}
118-
11984
getDocumentSymbols(document: Document): SymbolInformation[] {
12085
if (!this.host.getConfig<boolean>('html.documentSymbols.enable')) {
12186
return [];

src/plugins/SveltePlugin.ts

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import cosmic from 'cosmiconfig';
2+
import * as prettier from 'prettier';
23
import {
34
DiagnosticsProvider,
45
Document,
@@ -8,11 +9,13 @@ import {
89
Fragment,
910
Position,
1011
Host,
12+
FormattingProvider,
13+
TextEdit,
1114
} from '../api';
1215
import { SvelteDocument } from '../lib/documents/SvelteDocument';
1316
import { RawSourceMap, RawIndexMap, SourceMapConsumer } from 'source-map';
1417
import { PreprocessOptions, CompileOptions, Warning } from 'svelte/compiler';
15-
import { loadSvelte } from './svelte/loadSvelte';
18+
import { importSvelte, getSveltePackageInfo } from './svelte/sveltePackage';
1619

1720
interface SvelteConfig extends CompileOptions {
1821
preprocess?: PreprocessOptions;
@@ -22,11 +25,12 @@ const DEFAULT_OPTIONS: CompileOptions = {
2225
dev: true,
2326
};
2427

25-
export class SveltePlugin implements DiagnosticsProvider {
28+
export class SveltePlugin implements DiagnosticsProvider, FormattingProvider {
2629
public pluginId = 'svelte';
2730
public defaultConfig = {
2831
enable: true,
2932
diagnostics: { enable: true },
33+
format: { enable: true },
3034
};
3135

3236
private host!: Host;
@@ -43,7 +47,7 @@ export class SveltePlugin implements DiagnosticsProvider {
4347
let source = document.getText();
4448

4549
const config = await this.loadConfig(document.getFilePath()!);
46-
const svelte = loadSvelte(document.getFilePath()!) as any;
50+
const svelte = importSvelte(document.getFilePath()!) as any;
4751

4852
const preprocessor = makePreprocessor(document as SvelteDocument, config.preprocess);
4953
source = (await svelte.preprocess(source, preprocessor)).toString();
@@ -93,6 +97,27 @@ export class SveltePlugin implements DiagnosticsProvider {
9397
return { ...DEFAULT_OPTIONS, preprocess: {} };
9498
}
9599
}
100+
101+
async formatDocument(document: Document): Promise<TextEdit[]> {
102+
if (!this.host.getConfig<boolean>('svelte.format.enable')) {
103+
return [];
104+
}
105+
106+
const config = await prettier.resolveConfig(document.getFilePath()!);
107+
const sveltePkg = getSveltePackageInfo(document.getFilePath()!);
108+
const formattedCode = prettier.format(document.getText(), {
109+
...config,
110+
plugins: [require.resolve('prettier-plugin-svelte')],
111+
parser: sveltePkg.version.major >= 3 ? ('svelte' as any) : 'html',
112+
});
113+
114+
return [
115+
TextEdit.replace(
116+
Range.create(document.positionAt(0), document.positionAt(document.getTextLength())),
117+
formattedCode,
118+
),
119+
];
120+
}
96121
}
97122

98123
interface Preprocessor extends PreprocessOptions {

src/plugins/TypeScriptPlugin.ts

Lines changed: 0 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
import ts, { NavigationTree } from 'typescript';
2-
import * as prettier from 'prettier';
3-
import detectIndent from 'detect-indent';
4-
import indentString from 'indent-string';
52
import URL from 'vscode-uri';
63
import {
74
DiagnosticsProvider,
@@ -13,8 +10,6 @@ import {
1310
HoverProvider,
1411
Position,
1512
Hover,
16-
FormattingProvider,
17-
TextEdit,
1813
OnRegister,
1914
Host,
2015
DocumentSymbolsProvider,
@@ -35,7 +30,6 @@ export class TypeScriptPlugin
3530
implements
3631
DiagnosticsProvider,
3732
HoverProvider,
38-
FormattingProvider,
3933
OnRegister,
4034
DocumentSymbolsProvider,
4135
CompletionsProvider {
@@ -48,7 +42,6 @@ export class TypeScriptPlugin
4842
enable: true,
4943
diagnostics: { enable: true },
5044
hover: { enable: true },
51-
format: { enable: true },
5245
};
5346

5447
private host!: Host;
@@ -112,31 +105,6 @@ export class TypeScriptPlugin
112105
};
113106
}
114107

115-
async formatDocument(document: Document): Promise<TextEdit[]> {
116-
if (!this.host.getConfig<boolean>('typescript.format.enable')) {
117-
return [];
118-
}
119-
120-
if (document.getTextLength() === 0) {
121-
return [];
122-
}
123-
124-
const config = await prettier.resolveConfig(document.getFilePath()!);
125-
const formattedCode = prettier.format(document.getText(), {
126-
...config,
127-
parser: getParserFromAttributes(document.getAttributes()),
128-
});
129-
130-
let indent = detectIndent(document.getText());
131-
return [
132-
TextEdit.replace(
133-
Range.create(document.positionAt(0), document.positionAt(document.getTextLength())),
134-
'\n' +
135-
indentString(formattedCode, indent.amount, indent.type == 'tab' ? '\t' : ' '),
136-
),
137-
];
138-
}
139-
140108
getDocumentSymbols(document: Document): SymbolInformation[] {
141109
if (!this.host.getConfig<boolean>('typescript.documentSymbols.enable')) {
142110
return [];
@@ -221,17 +189,3 @@ export class TypeScriptPlugin
221189
});
222190
}
223191
}
224-
225-
function getParserFromAttributes(attrs: Record<string, string>): prettier.BuiltInParserName {
226-
const type = attrs.lang || attrs.type;
227-
228-
switch (type) {
229-
case 'typescript':
230-
case 'text/typescript':
231-
return 'typescript';
232-
case 'javascript':
233-
case 'text/javascript':
234-
default:
235-
return 'babylon';
236-
}
237-
}

src/plugins/svelte/loadSvelte.ts

Lines changed: 0 additions & 19 deletions
This file was deleted.
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { dirname, resolve } from 'path';
2+
3+
export function getSveltePackageInfo(fromPath: string) {
4+
const packageJSONPath = require.resolve('svelte/package.json', {
5+
paths: [fromPath, __dirname],
6+
});
7+
const { version } = require(packageJSONPath);
8+
const [major, minor, patch] = version.split('.');
9+
10+
return {
11+
path: dirname(packageJSONPath),
12+
version: {
13+
full: version,
14+
major,
15+
minor,
16+
patch,
17+
},
18+
};
19+
}
20+
21+
export function importSvelte(fromPath: string) {
22+
const pkg = getSveltePackageInfo(fromPath);
23+
24+
let main = pkg.path;
25+
if (pkg.version.major > 2) {
26+
main = resolve(pkg.path, 'compiler');
27+
}
28+
29+
console.log('Using Svelte v' + pkg.version.full, 'from', main);
30+
31+
return require(main);
32+
}

src/server.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import { HTMLPlugin } from './plugins/HTMLPlugin';
1313
import { CSSPlugin } from './plugins/CSSPlugin';
1414
import { wrapFragmentPlugin } from './api/wrapFragmentPlugin';
1515
import { TypeScriptPlugin } from './plugins/TypeScriptPlugin';
16-
import { set, get } from 'lodash';
1716

1817
namespace TagCloseRequest {
1918
export const type: RequestType<
@@ -58,7 +57,6 @@ export function startServer() {
5857
});
5958

6059
connection.onDidChangeConfiguration(({ settings }) => {
61-
set(settings.svelte, 'plugin.html.format.settings', get(settings, 'html.format', {}));
6260
manager.updateConfig(settings.svelte);
6361
});
6462

yarn.lock

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,13 @@ path-to-regexp@^1.7.0:
415415
dependencies:
416416
isarray "0.0.1"
417417

418+
prettier-plugin-svelte@0.4.2:
419+
version "0.4.2"
420+
resolved "https://registry.npmjs.org/prettier-plugin-svelte/-/prettier-plugin-svelte-0.4.2.tgz#29f7ea4c8c2068674d950428ab7926fb8234190c"
421+
integrity sha512-BjMxmU5aZJSW5hDEG3BhZ4GUzx28cgOkfwO/SOCxkCq/4qbAR2AoCtB+t7j2mg0TPJG0oA7glCDri8QpcTSuQA==
422+
dependencies:
423+
tslib "^1.9.3"
424+
418425
prettier@1.17.0:
419426
version "1.17.0"
420427
resolved "https://registry.npmjs.org/prettier/-/prettier-1.17.0.tgz#53b303676eed22cc14a9f0cec09b477b3026c008"
@@ -516,6 +523,11 @@ ts-node@^7.0.1:
516523
source-map-support "^0.5.6"
517524
yn "^2.0.0"
518525

526+
tslib@^1.9.3:
527+
version "1.9.3"
528+
resolved "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz#d7e4dd79245d85428c4d7e4822a79917954ca286"
529+
integrity sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==
530+
519531
type-detect@4.0.8, type-detect@^4.0.5:
520532
version "4.0.8"
521533
resolved "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c"

0 commit comments

Comments
 (0)