Sources/OrgApp/DocumentSession.swift

46d6a046f519e5ab5a9338ff643341bd53e7788f
orgstar/Sources/OrgApp/DocumentSession.swift history · blame · raw

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