@@ -21,14 +21,29 @@ const doCssValidation = async (uri: vscode.Uri, ls: LanguageService) => {
2121 return ls . doValidation ( doc as any , sheet )
2222}
2323
24+ const doFormatting = async (
25+ uri : vscode . Uri ,
26+ range : vscode . Range | undefined ,
27+ options : vscode . FormattingOptions ,
28+ ls : LanguageService ,
29+ ) => {
30+ const doc = await vscode . workspace . openTextDocument ( uri )
31+ return ls . format ( doc as any , range , options ) as unknown as vscode . TextEdit [ ]
32+ }
33+
34+ const selectCssLanguageService = ( ) : LanguageService | null => {
35+ const mode = getWxssDiagnostics ( )
36+ if ( mode === 'CSS' ) return cssLangService
37+ if ( mode === 'LESS' ) return lessLangService
38+ if ( mode === 'SCSS' ) return scssLangService
39+ return null
40+ }
41+
2442const middleware : Middleware = {
2543 handleDiagnostics ( uri , diagnostics , next ) {
2644 if ( path . extname ( uri . path ) === '.wxss' ) {
27- const mode = getWxssDiagnostics ( )
28- if ( mode === 'CSS' || mode === 'LESS' || mode === 'SCSS' ) {
29- let ls : LanguageService = cssLangService
30- if ( mode === 'LESS' ) ls = lessLangService
31- else if ( mode === 'SCSS' ) ls = scssLangService
45+ const ls = selectCssLanguageService ( )
46+ if ( ls ) {
3247 // eslint-disable-next-line @typescript-eslint/no-floating-promises
3348 doCssValidation ( uri , ls )
3449 // eslint-disable-next-line promise/no-callback-in-promise
@@ -44,6 +59,24 @@ const middleware: Middleware = {
4459 }
4560 next ( uri , diagnostics )
4661 } ,
62+
63+ provideDocumentFormattingEdits ( document , options , token , next ) {
64+ if ( path . extname ( document . uri . path ) === '.wxss' ) {
65+ const ls = selectCssLanguageService ( )
66+ if ( ls ) {
67+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
68+ const ret = doFormatting ( document . uri , undefined , options , ls )
69+ // eslint-disable-next-line promise/no-callback-in-promise
70+ . catch ( ( ) => {
71+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
72+ vscode . window . showErrorMessage ( 'Failed to format CSS' )
73+ return [ ]
74+ } )
75+ return ret
76+ }
77+ }
78+ return next ( document , options , token )
79+ } ,
4780}
4881
4982export default middleware
0 commit comments