Sources/OrgApp/DocumentSession.swift

d32d29c0620e94a09a204185d1a2004a8d58c518
orgstar/Sources/OrgApp/DocumentSession.swift history · blame · raw

798 lines · 38561 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 a window, as Emacs's buffers: each keeps its text, caret, undo and
 46/// unsaved edits while another is shown. The current buffer's outline, saving and requests
 47/// for the editor to show a location are what most views use. The view layer attaches an
 48/// editor to each buffer and follows `path` and `revealRequest`.
 49@MainActor
 50@Observable
 51public final class DocumentSession {
 52    /// The current buffer's file.
 53    public private(set) var path: String?
 54    /// A copy of the current buffer's state as of its last change. Not observed: it changes
 55    /// on every keystroke; views follow `path`, `isDirty` and `outline`.
 56    @ObservationIgnored public private(set) var document: DocumentState?
 57    public private(set) var outline: [OutlineEntry] = []
 58    /// Bumped when the buffer settles after edits, and when a file opens: views that read
 59    /// `document` follow this.
 60    public private(set) var editVersion = 0
 61    public private(set) var isDirty = false
 62    /// The file isn't UTF-8, so it can't be edited or saved.
 63    public private(set) var isReadOnly = false
 64    /// Set while the buffer and the file on disk conflict; says how to resolve it.
 65    public private(set) var conflict: String?
 66    /// Bumped to ask the editor to reveal an offset.
 67    public private(set) var revealRequest: (offset: Int, id: Int)?
 68    /// Open files, in the order buffers were opened (each after the one current then).
 69    public private(set) var openPaths: [String] = []
 70    /// Open files with unsaved edits.
 71    public private(set) var dirtyPaths: Set<String> = []
 72    public var lastError: String?
 73    public var saveMode: SaveMode = .automatic
 74    public var autosaveDelay: Duration = .seconds(1)
 75    /// Org options for commands the session runs (refile, archive).
 76    public var options: EditingOptions = .org
 77    /// TODO keywords and priorities for files without their own settings.
 78    public var defaults: OrgSettings = .default
 79
 80    /// One open file.
 81    @MainActor
 82    final class Entry {
 83        let path: String
 84        var buffer: DocumentBuffer
 85        var conflict: String?
 86        var autosave: Task<Void, Never>?
 87
 88        init(path: String, buffer: DocumentBuffer) {
 89            self.path = path
 90            self.buffer = buffer
 91        }
 92    }
 93
 94    private let fileSystem: FileSystem
 95    private let recovery: RecoveryStore
 96    @ObservationIgnored private var entries: [Entry] = []
 97    @ObservationIgnored private var current: Entry?
 98    /// Paths, most recently shown first.
 99    @ObservationIgnored private var history: [String] = []
100    @ObservationIgnored private var outlineUpdate: Task<Void, Never>?
101    private var requestID = 0
102
103    public init(
104        fileSystem: FileSystem = CoordinatedFileSystem(),
105        recovery: RecoveryStore = FileRecoveryStore(directory: WorkspaceModel.defaultDirectory.appendingPathComponent("Recovery"))
106    ) {
107        self.fileSystem = fileSystem
108        self.recovery = recovery
109    }
110
111    private var buffer: DocumentBuffer? { current?.buffer }
112    /// The current buffer's pending autosave, for tests to wait on.
113    var autosave: Task<Void, Never>? { current?.autosave }
114    private var url: URL? { path.map { URL(fileURLWithPath: $0) } }
115    /// Whether the open file is an org file (`.org`, `.org_archive`), not plain text.
116    public var isOrg: Bool { path.map(Self.isOrgPath) ?? false }
117
118    public static func isOrgPath(_ path: String) -> Bool {
119        path.hasSuffix(".org") || path.hasSuffix(".org_archive")
120    }
121
122    /// The caret in the open file.
123    public var caret: Int { buffer?.selection.first?.lowerBound ?? 0 }
124    private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" }
125
126    private func entry(_ path: String) -> Entry? { entries.first { $0.path == path } }
127
128    public func isOpen(_ path: String) -> Bool { entry(path) != nil }
129
130    /// The caret of an open file.
131    public func caret(of path: String) -> Int? { entry(path)?.buffer.selection.first?.lowerBound }
132
133    /// The text of every open file, for views that read files (the agenda, search).
134    public var openDocuments: [(path: String, document: DocumentState)] {
135        entries.map { ($0.path, $0.buffer.document) }
136    }
137
138    /// The text of every open file by path, for the agenda.
139    public var openTexts: [String: String] {
140        Dictionary(entries.map { ($0.path, $0.buffer.document.text) }, uniquingKeysWith: { a, _ in a })
141    }
142
143    /// Open buffers, most recently shown first.
144    public var recentPaths: [String] { history.filter(isOpen) }
145
146    /// Shows the buffer of `path`, opening the file if it isn't open.
147    public func open(_ path: String) {
148        if let existing = entry(path) {
149            activate(existing)
150            return
151        }
152        do {
153            guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
154                lastError = "\((path as NSString).lastPathComponent) no longer exists."
155                return
156            }
157            let entry = Entry(path: path, buffer: StateBuffer(DocumentState(bytes: bytes, defaults: defaults)))
158            let index = current.flatMap { c in entries.firstIndex { $0 === c } }.map { $0 + 1 } ?? entries.count
159            entries.insert(entry, at: index)
160            activate(entry)
161        } catch {
162            lastError = "Can't open \(path): \(error.localizedDescription)"
163        }
164    }
165
166    private func activate(_ entry: Entry) {
167        current = entry
168        path = entry.path
169        conflict = entry.conflict
170        revealRequest = nil
171        history.removeAll { $0 == entry.path }
172        history.insert(entry.path, at: 0)
173        refresh()
174    }
175
176    /// The buffer before or after the current one, wrapping.
177    public func cycle(_ step: Int) {
178        guard let current, let index = entries.firstIndex(where: { $0 === current }), entries.count > 1 else { return }
179        activate(entries[((index + step) % entries.count + entries.count) % entries.count])
180    }
181
182    /// The buffer shown before the current one.
183    public func showPrevious() {
184        guard let previous = recentPaths.dropFirst().first else { return }
185        open(previous)
186    }
187
188    /// Closes the buffer of `path` without saving it; the most recent other buffer shows.
189    public func kill(_ path: String) {
190        guard let entry = entry(path) else { return }
191        entry.autosave?.cancel()
192        entries.removeAll { $0 === entry }
193        history.removeAll { $0 == path }
194        if entry === current {
195            current = nil
196            if let next = recentPaths.first.flatMap(self.entry) ?? entries.last {
197                activate(next)
198            } else {
199                outlineUpdate?.cancel()
200                self.path = nil
201                document = nil
202                outline = []
203                isDirty = false
204                conflict = nil
205                revealRequest = nil
206                refreshLists()
207            }
208        } else {
209            refreshLists()
210        }
211    }
212
213    /// Closes the current buffer without saving, as when its file was deleted.
214    public func close() {
215        if let path { kill(path) }
216    }
217
218    /// Makes `buffer`, built from `document`, the live state of the current file.
219    public func attach(_ buffer: DocumentBuffer) {
220        current?.buffer = buffer
221        refresh()
222    }
223
224    /// The buffer of `path` changed in its editor: the current one updates its views, another
225    /// saves on its own.
226    public func bufferChanged(_ path: String) {
227        guard let entry = entry(path) else { return }
228        if entry === current { bufferChanged() } else { scheduleAutosave(entry); refreshLists() }
229    }
230
231    /// The buffer changed through typing. The outline follows once typing pauses.
232    public func bufferChanged() {
233        refresh(outline: false)
234        outlineUpdate?.cancel()
235        outlineUpdate = Task { [weak self] in
236            try? await Task.sleep(for: .milliseconds(300))
237            guard !Task.isCancelled, let self, let document = self.document else { return }
238            self.outline = self.isOrg ? Presentation.outline(document.tree) : []
239            self.editVersion += 1
240        }
241        if let current { scheduleAutosave(current) }
242    }
243
244    private func refresh(outline updateOutline: Bool = true) {
245        refreshLists()
246        guard let buffer else { return }
247        let state = buffer.document
248        document = state
249        if isDirty != state.isDirty { isDirty = state.isDirty }
250        if isReadOnly == state.isEditable { isReadOnly = !state.isEditable }
251        if conflict != current?.conflict { conflict = current?.conflict }
252        if updateOutline {
253            outline = isOrg ? Presentation.outline(state.tree) : []
254            editVersion += 1
255        }
256    }
257
258    private func refreshLists() {
259        let paths = entries.map(\.path)
260        if paths != openPaths { openPaths = paths }
261        let dirty = Set(entries.filter { $0.buffer.document.isDirty }.map(\.path))
262        if dirty != dirtyPaths { dirtyPaths = dirty }
263    }
264
265    // MARK: - Saving
266
267    private var saver: Saver { Saver(fileSystem: fileSystem, recovery: recovery) }
268
269    private func scheduleAutosave(_ entry: Entry) {
270        entry.autosave?.cancel()
271        guard saveMode == .automatic, entry.buffer.document.isDirty, entry.conflict == nil else { return }
272        entry.autosave = Task { [weak self, weak entry, autosaveDelay] in
273            try? await Task.sleep(for: autosaveDelay)
274            guard !Task.isCancelled, let self, let entry else { return }
275            self.save(entry)
276        }
277    }
278
279    /// Saves the current buffer now. True when nothing is left unsaved.
280    @discardableResult
281    public func save() -> Bool {
282        guard let current else { return true }
283        return save(current)
284    }
285
286    /// Saves the buffer of `path`. True when nothing is left unsaved.
287    @discardableResult
288    public func save(_ path: String) -> Bool {
289        guard let entry = entry(path) else { return true }
290        return save(entry)
291    }
292
293    /// Saves every open buffer. True when nothing is left unsaved.
294    @discardableResult
295    public func saveAll() -> Bool {
296        entries.map { save($0) }.allSatisfy { $0 }
297    }
298
299    @discardableResult
300    private func save(_ entry: Entry) -> Bool {
301        entry.autosave?.cancel()
302        let name = (entry.path as NSString).lastPathComponent
303        guard entry.buffer.document.isDirty else { return true }
304        guard entry.conflict == nil else { return false }
305        do {
306            let outcome = try entry.buffer.update { try saver.save(&$0, to: URL(fileURLWithPath: entry.path)) }
307            switch outcome {
308            case .saved, .mergedAndSaved:
309                break
310            case .conflict:
311                entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
312            case .overwroteExternalChange(let change), .changedAfterWrite(let change):
313                if case .conflict = change {
314                    entry.conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
315                }
316            }
317        } catch {
318            lastError = "Can't save \(name): \(error.localizedDescription)"
319        }
320        if entry === current { refresh() } else { refreshLists() }
321        return !entry.buffer.document.isDirty
322    }
323
324    /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
325    public func keepMine() {
326        guard let buffer, let url else { return }
327        do {
328            try buffer.update { try saver.overwrite(&$0, to: url) }
329            current?.conflict = nil
330        } catch {
331            lastError = "Can't save \(name): \(error.localizedDescription)"
332        }
333        refresh()
334    }
335
336    /// Resolves a conflict by loading the disk version; the buffer goes to recovery.
337    public func useDiskVersion() {
338        guard let buffer, let url else { return }
339        do {
340            guard let bytes = try fileSystem.read(url) else { return }
341            if isDirty { try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") }
342            buffer.update { $0 = DocumentState(bytes: bytes, defaults: $0.defaults) }
343            current?.conflict = nil
344        } catch {
345            lastError = "Can't read \(name): \(error.localizedDescription)"
346        }
347        refresh()
348    }
349
350    // MARK: - Comparing versions
351
352    /// The buffer, the file on disk and the version both started from, while they conflict.
353    public func conflictVersions() -> (mine: String, disk: String, base: String)? {
354        guard current?.conflict != nil, let buffer, let url, let disk = try? fileSystem.read(url) else { return nil }
355        return (buffer.document.text, SourceText(bytes: disk).text, SourceText(bytes: buffer.document.mergeBase).text)
356    }
357
358    /// Resolves a conflict as `git merge` leaves one: the buffer holds both sides' changes, those
359    /// that conflict between markers, to fix and save. The disk version becomes the base, and
360    /// the buffer as it was goes to recovery.
361    public func mergeConflictWithMarkers() {
362        guard let versions = conflictVersions(), let buffer, let url, let disk = try? fileSystem.read(url) else { return }
363        do {
364            try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
365            let merged = mergeWithMarkers(base: versions.base, ours: versions.mine, theirs: versions.disk, oursLabel: "yours", theirsLabel: "disk")
366            try buffer.update { state in
367                state = DocumentState(bytes: disk, defaults: state.defaults)
368                try state.apply(lineEdits(from: versions.disk, to: merged), baseRevision: state.revision)
369            }
370            current?.conflict = nil
371        } catch {
372            lastError = "Can't merge \(name): \(error.localizedDescription)"
373        }
374        refresh()
375    }
376
377    /// Syncthing's conflict copies of the open file beside it: `name.sync-conflict-DATE-TIME-ID.ext`.
378    public func syncConflictCopies() -> [URL] {
379        guard let url else { return [] }
380        let folder = url.deletingLastPathComponent()
381        let stem = NSRegularExpression.escapedPattern(for: url.deletingPathExtension().lastPathComponent)
382        let ext = url.pathExtension.isEmpty ? "" : "\\." + NSRegularExpression.escapedPattern(for: url.pathExtension)
383        let pattern = "^" + stem + "\\.sync-conflict-[0-9]{8}-[0-9]{6}-[A-Z0-9]+" + ext + "$"
384        let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []
385        return names.filter { $0.range(of: pattern, options: .regularExpression) != nil }.sorted().map { folder.appendingPathComponent($0) }
386    }
387
388    /// What to do with a conflict copy: keep the file as it is, take the copy's text, or merge
389    /// the two with markers. The copy goes to recovery and is removed.
390    public enum CopyResolution { case keepFile, useCopy, merge }
391
392    public func resolve(copy: URL, _ resolution: CopyResolution) -> String? {
393        guard let buffer, let url else { return "No file is open" }
394        do {
395            guard let bytes = try fileSystem.read(copy) else { return "\(copy.lastPathComponent) is gone" }
396            let copyText = SourceText(bytes: bytes).text
397            let mine = buffer.document.text
398            let new: String? = switch resolution {
399            case .keepFile: nil
400            case .useCopy: copyText
401            case .merge: mergeWithMarkers(base: nil, ours: mine, theirs: copyText, oursLabel: url.lastPathComponent, theirsLabel: copy.lastPathComponent)
402            }
403            if let new, new != mine {
404                let result = EditResult(baseRevision: buffer.document.revision, edits: lineEdits(from: mine, to: new))
405                if case .failed(let message) = buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
406            }
407            try recovery.keep(bytes, for: url, label: "sync-conflict")
408            try FileManager.default.removeItem(at: copy)
409        } catch {
410            return "Can't resolve \(copy.lastPathComponent): \(error.localizedDescription)"
411        }
412        if let current { changed(current) }
413        return nil
414    }
415
416    /// Versions of the open file kept in recovery, newest first, with when and why each was
417    /// kept.
418    public func recoveryVersions() -> [(url: URL, date: Date, label: String)] {
419        guard let url, let store = recovery as? FileRecoveryStore, let versions = try? store.versions(for: url) else { return [] }
420        // `STAMP-LABEL-UUID8-NAME`, as `FileRecoveryStore.keep` names them.
421        return versions.reversed().map { version in
422            let m = version.lastPathComponent.firstMatch(of: /^([0-9]+)-(.+?)-([0-9A-Fa-f]{8})-/)
423            let nanos = m.flatMap { UInt64($0.1) } ?? 0
424            return (version, Date(timeIntervalSince1970: Double(nanos) / 1_000_000_000), m.map { String($0.2) } ?? "")
425        }
426    }
427
428    /// The text of a kept version.
429    public func recoveryText(_ version: URL) -> String? {
430        (try? fileSystem.read(version)).flatMap { $0 }.map { SourceText(bytes: $0).text }
431    }
432
433    /// Puts a kept version's text in the buffer, as an edit that can be undone; the buffer as it
434    /// was goes to recovery.
435    public func restore(_ version: URL) -> String? {
436        guard let buffer, let url, let text = recoveryText(version) else { return "Can't read that version" }
437        do {
438            try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
439        } catch {
440            return "Can't keep the current version: \(error.localizedDescription)"
441        }
442        let mine = buffer.document.text
443        let result = EditResult(baseRevision: buffer.document.revision, edits: lineEdits(from: mine, to: text))
444        if case .failed(let message) = buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
445        if let current { changed(current) }
446        return nil
447    }
448
449    // MARK: - Moving subtrees
450
451    /// The current context of the buffer, as commands see it.
452    private func editContext(now: Date) -> EditContext? {
453        guard let buffer else { return nil }
454        let document = buffer.document
455        return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: buffer.selection, now: now, options: options)
456    }
457
458    /// The file and context a subtree command works on: `from` (a file and a heading in it,
459    /// as the agenda gives them), or the current buffer at its caret.
460    private func source(_ from: (path: String, offset: Int)?, now: Date) -> (path: String, context: EditContext)? {
461        guard let from else {
462            guard let path, let context = editContext(now: now) else { return nil }
463            return (path, context)
464        }
465        let state: DocumentState
466        if let open = entry(from.path) {
467            state = open.buffer.document
468        } else {
469            guard let bytes = try? fileSystem.read(URL(fileURLWithPath: from.path)) else { return nil }
470            state = DocumentState(bytes: bytes, defaults: defaults)
471        }
472        guard state.isEditable else { return nil }
473        let context = EditContext(revision: state.revision, text: state.text, tree: state.tree, selection: [from.offset..<from.offset], now: now, options: options)
474        return (from.path, context)
475    }
476
477    /// Applies an edit computed from `source(_:now:)` to that file, open or not.
478    private func applySource(_ edit: EditResult, path: String, now: Date) -> String? {
479        if case .failed(let message) = perform(PrecomputedEdit(edit), path: path, at: 0, expect: nil, now: now) { return message }
480        return nil
481    }
482
483    /// Moves the subtree at the caret, or at `from`, under `target`. For another file, that
484    /// file is written first, through the save path; the subtree leaves its file only once it
485    /// has. Returns a message for the echo area.
486    @discardableResult
487    public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
488        guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
489        if target.path == path {
490            let answers = ["refile": target.start.map(String.init) ?? ""]
491            let step = from == nil ? buffer?.perform(RefileWithinFile(), now: now, answers: answers)
492                : perform(RefileWithinFile(), path: path, at: from!.offset, expect: nil, answers: answers, now: now)
493            if case .failed(let message)? = step { return message }
494            if from == nil { bufferChanged() }
495            return "Refiled to \(target.label)"
496        }
497        let url = URL(fileURLWithPath: target.path)
498        let targetName = (target.path as NSString).lastPathComponent
499        // A target open in a buffer takes the subtree there, with its unsaved edits.
500        if let open = entry(target.path) {
501            let state = open.buffer.document
502            guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
503            guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
504            guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." }
505            let edit = EditResult(baseRevision: state.revision, edits: [result.target])
506            if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
507            changed(open)
508            if let message = applySource(result.source, path: path, now: now) { return message }
509            return "Refiled to \(target.label)"
510        }
511        do {
512            guard let bytes = try fileSystem.read(url) else { return "\(targetName) no longer exists." }
513            var state = DocumentState(bytes: bytes, defaults: defaults)
514            guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
515            guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
516            guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." }
517            try state.apply([result.target], baseRevision: state.revision)
518            if case .conflict = try saver.save(&state, to: url) { return "\(targetName) changed on disk; nothing was refiled." }
519            if let message = applySource(result.source, path: path, now: now) { return message }
520            return "Refiled to \(target.label)"
521        } catch {
522            return "Can't refile: \(error.localizedDescription)"
523        }
524    }
525
526    /// Archives the subtree at the caret, or at `from`, where `org-archive-subtree` would.
527    /// Returns a message.
528    @discardableResult
529    public func archive(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
530        guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
531        let destination: Archive.Destination
532        switch Archive.destination(context, sourcePath: path) {
533        case .success(let value): destination = value
534        case .failure(.message(let message)): return message
535        }
536        // An archive file open in a buffer takes the subtree there.
537        if !destination.isSameFile, let open = entry(destination.path) {
538            let state = open.buffer.document
539            let name = (destination.path as NSString).lastPathComponent
540            guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
541            let edits: Archive.Edits
542            switch Archive.run(context, sourcePath: path, destination: destination, archiveText: state.text) {
543            case .success(let value): edits = value
544            case .failure(.message(let message)): return message
545            }
546            if let archiveEdit = edits.archive {
547                let edit = EditResult(baseRevision: state.revision, edits: [archiveEdit])
548                if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
549                changed(open)
550            }
551            if let message = applySource(edits.source, path: path, now: now) { return message }
552            return "Archived to \(name)"
553        }
554        do {
555            let url = URL(fileURLWithPath: destination.path)
556            let existing = destination.isSameFile ? nil : try fileSystem.read(url)
557            var state = DocumentState(bytes: existing ?? [], defaults: defaults)
558            if !destination.isSameFile, !state.isEditable { return "\(url.lastPathComponent) isn't UTF-8, so it can't be changed." }
559            let edits: Archive.Edits
560            switch Archive.run(context, sourcePath: path, destination: destination, archiveText: existing.map { _ in state.text }) {
561            case .success(let value): edits = value
562            case .failure(.message(let message)): return message
563            }
564            if let archiveEdit = edits.archive {
565                try state.apply([archiveEdit], baseRevision: state.revision)
566                if case .conflict = try saver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
567            }
568            if let message = applySource(edits.source, path: path, now: now) { return message }
569            return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
570        } catch {
571            return "Can't archive: \(error.localizedDescription)"
572        }
573    }
574
575    // MARK: - Commands from other views
576
577    /// Where the heading line `line` is now in `path`: at `offset` if it still reads so, else
578    /// the copy of the line nearest `offset`. For acting on agenda entries after other edits
579    /// moved them.
580    public func locateHeading(path: String, line: String, near offset: Int) -> Int? {
581        guard let text = entry(path)?.buffer.document.text ?? (try? fileSystem.read(URL(fileURLWithPath: path))).flatMap({ $0.map { SourceText(bytes: $0).text } }) else { return nil }
582        let ns = text as NSString
583        let length = (line as NSString).length
584        if offset + length <= ns.length, ns.substring(with: NSRange(location: offset, length: length)) == line,
585           offset == 0 || ns.character(at: offset - 1) == 10 {
586            return offset
587        }
588        var best: Int?
589        var search = NSRange(location: 0, length: ns.length)
590        while true {
591            let found = ns.range(of: line, options: [], range: search)
592            guard found.location != NSNotFound else { break }
593            let atLineStart = found.location == 0 || ns.character(at: found.location - 1) == 10
594            let lineEnd = NSMaxRange(found) == ns.length || ns.character(at: NSMaxRange(found)) == 10
595            if atLineStart, lineEnd, best.map({ abs($0 - offset) > abs(found.location - offset) }) ?? true { best = found.location }
596            search = NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))
597        }
598        return best
599    }
600
601    /// Runs `command` with the caret at `offset` in the file at `path`, as the agenda does:
602    /// through the buffer when the file is open, leaving its caret alone; otherwise on the
603    /// file, written back at once through the save path. `expect` is the heading line the
604    /// caller saw at a position; if the text there changed, nothing runs.
605    public func perform(
606        _ command: any OrgCommand, path: String, at offset: Int, expect: (start: Int, line: String)?,
607        answers: [String: String] = [:], now: Date = Date()
608    ) -> CommandStep {
609        let stale = CommandStep.failed("The entry changed; the agenda has been refreshed.")
610        func matches(_ text: String) -> Bool {
611            guard let expect else { return true }
612            let ns = text as NSString
613            guard expect.start + (expect.line as NSString).length <= ns.length else { return false }
614            return ns.substring(with: NSRange(location: expect.start, length: (expect.line as NSString).length)) == expect.line
615        }
616        if let entry = entry(path) {
617            let buffer = entry.buffer
618            guard matches(buffer.document.text) else { return stale }
619            do {
620                let options = self.options
621                let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) }
622                if case .commit = step {
623                    if entry === current { bufferChanged() } else { scheduleAutosave(entry); refreshLists() }
624                }
625                return step
626            } catch {
627                return .failed("\(error)")
628            }
629        }
630        let url = URL(fileURLWithPath: path)
631        let name = url.lastPathComponent
632        do {
633            guard let bytes = try fileSystem.read(url) else { return .failed("\(name) no longer exists.") }
634            var state = DocumentState(bytes: bytes, defaults: defaults)
635            guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") }
636            guard matches(state.text) else { return stale }
637            let step = try state.run(command, selection: [offset..<offset], now: now, answers: answers, options: options)
638            if case .commit = step, state.isDirty, case .conflict = try saver.save(&state, to: url) {
639                return .failed("\(name) changed on disk; nothing was changed.")
640            }
641            return step
642        } catch {
643            return .failed("Can't change \(name): \(error.localizedDescription)")
644        }
645    }
646
647    // MARK: - External work
648
649    /// Recalculates a table in Emacs from a snapshot of the buffer, then replaces the table
650    /// with Emacs's text if it hasn't changed meanwhile. Returns a message for the echo area.
651    public func recalculateInEmacs(table: Range<Int>, point: Int, form: String) async -> String {
652        #if os(macOS)
653        guard let entry = current else { return "No file is open." }
654        let path = entry.path
655        let snapshot = entry.buffer.document.text as NSString
656        guard table.upperBound <= snapshot.length else { return "The table moved; try again." }
657        let old = snapshot.substring(with: NSRange(table))
658        let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
659        do {
660            let new = try await EmacsRunner.recalculateTable(text: snapshot as String, directory: directory, table: table, point: point, form: form)
661            guard entries.contains(where: { $0 === entry }) else { return "The file was closed before Emacs finished." }
662            let current = entry.buffer
663            let text = current.document.text as NSString
664            guard table.upperBound <= text.length, text.substring(with: NSRange(table)) == old else {
665                return "The table changed while Emacs recalculated it; nothing was changed."
666            }
667            guard new != old else { return "Recalculated in Emacs" }
668            let result = EditResult(baseRevision: current.document.revision, edits: [TextEdit(range: table, replacement: new)])
669            if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
670            changed(entry)
671            return "Recalculated in Emacs"
672        } catch {
673            return "\(error)"
674        }
675        #else
676        return "Tables that need Emacs aren't recalculated on iOS."
677        #endif
678    }
679
680    /// Runs a src block and writes its result under it, unless the block changed while it
681    /// ran. Returns a message for the echo area.
682    public func runBabel(_ job: BabelJob) async -> String {
683        #if os(macOS)
684        guard let entry = current else { return "No file is open." }
685        let directory = URL(fileURLWithPath: entry.path).deletingLastPathComponent()
686        do {
687            let output = try await BabelRunner.run(job, fileDirectory: directory)
688            guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
689            if let file = Babel.fileResult(job, output: output) {
690                let runDirectory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
691                let target = file.path.hasPrefix("/") ? URL(fileURLWithPath: file.path) : runDirectory.appendingPathComponent(file.path)
692                do {
693                    try file.contents.write(to: target, atomically: true, encoding: .utf8)
694                } catch {
695                    return "Can't write \(file.path): \(error.localizedDescription)"
696                }
697            }
698            let current = entry.buffer
699            let document = current.document
700            let done = output.problem ?? "Code block evaluation complete."
701            switch Babel.finish(job, output: output, text: document.text, settings: document.tree.settings) {
702            case .failure(.message(let message)):
703                return message
704            case .success(let edits):
705                guard !edits.isEmpty else { return job.finish.params.contains("silent") ? output.problem ?? output.stdout : done }
706                let result = EditResult(baseRevision: document.revision, edits: edits)
707                if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
708                changed(entry)
709                return done
710            }
711        } catch is CancellationError {
712            return "Code block canceled."
713        } catch {
714            return "\(error)"
715        }
716        #else
717        return "Source blocks don't run on iOS."
718        #endif
719    }
720
721    /// The block running now, to cancel.
722    @ObservationIgnored private var babelTask: Task<String, Never>?
723    public private(set) var isRunningBabel = false
724
725    /// Runs a src block in the background; its message comes back through `report`.
726    public func startBabel(_ job: BabelJob, report: @escaping @MainActor (String) -> Void) {
727        babelTask?.cancel()
728        isRunningBabel = true
729        let task = Task { await runBabel(job) }
730        babelTask = task
731        Task {
732            let message = await task.value
733            if babelTask == task {
734                babelTask = nil
735                isRunningBabel = false
736            }
737            report(message)
738        }
739    }
740
741    /// Stops the running block; its results aren't inserted.
742    public func cancelBabel() {
743        babelTask?.cancel()
744    }
745
746    /// A buffer changed outside typing: the current one updates its views, another saves.
747    private func changed(_ entry: Entry) {
748        if entry === current { bufferChanged() } else { scheduleAutosave(entry); refreshLists() }
749    }
750
751    // MARK: - Locations
752
753    /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
754    /// are used only if the buffer matches what was indexed; otherwise the heading is found
755    /// again by position and title.
756    public func show(_ location: HeadingLocation) {
757        if path != location.path { open(location.path) }
758        guard let document else { return }
759        let hash = FileRecord.hash(document.mergeBase)
760        let offset: Int
761        if !isDirty, hash == location.contentHash {
762            offset = location.start
763        } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
764            offset = outline[location.ordinal].start
765        } else if let entry = outline.first(where: { $0.title == location.title }) {
766            offset = entry.start
767        } else {
768            return
769        }
770        reveal(offset)
771    }
772
773    public func reveal(_ offset: Int) {
774        requestID += 1
775        revealRequest = (offset, requestID)
776    }
777
778    /// Called when the workspace sees a file change on disk: an open buffer of it takes the
779    /// change in.
780    public func fileChanged(_ path: String) {
781        guard let entry = entry(path), let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
782        let buffer = entry.buffer
783        guard bytes != buffer.document.mergeBase else { return }
784        let name = (path as NSString).lastPathComponent
785        switch buffer.update({ $0.diskChanged(to: bytes) }) {
786        case .conflict:
787            entry.autosave?.cancel()
788            entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
789        case .merged, .reloaded:
790            entry.conflict = nil
791            // Edits merged with the disk's still need saving.
792            scheduleAutosave(entry)
793        case .unchanged:
794            break
795        }
796        if entry === current { refresh() } else { refreshLists() }
797    }
798}