11import cosmic from 'cosmiconfig' ;
2+ import * as prettier from 'prettier' ;
23import {
34 DiagnosticsProvider ,
45 Document ,
@@ -8,11 +9,13 @@ import {
89 Fragment ,
910 Position ,
1011 Host ,
12+ FormattingProvider ,
13+ TextEdit ,
1114} from '../api' ;
1215import { SvelteDocument } from '../lib/documents/SvelteDocument' ;
1316import { RawSourceMap , RawIndexMap , SourceMapConsumer } from 'source-map' ;
1417import { PreprocessOptions , CompileOptions , Warning } from 'svelte/compiler' ;
15- import { loadSvelte } from './svelte/loadSvelte ' ;
18+ import { importSvelte , getSveltePackageInfo } from './svelte/sveltePackage ' ;
1619
1720interface 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
98123interface Preprocessor extends PreprocessOptions {
0 commit comments