Sources/OrgApp/DocumentSession.swift

9abba9cfc504b344b7d267978a97f1c925a1d5dd
orgstar/Sources/OrgApp/DocumentSession.swift history · blame · raw

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