Sources/OrgApp/DocumentSession.swift

5eef7a168632da902fdd0979d57258320e4fdfc2
orgstar/Sources/OrgApp/DocumentSession.swift history · blame · raw

960 lines · 46480 bytes

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