Sources/OrgApp/DocumentSession.swift

1060 lines · 52215 bytes

   1import Foundation
   2import Observation
   3import OrgCore
   4import OrgDocument
   5import OrgIndex
   6import OrgPresentation
   7
   8/// A heading, or a whole file, a subtree can be refiled to.
   9public struct RefileTarget: Sendable, Hashable {
  10    /// `file.org/Parent/Heading`, as the prompt lists it.
  11    public let label: String
  12    public let path: String
  13    /// Start of the heading when the file had `contentHash`; nil refiles to the end of the file.
  14    public let start: Int?
  15    public let title: String
  16    public let level: Int
  17    public let contentHash: String
  18
  19    public init(label: String, path: String, start: Int?, title: String, level: Int, contentHash: String) {
  20        self.label = label
  21        self.path = path
  22        self.start = start
  23        self.title = title
  24        self.level = level
  25        self.contentHash = contentHash
  26    }
  27
  28    /// The heading's start in `state`: its indexed offset if the text is what was indexed,
  29    /// else the first heading with the same title and level. Nil for the end of the file.
  30    func locate(in state: DocumentState) -> Int?? {
  31        guard let start else { return .some(nil) }
  32        if !state.isDirty, FileRecord.hash(state.mergeBase) == contentHash { return .some(start) }
  33        let entry = Presentation.outline(state.tree).first { $0.title == title && $0.level == level }
  34        return entry.map { .some($0.start) }
  35    }
  36}
  37
  38public enum SaveMode: String, Sendable, CaseIterable {
  39    /// Save shortly after typing stops.
  40    case automatic
  41    /// Save only on ⌘S.
  42    case explicit
  43}
  44
  45/// The files open in the app, as Emacs's buffers: each keeps its text, caret, undo and
  46/// unsaved edits while another is shown. Buffers show in panes (`EditorPane`), one or more
  47/// per window; `focused` is the pane commands and menus act on, and the properties below
  48/// that describe one buffer (`path`, `outline`, `isDirty`, `conflict`, `revealRequest`) are
  49/// its. The view layer attaches an editor to each buffer and, per pane, follows the pane's
  50/// `path` and `revealRequest`.
  51@MainActor
  52@Observable
  53public final class DocumentSession {
  54    /// Where buffers show. There is always at least one.
  55    public private(set) var panes: [EditorPane]
  56    /// The pane with focus: what `open`, `reveal`, saving and the forwarders below act on.
  57    public var focused: EditorPane
  58    /// The focused pane's file.
  59    public var path: String? { focused.path }
  60    /// The focused pane's buffer state. Not observed: it changes on every keystroke; views
  61    /// follow `path`, `isDirty` and `outline`.
  62    public var document: DocumentState? { current?.buffer.document }
  63    public var outline: [OutlineEntry] { focused.outline }
  64    /// Bumped when the focused buffer settles after edits, and when a file opens: views that
  65    /// read `document` follow this.
  66    public var editVersion: Int { focused.editVersion }
  67    public var isDirty: Bool { focused.isDirty }
  68    /// The file isn't UTF-8, so it can't be edited or saved.
  69    public var isReadOnly: Bool { focused.isReadOnly }
  70    /// Set while the focused buffer and the file on disk conflict; says how to resolve it.
  71    public var conflict: String? { focused.conflict }
  72    /// Bumped to ask the focused pane's editor to reveal an offset.
  73    public var revealRequest: (offset: Int, id: Int)? { focused.revealRequest }
  74    /// Open files, in the order buffers were opened (each after the one focused then).
  75    public private(set) var openPaths: [String] = []
  76    /// Open files with unsaved edits.
  77    public private(set) var dirtyPaths: Set<String> = []
  78    public var lastError: String?
  79    public var saveMode: SaveMode = .automatic
  80    public var autosaveDelay: Duration = .seconds(1)
  81    /// Org options for commands the session runs (refile, archive).
  82    public var options: EditingOptions = .org
  83    /// Called with a file's path after its text changed through the session, typed or not.
  84    @ObservationIgnored public var textChanged: ((String) -> Void)?
  85    /// TODO keywords and priorities for files without their own settings.
  86    public var defaults: OrgSettings = .default
  87
  88    /// A buffer for `bytes` read from `path`, with the keywords of the setup files it names.
  89    func loaded(_ bytes: [UInt8], path: String) -> DocumentState {
  90        DocumentState(bytes: bytes, defaults: defaults.resolvingSetupFiles(in: SourceText(bytes: bytes).text, path: path, read: readText))
  91    }
  92
  93    /// A file's text, for setup files.
  94    func readText(_ file: String) -> String? {
  95        (try? fileSystem.read(URL(fileURLWithPath: file))).flatMap { $0 }.flatMap { String(bytes: $0, encoding: .utf8) }
  96    }
  97
  98    /// C-c C-c on a keyword line: the open file's setup files read again (`org-mode-restart`).
  99    public func refreshSetup() {
 100        guard let entry = current else { return }
 101        resolveSetup(entry)
 102        for pane in panes(showing: entry.path) {
 103            refresh(pane)
 104            pane.editVersion += 1
 105        }
 106    }
 107
 108    /// The entry's setup files read again, as its text names them now.
 109    private func resolveSetup(_ entry: Entry) {
 110        let settings = defaults.resolvingSetupFiles(in: entry.buffer.document.text, path: entry.path, read: readText)
 111        if settings != entry.buffer.document.defaults { entry.buffer.update { $0.setDefaults(settings) } }
 112    }
 113
 114    /// One open file.
 115    @MainActor
 116    final class Entry {
 117        let path: String
 118        var buffer: DocumentBuffer
 119        var conflict: String?
 120        var autosave: Task<Void, Never>?
 121
 122        init(path: String, buffer: DocumentBuffer) {
 123            self.path = path
 124            self.buffer = buffer
 125        }
 126    }
 127
 128    private let fileSystem: FileSystem
 129    private let recovery: RecoveryStore
 130    @ObservationIgnored private var entries: [Entry] = []
 131    /// The focused pane's buffer.
 132    private var current: Entry? { focused.path.flatMap(entry) }
 133    /// Paths, most recently shown first, across every pane.
 134    @ObservationIgnored private var history: [String] = []
 135    @ObservationIgnored private var outlineUpdates: [String: Task<Void, Never>] = [:]
 136    private var requestID = 0
 137
 138    public init(
 139        fileSystem: FileSystem = CoordinatedFileSystem(),
 140        recovery: RecoveryStore = FileRecoveryStore(directory: WorkspaceModel.defaultDirectory.appendingPathComponent("Recovery"))
 141    ) {
 142        self.fileSystem = fileSystem
 143        self.recovery = recovery
 144        let pane = EditorPane()
 145        panes = [pane]
 146        focused = pane
 147    }
 148
 149    // MARK: - Panes
 150
 151    /// A new, empty pane.
 152    public func makePane() -> EditorPane {
 153        let pane = EditorPane()
 154        panes.append(pane)
 155        return pane
 156    }
 157
 158    /// Removes `pane`; its buffers stay open. The last pane stays.
 159    public func closePane(_ pane: EditorPane) {
 160        guard panes.count > 1, let index = panes.firstIndex(where: { $0 === pane }) else { return }
 161        panes.remove(at: index)
 162        if focused === pane { focused = panes[0] }
 163    }
 164
 165    /// The panes showing `path`.
 166    private func panes(showing path: String) -> [EditorPane] {
 167        panes.filter { $0.path == path }
 168    }
 169
 170    private var buffer: DocumentBuffer? { current?.buffer }
 171    /// The focused buffer's pending autosave, for tests to wait on.
 172    var autosave: Task<Void, Never>? { current?.autosave }
 173    private var url: URL? { path.map { URL(fileURLWithPath: $0) } }
 174    /// Whether the open file is an org file (`.org`, `.org_archive`), not plain text.
 175    public var isOrg: Bool { path.map(Self.isOrgPath) ?? false }
 176
 177    public static func isOrgPath(_ path: String) -> Bool {
 178        path.hasSuffix(".org") || path.hasSuffix(".org_archive")
 179    }
 180
 181    /// The caret in the open file.
 182    public var caret: Int { buffer?.selection.first?.lowerBound ?? 0 }
 183    private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" }
 184
 185    /// The open buffer of `path`, or of the same file by another path (`find-buffer-visiting`
 186    /// by truename).
 187    private func entry(_ path: String) -> Entry? {
 188        if let exact = entries.first(where: { $0.path == path }) { return exact }
 189        let truename = URL(fileURLWithPath: path).resolvingSymlinksInPath().path
 190        return entries.first { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath().path == truename }
 191    }
 192
 193    /// The text of `path`: its buffer's when it's open, else what's on disk.
 194    public func text(of path: String) -> String? {
 195        if let entry = entry(path) { return entry.buffer.document.text }
 196        guard let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return nil }
 197        let state = loaded(bytes, path: path)
 198        return state.isEditable ? state.text : nil
 199    }
 200
 201    /// The buffer's name as uniquify writes it (`post-forward-angle-brackets`): the file name,
 202    /// with as many of its folders as tell it apart from other open files of the same name.
 203    public func bufferName(_ path: String) -> String {
 204        let name = (path as NSString).lastPathComponent
 205        let others = openPaths.filter { $0 != path && ($0 as NSString).lastPathComponent == name }
 206        guard !others.isEmpty else { return name }
 207        func folders(_ p: String) -> [String] { (p as NSString).deletingLastPathComponent.split(separator: "/").map(String.init).reversed() }
 208        let mine = folders(path)
 209        var count = 1
 210        while count < mine.count, others.contains(where: { folders($0).prefix(count) == mine.prefix(count) }) { count += 1 }
 211        return name + "<" + mine.prefix(count).reversed().joined(separator: "/") + ">"
 212    }
 213
 214    public func isOpen(_ path: String) -> Bool { entry(path) != nil }
 215
 216    /// The document of an open file, whichever pane shows it.
 217    public func document(of path: String) -> DocumentState? { entry(path)?.buffer.document }
 218
 219    /// Whether `buffer` is the live state of `path`, as `attach` made it.
 220    public func isAttached(_ buffer: DocumentBuffer, for path: String) -> Bool { entry(path)?.buffer === buffer }
 221
 222    /// The caret of an open file.
 223    public func caret(of path: String) -> Int? { entry(path)?.buffer.selection.first?.lowerBound }
 224
 225    /// The text of every open file, for views that read files (the agenda, search).
 226    public var openDocuments: [(path: String, document: DocumentState)] {
 227        entries.map { ($0.path, $0.buffer.document) }
 228    }
 229
 230    /// The text of every open file by path, for the agenda.
 231    public var openTexts: [String: String] {
 232        Dictionary(entries.map { ($0.path, $0.buffer.document.text) }, uniquingKeysWith: { a, _ in a })
 233    }
 234
 235    /// Open buffers, most recently shown first.
 236    public var recentPaths: [String] { history.filter(isOpen) }
 237
 238    /// Shows the buffer of `path` in the focused pane, opening the file if it isn't open.
 239    public func open(_ path: String) {
 240        open(path, in: focused)
 241    }
 242
 243    /// Shows the buffer of `path` in `pane`, opening the file if it isn't open.
 244    public func open(_ path: String, in pane: EditorPane) {
 245        let interval = Perf.begin("session.open")
 246        defer { interval.end((path as NSString).lastPathComponent) }
 247        if let existing = entry(path) {
 248            show(existing, in: pane)
 249            return
 250        }
 251        do {
 252            guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
 253                lastError = "\((path as NSString).lastPathComponent) no longer exists."
 254                return
 255            }
 256            let entry = Entry(path: path, buffer: StateBuffer(loaded(bytes, path: path)))
 257            let index = pane.path.flatMap(self.entry).flatMap { c in entries.firstIndex { $0 === c } }.map { $0 + 1 } ?? entries.count
 258            entries.insert(entry, at: index)
 259            show(entry, in: pane)
 260        } catch {
 261            lastError = "Can't open \(path): \(error.localizedDescription)"
 262        }
 263    }
 264
 265    private func show(_ entry: Entry, in pane: EditorPane) {
 266        pane.path = entry.path
 267        if !pane.shown.contains(entry.path) { pane.shown.append(entry.path) }
 268        pane.history.removeAll { $0 == entry.path }
 269        pane.history.insert(entry.path, at: 0)
 270        pane.revealRequest = nil
 271        history.removeAll { $0 == entry.path }
 272        history.insert(entry.path, at: 0)
 273        refresh(pane)
 274    }
 275
 276    /// The buffer before or after the focused one, wrapping, in the focused pane.
 277    public func cycle(_ step: Int) {
 278        guard let current, let index = entries.firstIndex(where: { $0 === current }), entries.count > 1 else { return }
 279        show(entries[((index + step) % entries.count + entries.count) % entries.count], in: focused)
 280    }
 281
 282    /// The buffer shown before the focused one.
 283    public func showPrevious() {
 284        guard let previous = recentPaths.dropFirst().first else { return }
 285        open(previous)
 286    }
 287
 288    /// Closes the buffer of `path` without saving it. A pane showing it shows the buffer it
 289    /// showed before, else the most recent other buffer, else nothing.
 290    public func kill(_ path: String) {
 291        guard let entry = entry(path) else { return }
 292        entry.autosave?.cancel()
 293        entries.removeAll { $0 === entry }
 294        history.removeAll { $0 == path }
 295        outlineUpdates[path]?.cancel()
 296        outlineUpdates[path] = nil
 297        for pane in panes {
 298            pane.shown.removeAll { $0 == path }
 299            pane.history.removeAll { $0 == path }
 300            guard pane.path == path else { continue }
 301            if let next = pane.history.first.flatMap(self.entry) ?? recentPaths.first.flatMap(self.entry) ?? entries.last {
 302                show(next, in: pane)
 303            } else {
 304                pane.path = nil
 305                pane.outline = []
 306                pane.isDirty = false
 307                pane.isReadOnly = false
 308                pane.conflict = nil
 309                pane.revealRequest = nil
 310            }
 311        }
 312        refreshLists()
 313    }
 314
 315    /// Closes the focused buffer without saving, as when its file was deleted.
 316    public func close() {
 317        if let path { kill(path) }
 318    }
 319
 320    /// Makes `buffer`, built from `document`, the live state of the focused file.
 321    public func attach(_ buffer: DocumentBuffer) {
 322        if let path { attach(buffer, for: path) }
 323    }
 324
 325    /// Makes `buffer`, built from the file's `document`, the live state of `path`.
 326    public func attach(_ buffer: DocumentBuffer, for path: String) {
 327        guard let entry = entry(path) else { return }
 328        entry.buffer = buffer
 329        for pane in panes(showing: path) { refresh(pane) }
 330    }
 331
 332    /// The buffer of `path` changed in its editor: the panes showing it update their views
 333    /// once typing pauses, and it saves on its own.
 334    public func bufferChanged(_ path: String) {
 335        guard let entry = entry(path) else { return }
 336        changed(entry)
 337    }
 338
 339    /// The focused buffer changed through typing.
 340    public func bufferChanged() {
 341        if let current { changed(current) }
 342    }
 343
 344    /// A buffer changed, typed or not: the panes showing it update their views, the outline
 345    /// once typing pauses, and it saves on its own.
 346    private func changed(_ entry: Entry) {
 347        let showing = panes(showing: entry.path)
 348        for pane in showing { refresh(pane, outline: false) }
 349        outlineUpdates[entry.path]?.cancel()
 350        if !showing.isEmpty {
 351            let path = entry.path
 352            outlineUpdates[path] = Task { [weak self, weak entry] in
 353                try? await Task.sleep(for: .milliseconds(300))
 354                guard !Task.isCancelled, let self, let entry else { return }
 355                let outline = Self.isOrgPath(path) ? Presentation.outline(entry.buffer.document.tree) : []
 356                for pane in self.panes(showing: path) {
 357                    pane.outline = outline
 358                    pane.editVersion += 1
 359                }
 360            }
 361        }
 362        scheduleAutosave(entry)
 363        refreshLists()
 364        textChanged?(entry.path)
 365    }
 366
 367    /// `pane`'s view of its buffer, from the buffer's state.
 368    private func refresh(_ pane: EditorPane, outline updateOutline: Bool = true) {
 369        let interval = Perf.begin("session.refresh")
 370        defer { interval.end() }
 371        refreshLists()
 372        guard let entry = pane.path.flatMap(entry) else { return }
 373        let state = entry.buffer.document
 374        if pane.isDirty != state.isDirty { pane.isDirty = state.isDirty }
 375        if pane.isReadOnly == state.isEditable { pane.isReadOnly = !state.isEditable }
 376        if pane.conflict != entry.conflict { pane.conflict = entry.conflict }
 377        if updateOutline {
 378            pane.outline = Self.isOrgPath(entry.path) ? Presentation.outline(state.tree) : []
 379            pane.editVersion += 1
 380        }
 381    }
 382
 383    /// Every pane showing `entry`, from the buffer's state.
 384    private func refresh(_ entry: Entry) {
 385        for pane in panes(showing: entry.path) { refresh(pane) }
 386    }
 387
 388    /// The focused pane, from its buffer's state.
 389    private func refresh() {
 390        refresh(focused)
 391    }
 392
 393    private func refreshLists() {
 394        let paths = entries.map(\.path)
 395        if paths != openPaths { openPaths = paths }
 396        let dirty = Set(entries.filter { $0.buffer.document.isDirty }.map(\.path))
 397        if dirty != dirtyPaths { dirtyPaths = dirty }
 398    }
 399
 400    // MARK: - Saving
 401
 402    private var saver: Saver { Saver(fileSystem: fileSystem, recovery: recovery) }
 403
 404    private func scheduleAutosave(_ entry: Entry) {
 405        entry.autosave?.cancel()
 406        guard saveMode == .automatic, entry.buffer.document.isDirty, entry.conflict == nil else { return }
 407        entry.autosave = Task { [weak self, weak entry, autosaveDelay] in
 408            try? await Task.sleep(for: autosaveDelay)
 409            guard !Task.isCancelled, let self, let entry else { return }
 410            self.save(entry)
 411        }
 412    }
 413
 414    /// Saves the current buffer now. True when nothing is left unsaved.
 415    @discardableResult
 416    public func save() -> Bool {
 417        guard let current else { return true }
 418        return save(current)
 419    }
 420
 421    /// Saves the buffer of `path`. True when nothing is left unsaved.
 422    @discardableResult
 423    public func save(_ path: String) -> Bool {
 424        guard let entry = entry(path) else { return true }
 425        return save(entry)
 426    }
 427
 428    /// Saves every open buffer. True when nothing is left unsaved.
 429    @discardableResult
 430    public func saveAll() -> Bool {
 431        entries.map { save($0) }.allSatisfy { $0 }
 432    }
 433
 434    @discardableResult
 435    private func save(_ entry: Entry) -> Bool {
 436        let interval = Perf.begin("session.save")
 437        defer { interval.end((entry.path as NSString).lastPathComponent) }
 438        entry.autosave?.cancel()
 439        let name = (entry.path as NSString).lastPathComponent
 440        guard entry.buffer.document.isDirty else { return true }
 441        guard entry.conflict == nil else { return false }
 442        do {
 443            let outcome = try entry.buffer.update { try saver.save(&$0, to: URL(fileURLWithPath: entry.path)) }
 444            switch outcome {
 445            case .saved, .mergedAndSaved:
 446                break
 447            case .conflict:
 448                entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
 449            case .overwroteExternalChange(let change), .changedAfterWrite(let change):
 450                if case .conflict = change {
 451                    entry.conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
 452                }
 453            }
 454        } catch {
 455            lastError = "Can't save \(name): \(error.localizedDescription)"
 456        }
 457        refresh(entry)
 458        return !entry.buffer.document.isDirty
 459    }
 460
 461    /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
 462    public func keepMine() {
 463        guard let buffer, let url else { return }
 464        do {
 465            try buffer.update { try saver.overwrite(&$0, to: url) }
 466            current?.conflict = nil
 467        } catch {
 468            lastError = "Can't save \(name): \(error.localizedDescription)"
 469        }
 470        refresh()
 471    }
 472
 473    /// Resolves a conflict by loading the disk version; the buffer goes to recovery.
 474    public func useDiskVersion() {
 475        guard let buffer, let url else { return }
 476        do {
 477            guard let bytes = try fileSystem.read(url) else { return }
 478            if isDirty { try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") }
 479            let path = url.path
 480            buffer.update { $0 = loaded(bytes, path: path) }
 481            current?.conflict = nil
 482        } catch {
 483            lastError = "Can't read \(name): \(error.localizedDescription)"
 484        }
 485        refresh()
 486    }
 487
 488    // MARK: - Comparing versions
 489
 490    /// The buffer, the file on disk and the version both started from, while they conflict.
 491    public func conflictVersions() -> (mine: String, disk: String, base: String)? {
 492        guard current?.conflict != nil, let buffer, let url, let disk = try? fileSystem.read(url) else { return nil }
 493        return (buffer.document.text, SourceText(bytes: disk).text, SourceText(bytes: buffer.document.mergeBase).text)
 494    }
 495
 496    /// Resolves a conflict as `git merge` leaves one: the buffer holds both sides' changes, those
 497    /// that conflict between markers, to fix and save. The disk version becomes the base, and
 498    /// the buffer as it was goes to recovery.
 499    public func mergeConflictWithMarkers() {
 500        guard let versions = conflictVersions(), let buffer, let url, let disk = try? fileSystem.read(url) else { return }
 501        do {
 502            try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
 503            let merged = mergeWithMarkers(base: versions.base, ours: versions.mine, theirs: versions.disk, oursLabel: "yours", theirsLabel: "disk")
 504            try buffer.update { state in
 505                state = loaded(disk, path: url.path)
 506                try state.apply(lineEdits(from: versions.disk, to: merged), baseRevision: state.revision)
 507            }
 508            current?.conflict = nil
 509        } catch {
 510            lastError = "Can't merge \(name): \(error.localizedDescription)"
 511        }
 512        refresh()
 513    }
 514
 515    /// Syncthing's conflict copies of the open file beside it: `name.sync-conflict-DATE-TIME-ID.ext`.
 516    public func syncConflictCopies() -> [URL] {
 517        guard let url else { return [] }
 518        let folder = url.deletingLastPathComponent()
 519        let stem = NSRegularExpression.escapedPattern(for: url.deletingPathExtension().lastPathComponent)
 520        let ext = url.pathExtension.isEmpty ? "" : "\\." + NSRegularExpression.escapedPattern(for: url.pathExtension)
 521        let pattern = "^" + stem + "\\.sync-conflict-[0-9]{8}-[0-9]{6}-[A-Z0-9]+" + ext + "$"
 522        let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []
 523        return names.filter { $0.range(of: pattern, options: .regularExpression) != nil }.sorted().map { folder.appendingPathComponent($0) }
 524    }
 525
 526    /// What to do with a conflict copy: keep the file as it is, take the copy's text, or merge
 527    /// the two with markers. The copy goes to recovery and is removed.
 528    public enum CopyResolution { case keepFile, useCopy, merge }
 529
 530    public func resolve(copy: URL, _ resolution: CopyResolution) -> String? {
 531        guard let buffer, let url else { return "No file is open" }
 532        do {
 533            guard let bytes = try fileSystem.read(copy) else { return "\(copy.lastPathComponent) is gone" }
 534            let copyText = SourceText(bytes: bytes).text
 535            let mine = buffer.document.text
 536            let new: String? = switch resolution {
 537            case .keepFile: nil
 538            case .useCopy: copyText
 539            case .merge: mergeWithMarkers(base: nil, ours: mine, theirs: copyText, oursLabel: url.lastPathComponent, theirsLabel: copy.lastPathComponent)
 540            }
 541            if let new, new != mine {
 542                let result = EditResult(baseRevision: buffer.document.revision, edits: lineEdits(from: mine, to: new))
 543                if case .failed(let message) = buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
 544            }
 545            try recovery.keep(bytes, for: url, label: "sync-conflict")
 546            try FileManager.default.removeItem(at: copy)
 547        } catch {
 548            return "Can't resolve \(copy.lastPathComponent): \(error.localizedDescription)"
 549        }
 550        if let current { changed(current) }
 551        return nil
 552    }
 553
 554    /// Versions of the open file kept in recovery, newest first, with when and why each was
 555    /// kept.
 556    public func recoveryVersions() -> [(url: URL, date: Date, label: String)] {
 557        guard let url, let store = recovery as? FileRecoveryStore, let versions = try? store.versions(for: url) else { return [] }
 558        // `STAMP-LABEL-UUID8-NAME`, as `FileRecoveryStore.keep` names them.
 559        return versions.reversed().map { version in
 560            let m = version.lastPathComponent.firstMatch(of: /^([0-9]+)-(.+?)-([0-9A-Fa-f]{8})-/)
 561            let nanos = m.flatMap { UInt64($0.1) } ?? 0
 562            return (version, Date(timeIntervalSince1970: Double(nanos) / 1_000_000_000), m.map { String($0.2) } ?? "")
 563        }
 564    }
 565
 566    /// The text of a kept version.
 567    public func recoveryText(_ version: URL) -> String? {
 568        (try? fileSystem.read(version)).flatMap { $0 }.map { SourceText(bytes: $0).text }
 569    }
 570
 571    /// Puts a kept version's text in the buffer, as an edit that can be undone; the buffer as it
 572    /// was goes to recovery.
 573    public func restore(_ version: URL) -> String? {
 574        guard let buffer, let url, let text = recoveryText(version) else { return "Can't read that version" }
 575        do {
 576            try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
 577        } catch {
 578            return "Can't keep the current version: \(error.localizedDescription)"
 579        }
 580        let mine = buffer.document.text
 581        let result = EditResult(baseRevision: buffer.document.revision, edits: lineEdits(from: mine, to: text))
 582        if case .failed(let message) = buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
 583        if let current { changed(current) }
 584        return nil
 585    }
 586
 587    // MARK: - Moving subtrees
 588
 589    /// The current context of the buffer, as commands see it.
 590    private func editContext(now: Date) -> EditContext? {
 591        guard let buffer else { return nil }
 592        let document = buffer.document
 593        return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: buffer.selection, now: now, options: options)
 594    }
 595
 596    /// The file and context a subtree command works on: `from` (a file and a heading in it,
 597    /// as the agenda gives them), or the current buffer at its caret.
 598    private func source(_ from: (path: String, offset: Int)?, now: Date) -> (path: String, context: EditContext)? {
 599        guard let from else {
 600            guard let path, let context = editContext(now: now) else { return nil }
 601            return (path, context)
 602        }
 603        let state: DocumentState
 604        if let open = entry(from.path) {
 605            state = open.buffer.document
 606        } else {
 607            guard let bytes = try? fileSystem.read(URL(fileURLWithPath: from.path)) else { return nil }
 608            state = loaded(bytes, path: from.path)
 609        }
 610        guard state.isEditable else { return nil }
 611        let context = EditContext(revision: state.revision, text: state.text, tree: state.tree, selection: [from.offset..<from.offset], now: now, options: options)
 612        return (from.path, context)
 613    }
 614
 615    /// Applies an edit computed from `source(_:now:)` to that file, open or not.
 616    private func applySource(_ edit: EditResult, path: String, now: Date) -> String? {
 617        if case .failed(let message) = perform(PrecomputedEdit(edit), path: path, at: 0, expect: nil, now: now) { return message }
 618        return nil
 619    }
 620
 621    /// Moves the subtree at the caret, or at `from`, under `target`, or with `keep` copies it
 622    /// there (`org-copy`). For another file, that file is written first, through the save
 623    /// path; the subtree leaves its file only once it has. Returns a message for the echo area.
 624    @discardableResult
 625    public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, keep: Bool = false, now: Date = Date()) -> String? {
 626        guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
 627        let done = (keep ? "Copied to " : "Refiled to ") + target.label
 628        if target.path == path {
 629            let answers = ["refile": target.start.map(String.init) ?? ""]
 630            let command = RefileWithinFile(keep: keep)
 631            let step = from == nil ? buffer?.perform(command, now: now, answers: answers)
 632                : perform(command, path: path, at: from!.offset, expect: nil, answers: answers, now: now)
 633            if case .failed(let message)? = step { return message }
 634            if from == nil { bufferChanged() }
 635            return done
 636        }
 637        let url = URL(fileURLWithPath: target.path)
 638        let targetName = (target.path as NSString).lastPathComponent
 639        // A target open in a buffer takes the subtree there, with its unsaved edits.
 640        if let open = entry(target.path) {
 641            let state = open.buffer.document
 642            guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
 643            guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
 644            guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." }
 645            let edit = EditResult(baseRevision: state.revision, edits: [result.target])
 646            if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
 647            changed(open)
 648            if !keep, let message = applySource(result.source, path: path, now: now) { return message }
 649            return done
 650        }
 651        do {
 652            guard let bytes = try fileSystem.read(url) else { return "\(targetName) no longer exists." }
 653            var state = loaded(bytes, path: url.path)
 654            guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
 655            guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
 656            guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." }
 657            try state.apply([result.target], baseRevision: state.revision)
 658            if case .conflict = try saver.save(&state, to: url) { return "\(targetName) changed on disk; nothing was refiled." }
 659            if !keep, let message = applySource(result.source, path: path, now: now) { return message }
 660            return done
 661        } catch {
 662            return "Can't refile: \(error.localizedDescription)"
 663        }
 664    }
 665
 666    /// `org-refile-new-child`: a heading `title` at the end of `parent`'s subtree, one level
 667    /// below it, or at the end of the file for a file target. Returns the new heading as a
 668    /// target, or a message.
 669    public func createRefileChild(under parent: RefileTarget, title: String, now: Date = Date()) -> Result<RefileTarget, RefileFailure> {
 670        let name = (parent.path as NSString).lastPathComponent
 671        func insert(into state: DocumentState) -> (edit: TextEdit, start: Int, level: Int)? {
 672            guard let start = parent.locate(in: state) else { return nil }
 673            return Self.newChild(state.text, under: start, title: title)
 674        }
 675        func target(_ start: Int, _ level: Int, _ hash: String) -> RefileTarget {
 676            RefileTarget(label: parent.label + "/" + title, path: parent.path, start: start, title: title, level: level, contentHash: hash)
 677        }
 678        if let open = entry(parent.path) {
 679            let state = open.buffer.document
 680            guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) }
 681            guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) }
 682            if case .failed(let message) = open.buffer.perform(PrecomputedEdit(EditResult(baseRevision: state.revision, edits: [edit])), now: now, answers: [:]) {
 683                return .failure(.message(message))
 684            }
 685            changed(open)
 686            return .success(target(start, level, ""))
 687        }
 688        do {
 689            let url = URL(fileURLWithPath: parent.path)
 690            guard let bytes = try fileSystem.read(url) else { return .failure(.message("\(name) no longer exists.")) }
 691            var state = loaded(bytes, path: url.path)
 692            guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) }
 693            guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) }
 694            try state.apply([edit], baseRevision: state.revision)
 695            if case .conflict = try saver.save(&state, to: url) { return .failure(.message("\(name) changed on disk; nothing was added.")) }
 696            return .success(target(start, level, FileRecord.hash(state.mergeBase)))
 697        } catch {
 698            return .failure(.message("Can't add \(title): \(error.localizedDescription)"))
 699        }
 700    }
 701
 702    public enum RefileFailure: Error, Equatable {
 703        case message(String)
 704    }
 705
 706    /// The edit `org-refile-new-child` makes in `text` under the heading at `start` (nil for
 707    /// the file), and where the new heading starts and its level.
 708    static func newChild(_ text: String, under start: Int??, title: String) -> (edit: TextEdit, start: Int, level: Int) {
 709        let ns = text as NSString
 710        var prefix = ""
 711        var pos = ns.length
 712        var level = 1
 713        if case .some(.some(let heading)) = start {
 714            var stars = 0
 715            while heading + stars < ns.length, ns.character(at: heading + stars) == 42 { stars += 1 }
 716            level = stars + 1
 717            // `org-end-of-subtree t t`: the next heading at this level or above.
 718            var at = NSMaxRange(ns.lineRange(for: NSRange(location: heading, length: 0)))
 719            pos = ns.length
 720            while at < ns.length {
 721                let line = ns.lineRange(for: NSRange(location: at, length: 0))
 722                var n = 0
 723                while at + n < NSMaxRange(line), ns.character(at: at + n) == 42 { n += 1 }
 724                if n > 0, n <= stars, at + n < ns.length, [32, 9].contains(ns.character(at: at + n)) {
 725                    pos = at
 726                    break
 727                }
 728                at = NSMaxRange(line)
 729            }
 730        } else if ns.length > 0, ns.character(at: ns.length - 1) != 10 {
 731            prefix = "\n"
 732        }
 733        // `org-back-over-empty-lines`.
 734        var back = pos
 735        while back > 0, [32, 9, 10, 13].contains(ns.character(at: back - 1)) { back -= 1 }
 736        var lineAfter = back
 737        while lineAfter < ns.length, ns.character(at: lineAfter) != 10 { lineAfter += 1 }
 738        if lineAfter < ns.length { lineAfter += 1 }
 739        if !prefix.isEmpty { lineAfter = ns.length }
 740        let at = min(lineAfter, pos)
 741        let insertion = prefix + "\n" + String(repeating: "*", count: level) + " " + title + "\n"
 742        let newStart = at + (prefix as NSString).length + 1
 743        return (TextEdit(range: at..<at, replacement: insertion), newStart, level)
 744    }
 745
 746    /// Archives the subtree at the caret, or at `from`, where `org-archive-subtree` would.
 747    /// Returns a message.
 748    @discardableResult
 749    public func archive(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
 750        guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
 751        let destination: Archive.Destination
 752        switch Archive.destination(context, sourcePath: path) {
 753        case .success(let value): destination = value
 754        case .failure(.message(let message)): return message
 755        }
 756        // An archive file open in a buffer takes the subtree there.
 757        if !destination.isSameFile, let open = entry(destination.path) {
 758            let state = open.buffer.document
 759            let name = (destination.path as NSString).lastPathComponent
 760            guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
 761            let edits: Archive.Edits
 762            switch Archive.run(context, sourcePath: path, destination: destination, archiveText: state.text) {
 763            case .success(let value): edits = value
 764            case .failure(.message(let message)): return message
 765            }
 766            if let archiveEdit = edits.archive {
 767                let edit = EditResult(baseRevision: state.revision, edits: [archiveEdit])
 768                if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
 769                changed(open)
 770            }
 771            if let message = applySource(edits.source, path: path, now: now) { return message }
 772            return "Archived to \(name)"
 773        }
 774        do {
 775            let url = URL(fileURLWithPath: destination.path)
 776            let existing = destination.isSameFile ? nil : try fileSystem.read(url)
 777            var state = loaded(existing ?? [], path: url.path)
 778            if !destination.isSameFile, !state.isEditable { return "\(url.lastPathComponent) isn't UTF-8, so it can't be changed." }
 779            let edits: Archive.Edits
 780            switch Archive.run(context, sourcePath: path, destination: destination, archiveText: existing.map { _ in state.text }) {
 781            case .success(let value): edits = value
 782            case .failure(.message(let message)): return message
 783            }
 784            if let archiveEdit = edits.archive {
 785                try state.apply([archiveEdit], baseRevision: state.revision)
 786                if case .conflict = try saver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
 787            }
 788            if let message = applySource(edits.source, path: path, now: now) { return message }
 789            return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
 790        } catch {
 791            return "Can't archive: \(error.localizedDescription)"
 792        }
 793    }
 794
 795    // MARK: - Commands from other views
 796
 797    /// Where the heading line `line` is now in `path`: at `offset` if it still reads so, else
 798    /// the copy of the line nearest `offset`. For acting on agenda entries after other edits
 799    /// moved them.
 800    public func locateHeading(path: String, line: String, near offset: Int) -> Int? {
 801        guard let text = entry(path)?.buffer.document.text ?? (try? fileSystem.read(URL(fileURLWithPath: path))).flatMap({ $0.map { SourceText(bytes: $0).text } }) else { return nil }
 802        let ns = text as NSString
 803        let length = (line as NSString).length
 804        if offset + length <= ns.length, ns.substring(with: NSRange(location: offset, length: length)) == line,
 805           offset == 0 || ns.character(at: offset - 1) == 10 {
 806            return offset
 807        }
 808        var best: Int?
 809        var search = NSRange(location: 0, length: ns.length)
 810        while true {
 811            let found = ns.range(of: line, options: [], range: search)
 812            guard found.location != NSNotFound else { break }
 813            let atLineStart = found.location == 0 || ns.character(at: found.location - 1) == 10
 814            let lineEnd = NSMaxRange(found) == ns.length || ns.character(at: NSMaxRange(found)) == 10
 815            if atLineStart, lineEnd, best.map({ abs($0 - offset) > abs(found.location - offset) }) ?? true { best = found.location }
 816            search = NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))
 817        }
 818        return best
 819    }
 820
 821    /// Runs `command` with the caret at `offset` in the file at `path`, as the agenda does:
 822    /// through the buffer when the file is open, leaving its caret alone; otherwise on the
 823    /// file, written back at once through the save path. `expect` is the heading line the
 824    /// caller saw at a position; if the text there changed, nothing runs.
 825    public func perform(
 826        _ command: any OrgCommand, path: String, at offset: Int, expect: (start: Int, line: String)?,
 827        answers: [String: String] = [:], now: Date = Date()
 828    ) -> CommandStep {
 829        let stale = CommandStep.failed("The entry changed; the agenda has been refreshed.")
 830        func matches(_ text: String) -> Bool {
 831            guard let expect else { return true }
 832            let ns = text as NSString
 833            guard expect.start + (expect.line as NSString).length <= ns.length else { return false }
 834            return ns.substring(with: NSRange(location: expect.start, length: (expect.line as NSString).length)) == expect.line
 835        }
 836        if let entry = entry(path) {
 837            let buffer = entry.buffer
 838            guard matches(buffer.document.text) else { return stale }
 839            do {
 840                let options = self.options
 841                let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) }
 842                if case .commit = step { changed(entry) }
 843                return step
 844            } catch {
 845                return .failed("\(error)")
 846            }
 847        }
 848        let url = URL(fileURLWithPath: path)
 849        let name = url.lastPathComponent
 850        do {
 851            guard let bytes = try fileSystem.read(url) else { return .failed("\(name) no longer exists.") }
 852            var state = loaded(bytes, path: path)
 853            guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") }
 854            guard matches(state.text) else { return stale }
 855            let step = try state.run(command, selection: [offset..<offset], now: now, answers: answers, options: options)
 856            if case .commit = step, state.isDirty, case .conflict = try saver.save(&state, to: url) {
 857                return .failed("\(name) changed on disk; nothing was changed.")
 858            }
 859            if case .commit = step { textChanged?(path) }
 860            return step
 861        } catch {
 862            return .failed("Can't change \(name): \(error.localizedDescription)")
 863        }
 864    }
 865
 866    // MARK: - External work
 867
 868    /// Recalculates a table in Emacs from a snapshot of the buffer, then replaces the table
 869    /// with Emacs's text if it hasn't changed meanwhile. Returns a message for the echo area.
 870    public func recalculateInEmacs(table: Range<Int>, point: Int, form: String) async -> String {
 871        #if os(macOS)
 872        guard let entry = current else { return "No file is open." }
 873        let path = entry.path
 874        let snapshot = entry.buffer.document.text as NSString
 875        guard table.upperBound <= snapshot.length else { return "The table moved; try again." }
 876        let old = snapshot.substring(with: NSRange(table))
 877        let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
 878        do {
 879            let new = try await EmacsRunner.recalculateTable(text: snapshot as String, directory: directory, table: table, point: point, form: form)
 880            guard entries.contains(where: { $0 === entry }) else { return "The file was closed before Emacs finished." }
 881            let current = entry.buffer
 882            let text = current.document.text as NSString
 883            guard table.upperBound <= text.length, text.substring(with: NSRange(table)) == old else {
 884                return "The table changed while Emacs recalculated it; nothing was changed."
 885            }
 886            guard new != old else { return "Recalculated in Emacs" }
 887            let result = EditResult(baseRevision: current.document.revision, edits: [TextEdit(range: table, replacement: new)])
 888            if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
 889            changed(entry)
 890            return "Recalculated in Emacs"
 891        } catch is CancellationError {
 892            return "Recalculation canceled"
 893        } catch {
 894            return "\(error)"
 895        }
 896        #else
 897        return "Tables that need Emacs aren't recalculated on iOS."
 898        #endif
 899    }
 900
 901    /// Runs a src block and writes its result under it, unless the block changed while it
 902    /// ran. Returns a message for the echo area.
 903    public func runBabel(_ job: BabelJob) async -> String {
 904        guard let entry = current else { return "No file is open." }
 905        let directory = URL(fileURLWithPath: entry.path).deletingLastPathComponent()
 906        /// A program on the Mac; on iOS, Emacs Lisp in `Elisp`, and nothing else.
 907        func run(_ job: BabelJob) async throws -> BabelOutput {
 908            #if os(macOS)
 909            return try await BabelRunner.run(job, fileDirectory: directory)
 910            #else
 911            guard let output = try Babel.evaluateNatively(job) else {
 912                throw Babel.Failure.message(job.lispForm == nil
 913                    ? "\(job.language) blocks need the Mac to run."
 914                    : "This block uses Emacs Lisp that runs only in Emacs, on the Mac.")
 915            }
 916            return output
 917            #endif
 918        }
 919        do {
 920            // Blocks the `:var`s refer to run first, one at a time.
 921            // Each is one of the blocks agreed to, or the run stops: the text may have changed
 922            // while a block ran.
 923            var job = job
 924            let approved = job.approved
 925            func agreed(_ block: BabelJob) -> Bool { approved.isEmpty || approved.contains(block.blockText) }
 926            if job.needsFile {
 927                let document = entry.buffer.document
 928                switch Babel.replan(job, file: entry.path, text: document.text, tree: document.tree) {
 929                case .failure(.message(let message)): return message
 930                case .success(let next): job = next
 931                }
 932            }
 933            while let need = job.needs.first {
 934                guard agreed(need.job) else { return "The blocks changed while running; nothing more was run." }
 935                let output = try await run(need.job)
 936                guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
 937                let document = entry.buffer.document
 938                switch Babel.resume(job, need: need, output: output, text: document.text, tree: document.tree) {
 939                case .failure(.message(let message)): return message
 940                case .success(let next): job = next
 941                }
 942            }
 943            guard agreed(job) else { return "The blocks changed while running; nothing more was run." }
 944            let output = try await run(job)
 945            guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
 946            if let file = Babel.fileResult(job, output: output) {
 947                let runDirectory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
 948                let target = file.path.hasPrefix("/") ? URL(fileURLWithPath: file.path) : runDirectory.appendingPathComponent(file.path)
 949                do {
 950                    try file.contents.write(to: target, atomically: true, encoding: .utf8)
 951                } catch {
 952                    return "Can't write \(file.path): \(error.localizedDescription)"
 953                }
 954            }
 955            let current = entry.buffer
 956            let document = current.document
 957            let done = output.problem ?? "Code block evaluation complete."
 958            switch Babel.finish(job, output: output, text: document.text, settings: document.tree.settings) {
 959            case .failure(.message(let message)):
 960                return message
 961            case .success(let edits):
 962                guard !edits.isEmpty else { return job.finish.params.contains("silent") ? output.problem ?? output.stdout : done }
 963                let result = EditResult(baseRevision: document.revision, edits: edits)
 964                if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
 965                changed(entry)
 966                return done
 967            }
 968        } catch is CancellationError {
 969            return "Code block canceled."
 970        } catch Babel.Failure.message(let message) {
 971            return message
 972        } catch {
 973            return "\(error)"
 974        }
 975    }
 976
 977    /// The block running now, to cancel.
 978    @ObservationIgnored private var babelTask: Task<String, Never>?
 979    public private(set) var isRunningBabel = false
 980
 981    /// Runs a src block in the background; its message comes back through `report`.
 982    public func startBabel(_ job: BabelJob, report: @escaping @MainActor (String) -> Void) {
 983        babelTask?.cancel()
 984        isRunningBabel = true
 985        let task = Task { await runBabel(job) }
 986        babelTask = task
 987        Task {
 988            let message = await task.value
 989            if babelTask == task {
 990                babelTask = nil
 991                isRunningBabel = false
 992            }
 993            report(message)
 994        }
 995    }
 996
 997    /// Stops the running block; its results aren't inserted.
 998    public func cancelBabel() {
 999        babelTask?.cancel()
1000    }
1001
1002    // MARK: - Locations
1003
1004    /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
1005    /// are used only if the buffer matches what was indexed; otherwise the heading is found
1006    /// again by position and title.
1007    public func show(_ location: HeadingLocation) {
1008        if path != location.path { open(location.path) }
1009        guard let document else { return }
1010        let hash = FileRecord.hash(document.mergeBase)
1011        let offset: Int
1012        if !isDirty, hash == location.contentHash {
1013            offset = location.start
1014        } else if location.ordinal == HeadingLocation.fileOrdinal {
1015            offset = 0
1016        } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
1017            offset = outline[location.ordinal].start
1018        } else if let entry = outline.first(where: { $0.title == location.title }) {
1019            offset = entry.start
1020        } else {
1021            return
1022        }
1023        reveal(offset)
1024    }
1025
1026    /// Asks the focused pane's editor to show `offset`.
1027    public func reveal(_ offset: Int) {
1028        reveal(offset, in: focused)
1029    }
1030
1031    /// Asks `pane`'s editor to show `offset`.
1032    public func reveal(_ offset: Int, in pane: EditorPane) {
1033        requestID += 1
1034        pane.revealRequest = (offset, requestID)
1035    }
1036
1037    /// Called when the workspace sees a file change on disk: an open buffer of it takes the
1038    /// change in.
1039    public func fileChanged(_ path: String) {
1040        let interval = Perf.begin("session.fileChanged")
1041        defer { interval.end((path as NSString).lastPathComponent) }
1042        guard let entry = entry(path), let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
1043        let buffer = entry.buffer
1044        guard bytes != buffer.document.mergeBase else { return }
1045        let name = (path as NSString).lastPathComponent
1046        switch buffer.update({ $0.diskChanged(to: bytes) }) {
1047        case .conflict:
1048            entry.autosave?.cancel()
1049            entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
1050        case .merged, .reloaded:
1051            entry.conflict = nil
1052            resolveSetup(entry)
1053            // Edits merged with the disk's still need saving.
1054            scheduleAutosave(entry)
1055        case .unchanged:
1056            break
1057        }
1058        refresh(entry)
1059    }
1060}