Sources/OrgApp/DocumentSession.swift

24ce0772eaab6c1bbdee07384de234975cf3769b
orgstar/Sources/OrgApp/DocumentSession.swift history · blame · raw

388 lines · 18039 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    private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" }
 91
 92    public func open(_ path: String) {
 93        do {
 94            guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
 95                lastError = "\((path as NSString).lastPathComponent) no longer exists."
 96                return
 97            }
 98            autosave?.cancel()
 99            self.path = path
100            buffer = StateBuffer(DocumentState(bytes: bytes, defaults: defaults))
101            conflict = nil
102            revealRequest = nil
103            refresh()
104        } catch {
105            lastError = "Can't open \(path): \(error.localizedDescription)"
106        }
107    }
108
109    /// Makes `buffer`, built from `document`, the live state of the open file.
110    public func attach(_ buffer: DocumentBuffer) {
111        self.buffer = buffer
112        refresh()
113    }
114
115    /// The buffer changed through typing. The outline follows once typing pauses.
116    public func bufferChanged() {
117        refresh(outline: false)
118        outlineUpdate?.cancel()
119        outlineUpdate = Task { [weak self] in
120            try? await Task.sleep(for: .milliseconds(300))
121            guard !Task.isCancelled, let self, let document = self.document else { return }
122            self.outline = Presentation.outline(document.tree)
123            self.editVersion += 1
124        }
125        scheduleAutosave()
126    }
127
128    private func refresh(outline updateOutline: Bool = true) {
129        guard let buffer else { return }
130        let state = buffer.document
131        document = state
132        if isDirty != state.isDirty { isDirty = state.isDirty }
133        if isReadOnly == state.isEditable { isReadOnly = !state.isEditable }
134        if updateOutline {
135            outline = Presentation.outline(state.tree)
136            editVersion += 1
137        }
138    }
139
140    // MARK: - Saving
141
142    private var saver: Saver { Saver(fileSystem: fileSystem, recovery: recovery) }
143
144    private func scheduleAutosave() {
145        autosave?.cancel()
146        guard saveMode == .automatic, isDirty, conflict == nil else { return }
147        autosave = Task { [weak self, autosaveDelay] in
148            try? await Task.sleep(for: autosaveDelay)
149            guard !Task.isCancelled else { return }
150            self?.save()
151        }
152    }
153
154    /// Saves now. True when nothing is left unsaved.
155    @discardableResult
156    public func save() -> Bool {
157        autosave?.cancel()
158        guard let buffer, let url, isDirty else { return !isDirty }
159        guard conflict == nil else { return false }
160        do {
161            let outcome = try buffer.update { try saver.save(&$0, to: url) }
162            switch outcome {
163            case .saved, .mergedAndSaved:
164                break
165            case .conflict:
166                conflict = "\(name) changed on disk, and the changes conflict with yours."
167            case .overwroteExternalChange(let change), .changedAfterWrite(let change):
168                if case .conflict = change {
169                    conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
170                }
171            }
172        } catch {
173            lastError = "Can't save \(name): \(error.localizedDescription)"
174        }
175        refresh()
176        return !isDirty
177    }
178
179    /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
180    public func keepMine() {
181        guard let buffer, let url else { return }
182        do {
183            try buffer.update { try saver.overwrite(&$0, to: url) }
184            conflict = nil
185        } catch {
186            lastError = "Can't save \(name): \(error.localizedDescription)"
187        }
188        refresh()
189    }
190
191    /// Resolves a conflict by loading the disk version; the buffer goes to recovery.
192    public func useDiskVersion() {
193        guard let buffer, let url else { return }
194        do {
195            guard let bytes = try fileSystem.read(url) else { return }
196            if isDirty { try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") }
197            buffer.update { $0 = DocumentState(bytes: bytes, defaults: $0.defaults) }
198            conflict = nil
199        } catch {
200            lastError = "Can't read \(name): \(error.localizedDescription)"
201        }
202        refresh()
203    }
204
205    // MARK: - Moving subtrees
206
207    /// The current context of the buffer, as commands see it.
208    private func editContext(now: Date) -> EditContext? {
209        guard let buffer else { return nil }
210        let document = buffer.document
211        return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: buffer.selection, now: now, options: options)
212    }
213
214    /// Moves the subtree at the caret under `target`. For another file, that file is written
215    /// first, through the save path; the subtree leaves this buffer only once it has. Returns a
216    /// message for the echo area.
217    @discardableResult
218    public func refile(to target: RefileTarget, now: Date = Date()) -> String? {
219        guard let buffer, let path, let context = editContext(now: now) else { return nil }
220        if target.path == path {
221            let step = buffer.perform(RefileWithinFile(), now: now, answers: ["refile": target.start.map(String.init) ?? ""])
222            if case .failed(let message) = step { return message }
223            bufferChanged()
224            return "Refiled to \(target.label)"
225        }
226        let url = URL(fileURLWithPath: target.path)
227        do {
228            guard let bytes = try fileSystem.read(url) else { return "\((target.path as NSString).lastPathComponent) no longer exists." }
229            var state = DocumentState(bytes: bytes, defaults: defaults)
230            guard state.isEditable else { return "\((target.path as NSString).lastPathComponent) isn't UTF-8, so it can't be changed." }
231            guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
232            guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." }
233            try state.apply([result.target], baseRevision: state.revision)
234            if case .conflict = try saver.save(&state, to: url) { return "\((target.path as NSString).lastPathComponent) changed on disk; nothing was refiled." }
235            if case .failed(let message) = buffer.perform(PrecomputedEdit(result.source), now: now, answers: [:]) { return message }
236            bufferChanged()
237            return "Refiled to \(target.label)"
238        } catch {
239            return "Can't refile: \(error.localizedDescription)"
240        }
241    }
242
243    /// Archives the subtree at the caret where `org-archive-subtree` would. Returns a message.
244    @discardableResult
245    public func archive(now: Date = Date()) -> String? {
246        guard let buffer, let path, let context = editContext(now: now) else { return nil }
247        let destination: Archive.Destination
248        switch Archive.destination(context, sourcePath: path) {
249        case .success(let value): destination = value
250        case .failure(.message(let message)): return message
251        }
252        do {
253            let url = URL(fileURLWithPath: destination.path)
254            let existing = destination.isSameFile ? nil : try fileSystem.read(url)
255            var state = DocumentState(bytes: existing ?? [], defaults: defaults)
256            if !destination.isSameFile, !state.isEditable { return "\(url.lastPathComponent) isn't UTF-8, so it can't be changed." }
257            let edits: Archive.Edits
258            switch Archive.run(context, sourcePath: path, destination: destination, archiveText: existing.map { _ in state.text }) {
259            case .success(let value): edits = value
260            case .failure(.message(let message)): return message
261            }
262            if let archiveEdit = edits.archive {
263                try state.apply([archiveEdit], baseRevision: state.revision)
264                if case .conflict = try saver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
265            }
266            if case .failed(let message) = buffer.perform(PrecomputedEdit(edits.source), now: now, answers: [:]) { return message }
267            bufferChanged()
268            return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
269        } catch {
270            return "Can't archive: \(error.localizedDescription)"
271        }
272    }
273
274    // MARK: - Commands from other views
275
276    /// Runs `command` with the caret at `offset` in the file at `path`, as the agenda does:
277    /// through the buffer when the file is open, leaving its caret alone; otherwise on the
278    /// file, written back at once through the save path. `expect` is the heading line the
279    /// caller saw at a position; if the text there changed, nothing runs.
280    public func perform(
281        _ command: any OrgCommand, path: String, at offset: Int, expect: (start: Int, line: String)?,
282        answers: [String: String] = [:], now: Date = Date()
283    ) -> CommandStep {
284        let stale = CommandStep.failed("The entry changed; the agenda has been refreshed.")
285        func matches(_ text: String) -> Bool {
286            guard let expect else { return true }
287            let ns = text as NSString
288            guard expect.start + (expect.line as NSString).length <= ns.length else { return false }
289            return ns.substring(with: NSRange(location: expect.start, length: (expect.line as NSString).length)) == expect.line
290        }
291        if path == self.path, let buffer {
292            guard matches(buffer.document.text) else { return stale }
293            do {
294                let options = self.options
295                let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) }
296                if case .commit = step { bufferChanged() }
297                return step
298            } catch {
299                return .failed("\(error)")
300            }
301        }
302        let url = URL(fileURLWithPath: path)
303        let name = url.lastPathComponent
304        do {
305            guard let bytes = try fileSystem.read(url) else { return .failed("\(name) no longer exists.") }
306            var state = DocumentState(bytes: bytes, defaults: defaults)
307            guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") }
308            guard matches(state.text) else { return stale }
309            let step = try state.run(command, selection: [offset..<offset], now: now, answers: answers, options: options)
310            if case .commit = step, state.isDirty, case .conflict = try saver.save(&state, to: url) {
311                return .failed("\(name) changed on disk; nothing was changed.")
312            }
313            return step
314        } catch {
315            return .failed("Can't change \(name): \(error.localizedDescription)")
316        }
317    }
318
319    // MARK: - External work
320
321    /// Recalculates a table in Emacs from a snapshot of the buffer, then replaces the table
322    /// with Emacs's text if it hasn't changed meanwhile. Returns a message for the echo area.
323    public func recalculateInEmacs(table: Range<Int>, point: Int, form: String) async -> String {
324        guard let buffer, let path else { return "No file is open." }
325        let snapshot = buffer.document.text as NSString
326        guard table.upperBound <= snapshot.length else { return "The table moved; try again." }
327        let old = snapshot.substring(with: NSRange(table))
328        let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
329        do {
330            let new = try await EmacsRunner.recalculateTable(text: snapshot as String, directory: directory, table: table, point: point, form: form)
331            guard let current = self.buffer, self.path == path else { return "The file was closed before Emacs finished." }
332            let text = current.document.text as NSString
333            guard table.upperBound <= text.length, text.substring(with: NSRange(table)) == old else {
334                return "The table changed while Emacs recalculated it; nothing was changed."
335            }
336            guard new != old else { return "Recalculated in Emacs" }
337            let result = EditResult(baseRevision: current.document.revision, edits: [TextEdit(range: table, replacement: new)])
338            if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
339            bufferChanged()
340            return "Recalculated in Emacs"
341        } catch {
342            return "\(error)"
343        }
344    }
345
346    // MARK: - Locations
347
348    /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
349    /// are used only if the buffer matches what was indexed; otherwise the heading is found
350    /// again by position and title.
351    public func show(_ location: HeadingLocation) {
352        if path != location.path { open(location.path) }
353        guard let document else { return }
354        let hash = FileRecord.hash(document.mergeBase)
355        let offset: Int
356        if !isDirty, hash == location.contentHash {
357            offset = location.start
358        } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
359            offset = outline[location.ordinal].start
360        } else if let entry = outline.first(where: { $0.title == location.title }) {
361            offset = entry.start
362        } else {
363            return
364        }
365        reveal(offset)
366    }
367
368    public func reveal(_ offset: Int) {
369        requestID += 1
370        revealRequest = (offset, requestID)
371    }
372
373    /// Called when the workspace sees the open file change on disk.
374    public func fileChanged(_ path: String) {
375        guard path == self.path, let buffer, let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
376        guard bytes != buffer.document.mergeBase else { return }
377        switch buffer.update({ $0.diskChanged(to: bytes) }) {
378        case .conflict:
379            autosave?.cancel()
380            conflict = "\(name) changed on disk, and the changes conflict with yours."
381        case .merged, .reloaded:
382            conflict = nil
383        case .unchanged:
384            break
385        }
386        refresh()
387    }
388}