Sources/OrgApp/DocumentSession.swift

8dea72acea277d24d8a83e0843087d50d5af8667
orgstar/Sources/OrgApp/DocumentSession.swift

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