1
1
import { GetConfig } from './types'
2
- import { patchMethod } from './utils'
3
2
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 ) => {
5
4
// todo: add our formatting rules!
6
5
// tsFull.formatting.getAllRules
7
6
@@ -13,8 +12,7 @@ export default (proxy: ts.LanguageService, languageService: ts.LanguageService,
13
12
if ( line . startsWith ( expected ) ) return true
14
13
return false
15
14
}
16
- const isFormattingLineIgnored = ( sourceFile : ts . SourceFile , position : number ) => {
17
- const fullText = sourceFile . getFullText ( )
15
+ const isFormattingLineIgnored = ( fullText : string , position : number ) => {
18
16
// check that lines before line are not ignored
19
17
const linesBefore = fullText . slice ( 0 , position ) . split ( '\n' )
20
18
if ( isExpectedDirective ( linesBefore [ linesBefore . length - 2 ] , '@ts-format-ignore-line' ) ) {
@@ -32,20 +30,24 @@ export default (proxy: ts.LanguageService, languageService: ts.LanguageService,
32
30
}
33
31
return isInsideIgnoredRegion
34
32
}
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 ) ) {
43
47
return false
44
48
}
45
49
return true
46
50
} )
47
- } )
51
+ }
48
52
}
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
51
53
}
0 commit comments