Sources/OrgApp/DocumentSession.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/OrgApp/DocumentSession.swift history · blame · raw

964 lines · 46731 bytes

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