1313 DidOpenTextDocumentParams ,
1414 DidSaveTextDocumentParams ,
1515 DocumentUri ,
16+ FileEvent ,
1617 TextDocumentContentChangeEvent ,
1718 TextDocumentContentRangeChangeEvent ,
1819 TextDocumentContentTextChangeEvent ,
2324 TextDocumentSyncOptions ,
2425 TextEdit ,
2526 VersionedTextDocumentIdentifier ,
27+ WatchKind ,
2628 WillSaveTextDocumentParams ,
2729)
2830from ..text_document import TextDocument
@@ -46,6 +48,26 @@ class TextDocumentProtocolPart(LanguageServerProtocolPart, Mapping[DocumentUri,
4648 def __init__ (self , parent : LanguageServerProtocol ) -> None :
4749 super ().__init__ (parent )
4850 self ._documents : Dict [DocumentUri , TextDocument ] = {}
51+ self .parent .on_initialized .add (self ._protocol_initialized )
52+
53+ async def _protocol_initialized (self , sender : Any ) -> None :
54+ await self ._update_filewatchers ()
55+
56+ async def _update_filewatchers (self ) -> None :
57+ await self .parent .workspace .add_file_watcher (self ._file_watcher , "**/*" , WatchKind .CHANGE | WatchKind .DELETE )
58+
59+ @_logger .call
60+ async def _file_watcher (self , sender : Any , changes : List [FileEvent ]) -> None :
61+ self ._logger .debug (f"filewatcher { changes } " )
62+ to_change : Dict [str , FileEvent ] = {}
63+ for change in changes :
64+ to_change [change .uri ] = change
65+
66+ for change in to_change .values ():
67+ document = self ._documents .get (DocumentUri (Uri (change .uri ).normalized ()), None )
68+ if document is not None and not document .opened_in_editor :
69+ await self .did_close (self , document )
70+ await self .close_document (document , True )
4971
5072 @async_event
5173 async def did_open (sender , document : TextDocument ) -> None :
@@ -117,6 +139,7 @@ async def _text_document_did_open(self, text_document: TextDocumentItem, *args:
117139 else :
118140 await document .apply_full_change (text_document .version , text_document .text )
119141
142+ document .opened_in_editor = True
120143 document .references .add (self )
121144
122145 await self .did_open (self , document )
@@ -129,12 +152,13 @@ async def _text_document_did_close(self, text_document: TextDocumentIdentifier,
129152
130153 if document is not None :
131154 document .references .remove (self )
132-
155+ document . opened_in_editor = False
133156 await self .did_close (self , document )
134157 await self .close_document (document )
135158
136- async def close_document (self , document : TextDocument ) -> None :
137- if len (document .references ) == 0 :
159+ @_logger .call
160+ async def close_document (self , document : TextDocument , ignore_references : bool = False ) -> None :
161+ if len (document .references ) == 0 or ignore_references :
138162 self ._documents .pop (str (document .uri ), None )
139163
140164 await document .clear ()
0 commit comments