Sources/OrgApp/DocumentSession.swift

3959d9c38d34f2d30757a8c9c88309a5328522e5
orgstar/Sources/OrgApp/DocumentSession.swift history · blame · raw

564 lines · 25687 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 file hasn't changed, else the
 29    /// 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 FileRecord.hash(state.mergeBase) == contentHash { return .some(start) }
 33        let entry = Presentation.outline(state.tree).first { $0.title == title && $0.level == level }
 34        return entry.map { .some($0.start) }
 35    }
 36}
 37
 38public enum SaveMode: String, Sendable, CaseIterable {
 39    /// Save shortly after typing stops.
 40    case automatic
 41    /// Save only on ⌘S.
 42    case explicit
 43}
 44
 45/// The files open in a window, as Emacs's buffers: each keeps its text, caret, undo and
 46/// unsaved edits while another is shown. The current buffer's outline, saving and requests
 47/// for the editor to show a location are what most views use. The view layer attaches an
 48/// editor to each buffer and follows `path` and `revealRequest`.
 49@MainActor
 50@Observable
 51public final class DocumentSession {
 52    /// The current buffer's file.
 53    public private(set) var path: String?
 54    /// A copy of the current buffer's state as of its last change. Not observed: it changes
 55    /// on every keystroke; views follow `path`, `isDirty` and `outline`.
 56    @ObservationIgnored public private(set) var document: DocumentState?
 57    public private(set) var outline: [OutlineEntry] = []
 58    /// Bumped when the buffer settles after edits, and when a file opens: views that read
 59    /// `document` follow this.
 60    public private(set) var editVersion = 0
 61    public private(set) var isDirty = false
 62    /// The file isn't UTF-8, so it can't be edited or saved.
 63    public private(set) var isReadOnly = false
 64    /// Set while the buffer and the file on disk conflict; says how to resolve it.
 65    public private(set) var conflict: String?
 66    /// Bumped to ask the editor to reveal an offset.
 67    public private(set) var revealRequest: (offset: Int, id: Int)?
 68    /// Open files, in the order buffers were opened (each after the one current then).
 69    public private(set) var openPaths: [String] = []
 70    /// Open files with unsaved edits.
 71    public private(set) var dirtyPaths: Set<String> = []
 72    public var lastError: String?
 73    public var saveMode: SaveMode = .automatic
 74    public var autosaveDelay: Duration = .seconds(1)
 75    /// Org options for commands the session runs (refile, archive).
 76    public var options: EditingOptions = .org
 77    /// TODO keywords and priorities for files without their own settings.
 78    public var defaults: OrgSettings = .default
 79
 80    /// One open file.
 81    @MainActor
 82    final class Entry {
 83        let path: String
 84        var buffer: DocumentBuffer
 85        var conflict: String?
 86        var autosave: Task<Void, Never>?
 87
 88        init(path: String, buffer: DocumentBuffer) {
 89            self.path = path
 90            self.buffer = buffer
 91        }
 92    }
 93
 94    private let fileSystem: FileSystem
 95    private let recovery: RecoveryStore
 96    @ObservationIgnored private var entries: [Entry] = []
 97    @ObservationIgnored private var current: Entry?
 98    /// Paths, most recently shown first.
 99    @ObservationIgnored private var history: [String] = []
100    @ObservationIgnored private var outlineUpdate: Task<Void, Never>?
101    private var requestID = 0
102
103    public init(
104        fileSystem: FileSystem = CoordinatedFileSystem(),
105        recovery: RecoveryStore = FileRecoveryStore(directory: WorkspaceModel.defaultDirectory.appendingPathComponent("Recovery"))
106    ) {
107        self.fileSystem = fileSystem
108        self.recovery = recovery
109    }
110
111    private var buffer: DocumentBuffer? { current?.buffer }
112    /// The current buffer's pending autosave, for tests to wait on.
113    var autosave: Task<Void, Never>? { current?.autosave }
114    private var url: URL? { path.map { URL(fileURLWithPath: $0) } }
115    /// Whether the open file is an org file (`.org`, `.org_archive`), not plain text.
116    public var isOrg: Bool { path.map(Self.isOrgPath) ?? false }
117
118    public static func isOrgPath(_ path: String) -> Bool {
119        path.hasSuffix(".org") || path.hasSuffix(".org_archive")
120    }
121
122    /// The caret in the open file.
123    public var caret: Int { buffer?.selection.first?.lowerBound ?? 0 }
124    private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" }
125
126    private func entry(_ path: String) -> Entry? { entries.first { $0.path == path } }
127
128    public func isOpen(_ path: String) -> Bool { entry(path) != nil }
129
130    /// The caret of an open file.
131    public func caret(of path: String) -> Int? { entry(path)?.buffer.selection.first?.lowerBound }
132
133    /// The text of every open file, for views that read files (the agenda, search).
134    public var openDocuments: [(path: String, document: DocumentState)] {
135        entries.map { ($0.path, $0.buffer.document) }
136    }
137
138    /// The text of every open file by path, for the agenda.
139    public var openTexts: [String: String] {
140        Dictionary(entries.map { ($0.path, $0.buffer.document.text) }, uniquingKeysWith: { a, _ in a })
141    }
142
143    /// Open buffers, most recently shown first.
144    public var recentPaths: [String] { history.filter(isOpen) }
145
146    /// Shows the buffer of `path`, opening the file if it isn't open.
147    public func open(_ path: String) {
148        if let existing = entry(path) {
149            activate(existing)
150            return
151        }
152        do {
153            guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
154                lastError = "\((path as NSString).lastPathComponent) no longer exists."
155                return
156            }
157            let entry = Entry(path: path, buffer: StateBuffer(DocumentState(bytes: bytes, defaults: defaults)))
158            let index = current.flatMap { c in entries.firstIndex { $0 === c } }.map { $0 + 1 } ?? entries.count
159            entries.insert(entry, at: index)
160            activate(entry)
161        } catch {
162            lastError = "Can't open \(path): \(error.localizedDescription)"
163        }
164    }
165
166    private func activate(_ entry: Entry) {
167        current = entry
168        path = entry.path
169        conflict = entry.conflict
170        revealRequest = nil
171        history.removeAll { $0 == entry.path }
172        history.insert(entry.path, at: 0)
173        refresh()
174    }
175
176    /// The buffer before or after the current one, wrapping.
177    public func cycle(_ step: Int) {
178        guard let current, let index = entries.firstIndex(where: { $0 === current }), entries.count > 1 else { return }
179        activate(entries[((index + step) % entries.count + entries.count) % entries.count])
180    }
181
182    /// The buffer shown before the current one.
183    public func showPrevious() {
184        guard let previous = recentPaths.dropFirst().first else { return }
185        open(previous)
186    }
187
188    /// Closes the buffer of `path` without saving it; the most recent other buffer shows.
189    public func kill(_ path: String) {
190        guard let entry = entry(path) else { return }
191        entry.autosave?.cancel()
192        entries.removeAll { $0 === entry }
193        history.removeAll { $0 == path }
194        if entry === current {
195            current = nil
196            if let next = recentPaths.first.flatMap(self.entry) ?? entries.last {
197                activate(next)
198            } else {
199                outlineUpdate?.cancel()
200                self.path = nil
201                document = nil
202                outline = []
203                isDirty = false
204                conflict = nil
205                revealRequest = nil
206                refreshLists()
207            }
208        } else {
209            refreshLists()
210        }
211    }
212
213    /// Closes the current buffer without saving, as when its file was deleted.
214    public func close() {
215        if let path { kill(path) }
216    }
217
218    /// Makes `buffer`, built from `document`, the live state of the current file.
219    public func attach(_ buffer: DocumentBuffer) {
220        current?.buffer = buffer
221        refresh()
222    }
223
224    /// The buffer changed through typing. The outline follows once typing pauses.
225    public func bufferChanged() {
226        refresh(outline: false)
227        outlineUpdate?.cancel()
228        outlineUpdate = Task { [weak self] in
229            try? await Task.sleep(for: .milliseconds(300))
230            guard !Task.isCancelled, let self, let document = self.document else { return }
231            self.outline = self.isOrg ? Presentation.outline(document.tree) : []
232            self.editVersion += 1
233        }
234        if let current { scheduleAutosave(current) }
235    }
236
237    private func refresh(outline updateOutline: Bool = true) {
238        refreshLists()
239        guard let buffer else { return }
240        let state = buffer.document
241        document = state
242        if isDirty != state.isDirty { isDirty = state.isDirty }
243        if isReadOnly == state.isEditable { isReadOnly = !state.isEditable }
244        if conflict != current?.conflict { conflict = current?.conflict }
245        if updateOutline {
246            outline = isOrg ? Presentation.outline(state.tree) : []
247            editVersion += 1
248        }
249    }
250
251    private func refreshLists() {
252        let paths = entries.map(\.path)
253        if paths != openPaths { openPaths = paths }
254        let dirty = Set(entries.filter { $0.buffer.document.isDirty }.map(\.path))
255        if dirty != dirtyPaths { dirtyPaths = dirty }
256    }
257
258    // MARK: - Saving
259
260    private var saver: Saver { Saver(fileSystem: fileSystem, recovery: recovery) }
261
262    private func scheduleAutosave(_ entry: Entry) {
263        entry.autosave?.cancel()
264        guard saveMode == .automatic, entry.buffer.document.isDirty, entry.conflict == nil else { return }
265        entry.autosave = Task { [weak self, weak entry, autosaveDelay] in
266            try? await Task.sleep(for: autosaveDelay)
267            guard !Task.isCancelled, let self, let entry else { return }
268            self.save(entry)
269        }
270    }
271
272    /// Saves the current buffer now. True when nothing is left unsaved.
273    @discardableResult
274    public func save() -> Bool {
275        guard let current else { return true }
276        return save(current)
277    }
278
279    /// Saves the buffer of `path`. True when nothing is left unsaved.
280    @discardableResult
281    public func save(_ path: String) -> Bool {
282        guard let entry = entry(path) else { return true }
283        return save(entry)
284    }
285
286    /// Saves every open buffer. True when nothing is left unsaved.
287    @discardableResult
288    public func saveAll() -> Bool {
289        entries.map { save($0) }.allSatisfy { $0 }
290    }
291
292    @discardableResult
293    private func save(_ entry: Entry) -> Bool {
294        entry.autosave?.cancel()
295        let name = (entry.path as NSString).lastPathComponent
296        guard entry.buffer.document.isDirty else { return true }
297        guard entry.conflict == nil else { return false }
298        do {
299            let outcome = try entry.buffer.update { try saver.save(&$0, to: URL(fileURLWithPath: entry.path)) }
300            switch outcome {
301            case .saved, .mergedAndSaved:
302                break
303            case .conflict:
304                entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
305            case .overwroteExternalChange(let change), .changedAfterWrite(let change):
306                if case .conflict = change {
307                    entry.conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
308                }
309            }
310        } catch {
311            lastError = "Can't save \(name): \(error.localizedDescription)"
312        }
313        if entry === current { refresh() } else { refreshLists() }
314        return !entry.buffer.document.isDirty
315    }
316
317    /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
318    public func keepMine() {
319        guard let buffer, let url else { return }
320        do {
321            try buffer.update { try saver.overwrite(&$0, to: url) }
322            current?.conflict = nil
323        } catch {
324            lastError = "Can't save \(name): \(error.localizedDescription)"
325        }
326        refresh()
327    }
328
329    /// Resolves a conflict by loading the disk version; the buffer goes to recovery.
330    public func useDiskVersion() {
331        guard let buffer, let url else { return }
332        do {
333            guard let bytes = try fileSystem.read(url) else { return }
334            if isDirty { try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") }
335            buffer.update { $0 = DocumentState(bytes: bytes, defaults: $0.defaults) }
336            current?.conflict = nil
337        } catch {
338            lastError = "Can't read \(name): \(error.localizedDescription)"
339        }
340        refresh()
341    }
342
343    // MARK: - Moving subtrees
344
345    /// The current context of the buffer, as commands see it.
346    private func editContext(now: Date) -> EditContext? {
347        guard let buffer else { return nil }
348        let document = buffer.document
349        return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: buffer.selection, now: now, options: options)
350    }
351
352    /// Moves the subtree at the caret under `target`. For another file, that file is written
353    /// first, through the save path; the subtree leaves this buffer only once it has. Returns a
354    /// message for the echo area.
355    @discardableResult
356    public func refile(to target: RefileTarget, now: Date = Date()) -> String? {
357        guard let buffer, let path, let context = editContext(now: now) else { return nil }
358        if target.path == path {
359            let step = buffer.perform(RefileWithinFile(), now: now, answers: ["refile": target.start.map(String.init) ?? ""])
360            if case .failed(let message) = step { return message }
361            bufferChanged()
362            return "Refiled to \(target.label)"
363        }
364        let url = URL(fileURLWithPath: target.path)
365        do {
366            guard let bytes = try fileSystem.read(url) else { return "\((target.path as NSString).lastPathComponent) no longer exists." }
367            var state = DocumentState(bytes: bytes, defaults: defaults)
368            guard state.isEditable else { return "\((target.path as NSString).lastPathComponent) isn't UTF-8, so it can't be changed." }
369            guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
370            guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." }
371            try state.apply([result.target], baseRevision: state.revision)
372            if case .conflict = try saver.save(&state, to: url) { return "\((target.path as NSString).lastPathComponent) changed on disk; nothing was refiled." }
373            if case .failed(let message) = buffer.perform(PrecomputedEdit(result.source), now: now, answers: [:]) { return message }
374            bufferChanged()
375            return "Refiled to \(target.label)"
376        } catch {
377            return "Can't refile: \(error.localizedDescription)"
378        }
379    }
380
381    /// Archives the subtree at the caret where `org-archive-subtree` would. Returns a message.
382    @discardableResult
383    public func archive(now: Date = Date()) -> String? {
384        guard let buffer, let path, let context = editContext(now: now) else { return nil }
385        let destination: Archive.Destination
386        switch Archive.destination(context, sourcePath: path) {
387        case .success(let value): destination = value
388        case .failure(.message(let message)): return message
389        }
390        do {
391            let url = URL(fileURLWithPath: destination.path)
392            let existing = destination.isSameFile ? nil : try fileSystem.read(url)
393            var state = DocumentState(bytes: existing ?? [], defaults: defaults)
394            if !destination.isSameFile, !state.isEditable { return "\(url.lastPathComponent) isn't UTF-8, so it can't be changed." }
395            let edits: Archive.Edits
396            switch Archive.run(context, sourcePath: path, destination: destination, archiveText: existing.map { _ in state.text }) {
397            case .success(let value): edits = value
398            case .failure(.message(let message)): return message
399            }
400            if let archiveEdit = edits.archive {
401                try state.apply([archiveEdit], baseRevision: state.revision)
402                if case .conflict = try saver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
403            }
404            if case .failed(let message) = buffer.perform(PrecomputedEdit(edits.source), now: now, answers: [:]) { return message }
405            bufferChanged()
406            return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
407        } catch {
408            return "Can't archive: \(error.localizedDescription)"
409        }
410    }
411
412    // MARK: - Commands from other views
413
414    /// Runs `command` with the caret at `offset` in the file at `path`, as the agenda does:
415    /// through the buffer when the file is open, leaving its caret alone; otherwise on the
416    /// file, written back at once through the save path. `expect` is the heading line the
417    /// caller saw at a position; if the text there changed, nothing runs.
418    public func perform(
419        _ command: any OrgCommand, path: String, at offset: Int, expect: (start: Int, line: String)?,
420        answers: [String: String] = [:], now: Date = Date()
421    ) -> CommandStep {
422        let stale = CommandStep.failed("The entry changed; the agenda has been refreshed.")
423        func matches(_ text: String) -> Bool {
424            guard let expect else { return true }
425            let ns = text as NSString
426            guard expect.start + (expect.line as NSString).length <= ns.length else { return false }
427            return ns.substring(with: NSRange(location: expect.start, length: (expect.line as NSString).length)) == expect.line
428        }
429        if let entry = entry(path) {
430            let buffer = entry.buffer
431            guard matches(buffer.document.text) else { return stale }
432            do {
433                let options = self.options
434                let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) }
435                if case .commit = step {
436                    if entry === current { bufferChanged() } else { scheduleAutosave(entry); refreshLists() }
437                }
438                return step
439            } catch {
440                return .failed("\(error)")
441            }
442        }
443        let url = URL(fileURLWithPath: path)
444        let name = url.lastPathComponent
445        do {
446            guard let bytes = try fileSystem.read(url) else { return .failed("\(name) no longer exists.") }
447            var state = DocumentState(bytes: bytes, defaults: defaults)
448            guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") }
449            guard matches(state.text) else { return stale }
450            let step = try state.run(command, selection: [offset..<offset], now: now, answers: answers, options: options)
451            if case .commit = step, state.isDirty, case .conflict = try saver.save(&state, to: url) {
452                return .failed("\(name) changed on disk; nothing was changed.")
453            }
454            return step
455        } catch {
456            return .failed("Can't change \(name): \(error.localizedDescription)")
457        }
458    }
459
460    // MARK: - External work
461
462    /// Recalculates a table in Emacs from a snapshot of the buffer, then replaces the table
463    /// with Emacs's text if it hasn't changed meanwhile. Returns a message for the echo area.
464    public func recalculateInEmacs(table: Range<Int>, point: Int, form: String) async -> String {
465        guard let entry = current else { return "No file is open." }
466        let path = entry.path
467        let snapshot = entry.buffer.document.text as NSString
468        guard table.upperBound <= snapshot.length else { return "The table moved; try again." }
469        let old = snapshot.substring(with: NSRange(table))
470        let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
471        do {
472            let new = try await EmacsRunner.recalculateTable(text: snapshot as String, directory: directory, table: table, point: point, form: form)
473            guard entries.contains(where: { $0 === entry }) else { return "The file was closed before Emacs finished." }
474            let current = entry.buffer
475            let text = current.document.text as NSString
476            guard table.upperBound <= text.length, text.substring(with: NSRange(table)) == old else {
477                return "The table changed while Emacs recalculated it; nothing was changed."
478            }
479            guard new != old else { return "Recalculated in Emacs" }
480            let result = EditResult(baseRevision: current.document.revision, edits: [TextEdit(range: table, replacement: new)])
481            if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
482            changed(entry)
483            return "Recalculated in Emacs"
484        } catch {
485            return "\(error)"
486        }
487    }
488
489    /// Runs a src block and writes its result under it, unless the block changed while it
490    /// ran. Returns a message for the echo area.
491    public func runBabel(_ job: BabelJob) async -> String {
492        guard let entry = current else { return "No file is open." }
493        let directory = URL(fileURLWithPath: entry.path).deletingLastPathComponent()
494        do {
495            let output = try await BabelRunner.run(job, fileDirectory: directory)
496            guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
497            let current = entry.buffer
498            let document = current.document
499            switch Babel.finish(job, output: output, text: document.text, settings: document.tree.settings) {
500            case .failure(.message(let message)):
501                return message
502            case .success(let edits):
503                guard !edits.isEmpty else { return job.finish.params.contains("silent") ? output.stdout : "Code block evaluation complete." }
504                let result = EditResult(baseRevision: document.revision, edits: edits)
505                if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
506                changed(entry)
507                return "Code block evaluation complete."
508            }
509        } catch {
510            return "\(error)"
511        }
512    }
513
514    /// A buffer changed outside typing: the current one updates its views, another saves.
515    private func changed(_ entry: Entry) {
516        if entry === current { bufferChanged() } else { scheduleAutosave(entry); refreshLists() }
517    }
518
519    // MARK: - Locations
520
521    /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
522    /// are used only if the buffer matches what was indexed; otherwise the heading is found
523    /// again by position and title.
524    public func show(_ location: HeadingLocation) {
525        if path != location.path { open(location.path) }
526        guard let document else { return }
527        let hash = FileRecord.hash(document.mergeBase)
528        let offset: Int
529        if !isDirty, hash == location.contentHash {
530            offset = location.start
531        } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
532            offset = outline[location.ordinal].start
533        } else if let entry = outline.first(where: { $0.title == location.title }) {
534            offset = entry.start
535        } else {
536            return
537        }
538        reveal(offset)
539    }
540
541    public func reveal(_ offset: Int) {
542        requestID += 1
543        revealRequest = (offset, requestID)
544    }
545
546    /// Called when the workspace sees a file change on disk: an open buffer of it takes the
547    /// change in.
548    public func fileChanged(_ path: String) {
549        guard let entry = entry(path), let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
550        let buffer = entry.buffer
551        guard bytes != buffer.document.mergeBase else { return }
552        let name = (path as NSString).lastPathComponent
553        switch buffer.update({ $0.diskChanged(to: bytes) }) {
554        case .conflict:
555            entry.autosave?.cancel()
556            entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
557        case .merged, .reloaded:
558            entry.conflict = nil
559        case .unchanged:
560            break
561        }
562        if entry === current { refresh() } else { refreshLists() }
563    }
564}