Sources/OrgApp/DocumentSession.swift

d84591dd4402f983173a2d86d65eef6b24957599
orgstar/Sources/OrgApp/DocumentSession.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form