Skip to content

Commit 46025a9

Browse files
authored
Discard selection history for external edits (#1380)
1 parent 2271c4d commit 46025a9

3 files changed

Lines changed: 23 additions & 7 deletions

File tree

MarkEditMac/Sources/Editor/Controllers/EditorViewController.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,12 @@ extension EditorViewController {
356356
return nil
357357
}
358358

359+
// Content was reloaded from disk due to an external edit, discard stale offsets
360+
if document?.hasBeenReverted == true {
361+
EditorSelectionHistory.discard(for: fileURL)
362+
return nil
363+
}
364+
359365
// Non-LF files have mismatched lengths due to CodeMirror normalization, skip the check
360366
let fileSize = textContent.contains("\r") ? nil : textContent.utf16.count
361367
return EditorSelectionHistory.selectionRange(for: fileURL, fileSize: fileSize)

MarkEditMac/Sources/Editor/EditorSelectionHistory.swift

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,7 @@ enum EditorSelectionHistory {
3737

3838
// Discard if the content length changed, the file was likely externally edited
3939
if let fileSize, entry.fileSize != fileSize {
40-
var current = EditorHistory.selectionRanges
41-
current.removeValue(forKey: key)
42-
EditorHistory.selectionRanges = current
40+
discard(for: fileURL)
4341
return nil
4442
}
4543

@@ -50,6 +48,18 @@ enum EditorSelectionHistory {
5048
return entry.selectionRange
5149
}
5250

51+
static func discard(for fileURL: URL) {
52+
if pendingInfo?.fileURL == fileURL {
53+
saveTask?.cancel()
54+
saveTask = nil
55+
pendingInfo = nil
56+
}
57+
58+
var current = EditorHistory.selectionRanges
59+
current.removeValue(forKey: fileURL.cacheKey)
60+
EditorHistory.selectionRanges = current
61+
}
62+
5363
/// Removes selection entries older than the retention period and enforces a maximum entry limit
5464
static func purgeStaleEntries() {
5565
// Flush any pending saves before purging

MarkEditMac/Sources/Editor/Models/EditorDocument.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ final class EditorDocument: NSDocument {
3232
isDraft || fileURL == nil || fileData != nil
3333
}
3434

35+
var hasBeenReverted: Bool {
36+
Date.now.timeIntervalSince(revertedDate) < 1
37+
}
38+
3539
var canUndo: Bool {
3640
get async {
3741
if isReadOnlyMode {
@@ -614,10 +618,6 @@ private extension EditorDocument {
614618
UserDefaults.standard.bool(forKey: NSCloseAlwaysConfirmsChanges)
615619
}
616620

617-
var hasBeenReverted: Bool {
618-
Date.now.timeIntervalSince(revertedDate) < 1
619-
}
620-
621621
var needsFormatting: Bool {
622622
guard !formatCompleted else {
623623
return false

0 commit comments

Comments
 (0)