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

Commit

Permalink
switch to using prettier-plugin-svelte for formatting (#10)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
jamesbirtles committed May 5, 2019
1 parent 644261b commit 8a5d23c
Show file tree
Hide file tree
Showing 9 changed files with 75 additions and 139 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"indent-string": "^3.2.0",
"lodash": "^4.17.10",
"prettier": "1.17.0",
"prettier-plugin-svelte": "0.4.2",
"sinon": "^4.5.0",
"source-map": "^0.7.3",
"svelte": "3.2.0",
Expand Down
32 changes: 0 additions & 32 deletions src/plugins/CSSPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@ import {
getLESSLanguageService,
LanguageService,
} from 'vscode-css-languageservice';
import * as prettier from 'prettier';
import detectIndent from 'detect-indent';
import indentString from 'indent-string';
import {
Host,
Document,
Expand All @@ -19,9 +16,7 @@ import {
Fragment,
DiagnosticsProvider,
Diagnostic,
TextEdit,
Range,
FormattingProvider,
CompletionList,
DocumentColorsProvider,
ColorInformation,
Expand All @@ -38,7 +33,6 @@ export class CSSPlugin
HoverProvider,
CompletionsProvider,
DiagnosticsProvider,
FormattingProvider,
DocumentColorsProvider,
ColorPresentationsProvider,
DocumentSymbolsProvider {
Expand All @@ -52,7 +46,6 @@ export class CSSPlugin
diagnostics: { enable: true },
hover: { enable: true },
completions: { enable: true },
format: { enable: true },
documentColors: { enable: true },
colorPresentations: { enable: true },
documentSymbols: { enable: true },
Expand Down Expand Up @@ -127,31 +120,6 @@ export class CSSPlugin
return [...(results ? results.items : []), ...emmetResults.items];
}

async formatDocument(document: Document): Promise<TextEdit[]> {
if (!this.host.getConfig<boolean>('css.format.enable')) {
return [];
}

if (document.getTextLength() === 0) {
return [];
}

const config = await prettier.resolveConfig(document.getFilePath()!);
const formattedCode = prettier.format(document.getText(), {
...config,
parser: getLanguage(extractLanguage(document)),
});

let indent = detectIndent(document.getText());
return [
TextEdit.replace(
Range.create(document.positionAt(0), document.positionAt(document.getTextLength())),
'\n' +
indentString(formattedCode, indent.amount, indent.type == 'tab' ? '\t' : ' '),
),
];
}

getDocumentColors(document: Document): ColorInformation[] {
if (!this.host.getConfig<boolean>('css.documentColors.enable')) {
return [];
Expand Down
39 changes: 2 additions & 37 deletions src/plugins/HTMLPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import {
getLanguageService,
HTMLDocument,
HTMLFormatConfiguration,
} from 'vscode-html-languageservice';
import { getLanguageService, HTMLDocument } from 'vscode-html-languageservice';
import { getEmmetCompletionParticipants } from 'vscode-emmet-helper';
import {
Host,
Expand All @@ -13,20 +9,16 @@ import {
CompletionsProvider,
CompletionItem,
CompletionList,
FormattingProvider,
TextEdit,
Range,
SymbolInformation,
} from '../api';

export class HTMLPlugin implements HoverProvider, CompletionsProvider, FormattingProvider {
export class HTMLPlugin implements HoverProvider, CompletionsProvider {
public pluginId = 'html';
public defaultConfig = {
enable: true,
hover: { enable: true },
completions: { enable: true },
tagComplete: { enable: true },
format: { enable: true },
documentSymbols: { enable: true },
};

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

formatDocument(document: Document): TextEdit[] {
if (!this.host.getConfig<boolean>('html.format.enable')) {
return [];
}

const html = this.documents.get(document);
if (!html) {
return [];
}

const style = html.roots.find(node => node.tag === 'style');
const script = html.roots.find(node => node.tag === 'script');

let rangeEnd = document.getTextLength();
if (style && style.start < rangeEnd) {
rangeEnd = style.start + 1;
}
if (script && script.start < rangeEnd) {
rangeEnd = script.start + 1;
}

const range = Range.create(document.positionAt(0), document.positionAt(rangeEnd));

const settings = this.host.getConfig<HTMLFormatConfiguration>('html.format.settings') || {};
return this.lang.format(document, range, settings);
}

getDocumentSymbols(document: Document): SymbolInformation[] {
if (!this.host.getConfig<boolean>('html.documentSymbols.enable')) {
return [];
Expand Down
31 changes: 28 additions & 3 deletions src/plugins/SveltePlugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import cosmic from 'cosmiconfig';
import * as prettier from 'prettier';
import {
DiagnosticsProvider,
Document,
Expand All @@ -8,11 +9,13 @@ import {
Fragment,
Position,
Host,
FormattingProvider,
TextEdit,
} from '../api';
import { SvelteDocument } from '../lib/documents/SvelteDocument';
import { RawSourceMap, RawIndexMap, SourceMapConsumer } from 'source-map';
import { PreprocessOptions, CompileOptions, Warning } from 'svelte/compiler';
import { loadSvelte } from './svelte/loadSvelte';
import { importSvelte, getSveltePackageInfo } from './svelte/sveltePackage';

interface SvelteConfig extends CompileOptions {
preprocess?: PreprocessOptions;
Expand All @@ -22,11 +25,12 @@ const DEFAULT_OPTIONS: CompileOptions = {
dev: true,
};

export class SveltePlugin implements DiagnosticsProvider {
export class SveltePlugin implements DiagnosticsProvider, FormattingProvider {
public pluginId = 'svelte';
public defaultConfig = {
enable: true,
diagnostics: { enable: true },
format: { enable: true },
};

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

const config = await this.loadConfig(document.getFilePath()!);
const svelte = loadSvelte(document.getFilePath()!) as any;
const svelte = importSvelte(document.getFilePath()!) as any;

const preprocessor = makePreprocessor(document as SvelteDocument, config.preprocess);
source = (await svelte.preprocess(source, preprocessor)).toString();
Expand Down Expand Up @@ -93,6 +97,27 @@ export class SveltePlugin implements DiagnosticsProvider {
return { ...DEFAULT_OPTIONS, preprocess: {} };
}
}

async formatDocument(document: Document): Promise<TextEdit[]> {
if (!this.host.getConfig<boolean>('svelte.format.enable')) {
return [];
}

const config = await prettier.resolveConfig(document.getFilePath()!);
const sveltePkg = getSveltePackageInfo(document.getFilePath()!);
const formattedCode = prettier.format(document.getText(), {
...config,
plugins: [require.resolve('prettier-plugin-svelte')],
parser: sveltePkg.version.major >= 3 ? ('svelte' as any) : 'html',
});

return [
TextEdit.replace(
Range.create(document.positionAt(0), document.positionAt(document.getTextLength())),
formattedCode,
),
];
}
}

interface Preprocessor extends PreprocessOptions {
Expand Down
46 changes: 0 additions & 46 deletions src/plugins/TypeScriptPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import ts, { NavigationTree } from 'typescript';
import * as prettier from 'prettier';
import detectIndent from 'detect-indent';
import indentString from 'indent-string';
import URL from 'vscode-uri';
import {
DiagnosticsProvider,
Expand All @@ -13,8 +10,6 @@ import {
HoverProvider,
Position,
Hover,
FormattingProvider,
TextEdit,
OnRegister,
Host,
DocumentSymbolsProvider,
Expand All @@ -35,7 +30,6 @@ export class TypeScriptPlugin
implements
DiagnosticsProvider,
HoverProvider,
FormattingProvider,
OnRegister,
DocumentSymbolsProvider,
CompletionsProvider {
Expand All @@ -48,7 +42,6 @@ export class TypeScriptPlugin
enable: true,
diagnostics: { enable: true },
hover: { enable: true },
format: { enable: true },
};

private host!: Host;
Expand Down Expand Up @@ -112,31 +105,6 @@ export class TypeScriptPlugin
};
}

async formatDocument(document: Document): Promise<TextEdit[]> {
if (!this.host.getConfig<boolean>('typescript.format.enable')) {
return [];
}

if (document.getTextLength() === 0) {
return [];
}

const config = await prettier.resolveConfig(document.getFilePath()!);
const formattedCode = prettier.format(document.getText(), {
...config,
parser: getParserFromAttributes(document.getAttributes()),
});

let indent = detectIndent(document.getText());
return [
TextEdit.replace(
Range.create(document.positionAt(0), document.positionAt(document.getTextLength())),
'\n' +
indentString(formattedCode, indent.amount, indent.type == 'tab' ? '\t' : ' '),
),
];
}

getDocumentSymbols(document: Document): SymbolInformation[] {
if (!this.host.getConfig<boolean>('typescript.documentSymbols.enable')) {
return [];
Expand Down Expand Up @@ -221,17 +189,3 @@ export class TypeScriptPlugin
});
}
}

function getParserFromAttributes(attrs: Record<string, string>): prettier.BuiltInParserName {
const type = attrs.lang || attrs.type;

switch (type) {
case 'typescript':
case 'text/typescript':
return 'typescript';
case 'javascript':
case 'text/javascript':
default:
return 'babylon';
}
}
19 changes: 0 additions & 19 deletions src/plugins/svelte/loadSvelte.ts

This file was deleted.

32 changes: 32 additions & 0 deletions src/plugins/svelte/sveltePackage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { dirname, resolve } from 'path';

export function getSveltePackageInfo(fromPath: string) {
const packageJSONPath = require.resolve('svelte/package.json', {
paths: [fromPath, __dirname],
});
const { version } = require(packageJSONPath);
const [major, minor, patch] = version.split('.');

return {
path: dirname(packageJSONPath),
version: {
full: version,
major,
minor,
patch,
},
};
}

export function importSvelte(fromPath: string) {
const pkg = getSveltePackageInfo(fromPath);

let main = pkg.path;
if (pkg.version.major > 2) {
main = resolve(pkg.path, 'compiler');
}

console.log('Using Svelte v' + pkg.version.full, 'from', main);

return require(main);
}
2 changes: 0 additions & 2 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { HTMLPlugin } from './plugins/HTMLPlugin';
import { CSSPlugin } from './plugins/CSSPlugin';
import { wrapFragmentPlugin } from './api/wrapFragmentPlugin';
import { TypeScriptPlugin } from './plugins/TypeScriptPlugin';
import { set, get } from 'lodash';

namespace TagCloseRequest {
export const type: RequestType<
Expand Down Expand Up @@ -58,7 +57,6 @@ export function startServer() {
});

connection.onDidChangeConfiguration(({ settings }) => {
set(settings.svelte, 'plugin.html.format.settings', get(settings, 'html.format', {}));
manager.updateConfig(settings.svelte);
});

Expand Down
12 changes: 12 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,13 @@ path-to-regexp@^1.7.0:
dependencies:
isarray "0.0.1"

prettier-plugin-svelte@0.4.2:
version "0.4.2"
resolved "https://registry.npmjs.org/prettier-plugin-svelte/-/prettier-plugin-svelte-0.4.2.tgz#29f7ea4c8c2068674d950428ab7926fb8234190c"
integrity sha512-BjMxmU5aZJSW5hDEG3BhZ4GUzx28cgOkfwO/SOCxkCq/4qbAR2AoCtB+t7j2mg0TPJG0oA7glCDri8QpcTSuQA==
dependencies:
tslib "^1.9.3"

prettier@1.17.0:
version "1.17.0"
resolved "https://registry.npmjs.org/prettier/-/prettier-1.17.0.tgz#53b303676eed22cc14a9f0cec09b477b3026c008"
Expand Down Expand Up @@ -516,6 +523,11 @@ ts-node@^7.0.1:
source-map-support "^0.5.6"
yn "^2.0.0"

tslib@^1.9.3:
version "1.9.3"
resolved "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz#d7e4dd79245d85428c4d7e4822a79917954ca286"
integrity sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==

type-detect@4.0.8, type-detect@^4.0.5:
version "4.0.8"
resolved "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c"
Expand Down

0 comments on commit 8a5d23c

Please sign in to comment.