Sources/OrgApp/DocumentSession.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgApp/DocumentSession.swift history · blame · raw

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