Sources/OrgApp/DocumentSession.swift

cf97b142eed5030eb13f4119afa246dac681d430
orgstar/Sources/OrgApp/DocumentSession.swift history · blame · raw

434 lines · 20161 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 file open in a window: its buffer, outline, saving, and requests for the editor to
 46/// show a location. The view layer attaches the editor as the buffer and follows
 47/// `revealRequest`.
 48@MainActor
 49@Observable
 50public final class DocumentSession {
 51    public private(set) var path: String?
 52    /// A copy of the buffer's state as of its last change. Not observed: it changes on every
 53    /// keystroke; views follow `path`, `isDirty` and `outline`.
 54    @ObservationIgnored public private(set) var document: DocumentState?
 55    public private(set) var outline: [OutlineEntry] = []
 56    /// Bumped when the buffer settles after edits, and when a file opens: views that read
 57    /// `document` follow this.
 58    public private(set) var editVersion = 0
 59    public private(set) var isDirty = false
 60    /// The file isn't UTF-8, so it can't be edited or saved.
 61    public private(set) var isReadOnly = false
 62    /// Set while the buffer and the file on disk conflict; says how to resolve it.
 63    public private(set) var conflict: String?
 64    /// Bumped to ask the editor to reveal an offset.
 65    public private(set) var revealRequest: (offset: Int, id: Int)?
 66    public var lastError: String?
 67    public var saveMode: SaveMode = .automatic
 68    public var autosaveDelay: Duration = .seconds(1)
 69    /// Org options for commands the session runs (refile, archive).
 70    public var options: EditingOptions = .org
 71    /// TODO keywords and priorities for files without their own settings.
 72    public var defaults: OrgSettings = .default
 73
 74    private let fileSystem: FileSystem
 75    private let recovery: RecoveryStore
 76    @ObservationIgnored private var buffer: DocumentBuffer?
 77    @ObservationIgnored var autosave: Task<Void, Never>?
 78    @ObservationIgnored private var outlineUpdate: Task<Void, Never>?
 79    private var requestID = 0
 80
 81    public init(
 82        fileSystem: FileSystem = CoordinatedFileSystem(),
 83        recovery: RecoveryStore = FileRecoveryStore(directory: WorkspaceModel.defaultDirectory.appendingPathComponent("Recovery"))
 84    ) {
 85        self.fileSystem = fileSystem
 86        self.recovery = recovery
 87    }
 88
 89    private var url: URL? { path.map { URL(fileURLWithPath: $0) } }
 90    /// Whether the open file is an org file (`.org`, `.org_archive`), not plain text.
 91    public var isOrg: Bool { path.map(Self.isOrgPath) ?? false }
 92
 93    public static func isOrgPath(_ path: String) -> Bool {
 94        path.hasSuffix(".org") || path.hasSuffix(".org_archive")
 95    }
 96
 97    /// The caret in the open file.
 98    public var caret: Int { buffer?.selection.first?.lowerBound ?? 0 }
 99    private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" }
100
101    public func open(_ path: String) {
102        do {
103            guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
104                lastError = "\((path as NSString).lastPathComponent) no longer exists."
105                return
106            }
107            autosave?.cancel()
108            self.path = path
109            buffer = StateBuffer(DocumentState(bytes: bytes, defaults: defaults))
110            conflict = nil
111            revealRequest = nil
112            refresh()
113        } catch {
114            lastError = "Can't open \(path): \(error.localizedDescription)"
115        }
116    }
117
118    /// Closes the open file without saving, as when it was deleted.
119    public func close() {
120        autosave?.cancel()
121        outlineUpdate?.cancel()
122        path = nil
123        buffer = nil
124        document = nil
125        outline = []
126        isDirty = false
127        conflict = nil
128        revealRequest = nil
129    }
130
131    /// Makes `buffer`, built from `document`, the live state of the open file.
132    public func attach(_ buffer: DocumentBuffer) {
133        self.buffer = buffer
134        refresh()
135    }
136
137    /// The buffer changed through typing. The outline follows once typing pauses.
138    public func bufferChanged() {
139        refresh(outline: false)
140        outlineUpdate?.cancel()
141        outlineUpdate = Task { [weak self] in
142            try? await Task.sleep(for: .milliseconds(300))
143            guard !Task.isCancelled, let self, let document = self.document else { return }
144            self.outline = self.isOrg ? Presentation.outline(document.tree) : []
145            self.editVersion += 1
146        }
147        scheduleAutosave()
148    }
149
150    private func refresh(outline updateOutline: Bool = true) {
151        guard let buffer else { return }
152        let state = buffer.document
153        document = state
154        if isDirty != state.isDirty { isDirty = state.isDirty }
155        if isReadOnly == state.isEditable { isReadOnly = !state.isEditable }
156        if updateOutline {
157            outline = isOrg ? Presentation.outline(state.tree) : []
158            editVersion += 1
159        }
160    }
161
162    // MARK: - Saving
163
164    private var saver: Saver { Saver(fileSystem: fileSystem, recovery: recovery) }
165
166    private func scheduleAutosave() {
167        autosave?.cancel()
168        guard saveMode == .automatic, isDirty, conflict == nil else { return }
169        autosave = Task { [weak self, autosaveDelay] in
170            try? await Task.sleep(for: autosaveDelay)
171            guard !Task.isCancelled else { return }
172            self?.save()
173        }
174    }
175
176    /// Saves now. True when nothing is left unsaved.
177    @discardableResult
178    public func save() -> Bool {
179        autosave?.cancel()
180        guard let buffer, let url, isDirty else { return !isDirty }
181        guard conflict == nil else { return false }
182        do {
183            let outcome = try buffer.update { try saver.save(&$0, to: url) }
184            switch outcome {
185            case .saved, .mergedAndSaved:
186                break
187            case .conflict:
188                conflict = "\(name) changed on disk, and the changes conflict with yours."
189            case .overwroteExternalChange(let change), .changedAfterWrite(let change):
190                if case .conflict = change {
191                    conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
192                }
193            }
194        } catch {
195            lastError = "Can't save \(name): \(error.localizedDescription)"
196        }
197        refresh()
198        return !isDirty
199    }
200
201    /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
202    public func keepMine() {
203        guard let buffer, let url else { return }
204        do {
205            try buffer.update { try saver.overwrite(&$0, to: url) }
206            conflict = nil
207        } catch {
208            lastError = "Can't save \(name): \(error.localizedDescription)"
209        }
210        refresh()
211    }
212
213    /// Resolves a conflict by loading the disk version; the buffer goes to recovery.
214    public func useDiskVersion() {
215        guard let buffer, let url else { return }
216        do {
217            guard let bytes = try fileSystem.read(url) else { return }
218            if isDirty { try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") }
219            buffer.update { $0 = DocumentState(bytes: bytes, defaults: $0.defaults) }
220            conflict = nil
221        } catch {
222            lastError = "Can't read \(name): \(error.localizedDescription)"
223        }
224        refresh()
225    }
226
227    // MARK: - Moving subtrees
228
229    /// The current context of the buffer, as commands see it.
230    private func editContext(now: Date) -> EditContext? {
231        guard let buffer else { return nil }
232        let document = buffer.document
233        return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: buffer.selection, now: now, options: options)
234    }
235
236    /// Moves the subtree at the caret under `target`. For another file, that file is written
237    /// first, through the save path; the subtree leaves this buffer only once it has. Returns a
238    /// message for the echo area.
239    @discardableResult
240    public func refile(to target: RefileTarget, now: Date = Date()) -> String? {
241        guard let buffer, let path, let context = editContext(now: now) else { return nil }
242        if target.path == path {
243            let step = buffer.perform(RefileWithinFile(), now: now, answers: ["refile": target.start.map(String.init) ?? ""])
244            if case .failed(let message) = step { return message }
245            bufferChanged()
246            return "Refiled to \(target.label)"
247        }
248        let url = URL(fileURLWithPath: target.path)
249        do {
250            guard let bytes = try fileSystem.read(url) else { return "\((target.path as NSString).lastPathComponent) no longer exists." }
251            var state = DocumentState(bytes: bytes, defaults: defaults)
252            guard state.isEditable else { return "\((target.path as NSString).lastPathComponent) isn't UTF-8, so it can't be changed." }
253            guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
254            guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." }
255            try state.apply([result.target], baseRevision: state.revision)
256            if case .conflict = try saver.save(&state, to: url) { return "\((target.path as NSString).lastPathComponent) changed on disk; nothing was refiled." }
257            if case .failed(let message) = buffer.perform(PrecomputedEdit(result.source), now: now, answers: [:]) { return message }
258            bufferChanged()
259            return "Refiled to \(target.label)"
260        } catch {
261            return "Can't refile: \(error.localizedDescription)"
262        }
263    }
264
265    /// Archives the subtree at the caret where `org-archive-subtree` would. Returns a message.
266    @discardableResult
267    public func archive(now: Date = Date()) -> String? {
268        guard let buffer, let path, let context = editContext(now: now) else { return nil }
269        let destination: Archive.Destination
270        switch Archive.destination(context, sourcePath: path) {
271        case .success(let value): destination = value
272        case .failure(.message(let message)): return message
273        }
274        do {
275            let url = URL(fileURLWithPath: destination.path)
276            let existing = destination.isSameFile ? nil : try fileSystem.read(url)
277            var state = DocumentState(bytes: existing ?? [], defaults: defaults)
278            if !destination.isSameFile, !state.isEditable { return "\(url.lastPathComponent) isn't UTF-8, so it can't be changed." }
279            let edits: Archive.Edits
280            switch Archive.run(context, sourcePath: path, destination: destination, archiveText: existing.map { _ in state.text }) {
281            case .success(let value): edits = value
282            case .failure(.message(let message)): return message
283            }
284            if let archiveEdit = edits.archive {
285                try state.apply([archiveEdit], baseRevision: state.revision)
286                if case .conflict = try saver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
287            }
288            if case .failed(let message) = buffer.perform(PrecomputedEdit(edits.source), now: now, answers: [:]) { return message }
289            bufferChanged()
290            return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
291        } catch {
292            return "Can't archive: \(error.localizedDescription)"
293        }
294    }
295
296    // MARK: - Commands from other views
297
298    /// Runs `command` with the caret at `offset` in the file at `path`, as the agenda does:
299    /// through the buffer when the file is open, leaving its caret alone; otherwise on the
300    /// file, written back at once through the save path. `expect` is the heading line the
301    /// caller saw at a position; if the text there changed, nothing runs.
302    public func perform(
303        _ command: any OrgCommand, path: String, at offset: Int, expect: (start: Int, line: String)?,
304        answers: [String: String] = [:], now: Date = Date()
305    ) -> CommandStep {
306        let stale = CommandStep.failed("The entry changed; the agenda has been refreshed.")
307        func matches(_ text: String) -> Bool {
308            guard let expect else { return true }
309            let ns = text as NSString
310            guard expect.start + (expect.line as NSString).length <= ns.length else { return false }
311            return ns.substring(with: NSRange(location: expect.start, length: (expect.line as NSString).length)) == expect.line
312        }
313        if path == self.path, let buffer {
314            guard matches(buffer.document.text) else { return stale }
315            do {
316                let options = self.options
317                let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) }
318                if case .commit = step { bufferChanged() }
319                return step
320            } catch {
321                return .failed("\(error)")
322            }
323        }
324        let url = URL(fileURLWithPath: path)
325        let name = url.lastPathComponent
326        do {
327            guard let bytes = try fileSystem.read(url) else { return .failed("\(name) no longer exists.") }
328            var state = DocumentState(bytes: bytes, defaults: defaults)
329            guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") }
330            guard matches(state.text) else { return stale }
331            let step = try state.run(command, selection: [offset..<offset], now: now, answers: answers, options: options)
332            if case .commit = step, state.isDirty, case .conflict = try saver.save(&state, to: url) {
333                return .failed("\(name) changed on disk; nothing was changed.")
334            }
335            return step
336        } catch {
337            return .failed("Can't change \(name): \(error.localizedDescription)")
338        }
339    }
340
341    // MARK: - External work
342
343    /// Recalculates a table in Emacs from a snapshot of the buffer, then replaces the table
344    /// with Emacs's text if it hasn't changed meanwhile. Returns a message for the echo area.
345    public func recalculateInEmacs(table: Range<Int>, point: Int, form: String) async -> String {
346        guard let buffer, let path else { return "No file is open." }
347        let snapshot = buffer.document.text as NSString
348        guard table.upperBound <= snapshot.length else { return "The table moved; try again." }
349        let old = snapshot.substring(with: NSRange(table))
350        let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
351        do {
352            let new = try await EmacsRunner.recalculateTable(text: snapshot as String, directory: directory, table: table, point: point, form: form)
353            guard let current = self.buffer, self.path == path else { return "The file was closed before Emacs finished." }
354            let text = current.document.text as NSString
355            guard table.upperBound <= text.length, text.substring(with: NSRange(table)) == old else {
356                return "The table changed while Emacs recalculated it; nothing was changed."
357            }
358            guard new != old else { return "Recalculated in Emacs" }
359            let result = EditResult(baseRevision: current.document.revision, edits: [TextEdit(range: table, replacement: new)])
360            if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
361            bufferChanged()
362            return "Recalculated in Emacs"
363        } catch {
364            return "\(error)"
365        }
366    }
367
368    /// Runs a src block and writes its result under it, unless the block changed while it
369    /// ran. Returns a message for the echo area.
370    public func runBabel(_ job: BabelJob) async -> String {
371        guard let path, buffer != nil else { return "No file is open." }
372        let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
373        do {
374            let output = try await BabelRunner.run(job, fileDirectory: directory)
375            guard let current = self.buffer, self.path == path else { return "The file was closed before the block finished." }
376            let document = current.document
377            switch Babel.finish(job, output: output, text: document.text, settings: document.tree.settings) {
378            case .failure(.message(let message)):
379                return message
380            case .success(let edits):
381                guard !edits.isEmpty else { return job.finish.params.contains("silent") ? output.stdout : "Code block evaluation complete." }
382                let result = EditResult(baseRevision: document.revision, edits: edits)
383                if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
384                bufferChanged()
385                return "Code block evaluation complete."
386            }
387        } catch {
388            return "\(error)"
389        }
390    }
391
392    // MARK: - Locations
393
394    /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
395    /// are used only if the buffer matches what was indexed; otherwise the heading is found
396    /// again by position and title.
397    public func show(_ location: HeadingLocation) {
398        if path != location.path { open(location.path) }
399        guard let document else { return }
400        let hash = FileRecord.hash(document.mergeBase)
401        let offset: Int
402        if !isDirty, hash == location.contentHash {
403            offset = location.start
404        } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
405            offset = outline[location.ordinal].start
406        } else if let entry = outline.first(where: { $0.title == location.title }) {
407            offset = entry.start
408        } else {
409            return
410        }
411        reveal(offset)
412    }
413
414    public func reveal(_ offset: Int) {
415        requestID += 1
416        revealRequest = (offset, requestID)
417    }
418
419    /// Called when the workspace sees the open file change on disk.
420    public func fileChanged(_ path: String) {
421        guard path == self.path, let buffer, let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
422        guard bytes != buffer.document.mergeBase else { return }
423        switch buffer.update({ $0.diskChanged(to: bytes) }) {
424        case .conflict:
425            autosave?.cancel()
426            conflict = "\(name) changed on disk, and the changes conflict with yours."
427        case .merged, .reloaded:
428            conflict = nil
429        case .unchanged:
430            break
431        }
432        refresh()
433    }
434}