@@ -41,9 +41,7 @@ export class Formatter {
4141 formatOptions ?: LSP . FormattingOptions | null ,
4242 shfmtConfig ?: Record < string , string | boolean > | null ,
4343 ) : Promise < TextEdit [ ] > {
44- const documentText = document . getText ( )
45-
46- const result = await this . runShfmt ( documentText , formatOptions , shfmtConfig )
44+ const result = await this . runShfmt ( document , formatOptions , shfmtConfig )
4745
4846 if ( ! this . _canFormat ) {
4947 return [ ]
@@ -61,7 +59,7 @@ export class Formatter {
6159 }
6260
6361 private async runShfmt (
64- documentText : string ,
62+ document : TextDocument ,
6563 formatOptions ?: LSP . FormattingOptions | null ,
6664 shfmtConfig ?: Record < string , string | boolean > | null ,
6765 ) : Promise < string > {
@@ -74,6 +72,12 @@ export class Formatter {
7472 if ( shfmtConfig ?. simplifyCode ) args . push ( '-s' ) // --simplify
7573 if ( shfmtConfig ?. spaceRedirects ) args . push ( '-sr' ) // --space-redirects
7674
75+ // If we can determine a local filename, pass that to shfmt to aid language dialect detection
76+ const filePathMatch = document . uri . match ( / ^ f i l e : \/ \/ ( .* ) $ / )
77+ if ( filePathMatch ) {
78+ args . push ( `--filename=${ filePathMatch [ 1 ] } ` )
79+ }
80+
7781 logger . debug ( `Shfmt: running "${ this . executablePath } ${ args . join ( ' ' ) } "` )
7882
7983 let out = ''
@@ -90,7 +94,7 @@ export class Formatter {
9094 // This is solved in Node >= 15.1 by the "on('spawn', ...)" event, but we need to
9195 // support earlier versions.
9296 } )
93- proc . stdin . end ( documentText )
97+ proc . stdin . end ( document . getText ( ) )
9498 } )
9599
96100 let exit
0 commit comments