@@ -164,6 +164,11 @@ final class CodeFileDocument: NSDocument, ObservableObject {
164164 if let validEncoding = FileEncoding ( rawEncoding) , let nsString {
165165 self . sourceEncoding = validEncoding
166166 self . content = NSTextStorage ( string: nsString as String )
167+ if let content {
168+ content. mutableString. setString ( nsString as String )
169+ } else {
170+ self . content = NSTextStorage ( string: nsString as String )
171+ }
167172 } else {
168173 Self . logger. error ( " Failed to read file from data using encoding: \( rawEncoding) " )
169174 }
@@ -217,6 +222,32 @@ final class CodeFileDocument: NSDocument, ObservableObject {
217222 }
218223 }
219224
225+ // MARK: - External Changes
226+
227+ /// Handle the notification that the represented file item changed.
228+ override func presentedItemDidChange( ) {
229+ // Grab the file saved date
230+ if fileModificationDate != getModificationDate ( ) {
231+ Self . logger. debug ( " Detected outside change to file " )
232+ guard isDocumentEdited else {
233+ fileModificationDate = getModificationDate ( )
234+ if let fileURL, let fileType {
235+ DispatchQueue . main. asyncAndWait {
236+ try ? self . read ( from: fileURL, ofType: fileType)
237+ }
238+ }
239+ return
240+ }
241+ }
242+
243+ super. presentedItemDidChange ( )
244+ }
245+
246+ private func getModificationDate( ) -> Date ? {
247+ guard let path = fileURL? . absolutePath else { return nil }
248+ return try ? FileManager . default. attributesOfItem ( atPath: path) [ . modificationDate] as? Date
249+ }
250+
220251 // MARK: - Close
221252
222253 override func close( ) {
0 commit comments