11import { GetConfig } from './types'
2- import { patchMethod } from './utils'
32
4- export default ( proxy : ts . LanguageService , languageService : ts . LanguageService , c : GetConfig ) => {
3+ export default ( proxy : ts . LanguageService , languageService : ts . LanguageService , languageServiceHost : ts . LanguageServiceHost , c : GetConfig ) => {
54 // todo: add our formatting rules!
65 // tsFull.formatting.getAllRules
76
@@ -13,8 +12,7 @@ export default (proxy: ts.LanguageService, languageService: ts.LanguageService,
1312 if ( line . startsWith ( expected ) ) return true
1413 return false
1514 }
16- const isFormattingLineIgnored = ( sourceFile : ts . SourceFile , position : number ) => {
17- const fullText = sourceFile . getFullText ( )
15+ const isFormattingLineIgnored = ( fullText : string , position : number ) => {
1816 // check that lines before line are not ignored
1917 const linesBefore = fullText . slice ( 0 , position ) . split ( '\n' )
2018 if ( isExpectedDirective ( linesBefore [ linesBefore . length - 2 ] , '@ts-format-ignore-line' ) ) {
@@ -32,20 +30,24 @@ export default (proxy: ts.LanguageService, languageService: ts.LanguageService,
3230 }
3331 return isInsideIgnoredRegion
3432 }
35- const toPatchFormatMethods = [ 'formatSelection' , 'formatOnOpeningCurly' , 'formatOnClosingCurly' , 'formatOnSemicolon' , 'formatOnEnter' ]
36- for ( const toPatchFormatMethod of toPatchFormatMethods ) {
37- patchMethod ( tsFull . formatting , toPatchFormatMethod as any , oldFn => ( ...args ) => {
38- const result = oldFn ( ...args )
39- // arg position depends on the method, so we need to find it
40- const sourceFile = args . find ( arg => ts . isSourceFile ( arg as any ) )
41- return result . filter ( ( { span } ) => {
42- if ( isFormattingLineIgnored ( sourceFile as ts . SourceFile , span . start ) ) {
33+
34+ for ( const method of [
35+ 'getFormattingEditsForDocument' ,
36+ 'getFormattingEditsForRange' ,
37+ 'getFormattingEditsAfterKeystroke' ,
38+ ] satisfies ( keyof ts . LanguageService ) [ ] ) {
39+ proxy [ method ] = ( ...args ) => {
40+ const textChanges : ts . TextChange [ ] = ( languageService [ method ] as any ) ( ...args )
41+ const fileName = args [ 0 ]
42+ const scriptSnapshot = languageServiceHost . getScriptSnapshot ( fileName ) !
43+ const fileContent = scriptSnapshot . getText ( 0 , scriptSnapshot . getLength ( ) )
44+
45+ return textChanges . filter ( ( { span } ) => {
46+ if ( isFormattingLineIgnored ( fileContent , span . start ) ) {
4347 return false
4448 }
4549 return true
4650 } )
47- } )
51+ }
4852 }
49- // we could easily patch languageService methods getFormattingEditsForDocument, getFormattingEditsAfterKeystroke and getFormattingEditsForRange
50- // but since formatting happens in syntax server, we don't have access to actual sourceFile, so we can't provide implementation
5153}
0 commit comments